void CallReturnChannel(LibraryChannel channel, bool bEndLoop) { if (this.ReturnChannel == null) return; ReturnChannelEventArgs e = new ReturnChannelEventArgs(); e.Channel = channel; e.EndLoop = bEndLoop; this.ReturnChannel(this, e); }
public DirItemLoader(LibraryChannel channel, DigitalPlatform.Stop stop, string path, string style, string lang = "zh") { this.Channel = channel; this.Stop = stop; this.Path = path; this.Style = style; this.Lang = lang; }
public void Close() { if (stop != null) // 脱离关联 { stop.Unregister(); // 和容器关联 stop = null; } if (this.Channel != null) { this.Channel.Close(); this.Channel = null; } }
public void Dispose() { if (this._client != null) { try { this._client.Close(); } catch { } this._client = null; } if (this._channel != null) { this._channel.Close(); this._channel = null; } }
// 初始化数据成员 public int Initial( MainForm mainform, string[] aPaths, string strMessage, LibraryChannel channel, Stop stop, out string strError) { strError = ""; this.MainForm = mainform; this.Channel = channel; this.stop = stop; this.aPaths = aPaths; this.textBox_message.Text = strMessage; this.InfoColor = InfoColor.LightRed; // 红色表示警告 return 0; }
internal static int GetRemoteBiblioDbNames( string strUrl, string strUserName, string strPassword, out List <string> dbnames, out string strError) { strError = ""; dbnames = new List <string>(); string strValue = ""; LibraryChannel channel = new LibraryChannel(); channel.Url = strUrl; try { long lRet = channel.Login(strUserName, strPassword, "type=worker,client=dp2circulation|" + Program.ClientVersion, out strError); if (lRet != 1) { strError = "对服务器 '" + channel.Url + "' 以用户 '" + strUserName + "' 进行登录时发生错误: " + strError; return(-1); } lRet = channel.GetSystemParameter(null, "system", "biblioDbGroup", out strValue, out strError); if (lRet == -1) { strError = "针对服务器 " + channel.Url + " 获得书目库信息过程发生错误:" + strError; return(-1); } } finally { channel.Close(); } { // 解析 XML XmlDocument dom = new XmlDocument(); dom.LoadXml("<root />"); try { dom.DocumentElement.InnerXml = strValue; } catch (Exception ex) { strError = "category=system,name=biblioDbGroup 所返回的 XML 片段在装入 InnerXml 时出错: " + ex.Message; return(-1); } XmlNodeList nodes = dom.DocumentElement.SelectNodes("database"); foreach (XmlNode node in nodes) { string strDbName = DomUtil.GetAttr(node, "biblioDbName"); dbnames.Add(strDbName); } } return(0); }
// return: // -1 error // 0 没有装载 // 1 已经装载 public int LoadObject( LibraryChannel channel, string strBiblioRecPath, string strXml, string dp2library_version, out string strError) { strError = ""; this.ErrorInfo = ""; // 2007/12/2 if (String.IsNullOrEmpty(strXml) == true) { this.Changed = false; return 0; } this.BiblioRecPath = strBiblioRecPath; XmlDocument dom = new XmlDocument(); try { dom.LoadXml(strXml); } catch (Exception ex) { strError = "XML记录装载到DOM时出错: " + ex.Message; return -1; } XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable()); nsmgr.AddNamespace("dprms", DpNs.dprms); XmlNodeList nodes = dom.DocumentElement.SelectNodes("//dprms:file", nsmgr); return LoadObject( channel, nodes, dp2library_version, out strError); }
// 从服务器端得到XML数据,初始化若干变量 // parameters: // page 如果!=null,允许灵敏中断 // return: // -1 出错 // 0 正常结束 // 1 被用户中断 public int InitialInfo( System.Web.UI.Page page, LibraryChannel channel, out string strError) { strError = ""; Line line = this; if (this.m_bInfoInitilized == true) return 0; if (String.IsNullOrEmpty(this.m_strRecPath) == true) { strError = "m_strRecPath尚未初始化"; return -1; } string strStyle = "content,data"; string strContent; string strMetaData; byte[] baTimeStamp; string strOutputPath; Debug.Assert(channel != null, "Channels.GetChannel 异常"); if (page != null && page.Response.IsClientConnected == false) // 灵敏中断 return 1; long nRet = channel.GetRes(null, this.m_strRecPath, strStyle, out strContent, out strMetaData, out baTimeStamp, out strOutputPath, out strError); if (nRet == -1) { strError = "获取记录 '" + this.m_strRecPath + "' 时出错: " + strError; return -1; } if (page != null && page.Response.IsClientConnected == false) // 灵敏中断 return 1; // 处理数据 nRet = line.ProcessXml( page, strContent, out strError); if (nRet == -1) { return -1; } this.m_bInfoInitilized = true; return 0; }
protected void ItemSearchControl1_Search(object sender, DigitalPlatform.OPAC.Web.SearchEventArgs e) { if (WebUtil.PrepareEnvironment(this, ref app, ref sessioninfo) == false) { return; } string strError = ""; // string strResultSetNamePrefix = "opac_item_base"; string strResultSetNamePrefix = Session.SessionID + "opac_item_base"; string strResultSetName = GetResultSetName(strResultSetNamePrefix); LibraryChannel channel = sessioninfo.GetChannel(true); // sessioninfo.Channel. channel.Idle += new IdleEventHandler(channel_Idle); try { long lRet = // sessioninfo.Channel. channel.Search( null, e.QueryXml, strResultSetName, "", // strOutputStyle out strError); if (lRet == -1) { goto ERROR1; } // not found if (lRet == 0) { this.BrowseSearchResultControl1.Visible = false; strError = "没有找到"; goto ERROR1; } e.ErrorInfo = string.Format( this.ItemSearchControl1.GetString("hit_records_number"), lRet.ToString()); // e.ErrorInfo = "命中记录 " +lRet.ToString()+ " 条"; this.BrowseSearchResultControl1.Clear(); this.BrowseSearchResultControl1.Visible = true; this.BrowseSearchResultControl1.ResultSetName = strResultSetName; this.BrowseSearchResultControl1.ResultCount = (int)lRet; this.BrowseSearchResultControl1.StartIndex = 0; // 2008/12/15 } finally { // sessioninfo.Channel. channel.Idle -= new IdleEventHandler(channel_Idle); sessioninfo.ReturnChannel(channel); } return; ERROR1: /* * Response.Write(HttpUtility.HtmlEncode(strError)); * Response.End(); * */ e.ErrorInfo = strError; this.BrowseSearchResultControl1.ResultSetName = ""; this.BrowseSearchResultControl1.ResultCount = 0; }
// 装入一个日志文件中的若干记录 // 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; }
// 检索出盘点库内全部批次号名称 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; }
/* * <locationTypes> * <item canborrow="no" itemBarcodeNullable="yes">保存本库</item> * <item canborrow="no" itemBarcodeNullable="yes">阅览室</item> * <item canborrow="yes" itemBarcodeNullable="yes">流通库</item> * <item canborrow="yes" itemBarcodeNullable="yes">测试库</item> * <library code="海淀分馆"> * <item canborrow="no" itemBarcodeNullable="no">流通库</item> * <item canborrow="yes" itemBarcodeNullable="no">班级书架</item> * <item canborrow="yes" itemBarcodeNullable="no"></item> * </library> * </locationTypes> * */ // 为系统添加新的馆藏地定义 // parameters: // strAction add/remove public static int AddLocationTypes( LibraryChannel channel, // Stop stop, string strAction, List <LocationItem> items, out string strError) { strError = ""; string strOutputInfo = ""; long lRet = channel.GetSystemParameter( // stop, "circulation", "locationTypes", out strOutputInfo, out strError); if (lRet == -1) { return(-1); } XmlDocument dom = new XmlDocument(); dom.LoadXml("<root />"); XmlDocumentFragment fragment = dom.CreateDocumentFragment(); try { fragment.InnerXml = strOutputInfo; } catch (Exception ex) { strError = "fragment XML 装入 XmlDocumentFragment 时出错: " + ex.Message; return(-1); } dom.DocumentElement.AppendChild(fragment); if (strAction == "add") { foreach (LocationItem item in items) { // 删除可能存在的同名定义 RemoveLocationItem(dom, item); XmlElement new_item = dom.CreateElement("item"); new_item.SetAttribute("canborrow", item.CanBorrow ? "yes" : "no"); new_item.SetAttribute("itemBarcodeNullable", item.ItemBarcodeNullable ? "yes" : "no"); if (string.IsNullOrEmpty(item.Room) == false) { new_item.InnerText = item.Room; } if (string.IsNullOrEmpty(item.LibraryCode) == false) { XmlElement library = null; library = dom.CreateElement("library"); dom.DocumentElement.AppendChild(library); library.SetAttribute("code", item.LibraryCode); library.AppendChild(new_item); } else { dom.DocumentElement.AppendChild(new_item); } } } else if (strAction == "remove") { foreach (LocationItem item in items) { RemoveLocationItem(dom, item); } } else { strError = "未知的 strAction '" + strAction + "'"; return(-1); } lRet = channel.SetSystemParameter( // stop, "circulation", "locationTypes", dom.DocumentElement.InnerXml, out strError); if (lRet == -1) { return(-1); } return(0); }
int FillList(bool bSort, out string strError) { strError = ""; // int nRet = 0; this.listView_number.Items.Clear(); this.MaxNumber = ""; // 获得server url if (String.IsNullOrEmpty(this.LibraryServerName) == true) { strError = "尚未指定服务器名"; goto ERROR1; } dp2Server server = this.MainForm.Servers.GetServerByName(this.LibraryServerName); if (server == null) { strError = "服务器名为 '" + this.LibraryServerName + "' 的服务器不存在..."; goto ERROR1; } string strServerUrl = server.Url; this.Channel = this.Channels.GetChannel(strServerUrl); /* if (dom == null) { strError = "请先调用GetGlobalCfgFile()函数"; return -1; } * */ if (this.ClassNumber == "") { strError = "尚未指定分类号"; return -1; } if (this.BiblioDbName == "") { strError = "尚未指定书目库名"; return -1; } EnableControls(false); stop.OnStop += new StopEventHandler(this.DoStop); stop.Initial("正在检索同类书记录 ..."); stop.BeginLoop(); this.Update(); this.MainForm.Update(); try { string strQueryXml = ""; long lRet = Channel.SearchUsedZhongcihao( stop, GetZhongcihaoDbGroupName(this.BiblioDbName), // "!" + this.BiblioDbName, this.ClassNumber, "zhongcihao", out strQueryXml, out strError); if (lRet == -1) goto ERROR1; if (lRet == 0) { strError = "没有命中的记录。"; return 0; // not found } long lHitCount = lRet; long lStart = 0; long lPerCount = Math.Min(50, lHitCount); ZhongcihaoSearchResult[] searchresults = null; if (stop != null) stop.SetProgressRange(0, lHitCount); // 装入浏览格式 for (; ; ) { Application.DoEvents(); // 出让界面控制权 if (stop != null) { if (stop.State != 0) { strError = "用户中断"; goto ERROR1; } } long lCurrentPerCount = lPerCount; bool bShift = Control.ModifierKeys == Keys.Shift; string strBrowseStyle = "cols"; if (bShift == true || this.checkBox_returnBrowseCols.Checked == false) { strBrowseStyle = ""; lCurrentPerCount = lPerCount * 10; } stop.SetMessage("正在装入浏览信息 " + (lStart + 1).ToString() + " - " + (lStart + lPerCount).ToString() + " (命中 " + lHitCount.ToString() + " 条记录) ..."); lRet = Channel.GetZhongcihaoSearchResult( stop, GetZhongcihaoDbGroupName(this.BiblioDbName), // "!" + this.BiblioDbName, "zhongcihao", // strResultSetName lStart, lPerCount, strBrowseStyle, // style this.Lang, out searchresults, out strError); if (lRet == -1) goto ERROR1; if (lRet == 0) { strError = "未命中"; goto ERROR1; } // 处理浏览结果 for (int i = 0; i < searchresults.Length; i++) { ZhongcihaoSearchResult result_item = searchresults[i]; ListViewItem item = new ListViewItem(); item.Text = result_item.Path; item.SubItems.Add(result_item.Zhongcihao); if (result_item.Cols != null) { ListViewUtil.EnsureColumns(this.listView_number, result_item.Cols.Length + 1); for (int j = 0; j < result_item.Cols.Length; j++) { ListViewUtil.ChangeItemText(item, j + 2, result_item.Cols[j]); } } this.listView_number.Items.Add(item); if (stop != null) stop.SetProgressValue(lStart + i + 1); } lStart += searchresults.Length; if (lStart >= lHitCount || lPerCount <= 0) break; } } finally { stop.EndLoop(); stop.OnStop -= new StopEventHandler(this.DoStop); stop.Initial(""); stop.HideProgress(); EnableControls(true); } if (bSort == true) { // 排序 this.listView_number.ListViewItemSorter = new ZhongcihaoListViewItemComparer(); this.listView_number.ListViewItemSorter = null; // 把重复种次号的事项用特殊颜色标出来 ColorDup(); this.MaxNumber = GetTopNumber(this.listView_number); // this.listView_number.Items[0].SubItems[1].Text; } return 0; ERROR1: return -1; }
// 创建缺省的几个数据库 // TODO: 把过程显示在控制台 // parameters: // return: // -1 出错 // 0 没有必要创建,或者操作者放弃创建。原因在 strError 中 // 1 成功创建 public static int CreateDefaultDatabases( LibraryChannel channel, // Stop Stop, Delegate_prompt procPrompt, out string strError) { strError = ""; // 创建书目库的定义 XmlDocument database_dom = new XmlDocument(); database_dom.LoadXml("<root />"); List <string> biblio_dbnames = new List <string>(); List <string> biblio_aliases = new List <string>(); // 创建书目库 { // parameters: // strUsage book/series // strSyntax unimarc/usmarc CreateBiblioDatabaseNode(database_dom, "中文图书", "book", "orderRecommendStore,catalogTarget", // 2015/7/6 增加 catalogTarget "unimarc", true); biblio_dbnames.Add("中文图书"); biblio_aliases.Add("cbook"); CreateBiblioDatabaseNode(database_dom, "中文期刊", "series", "", "unimarc", true); biblio_dbnames.Add("中文期刊"); biblio_aliases.Add("cseries"); CreateBiblioDatabaseNode(database_dom, "西文图书", "book", "", "usmarc", true); biblio_dbnames.Add("西文图书"); biblio_aliases.Add("ebook"); CreateBiblioDatabaseNode(database_dom, "西文期刊", "series", "", "usmarc", true); biblio_dbnames.Add("西文期刊"); biblio_aliases.Add("eseries"); } // 创建读者库 CreateReaderDatabaseNode(database_dom, "读者", "", true); // 预约到书 CreateSimpleDatabaseNode(database_dom, "预约到书", "arrived"); // 违约金 CreateSimpleDatabaseNode(database_dom, "违约金", "amerce"); // 出版者 CreateSimpleDatabaseNode(database_dom, "出版者", "publisher"); // 消息 CreateSimpleDatabaseNode(database_dom, "消息", "message"); // 创建 OPAC 数据库的定义 XmlDocument opac_dom = new XmlDocument(); opac_dom.LoadXml("<virtualDatabases />"); Debug.Assert(biblio_aliases.Count == biblio_dbnames.Count, ""); int i = 0; foreach (string dbname in biblio_dbnames) { string alias = biblio_aliases[i]; XmlElement node = opac_dom.CreateElement("database"); opac_dom.DocumentElement.AppendChild(node); node.SetAttribute("name", dbname); node.SetAttribute("alias", alias); i++; } // 浏览格式 // 插入格式节点 XmlDocument browse_dom = new XmlDocument(); browse_dom.LoadXml("<browseformats />"); foreach (string dbname in biblio_dbnames) { XmlElement database = browse_dom.CreateElement("database"); browse_dom.DocumentElement.AppendChild(database); database.SetAttribute("name", dbname); XmlElement format = browse_dom.CreateElement("format"); database.AppendChild(format); format.SetAttribute("name", "详细"); format.SetAttribute("type", "biblio"); format.InnerXml = "<caption lang=\"zh-CN\">详细</caption><caption lang=\"en\">Detail</caption>"; } // 询问是否要创建? if (procPrompt != null) { string strText = "创建下列书目库: " + StringUtil.MakePathList(biblio_dbnames); if (procPrompt(strText) == false) { strError = "放弃创建"; return(0); } } TimeSpan old_timeout = channel.Timeout; channel.Timeout = new TimeSpan(0, 10, 0); try { string strOutputInfo = ""; long lRet = channel.ManageDatabase( // Stop, "create", "", database_dom.OuterXml, out strOutputInfo, out strError); if (lRet == -1) { return(-1); } lRet = channel.SetSystemParameter( // Stop, "opac", "databases", opac_dom.DocumentElement.InnerXml, out strError); if (lRet == -1) { return(-1); } lRet = channel.SetSystemParameter( // Stop, "opac", "browseformats", browse_dom.DocumentElement.InnerXml, out strError); if (lRet == -1) { return(-1); } return(1); } finally { channel.Timeout = old_timeout; } }
// 创建一个书目库 // parameters: // return: // -1 出错 // 0 没有必要创建,或者操作者放弃创建。原因在 strError 中 // 1 成功创建 public static int CreateBiblioDatabase( LibraryChannel channel, // Stop Stop, string strBiblioDbName, string strUsage, string strSyntax, out string strError) { strError = ""; // 创建书目库的定义 XmlDocument database_dom = new XmlDocument(); database_dom.LoadXml("<root />"); List <string> biblio_dbnames = new List <string>(); //List<string> biblio_aliases = new List<string>(); // 创建书目库 { // parameters: // strUsage book/series // strSyntax unimarc/usmarc CreateBiblioDatabaseNode(database_dom, strBiblioDbName, strUsage, // "book", "", // "orderRecommendStore,catalogTarget", // 2015/7/6 增加 catalogTarget strSyntax, // "unimarc", true); biblio_dbnames.Add(strBiblioDbName); // biblio_aliases.Add("cbook"); } // 创建 OPAC 数据库的定义 XmlDocument opac_dom = new XmlDocument(); opac_dom.LoadXml("<virtualDatabases />"); // Debug.Assert(biblio_aliases.Count == biblio_dbnames.Count, ""); int i = 0; foreach (string dbname in biblio_dbnames) { //string alias = biblio_aliases[i]; XmlElement node = opac_dom.CreateElement("database"); opac_dom.DocumentElement.AppendChild(node); node.SetAttribute("name", dbname); //node.SetAttribute("alias", alias); i++; } TimeSpan old_timeout = channel.Timeout; channel.Timeout = new TimeSpan(0, 10, 0); try { string strOutputInfo = ""; long lRet = channel.ManageDatabase( // Stop, "create", "", database_dom.OuterXml, out strOutputInfo, out strError); if (lRet == -1) { return(-1); } return(1); } finally { channel.Timeout = old_timeout; } }
// 获得一个日志文件的尺寸 // 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 = Path.Combine(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); }
// 获得日志文件中记录的总数 // parameters: // strDate 日志文件的日期,8 字符 // return: // -2 此类型的日志在 dp2library 端尚未启用 // -1 出错 // 0 日志文件不存在,或者记录数为 0 // >0 记录数 public static long GetOperLogCount( Stop stop, LibraryChannel channel, string strDate, LogType logType, out string strError) { strError = ""; if (strDate.Length != 8) { strError = "strDate 参数值应该是 8 字符 (当前为 '" + strDate + "')"; return(-1); } string strXml = ""; long lAttachmentTotalLength = 0; byte[] attachment_data = null; long lRecCount = 0; string strStyle = "getcount"; if ((logType & LogType.AccessLog) != 0) { strStyle += ",accessLog"; } // 获得日志文件尺寸 // return: // -1 error // 0 file not found // 1 succeed // 2 超过范围 long lRet = channel.GetOperLog( stop, strDate + ".log", -1, // lIndex, -1, // lHint, strStyle, "", // strFilter out strXml, out lRecCount, 0, // lAttachmentFragmentStart, 0, // nAttachmentFramengLength, out attachment_data, out lAttachmentTotalLength, out strError); if (lRet == 0) { lRecCount = 0; return(0); } if (lRet != 1) { return(-1); } if (lRecCount == -1) { strError = logType.ToString() + " 型的日志在 dp2library 中尚未启用"; return(-2); } Debug.Assert(lRecCount >= 0, ""); return(lRecCount); }
static void CrashReport(string strText) { // MainForm main_form = Form.ActiveForm as MainForm; MessageBar _messageBar = null; _messageBar = new MessageBar(); _messageBar.TopMost = false; //_messageBar.BackColor = SystemColors.Info; //_messageBar.ForeColor = SystemColors.InfoText; _messageBar.Text = "dp2Circulation 出现异常"; _messageBar.MessageText = "正在向 dp2003.com 发送异常报告 ..."; _messageBar.StartPosition = FormStartPosition.CenterScreen; _messageBar.Show(_mainForm); _messageBar.Update(); int nRet = 0; string strError = ""; try { string strSender = ""; if (_mainForm != null) { strSender = _mainForm.GetCurrentUserName() + "@" + _mainForm.ServerUID; } // 崩溃报告 nRet = LibraryChannel.CrashReport( strSender, "dp2circulation", strText, out strError); } catch (Exception ex) { strError = "CrashReport() 过程出现异常: " + ExceptionUtil.GetDebugText(ex); nRet = -1; } finally { _messageBar.Close(); _messageBar = null; } if (nRet == -1) { strError = "向 dp2003.com 发送异常报告时出错,未能发送成功。详细情况: " + strError; MessageBox.Show(_mainForm, strError); // 写入错误日志 MainForm.WriteErrorLog(strError); #if NO if (_mainForm != null) { _mainForm.WriteErrorLog(strError); } else { WriteWindowsLog(strError, EventLogEntryType.Error); } #endif } }
// 填充列表内容 // return: // -1 error // 0 没有填充任何内容,列表为空 // 1 已经填充了内容 public int LoadObject( LibraryChannel channel, XmlNodeList nodes, string dp2library_version, out string strError) { strError = ""; bool bOldEnabled = this.Enabled; this.Enabled = bOldEnabled; try { this.ListView.Items.Clear(); List<string> recpaths = new List<string>(); List<ListViewItem> items = new List<ListViewItem>(); // 第一阶段,把来自 XML 记录中的 <file> 元素信息填入。 // 这样就保证了至少可以在保存书目记录阶段能还原 XML 记录中的相关部分 foreach (XmlElement node in nodes) { string strID = DomUtil.GetAttr(node, "id"); string strUsage = DomUtil.GetAttr(node, "usage"); string strRights = DomUtil.GetAttr(node, "rights"); ListViewItem item = new ListViewItem(); // state SetLineInfo(item, LineState.Normal); // id ListViewUtil.ChangeItemText(item, COLUMN_ID, strID); // usage ListViewUtil.ChangeItemText(item, COLUMN_USAGE, strUsage); // rights ListViewUtil.ChangeItemText(item, COLUMN_RIGHTS, strRights); this.ListView.Items.Add(item); items.Add(item); string strResPath = this.BiblioRecPath + "/object/" + strID; strResPath = strResPath.Replace(":", "/"); recpaths.Add(strResPath); } if (StringUtil.CompareVersion(dp2library_version, "2.58") >= 0) { // 新方法,速度快 #if NO Stop.OnStop += new StopEventHandler(this.DoStop); Stop.Initial("正在下载对象的元数据"); Stop.BeginLoop(); #endif Stop.Initial("正在下载对象的元数据"); try { BrowseLoader loader = new BrowseLoader(); loader.Channel = channel; loader.Stop = this.Stop; loader.RecPaths = recpaths; loader.Format = "id,metadata,timestamp"; int i = 0; foreach (DigitalPlatform.LibraryClient.localhost.Record record in loader) { Application.DoEvents(); if (this.Stop != null && this.Stop.State != 0) { strError = "用户中断"; return -1; } Debug.Assert(record.Path == recpaths[i], ""); ListViewItem item = items[i]; if (record.RecordBody.Result != null && record.RecordBody.Result.ErrorCode != ErrorCodeValue.NoError) { strError = record.RecordBody.Result.ErrorString; // 2016/5/27 ListViewUtil.ChangeItemText(item, COLUMN_STATE, strError); item.ImageIndex = 1; // error! i++; continue; } string strMetadataXml = record.RecordBody.Metadata; //Debug.Assert(string.IsNullOrEmpty(strMetadataXml) == false, ""); byte[] baMetadataTimestamp = record.RecordBody.Timestamp; //Debug.Assert(baMetadataTimestamp != null, ""); // 取metadata值 Hashtable values = StringUtil.ParseMetaDataXml(strMetadataXml, out strError); if (values == null) { ListViewUtil.ChangeItemText(item, COLUMN_STATE, strError); item.ImageIndex = 1; // error! continue; } // localpath ListViewUtil.ChangeItemText(item, COLUMN_LOCALPATH, (string)values["localpath"]); // size ListViewUtil.ChangeItemText(item, COLUMN_SIZE, (string)values["size"]); // mime ListViewUtil.ChangeItemText(item, COLUMN_MIME, (string)values["mimetype"]); // tiemstamp string strTimestamp = ByteArray.GetHexTimeStampString(baMetadataTimestamp); ListViewUtil.ChangeItemText(item, COLUMN_TIMESTAMP, strTimestamp); i++; } } catch (Exception ex) { // TODO: 出现异常后,是否改为用原来的方法一个一个对象地获取 metadata? strError = ex.Message; return -1; } finally { #if NO Stop.EndLoop(); Stop.OnStop -= new StopEventHandler(this.DoStop); Stop.Initial(""); #endif Stop.Initial(""); } } else { // *** 以前的方法,速度较慢 // 第二阶段,从 dp2library 服务器获取 metadata 信息,填充其他字段内容 foreach (ListViewItem item in items) { string strID = ListViewUtil.GetItemText(item, COLUMN_ID); string strMetadataXml = ""; byte[] baMetadataTimestamp = null; // 获得一个对象资源的元数据 int nRet = GetOneObjectMetadata( channel, this.BiblioRecPath, strID, out strMetadataXml, out baMetadataTimestamp, out strError); if (nRet == -1) { if (channel.ErrorCode == ErrorCode.AccessDenied) { return -1; } // item.SubItems.Add(strError); ListViewUtil.ChangeItemText(item, COLUMN_STATE, strError); item.ImageIndex = 1; // error! continue; } // 取metadata值 Hashtable values = StringUtil.ParseMetaDataXml(strMetadataXml, out strError); if (values == null) { ListViewUtil.ChangeItemText(item, COLUMN_STATE, strError); item.ImageIndex = 1; // error! continue; } // localpath ListViewUtil.ChangeItemText(item, COLUMN_LOCALPATH, (string)values["localpath"]); // size ListViewUtil.ChangeItemText(item, COLUMN_SIZE, (string)values["size"]); // mime ListViewUtil.ChangeItemText(item, COLUMN_MIME, (string)values["mimetype"]); // tiemstamp string strTimestamp = ByteArray.GetHexTimeStampString(baMetadataTimestamp); ListViewUtil.ChangeItemText(item, COLUMN_TIMESTAMP, strTimestamp); } } this.Changed = false; if (this.ListView.Items.Count > 0) return 1; return 0; } finally { this.Enabled = bOldEnabled; } }
/* * <callNumber> * <group name="中图法" classType="中图法" qufenhaoType="GCAT,Cutter-Sanborn Three-Figure" zhongcihaodb="" callNumberStyle="索取类号+区分号"> * <location name="" /> * <location name="保存本库" /> * <location name="流通库" /> * </group> * <group name="种次号" classType="中图法" qufenhaoType="种次号" zhongcihaodb="" callNumberStyle="索取类号+区分号"> * <location name="阅览室" /> * <location name="测试库" /> * </group> * </callNumber> * */ // 修改排架体系定义。具体来说就是增补一个 group 元素片段 public static int ChangeCallNumberDef( LibraryChannel channel, // Stop stop, string strGroupFragment, out string strOldXml, out string strError) { strError = ""; strOldXml = ""; string strArrangementXml = ""; long lRet = channel.GetSystemParameter( // stop, "circulation", "callNumber", out strArrangementXml, out strError); if (lRet == -1) { return(-1); } XmlDocument dom = new XmlDocument(); dom.LoadXml("<callNumber />"); { XmlDocumentFragment fragment = dom.CreateDocumentFragment(); try { fragment.InnerXml = strArrangementXml; } catch (Exception ex) { strError = "fragment XML装入XmlDocumentFragment时出错: " + ex.Message; return(-1); } dom.DocumentElement.AppendChild(fragment); } strOldXml = dom.DocumentElement.OuterXml; { XmlDocumentFragment fragment = dom.CreateDocumentFragment(); try { fragment.InnerXml = strGroupFragment; } catch (Exception ex) { strError = "fragment XML 装入 XmlDocumentFragment 时出错: " + ex.Message; return(-1); } dom.DocumentElement.AppendChild(fragment); } lRet = channel.SetSystemParameter( // stop, "circulation", "callNumber", dom.DocumentElement.InnerXml, out strError); if (lRet == -1) { return(-1); } return(0); }
/// <summary> /// 关闭当前对象。包括关闭通讯通道 /// </summary> public void Close() { #if USE_THREAD this.StopThread(false); #endif if (this.m_webExternalHost != null) { this.m_webExternalHost.Destroy(); this.m_webExternalHost.Dispose(); this.m_webExternalHost = null; } #if USE_LOCAL_CHANNEL if (this.Channel != null) { this.Channel.Close(); this.Channel = null; } #endif }
// 映射内核脚本配置文件到本地 // parameters: // sessioninfo_param 如果为null,函数内部会自动创建一个SessionInfo对象,是管理员权限 // return: // -1 error // 0 成功,为.cs文件 // 1 成功,为.fltx文件 public int MapKernelScriptFile( string strBiblioDbName, string strScriptFileName, out string strLocalPath, out string strError) { strError = ""; strLocalPath = ""; int nRet = 0; LibraryChannel channel = this.GetChannel(); try { // 将种记录数据从XML格式转换为HTML格式 // 需要从内核映射过来文件 // string strScriptFileName = "./cfgs/loan_biblio.fltx"; // 将脚本文件名正规化 // 因为在定义脚本文件的时候, 有一个当前库名环境, // 如果定义为 ./cfgs/filename 表示在当前库下的cfgs目录下, // 而如果定义为 /cfgs/filename 则表示在同服务器的根下 string strRemotePath = OpacApplication.CanonicalizeScriptFileName( strBiblioDbName, strScriptFileName); // TODO: 还可以考虑支持http://这样的配置文件。 nRet = this.CfgsMap.MapFileToLocal( channel, // sessioninfo.Channel, strRemotePath, out strLocalPath, out strError); if (nRet == -1) { goto ERROR1; } if (nRet == 0) { strError = "内核配置文件 " + strRemotePath + "没有找到,因此无法获得书目html格式数据"; goto ERROR1; } bool bFltx = false; // 如果是一般.cs文件, 还需要获得.cs.ref配置文件 if (OpacApplication.IsCsFileName( strScriptFileName) == true) { string strTempPath = ""; nRet = this.CfgsMap.MapFileToLocal( channel, // sessioninfo_param.Channel, strRemotePath + ".ref", out strTempPath, out strError); if (nRet == -1) { strError = "内核配置文件 " + strRemotePath + ".ref" + "没有找到,因此无法获得书目html格式数据"; goto ERROR1; } bFltx = false; } else { bFltx = true; } if (bFltx == true) { return(1); // 为.fltx文件 } return(0); ERROR1: return(-1); } finally { this.ReturnChannel(channel); } }
public bool TestMode = false; // 是否为评估模式 // 获得编目库属性列表 // 调用前stop需要先OnStop += // parameters: // bUseNewChannel 是否使用新的Channel对象。如果==false,表示尽量使用以前的 public int Build(string strName, string strServerUrl, Stop stop, bool bUseNewChannel, // LibraryChannelCollection Channels, out string strError) { strError = ""; int nRet = 0; this.Url = strServerUrl; this.Name = strName; #if OLD_CHANNEL LibraryChannel Channel = null; if (bUseNewChannel == false) { Channel = Channels.GetChannel(strServerUrl); } else { Channel = Channels.NewChannel(strServerUrl); } #endif LibraryChannel channel = Program.MainForm.GetChannel(strServerUrl); if (stop != null) { stop.SetMessage("正在获得编目库属性 ..."); /* * stop.Initial("正在获得编目库属性 ..."); * stop.BeginLoop(); * */ } try { string version = "0.0"; // return: // -1 error // 0 dp2Library的版本号过低。警告信息在strError中 // 1 dp2Library版本号符合要求 nRet = LibraryChannel.GetServerVersion( channel, stop, out version, out strError); if (nRet != 1) { return(-1); } this.Version = version; if (this.TestMode == true && StringUtil.CompareVersion(this.Version, "2.34") < 0) { strError = "dp2 前端的评估模式只能在所连接的 dp2library 版本为 2.34 以上时才能使用 (当前 dp2library 版本为 " + this.Version.ToString() + ")"; return(-1); } this.BiblioDbProperties = new List <BiblioDbProperty>(); string strValue = ""; long lRet = channel.GetSystemParameter(stop, "biblio", "dbnames", out strValue, out strError); if (lRet == -1) { strError = "针对服务器 " + channel.Url + " 获得编目库名列表过程发生错误:" + strError; goto ERROR1; } string[] biblioDbNames = strValue.Split(new char[] { ',' }); for (int i = 0; i < biblioDbNames.Length; i++) { BiblioDbProperty property = new BiblioDbProperty(); property.DbName = biblioDbNames[i]; this.BiblioDbProperties.Add(property); } // 获得语法格式 lRet = channel.GetSystemParameter(stop, "biblio", "syntaxs", out strValue, out strError); if (lRet == -1) { strError = "针对服务器 " + channel.Url + " 获得编目库数据格式列表过程发生错误:" + strError; goto ERROR1; } string[] syntaxs = strValue.Split(new char[] { ',' }); if (syntaxs.Length != this.BiblioDbProperties.Count) { strError = "针对服务器 " + channel.Url + " 获得编目库名为 " + this.BiblioDbProperties.Count.ToString() + " 个,而数据格式为 " + syntaxs.Length.ToString() + " 个,数量不一致"; goto ERROR1; } // 增补数据格式 for (int i = 0; i < this.BiblioDbProperties.Count; i++) { this.BiblioDbProperties[i].Syntax = syntaxs[i]; } /// // 获得对应的实体库名 lRet = channel.GetSystemParameter(stop, "item", "dbnames", out strValue, out strError); if (lRet == -1) { strError = "针对服务器 " + channel.Url + " 获得实体库名列表过程发生错误:" + strError; goto ERROR1; } string[] itemdbnames = strValue.Split(new char[] { ',' }); if (itemdbnames.Length != this.BiblioDbProperties.Count) { strError = "针对服务器 " + channel.Url + " 获得编目库名为 " + this.BiblioDbProperties.Count.ToString() + " 个,而实体库名为 " + itemdbnames.Length.ToString() + " 个,数量不一致"; goto ERROR1; } // 增补数据格式 for (int i = 0; i < this.BiblioDbProperties.Count; i++) { this.BiblioDbProperties[i].ItemDbName = itemdbnames[i]; } // 获得对应的期库名 lRet = channel.GetSystemParameter(stop, "issue", "dbnames", out strValue, out strError); if (lRet == -1) { strError = "针对服务器 " + channel.Url + " 获得实体库名列表过程发生错误:" + strError; goto ERROR1; } string[] issuedbnames = strValue.Split(new char[] { ',' }); if (issuedbnames.Length != this.BiblioDbProperties.Count) { return(0); // TODO: 暂时不警告。等将来所有用户都更换了dp2libraryws 2007/10/19以后的版本后,这里再警告 /* * strError = "针对服务器 " + Channel.Url + " 获得编目库名为 " + this.BiblioDbProperties.Count.ToString() + " 个,而期库名为 " + issuedbnames.Length.ToString() + " 个,数量不一致"; * goto ERROR1; * */ } // 增补数据格式 for (int i = 0; i < this.BiblioDbProperties.Count; i++) { this.BiblioDbProperties[i].IssueDbName = issuedbnames[i]; } // 获得实用库信息 { this.UtilDbProperties = new List <UtilDbProperty>(); lRet = channel.GetSystemParameter(stop, "utilDb", "dbnames", out strValue, out strError); if (lRet == -1) { strError = "针对服务器 " + channel.Url + " 获得实用库名列表过程发生错误:" + strError; goto ERROR1; } string[] utilDbNames = strValue.Split(new char[] { ',' }); for (int i = 0; i < utilDbNames.Length; i++) { UtilDbProperty property = new UtilDbProperty(); property.DbName = utilDbNames[i]; this.UtilDbProperties.Add(property); } // 获得类型 lRet = channel.GetSystemParameter(stop, "utilDb", "types", out strValue, out strError); if (lRet == -1) { strError = "针对服务器 " + channel.Url + " 获得实用库数据格式列表过程发生错误:" + strError; goto ERROR1; } string[] types = strValue.Split(new char[] { ',' }); if (types.Length != this.UtilDbProperties.Count) { strError = "针对服务器 " + channel.Url + " 获得实用库名为 " + this.UtilDbProperties.Count.ToString() + " 个,而类型为 " + types.Length.ToString() + " 个,数量不一致"; goto ERROR1; } // 增补数据格式 for (int i = 0; i < this.UtilDbProperties.Count; i++) { this.UtilDbProperties[i].Type = types[i]; } } // MessageBox.Show(this, Convert.ToString(lRet) + " : " + strError); } finally { if (stop != null) { /* * stop.EndLoop(); * stop.Initial(""); * */ } Program.MainForm.ReturnChannel(channel); #if OLD_CHANNEL if (bUseNewChannel == true) { Channels.RemoveChannel(Channel); Channel = null; } #endif } return(0); ERROR1: return(-1); }
// 映射内核脚本配置文件到本地 // parameters: // sessioninfo_param 如果为null,函数内部会自动创建一个SessionInfo对象,是管理员权限 // return: // -1 error // 0 成功,为.cs文件 // 1 成功,为.fltx文件 public int MapKernelScriptFile( SessionInfo sessioninfo_param, string strBiblioDbName, string strScriptFileName, out string strLocalPath, out string strError) { strError = ""; strLocalPath = ""; int nRet = 0; LibraryChannel channel = null; #if NO SessionInfo sessioninfo = null; #endif // 应该用管理员的权限来做这个事情 // 临时的SessionInfo对象 if (sessioninfo_param == null) { #if NO sessioninfo = new SessionInfo(this); sessioninfo.UserID = this.ManagerUserName; sessioninfo.Password = this.ManagerPassword; sessioninfo.IsReader = false; #endif channel = this.GetChannel(); } else { #if NO sessioninfo = sessioninfo_param; #endif channel = sessioninfo_param.Channel; } try { // 将种记录数据从XML格式转换为HTML格式 // 需要从内核映射过来文件 // string strScriptFileName = "./cfgs/loan_biblio.fltx"; // 将脚本文件名正规化 // 因为在定义脚本文件的时候, 有一个当前库名环境, // 如果定义为 ./cfgs/filename 表示在当前库下的cfgs目录下, // 而如果定义为 /cfgs/filename 则表示在同服务器的根下 string strRemotePath = OpacApplication.CanonicalizeScriptFileName( strBiblioDbName, strScriptFileName); // TODO: 还可以考虑支持http://这样的配置文件。 nRet = this.CfgsMap.MapFileToLocal( channel, // sessioninfo.Channel, strRemotePath, out strLocalPath, out strError); if (nRet == -1) { goto ERROR1; } if (nRet == 0) { strError = "内核配置文件 " + strRemotePath + "没有找到,因此无法获得书目html格式数据"; goto ERROR1; } bool bFltx = false; // 如果是一般.cs文件, 还需要获得.cs.ref配置文件 if (OpacApplication.IsCsFileName( strScriptFileName) == true) { string strTempPath = ""; nRet = this.CfgsMap.MapFileToLocal( channel, // sessioninfo_param.Channel, strRemotePath + ".ref", out strTempPath, out strError); if (nRet == -1) { strError = "内核配置文件 " + strRemotePath + ".ref" + "没有找到,因此无法获得书目html格式数据"; goto ERROR1; } bFltx = false; } else { bFltx = true; } if (bFltx == true) { return(1); // 为.fltx文件 } return(0); ERROR1: return(-1); } finally { if (sessioninfo_param == null) { #if NO sessioninfo.CloseSession(); #endif this.ReturnChannel(channel); } } }
// 装载数据 public override bool LoadData() { string strError = ""; int nRet = 0; BiblioInfo info = this.BiblioInfo; string strRecPath = this.BiblioInfo.RecPath; if (string.IsNullOrEmpty(info.OldXml) == true) { lock (syncRoot) { channel = this.Container.MainForm.GetChannel(); } try { // 显示 正在处理 this.HTML = GetWaitingHtml("正在获取 "+this.DbType+" 记录 " + strRecPath); ShowData(); byte [] baTimestamp = null; string strOutputRecPath = ""; string strBiblio = ""; string strBiblioRecPath = ""; string strXml = ""; // 获得记录 channel.Timeout = new TimeSpan(0, 0, 5); long lRet = 0; if (this.DbType == "item") { lRet = channel.GetItemInfo( this.Stop, "@path:" + strRecPath, "xml", out strXml, out strOutputRecPath, out baTimestamp, "", out strBiblio, out strBiblioRecPath, out strError); } else if (this.DbType == "order") { lRet = channel.GetOrderInfo( this.Stop, "@path:" + strRecPath, "xml", out strXml, out strOutputRecPath, out baTimestamp, "", out strBiblio, out strBiblioRecPath, out strError); } else if (this.DbType == "issue") { lRet = channel.GetIssueInfo( this.Stop, "@path:" + strRecPath, "xml", out strXml, out strOutputRecPath, out baTimestamp, "", out strBiblio, out strBiblioRecPath, out strError); } else if (this.DbType == "comment") { lRet = channel.GetCommentInfo( this.Stop, "@path:" + strRecPath, "xml", out strXml, out strOutputRecPath, out baTimestamp, "", out strBiblio, out strBiblioRecPath, out strError); } else if (this.DbType == "patron") { string[] results = null; // 获得读者记录 lRet = channel.GetReaderInfo( this.Stop, "@path:" + strRecPath, "xml", out results, out strOutputRecPath, out baTimestamp, out strError); if (lRet == 1) { if (results == null || results.Length == 0) { strError = "results error"; nRet = -1; } else strXml = results[0]; } } else { lRet = -1; strError = "无法识别的 DbType '"+this.DbType+"'"; } if (lRet == 0) { nRet = -1; strError = "获取记录 " + strRecPath + " 时出错: " + strError; } else if (lRet == -1) { nRet = -1; strError = "获取记录 " + strRecPath + " 时出错: " + strError; } else { info.OldXml = strXml; info.Timestamp = baTimestamp; info.RecPath = strRecPath; } } finally { LibraryChannel temp_channel = channel; lock (syncRoot) { channel = null; } this.Container.MainForm.ReturnChannel(temp_channel); } } string strXml1 = ""; string strHtml2 = ""; if (nRet == -1) { strHtml2 = HttpUtility.HtmlEncode(strError); } else { nRet = ItemSearchForm.GetXmlHtml(info, out strXml1, out strHtml2, out strError); if (nRet == -1) throw new Exception(strError); } this.HTML = "<html>" + this.Container.MainForm.GetMarcHtmlHeadString(true) + "<body>" + strHtml2 + EntityForm.GetTimestampHtml(info.Timestamp) + "</body></html>"; this.XML = strXml1; return true; }
// 强制关闭服务器通道 // parameters: // strIdType 为 ip/sessionid 之一 // return: // -1 出错 // >=0 实际关闭的通道数 int CloseChannels( string strIdType, List <string> sessionids, out string strError) { strError = ""; int nCount = 0; EnableControls(false); LibraryChannel channel = this.GetChannel(); stop.OnStop += new StopEventHandler(this.DoStop); stop.Initial("正在关闭指定的通道 ..."); stop.BeginLoop(); this.Update(); this.MainForm.Update(); try { List <List <string> > batchs = new List <List <string> >(); List <string> batch = new List <string>(); foreach (string id in sessionids) { batch.Add(id); if (batch.Count >= 100) { batchs.Add(batch); batch = new List <string>(); } } if (batch.Count > 0) { batchs.Add(batch); } foreach (List <string> one in batchs) { ChannelInfo[] requests = new ChannelInfo[one.Count]; for (int i = 0; i < requests.Length; i++) { ChannelInfo info = new ChannelInfo(); if (strIdType == "sessionid") { info.SessionID = one[i]; } else if (strIdType == "ip") { info.ClientIP = one[i]; } else { strError = "未知的 strIdType 类型 '" + strIdType + "'"; return(-1); } requests[i] = info; } ChannelInfo[] results = null; long lRet = channel.ManageChannel( this.stop, "close", "", requests, out results, out strError); if (lRet == -1) { return(-1); } nCount += (int)lRet; } } finally { stop.EndLoop(); stop.OnStop -= new StopEventHandler(this.DoStop); stop.Initial(""); this.ReturnChannel(channel); EnableControls(true); } return(nCount); }
/// <summary> /// 结束检索 /// </summary> /// <returns>返回 0</returns> public int EndSearch() { if (Stop != null) // 脱离关联 { Stop.Unregister(); // 和容器关联 Stop = null; } this.Channel.BeforeLogin -= new DigitalPlatform.LibraryClient.BeforeLoginEventHandle(Channel_BeforeLogin); this.Channel.Close(); this.Channel = null; return 0; }
int DoSearch( string strUserName, string strIP, string strStyle, bool bRefresh, out string strError) { strError = ""; //int nRet = 0; bool bIpCount = (strStyle == "ip-count"); string strQuery = ""; Hashtable table = new Hashtable(); table["ip"] = strIP; table["username"] = strUserName; strQuery = StringUtil.BuildParameterString(table); // 确保延迟刷新被兑现 this._history.EnsureAdd(this.listView_channel, this._queryState.Clone()); // 如果有必要则加入 this.listView_channel.Items.Clear(); EnableControls(false); LibraryChannel channel = this.GetChannel(); stop.OnStop += new StopEventHandler(this.DoStop); stop.Initial("正在获得服务器通道信息 ..."); stop.BeginLoop(); this.Update(); this.MainForm.Update(); this.listView_channel.BeginUpdate(); try { int nStart = 0; for (; ;) { ChannelInfo[] contents = null; long lRet = channel.GetChannelInfo( this.stop, strQuery, strStyle, nStart, -1, out contents, out strError); if (lRet == -1) { goto ERROR1; } if (lRet == 0) { strError = "不存在用户信息。"; goto ERROR1; // not found } Debug.Assert(contents != null, ""); foreach (ChannelInfo info in contents) { ListViewItem item = new ListViewItem(); ListViewUtil.ChangeItemText(item, COLUMN_IP, AlignIpString(info.ClientIP)); ListViewUtil.ChangeItemText(item, COLUMN_VIA, info.Via); ListViewUtil.ChangeItemText(item, COLUMN_USERNAME, info.UserName); ListViewUtil.ChangeItemText(item, COLUMN_LIBRARYCODE, info.LibraryCode); if (bIpCount == true) { ListViewUtil.ChangeItemText(item, COLUMN_COUNT, info.Count.ToString()); } if (bIpCount == false) { ListViewUtil.ChangeItemText(item, COLUMN_CALLCOUNT, info.CallCount.ToString()); } ListViewUtil.ChangeItemText(item, COLUMN_SESSIONID, info.SessionID); ListViewUtil.ChangeItemText(item, COLUMN_LOCATION, info.Location); ListViewUtil.ChangeItemText(item, COLUMN_LANG, info.Lang); item.SubItems[0].Font = new Font("Courier New", this.Font.Size); this.listView_channel.Items.Add(item); } nStart += contents.Length; if (nStart >= lRet) { break; } } this.label_channel_message.Text = this.listView_channel.Items.Count.ToString(); this._queryState.Query = strQuery; this._queryState.Style = strStyle; this._queryState.Message = this.label_channel_message.Text; // 保存当前状态 if (bRefresh == true) { this._history.Refresh(this.listView_channel, this._queryState.Clone(), true); // 滞后刷新 } else { this._history.Add(this.listView_channel, this._queryState.Clone(), true); // 滞后加入 } #if NO if (bIpCount == true) { this._bCountMode = true; } else { this._bCountMode = false; } #endif } finally { this.listView_channel.EndUpdate(); stop.EndLoop(); stop.OnStop -= new StopEventHandler(this.DoStop); stop.Initial(""); this.ReturnChannel(channel); EnableControls(true); } RefreshBackForwardButtons(); return(0); ERROR1: return(-1); }
// 保存书目记录到数据库 // parameters: // bIncludeFileID (书目记录XML)是否要根据当前rescontrol内容合成<dprms:file>元素? // return: // -1 出错 // 0 没有保存 // 1 已经保存 /// <summary> /// 保存书目记录到数据库 /// </summary> /// <param name="channel_param">通讯通道。如果为 null,表示函数内使用自动获得的通道</param> /// <param name="bIncludeFileID">(书目记录XML)是否要根据当前对象控件内容合成<dprms:file>元素?</param> /// <param name="strHtml">返回新记录的 OPAC 格式内容</param> /// <param name="strStyle">风格。由 displaysuccess / searchdup 之一或者逗号间隔组合而成。displaysuccess 显示最后的成功消息在框架窗口的状态条; searchdup 保存成功后发送查重消息</param> /// <returns> /// <para>-1 出错</para> /// <para>0 没有保存</para> /// <para>1 已经保存</para> /// </returns> public int SaveBiblioToDatabase( LibraryChannel channel_param, bool bIncludeFileID, out string strHtml, string strStyle = "displaysuccess,searchdup") { string strError = ""; strHtml = ""; int nRet = 0; bool bDisplaySuccess = StringUtil.IsInList("displaysuccess", strStyle); bool bSearchDup = StringUtil.IsInList("searchdup", strStyle); if (this.Cataloging == false) { strError = "当前不允许编目功能,因此也不允许保存书目信息的功能"; return -1; } // 如果刚才在删除后模式,现在取消这个模式 2007/10/15 if (this.DeletedMode == true) { // TODO: 除了册信息,也要考虑期、采购信息 int nEntityCount = this.entityControl1.ItemCount; if (nEntityCount > 0) { DialogResult result = MessageBox.Show(this, "如果您用本功能将刚删除的书目记录保存回数据库,那么书目记录下属的 " + nEntityCount.ToString() + " 条实体记录将不会被保存回实体库。\r\n\r\n如果要在保存书目数据的同时也完整保存这些被删除的实体记录,请先在种册窗工具条上选择“.../使能编辑保存”功能,然后再使用“全部保存”按钮" + "\r\n\r\n是否要在不保存实体记录的情况下单独保存书目记录? (Yes 是 / No 放弃单独保存书目记录的操作)", "EntityForm", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (result == DialogResult.No) { strError = "放弃保存书目记录"; goto ERROR1; } } } string strTargetPath = this.BiblioRecPath; if (string.IsNullOrEmpty(strTargetPath) == true) { // 需要询问保存的路径 BiblioSaveToDlg dlg = new BiblioSaveToDlg(); MainForm.SetControlFont(dlg, this.Font, false); dlg.MainForm = this.MainForm; dlg.Text = "仅保存书目记录"; dlg.MessageText = "请指定新书目记录要保存到的位置"; dlg.EnableCopyChildRecords = false; dlg.BuildLink = false; dlg.CopyChildRecords = false; { string strMarcSyntax = this.GetCurrentMarcSyntax(); if (string.IsNullOrEmpty(strMarcSyntax) == true) strMarcSyntax = this.MarcSyntax; // 外来数据的 MARC 格式 dlg.MarcSyntax = strMarcSyntax; } dlg.CurrentBiblioRecPath = this.BiblioRecPath; this.MainForm.AppInfo.LinkFormState(dlg, "entityform_BiblioSaveToDlg_state"); dlg.ShowDialog(this); // this.MainForm.AppInfo.UnlinkFormState(dlg); if (dlg.DialogResult != DialogResult.OK) return 0; strTargetPath = dlg.RecPath; } // 保存前的准备工作 { // 初始化 dp2circulation_marc_autogen.cs 的 Assembly,并new DetailHost对象 // return: // -1 error // 0 没有重新初始化Assembly,而是直接用以前Cache的Assembly // 1 重新(或者首次)初始化了Assembly nRet = this._genData.InitialAutogenAssembly(strTargetPath, out strError); if (nRet == -1) goto ERROR1; if (this._genData.DetailHostObj != null) { BeforeSaveRecordEventArgs e = new BeforeSaveRecordEventArgs(); // this._genData.DetailHostObj.BeforeSaveRecord(this.m_marcEditor, e); this._genData.DetailHostObj.Invoke("BeforeSaveRecord", this.m_marcEditor, e); if (string.IsNullOrEmpty(e.ErrorInfo) == false) { MessageBox.Show(this, "保存前的准备工作失败: " + e.ErrorInfo + "\r\n\r\n但保存操作仍将继续"); } } } // 获得书目记录XML格式 string strXmlBody = ""; nRet = this.GetBiblioXml( "", // 迫使从记录路径中看marc格式 bIncludeFileID, out strXmlBody, out strError); if (nRet == -1) goto ERROR1; LibraryChannel channel = channel_param; if (channel == null) channel = this.MainForm.GetChannel(); try { bool bPartialDenied = false; string strOutputPath = ""; byte[] baNewTimestamp = null; string strWarning = ""; nRet = SaveXmlBiblioRecordToDatabase( channel, strTargetPath, this.DeletedMode == true, strXmlBody, this.BiblioTimestamp, out strOutputPath, out baNewTimestamp, out strWarning, out strError); if (nRet == -1) goto ERROR1; if (string.IsNullOrEmpty(strWarning) == false) MessageBox.Show(this, strWarning); if (channel.ErrorCode == ErrorCode.PartialDenied) bPartialDenied = true; this.BiblioTimestamp = baNewTimestamp; this.BiblioRecPath = strOutputPath; this.BiblioOriginPath = strOutputPath; this.BiblioChanged = false; // 如果刚才在删除后模式,现在取消这个模式 2007/10/15 if (this.DeletedMode == true) { this.DeletedMode = false; // 重新装载实体记录,以便反映其listview变空的事实 // 接着装入相关的所有册 nRet = this.entityControl1.LoadItemRecords( channel, this.BiblioRecPath, null, // this.DisplayOtherLibraryItem, this.DisplayOtherLibraryItem == true ? "getotherlibraryitem" : "", out strError); if (nRet == -1) goto ERROR1; } // 清除ReadOnly状态,如果998$t已经消失 if (this.m_marcEditor.ReadOnly == true) { string strTargetBiblioRecPath = this.m_marcEditor.Record.Fields.GetFirstSubfield("998", "t"); if (String.IsNullOrEmpty(strTargetBiblioRecPath) == true) this.m_marcEditor.ReadOnly = false; } if (bDisplaySuccess == true) { this.MainForm.StatusBarMessage = "书目记录 '" + this.BiblioRecPath + "' 保存成功"; // MessageBox.Show(this, "书目记录保存成功。"); } if (bSearchDup == true) { if (this.AutoSearchDup == true) API.PostMessage(this.Handle, WM_SEARCH_DUP, 0, 0); } // if (bPartialDenied == true) { // 获得实际保存的书目记录 string[] results = null; string[] formats = null; if (bPartialDenied == true) { formats = new string[2]; formats[0] = "html"; formats[1] = "xml"; } else { formats = new string[1]; formats[0] = "html"; } long lRet = channel.GetBiblioInfos( Progress, strOutputPath, "", formats, out results, out baNewTimestamp, out strError); if (lRet == 0) { strError = "重新装载时,路径为 '" + strOutputPath + "' 的书目记录没有找到 ..."; goto ERROR1; } if (results == null) { strError = "重新装载书目记录时出错: result == null {6C619D72-73B0-48E0-8248-AB9348297D4F}"; goto ERROR1; } { // 重新显示 OPAC 书目信息 // TODO: 需要在对象保存完以后发出这个指令 Debug.Assert(results.Length >= 1, ""); if (results.Length > 0) { strHtml = results[0]; #if NO this.m_webExternalHost_biblio.SetHtmlString(strHtml, "entityform_biblio"); #endif } } DoViewComment(false); // 重新显示固定面板区的属性 XML 2015/7/11 if (bPartialDenied == true) { if (results.Length < 2) { strError = "重新装载书目记录时出错: result.Length[" + results.Length.ToString() + "] 小于 2"; goto ERROR1; } PartialDeniedDialog dlg = new PartialDeniedDialog(); MainForm.SetControlFont(dlg, this.Font, false); dlg.SavingXml = strXmlBody; Debug.Assert(results.Length >= 2, ""); dlg.SavedXml = results[1]; dlg.MainForm = this.MainForm; this.MainForm.AppInfo.LinkFormState(dlg, "PartialDeniedDialog_state"); dlg.ShowDialog(this); this.MainForm.AppInfo.UnlinkFormState(dlg); if (dlg.DialogResult == System.Windows.Forms.DialogResult.OK) { string strOutputBiblioRecPath = ""; string strXml = ""; string strSubRecords = ""; // 将实际保存的记录装入 MARC 编辑器 // return: // -1 error // 0 not found // 1 found nRet = LoadBiblioRecord( channel, strOutputPath, "", false, false, out strOutputBiblioRecPath, out strXml, out strSubRecords, out strError); if (nRet == -1) { strError = "重新装载书目记录时出错: " + strError; goto ERROR1; } } } } return 1; } finally { if (channel_param == null) this.MainForm.ReturnChannel(channel); } ERROR1: MessageBox.Show(this, strError); return -1; }
// 下载图像文件 void DownloadImages() { string strError = ""; TraceObject info = null; lock (_trace_images) { if (_trace_images.Count == 0) { return; } info = _trace_images[0]; _trace_images.RemoveAt(0); } if (string.IsNullOrEmpty(info.FileName) == true) { info.FileName = GetTempFileName(); } // http 协议的图像文件 if (StringUtil.IsHttpUrl(info.ObjectPath) == true) { // 先从 cache 中找 if (_localFileCache != null) { string strLocalFile = (string)_localFileCache[info.ObjectPath]; if (string.IsNullOrEmpty(strLocalFile) == false) { if (string.IsNullOrEmpty(info.FileName) == false) { DeleteTempFile(info.FileName); info.FileName = ""; } info.FileName = strLocalFile; goto END1; } } if (_webClient == null) { _webClient = new MyWebClient(); _webClient.Timeout = 5000; _webClient.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.CacheIfAvailable); } try { _webClient.DownloadFile(new Uri(info.ObjectPath, UriKind.Absolute), info.FileName); } catch (WebException ex) { if (ex.Status == WebExceptionStatus.ProtocolError) { var response = ex.Response as HttpWebResponse; if (response != null) { if (response.StatusCode == HttpStatusCode.NotFound) { strError = ex.Message; goto ERROR1; } } } strError = ex.Message; goto ERROR1; } catch (Exception ex) { strError = ExceptionUtil.GetAutoText(ex); goto ERROR1; } _localFileCache[info.ObjectPath] = info.FileName; } else { // dp2library 协议的对象资源 LibraryChannel channel = this.ChannelPool.GetChannel(info.ServerUrl, info.UserName); try { byte[] baOutputTimeStamp = null; string strMetaData = ""; string strTempOutputPath = ""; long lRet = channel.GetRes( null, info.ObjectPath, info.FileName, "content,data,metadata,timestamp,outputpath,gzip", // 2017/10/7 增加 gzip out strMetaData, out baOutputTimeStamp, out strTempOutputPath, out strError); if (lRet == -1) { strError = "下载资源文件失败,原因: " + strError; goto ERROR1; } _localFileCache[info.ObjectPath] = info.FileName; } finally { this.ChannelPool.ReturnChannel(channel); // 2016/6/6 } } END1: // 通知 if (this.GetObjectComplete != null) { GetObjectCompleteEventArgs e = new GetObjectCompleteEventArgs(); e.TraceObject = info; this.GetObjectComplete(this, e); } this.Activate(); return; ERROR1: // 通知 if (this.GetObjectComplete != null) { GetObjectCompleteEventArgs e = new GetObjectCompleteEventArgs(); e.TraceObject = info; e.ErrorInfo = strError; this.GetObjectComplete(this, e); } }
// 获得资源。包装版本 -- 返回字符串版本、Cache版本。 // parameters: // remote_timestamp 远端时间戳。如果为 null,表示要从服务器实际获取时间戳 // return: // -1 出错。具体出错原因在this.ErrorCode中。this.ErrorInfo中有出错信息。 // 0 成功 public static long GetRes(this LibraryChannel channel, DigitalPlatform.Stop stop, CfgCache cache, string strPath, string strStyle, byte[] remote_timestamp, out string strResult, out string strMetaData, out byte[] baOutputTimeStamp, out string strOutputResPath, out string strError) { strError = ""; strResult = ""; strMetaData = ""; baOutputTimeStamp = null; strOutputResPath = ""; byte[] cached_timestamp = null; string strTimeStamp; string strLocalName; long lRet = 0; string strFullPath = channel.Url + "?" + strPath; if (StringUtil.IsInList("forceget", strStyle) == true) { // 强制获取 StringUtil.RemoveFromInList("forceget", true, ref strStyle); goto GETDATA; } // 从cache中得到timestamp // return: // -1 error // 0 not found // 1 found int nRet = cache.FindLocalFile(strFullPath, out strLocalName, out strTimeStamp); if (nRet == -1) { strError = "CfgCache 尚未初始化"; return(-1); } if (nRet == 1) { Debug.Assert(strLocalName != "", "FindLocalFile()返回的strLocalName为空"); if (strTimeStamp == "") { goto GETDATA; // 时间戳不对, 那就只好重新获取服务器端内容 } Debug.Assert(strTimeStamp != "", "FindLocalFile()获得的strTimeStamp为空"); cached_timestamp = ByteArray.GetTimeStampByteArray(strTimeStamp); // bExistInCache = true; } else { goto GETDATA; } if (remote_timestamp == null) { // 探测时间戳关系 string strNewStyle = strStyle; StringUtil.RemoveFromInList("content,data,metadata", // 2012/12/31 BUG 以前忘记了加入content true, ref strNewStyle); // 不要数据体和metadata lRet = channel.GetRes(stop, strPath, strNewStyle, out strResult, out strMetaData, out baOutputTimeStamp, out strOutputResPath, out strError); if (lRet == -1) { return(-1); } } else { baOutputTimeStamp = remote_timestamp; } // 如果证明timestamp没有变化, 但是本次并未返回内容,则从cache中取原来的内容 if (ByteArray.Compare(baOutputTimeStamp, cached_timestamp) == 0) // 时间戳相等 { Debug.Assert(strLocalName != "", "strLocalName不应为空"); try { using (StreamReader sr = new StreamReader(strLocalName, Encoding.UTF8)) { strResult = sr.ReadToEnd(); return(0); // 以无错误姿态返回 } } catch (Exception ex) { strError = ExceptionUtil.GetAutoText(ex); return(-1); } } GETDATA: // 重新正式获取内容 lRet = channel.GetRes( stop, strPath, strStyle, out strResult, out strMetaData, out baOutputTimeStamp, out strOutputResPath, out strError); if (lRet == -1) { return(-1); } // 因为时间戳不匹配而新获得了内容 // 保存到cache cache.PrepareLocalFile(strFullPath, out strLocalName); Debug.Assert(strLocalName != "", "PrepareLocalFile()返回的strLocalName为空"); // 写入文件,以便以后从cache获取 using (StreamWriter sw = new StreamWriter(strLocalName, false, // append System.Text.Encoding.UTF8)) { sw.Write(strResult); } Debug.Assert(baOutputTimeStamp != null, "下层GetRes()返回的baOutputTimeStamp为空"); nRet = cache.SetTimeStamp(strFullPath, ByteArray.GetHexTimeStampString(baOutputTimeStamp), out strError); if (nRet == -1) { return(-1); } return(lRet); }
// 获得一系列册的摘要字符串 // // paramters: // strStyle 风格。逗号间隔的列表。如果包含html text表示格式。forcelogin // strOtherParams <a>命令中其余的参数。例如" target='_blank' "可以用来打开新窗口 public static string GetBarcodesSummary( OpacApplication app, // SessionInfo sessioninfo, LibraryChannel channel, string strBarcodes, string strArrivedItemBarcode, string strStyle, string strOtherParams) { string strSummary = ""; if (strOtherParams == null) { strOtherParams = ""; } string strDisableClass = ""; if (string.IsNullOrEmpty(strArrivedItemBarcode) == false) { strDisableClass = "deleted"; } bool bForceLogin = false; if (StringUtil.IsInList("forcelogin", strStyle) == true) { bForceLogin = true; } string strPrevBiblioRecPath = ""; string[] barcodes = strBarcodes.Split(new char[] { ',' }); for (int j = 0; j < barcodes.Length; j++) { string strBarcode = barcodes[j]; if (String.IsNullOrEmpty(strBarcode) == true) { continue; } // 获得摘要 string strOneSummary = ""; string strBiblioRecPath = ""; string strError = ""; long lRet = channel.GetBiblioSummary( null, strBarcode, null, strPrevBiblioRecPath, // 前一个path out strBiblioRecPath, out strOneSummary, out strError); if (lRet == -1 || lRet == 0) { strOneSummary = strError; } /* * LibraryServerResult result = this.GetBiblioSummary(sessioninfo, * strBarcode, * null, * strPrevBiblioRecPath, // 前一个path * out strBiblioRecPath, * out strOneSummary); * if (result.Value == -1 || result.Value == 0) * strOneSummary = result.ErrorInfo; * */ if (strOneSummary == "" && strPrevBiblioRecPath == strBiblioRecPath) { strOneSummary = "(同上)"; } if (StringUtil.IsInList("html", strStyle) == true) { string strBarcodeLink = "<a " + (string.IsNullOrEmpty(strDisableClass) == false && strBarcode != strArrivedItemBarcode ? "class='" + strDisableClass + "'" : "") + " href='book.aspx?barcode=" + strBarcode + (bForceLogin == true ? "&forcelogin=userid" : "") + "' " + strOtherParams + " >" + strBarcode + "</a>"; strSummary += strBarcodeLink + " : " + strOneSummary + "<br/>"; } else { strSummary += strBarcode + " : " + strOneSummary + "<br/>"; } strPrevBiblioRecPath = strBiblioRecPath; } return(strSummary); }
protected void Page_Load(object sender, EventArgs e) { if (WebUtil.PrepareEnvironment(this, ref app, ref sessioninfo) == false) { return; } string strType = this.Request["type"]; if (String.IsNullOrEmpty(strType) == true) { strType = "item"; } if (GetVisible(strType) == false) { this.Response.Redirect("./searchbiblio.aspx", true); this.Response.End(); return; } string strSideBarFile = Server.MapPath("./search_sidebar.xml"); if (File.Exists(strSideBarFile) == true) { this.SideBarControl1.CfgFile = strSideBarFile; } else { this.SideBarControl1.Visible = false; } this.ItemSearchControl1.DbType = strType; this.ItemSearchControl1.FillList(); /* * // 是否登录? * if (sessioninfo.UserID == "") * { * sessioninfo.LoginCallStack.Push(Request.RawUrl); * Response.Redirect("login.aspx", true); * return; * } * */ if (this.BrowseSearchResultControl1.ResultCount > 0) { this.BrowseSearchResultControl1.Visible = true; } // 是否登录? if (sessioninfo.UserID == "") { if (this.Page.Request["forcelogin"] == "on") { sessioninfo.LoginCallStack.Push(Request.RawUrl); Response.Redirect("login.aspx", true); return; } if (this.Page.Request["forcelogin"] == "userid") { sessioninfo.LoginCallStack.Push(Request.RawUrl); Response.Redirect("login.aspx?loginstyle=librarian", true); return; } sessioninfo.UserID = "public"; sessioninfo.IsReader = false; /* * sessioninfo.LoginCallStack.Push(Request.RawUrl); * Response.Redirect("login.aspx", true); * return; */ } string strError = ""; // 如果有参数 string strWord = this.Request["word"]; if (String.IsNullOrEmpty(strWord) == false) { string strXml = ""; // 根据检索参数创建XML检索式 int nRet = OpacApplication.BuildQueryXml( this.app, this.Request["dbname"], strWord, this.Request["from"], this.Request["matchstyle"], null, null, app.SearchMaxResultCount, "", // strSearchStyle out strXml, out strError); if (nRet == -1) { goto ERROR1; } string strResultSetNamePrefix = ""; strResultSetNamePrefix = this.Request["resultsetname"]; if (String.IsNullOrEmpty(strResultSetNamePrefix) == true) { // strResultSetNamePrefix = "opac_item_1"; strResultSetNamePrefix = Session.SessionID + "opac_item_1"; } else { strResultSetNamePrefix = Session.SessionID + "_" + strResultSetNamePrefix; } string strResultSetName = GetResultSetName(strResultSetNamePrefix); LibraryChannel channel = sessioninfo.GetChannel(true); //sessioninfo.Channel. channel.Idle += new IdleEventHandler(channel_Idle); try { long lRet = //sessioninfo.Channel. channel.Search( null, strXml, strResultSetName, "", // strOutputStyle out strError); if (lRet == -1) { goto ERROR1; } // not found if (lRet == 0) { this.BrowseSearchResultControl1.Visible = false; strError = "没有找到"; goto ERROR1; } this.BrowseSearchResultControl1.Clear(); this.BrowseSearchResultControl1.Visible = true; this.BrowseSearchResultControl1.ResultSetName = strResultSetName; this.BrowseSearchResultControl1.ResultCount = (int)lRet; this.BrowseSearchResultControl1.StartIndex = 0; // 2008/12/15 string strFormat = this.Request["format"]; if (String.IsNullOrEmpty(strFormat) == false) { this.BrowseSearchResultControl1.FormatName = strFormat; } return; } finally { //sessioninfo.Channel. channel.Idle -= new IdleEventHandler(channel_Idle); sessioninfo.ReturnChannel(channel); } } return; ERROR1: Response.Write(HttpUtility.HtmlEncode(strError)); Response.End(); }
// 预约:删除请求 void reservationDeleteButton_Click(object sender, EventArgs e) { string strBarcodeList = GetChekcedReservationBarcodes(); if (String.IsNullOrEmpty(strBarcodeList) == true) { // text-level: 用户提示 this.SetDebugInfo("errorinfo", this.GetString("尚未选择要删除的预约事项")); // "尚未选择要删除的预约事项。" return; } OpacApplication app = (OpacApplication)this.Page.Application["app"]; SessionInfo sessioninfo = (SessionInfo)this.Page.Session["sessioninfo"]; string strReaderBarcode = ""; if (String.IsNullOrEmpty(this.ReaderBarcode) == false) { strReaderBarcode = this.ReaderBarcode; } else { strReaderBarcode = sessioninfo.ReaderInfo.Barcode; } if (String.IsNullOrEmpty(strReaderBarcode) == true) { // text-level: 用户提示 this.SetDebugInfo("errorinfo", this.GetString("尚未指定读者证条码号。操作失败")); // "尚未指定读者证条码号。操作失败。" return; } LibraryChannel channel = sessioninfo.GetChannel(true); try { string strError = ""; long lRet = // sessioninfo.Channel. channel.Reservation( null, "delete", strReaderBarcode, strBarcodeList, out strError); if (lRet == -1) { this.SetDebugInfo("errorinfo", strError); } else { // text-level: 用户提示 string strMessage = this.GetString("删除预约信息成功。请看预约列表"); // "删除预约信息成功。请看预约列表。" // 成功时也可能有提示信息 if (String.IsNullOrEmpty(strError) == false) { strMessage += "<br/><br/>" + strError; } this.SetDebugInfo(strMessage); } } finally { sessioninfo.ReturnChannel(channel); } // 清除读者记录缓存 sessioninfo.ClearLoginReaderDomCache(); }
// 保存资源到服务器 // return: // -1 error // >=0 实际上载的资源对象数 public int Save( LibraryChannel channel, string dp2library_version, out string strError) { strError = ""; if (this.ListView.Items.Count == 0) return 0; if (String.IsNullOrEmpty(this.BiblioRecPath) == true) { strError = "尚未指定BiblioRecPath"; return -1; } if (IsNewPath(this.BiblioRecPath) == true) { strError = "书目记录路径 '" + this.BiblioRecPath + "' 不是已保存的记录路径,无法用于对象资源上载"; return -1; } #if NO if (this.Channel == null) { strError = "BinaryResControl尚未指定Channel"; return -1; } #endif StopStyle old_stop_style = StopStyle.None; if (Stop != null) { old_stop_style = Stop.Style; Stop.Style = StopStyle.EnableHalfStop; #if NO Stop.OnStop += new StopEventHandler(this.DoStop); Stop.Initial("正在上载资源 ..."); Stop.BeginLoop(); #endif Stop.Initial("正在上载资源 ..."); } int nUploadCount = 0; // 实际上载的资源个数 try { // bNotAskTimestampMismatchWhenOverwrite = false; for (int i = 0; i < this.ListView.Items.Count; i++) { ListViewItem item = this.ListView.Items[i]; LineInfo info = (LineInfo)item.Tag; // string strUsage = ListViewUtil.GetItemText(item, COLUMN_USAGE); LineState state = GetLineState(item); bool bOnlyChangeMetadata = false; if (state == LineState.Changed || state == LineState.New) { if (state == LineState.Changed) { if (info != null && info.ResChanged == false) { if (StringUtil.CompareVersion(dp2library_version, "2.59") < 0) { strError = "单独修改对象 metadata 的操作需要连接的 dp2library 版本在 2.59 以上 (然而当前 dp2library 版本为 " + dp2library_version + ")"; return -1; } // 这种情况应该是 metadata 修改过 bOnlyChangeMetadata = true; #if NO SetLineInfo(item, // strUsage, LineState.Normal); SetXmlChanged(item, false); SetResChanged(item, false); continue; // 资源没有修改的,则跳过上载 #endif } } } else { // 标记删除的事项,只要书目XML重新构造的时候 // 不包含其ID,书目XML保存后,就等于删除了该事项。 // 所以本函数只是简单Remove这样的listview事项即可 if (state == LineState.Deleted) { this.ListView.Items.Remove(item); i--; } continue; } string strState = ListViewUtil.GetItemText(item, COLUMN_STATE); string strID = ListViewUtil.GetItemText(item, COLUMN_ID); string strResPath = this.BiblioRecPath + "/object/" + ListViewUtil.GetItemText(item, COLUMN_ID); string strLocalFilename = ListViewUtil.GetItemText(item, COLUMN_LOCALPATH); string strMime = ListViewUtil.GetItemText(item, COLUMN_MIME); string strTimestamp = ListViewUtil.GetItemText(item, COLUMN_TIMESTAMP); byte[] timestamp = ByteArray.GetTimeStampByteArray(strTimestamp); byte[] output_timestamp = null; nUploadCount++; if (bOnlyChangeMetadata) { long lRet = channel.SaveResObject( Stop, strResPath, "", strLocalFilename, strMime, "", // range true, // 最尾一次操作,提醒底层注意设置特殊的WebService API超时时间 timestamp, out output_timestamp, out strError); timestamp = output_timestamp; if (timestamp != null) ListViewUtil.ChangeItemText(item, COLUMN_TIMESTAMP, ByteArray.GetHexTimeStampString(timestamp)); if (lRet == -1) goto ERROR1; Debug.Assert(timestamp != null, ""); // TODO: 出错的情况下是否要修改 timestamp 显示?是否应为非空才兑现显示 } else { // 检测文件尺寸 FileInfo fi = new FileInfo(strLocalFilename); if (fi.Exists == false) { strError = "文件 '" + strLocalFilename + "' 不存在..."; return -1; } string[] ranges = null; if (fi.Length == 0) { // 空文件 ranges = new string[1]; ranges[0] = ""; } else { string strRange = ""; strRange = "0-" + Convert.ToString(fi.Length - 1); // 按照100K作为一个chunk // TODO: 实现滑动窗口,根据速率来决定chunk尺寸 ranges = RangeList.ChunkRange(strRange, channel.UploadResChunkSize // 500 * 1024 ); } // REDOWHOLESAVE: string strWarning = ""; for (int j = 0; j < ranges.Length; j++) { // REDOSINGLESAVE: Application.DoEvents(); // 出让界面控制权 if (Stop.State != 0) { strError = "用户中断"; goto ERROR1; } string strWaiting = ""; if (j == ranges.Length - 1) strWaiting = " 请耐心等待..."; string strPercent = ""; RangeList rl = new RangeList(ranges[j]); if (rl.Count >= 1) { double ratio = (double)((RangeItem)rl[0]).lStart / (double)fi.Length; strPercent = String.Format("{0,3:N}", ratio * (double)100) + "%"; } if (Stop != null) Stop.SetMessage("正在上载 " + ranges[j] + "/" + Convert.ToString(fi.Length) + " " + strPercent + " " + strLocalFilename + strWarning + strWaiting); long lRet = 0; TimeSpan old_timeout = channel.Timeout; channel.Timeout = new TimeSpan(0, 5, 0); try { lRet = channel.SaveResObject( Stop, strResPath, strLocalFilename, strLocalFilename, strMime, ranges[j], j == ranges.Length - 1 ? true : false, // 最尾一次操作,提醒底层注意设置特殊的WebService API超时时间 timestamp, out output_timestamp, out strError); } finally { channel.Timeout = old_timeout; } timestamp = output_timestamp; if (timestamp != null) ListViewUtil.ChangeItemText(item, COLUMN_TIMESTAMP, ByteArray.GetHexTimeStampString(timestamp)); strWarning = ""; if (lRet == -1) { /* if (channel.ErrorCode == ChannelErrorCode.TimestampMismatch) { if (this.bNotAskTimestampMismatchWhenOverwrite == true) { timestamp = new byte[output_timestamp.Length]; Array.Copy(output_timestamp, 0, timestamp, 0, output_timestamp.Length); strWarning = " (时间戳不匹配, 自动重试)"; if (ranges.Length == 1 || j == 0) goto REDOSINGLESAVE; goto REDOWHOLESAVE; } DialogResult result = MessageDlg.Show(this, "上载 '" + strLocalFilename + "' (片断:" + ranges[j] + "/总尺寸:" + Convert.ToString(fi.Length) + ") 时发现时间戳不匹配。详细情况如下:\r\n---\r\n" + strError + "\r\n---\r\n\r\n是否以新时间戳强行上载?\r\n注:(是)强行上载 (否)忽略当前记录或资源上载,但继续后面的处理 (取消)中断整个批处理", "dp2batch", MessageBoxButtons.YesNoCancel, MessageBoxDefaultButton.Button1, ref this.bNotAskTimestampMismatchWhenOverwrite); if (result == DialogResult.Yes) { timestamp = new byte[output_timestamp.Length]; Array.Copy(output_timestamp, 0, timestamp, 0, output_timestamp.Length); strWarning = " (时间戳不匹配, 应用户要求重试)"; if (ranges.Length == 1 || j == 0) goto REDOSINGLESAVE; goto REDOWHOLESAVE; } if (result == DialogResult.No) { goto END1; // 继续作后面的资源 } if (result == DialogResult.Cancel) { strError = "用户中断"; goto ERROR1; // 中断整个处理 } } * */ goto ERROR1; } } } SetLineInfo(item, // strUsage, LineState.Normal); SetXmlChanged(item, false); SetResChanged(item, false); } this.DeleteTempFiles(); this.Changed = false; return nUploadCount; ERROR1: return -1; } finally { if (Stop != null) { #if NO Stop.EndLoop(); Stop.OnStop -= new StopEventHandler(this.DoStop); if (nUploadCount > 0) Stop.Initial("上载资源完成"); else Stop.Initial(""); Stop.Style = old_stop_style; #endif if (nUploadCount > 0) Stop.Initial("上载资源完成"); else Stop.Initial(""); } } }
// 检索出评注数据 // return: // 命中的全部结果数量。 public static long SearchComments( OpacApplication app, LibraryChannel channel, string strBiblioRecPath, out string strError) { strError = ""; // string strXml = ""; Debug.Assert(String.IsNullOrEmpty(strBiblioRecPath) == false, ""); //string strBiblioDbName = ResPath.GetDbName(strBiblioRecPath); string strBiblioDbName = StringUtil.GetDbName(strBiblioRecPath); if (String.IsNullOrEmpty(strBiblioDbName) == true) { strError = "从书目记录路径 '" + strBiblioRecPath + "' 中无法获得库名部分"; return -1; } string strCommentDbName = ""; // 根据书目库名, 找到对应的评注库名 // return: // -1 出错 // 0 没有找到 // 1 找到 int nRet = app.GetCommentDbName(strBiblioDbName, out strCommentDbName, out strError); if (nRet == -1) return -1; //string strBiblioRecId = ResPath.GetRecordId(strBiblioRecPath); string strBiblioRecId = StringUtil.GetRecordId(strBiblioRecPath); string strQueryXml = "<target list='" + StringUtil.GetXmlStringSimple(strCommentDbName + ":" + "父记录") // 2007/9/14 + "'><item><order>DESC</order><word>" + strBiblioRecId + "</word><match>exact</match><relation>=</relation><dataType>string</dataType><maxCount>-1</maxCount></item><lang>zh</lang></target>"; // LibraryChannel channel = this.GetChannel(true, this.m_strParameters); try { long lRet = //this.Channel. channel.Search( null, strQueryXml, "default", "", // strOuputStyle out strError); if (lRet == -1) return -1; if (lRet == 0) { strError = "没有找到"; return 0; } return lRet; } finally { // this.ReturnChannel(channel); } }
// 获得一个对象资源的元数据 int GetOneObjectMetadata( LibraryChannel channel, string strBiblioRecPath, string strID, out string strMetadataXml, out byte[] timestamp, out string strError) { timestamp = null; strError = ""; string strResPath = strBiblioRecPath + "/object/" + strID; strResPath = strResPath.Replace(":", "/"); #if NO Stop.OnStop += new StopEventHandler(this.DoStop); Stop.Initial("正在下载对象的元数据 " + strResPath); Stop.BeginLoop(); #endif Stop.Initial("正在下载对象的元数据 " + strResPath); try { string strOutputPath = ""; // EnableControlsInLoading(true); string strResult = ""; // 只得到metadata long lRet = channel.GetRes( Stop, strResPath, "metadata,timestamp,outputpath", out strResult, out strMetadataXml, out timestamp, out strOutputPath, out strError); if (lRet == -1) { strError = "下载对象 " + strResPath + " 元数据失败,原因: " + strError; return -1; } return 0; } finally { // EnableControlsInLoading(false); #if NO Stop.EndLoop(); Stop.OnStop -= new StopEventHandler(this.DoStop); Stop.Initial(""); #endif Stop.Initial(""); } }
// TODO: 结果集是和 channel 在一起的。如果 channel 不确定,就需要用全局结果集 // 获得一定范围的检索命中结果 // return: public static int GetCommentsSearchResult( OpacApplication app, LibraryChannel channel, ItemLoadEventHandler itemLoadProc, int nStart, int nMaxCount, bool bGetRecord, string strLang, // 2012/7/9 out string strError) { strError = ""; List<string> aPath = null; long lRet = // this.Channel. channel.GetSearchResult( null, "default", nStart, // 0, nMaxCount, // -1, strLang, out aPath, out strError); if (lRet == -1) goto ERROR1; long lHitCount = lRet; if (aPath.Count == 0) { strError = "GetSearchResult aPath error"; goto ERROR1; } for (int i = 0; i < aPath.Count; i++) { if (bGetRecord == true) { string strXml = ""; string strMetaData = ""; byte[] timestamp = null; string strOutputPath = ""; string strStyle = LibraryChannel.GETRES_ALL_STYLE; lRet = // this.Channel. channel.GetRes( null, aPath[i], strStyle, out strXml, out strMetaData, out timestamp, out strOutputPath, out strError); if (lRet == -1) goto ERROR1; if (// this.ItemLoad != null itemLoadProc != null ) { ItemLoadEventArgs e = new ItemLoadEventArgs(); e.Path = aPath[i]; e.Index = i; e.Count = aPath.Count; e.Xml = strXml; e.Timestamp = timestamp; e.TotalCount = (int)lHitCount; // this.ItemLoad(this, e); e.Channel = channel; itemLoadProc(null, e); } } else { if (// this.ItemLoad != null itemLoadProc != null) { ItemLoadEventArgs e = new ItemLoadEventArgs(); e.Path = aPath[i]; e.Index = i; e.Count = aPath.Count; e.Xml = ""; e.Timestamp = null; e.TotalCount = (int)lHitCount; // this.ItemLoad(this, e); e.Channel = channel; itemLoadProc(null, e); } } } return 0; ERROR1: return -1; }
// 增量尾号 public int IncreaseTailNumber(string strDefaultNumber, out string strOutputNumber, out string strError) { strOutputNumber = ""; // 获得server url if (String.IsNullOrEmpty(this.LibraryServerName) == true) { strError = "尚未指定服务器名"; goto ERROR1; } dp2Server server = this.MainForm.Servers.GetServerByName(this.LibraryServerName); if (server == null) { strError = "服务器名为 '" + this.LibraryServerName + "' 的服务器不存在..."; goto ERROR1; } string strServerUrl = server.Url; this.Channel = this.Channels.GetChannel(strServerUrl); EnableControls(false); stop.OnStop += new StopEventHandler(this.DoStop); stop.Initial("正在增量尾号 ..."); stop.BeginLoop(); try { long lRet = Channel.SetZhongcihaoTailNumber( stop, "increase", GetZhongcihaoDbGroupName(this.BiblioDbName), // "!" + this.BiblioDbName, this.ClassNumber, strDefaultNumber, out strOutputNumber, out strError); if (lRet == -1) goto ERROR1; return (int)lRet; } finally { stop.EndLoop(); stop.OnStop -= new StopEventHandler(this.DoStop); stop.Initial(""); EnableControls(true); } // return 0; ERROR1: return -1; }
void ReleaseAllChannelsBut(LibraryChannel channel) { for (int i = 0; i < this.Channels.Count; i++) { LibraryChannel cur_channel = this.Channels[i]; if (cur_channel == channel) continue; channel.Abort(); this.Channels.RemoveChannel(channel); i--; } }
protected void Button_GetTempPassword_Click(object sender, EventArgs e) { string strError = ""; if (string.IsNullOrEmpty(this.TextBox_name.Text) == true) { strError = "请输入姓名。"; goto ERROR1; } if (string.IsNullOrEmpty(this.TextBox_readerBarcode.Text) == true) { strError = "请输入读者证条码号。"; goto ERROR1; } if (string.IsNullOrEmpty(this.TextBox_tel.Text) == true) { strError = "请输入手机号码。"; goto ERROR1; } if (this.TextBox_tel.Text.Length != 11) { strError = "手机号码格式不正确。应该为 11 位数字"; goto ERROR1; } string strParameters = "name=" + GetParamValue(this.TextBox_name.Text) + ",tel=" + GetParamValue(this.TextBox_tel.Text) + ",barcode=" + GetParamValue(this.TextBox_readerBarcode.Text) + ",queryword=" + GetParamValue(this.TextBox_readerBarcode.Text); LibraryChannel channel = sessioninfo.GetChannel(true); try { string strMessage = ""; long lRet = // sessioninfo.Channel. channel.ResetPassword( null, strParameters, "", out strMessage, out strError); if (lRet != 1) { goto ERROR1; } if (string.IsNullOrEmpty(strError) == true) { this.Label_message.Text = "临时密码已通过短信方式发送到手机 " + this.TextBox_tel.Text + "。请按照手机短信提示进行操作"; } else { this.Label_message.Text = strError; } return; } finally { sessioninfo.ReturnChannel(channel); } ERROR1: this.Label_message.Text = strError; }
// 根据记录数量的多少,少的时候可以立即返回结果,多的时候用线程后台处理,然后可以随时查询状态 // 线程用线程池,避免过多耗用线程数目 // 根据结果集名,提取全部书目 XML 记录,然后批处理经过 MarcFilter 过滤,创建若干个子结果集 // 最基本的功能是返回子结果集的显示名,文件名,包含记录数量,供前端显示在界面上 // 较为深入的功能是,将子结果集按照 key 排序归并,而显示出二级条目和数量。二级结果集是子结果集的子结果集 // TODO: 如何及时清理Task对象,避免内存过度膨胀? 是否仅保存最新10个Task对象? void GetFilterInfo( string strResultsetName, string strSelected, string strLang) { string strError = ""; GetFilterInfo result_info = new GetFilterInfo(); if (string.IsNullOrEmpty(strResultsetName) == true) { strError = "结果集名不应为空"; goto ERROR1; } FilterTask t = app.FindFilterTask(strResultsetName); // Task对象是利用 Session 内结果集名来进行管理的 if (t == null) { // 如果一个结果集还没有被后台任务处理,就立即启动一个后台任务 t = new FilterTask(); app.SetFilterTask(strResultsetName, t); string strGlobalResultSetName = ""; bool bShare = false; if (strResultsetName[0] == '#') { strGlobalResultSetName = strResultsetName.Substring(1); } else { // 构造全局结果集名 strGlobalResultSetName = sessioninfo.GetHashCode() + "_" + strResultsetName; LibraryChannel channel = sessioninfo.GetChannel(true); try { // 先把结果集共享 // 管理结果集 // parameters: // strAction share/remove 分别表示共享为全局结果集对象/删除全局结果集对象 long lRet = // sessioninfo.Channel. channel.ManageSearchResult( null, "share", strResultsetName, strGlobalResultSetName, out strError); if (lRet == -1) { goto ERROR1; } bShare = true; } finally { sessioninfo.ReturnChannel(channel); } } FilterTaskInput i = new FilterTaskInput(); i.App = app; i.FilterFileName = Path.Combine(app.DataDir, "cfgs/facet.fltx"); i.ResultSetName = strGlobalResultSetName; i.ShareResultSet = bShare; // i.SessionInfo = sessioninfo; i.TempDir = app.TempDir; i.TaskName = strResultsetName; // Task对象是利用Session内结果集名来进行管理的 i.MaxCount = 1000; // i.aggregation_names = new List<string>() {"author"}; XmlDocument def_dom = GetFacetDefDom(out strError); if (def_dom == null) { goto ERROR1; } i.DefDom = def_dom; ThreadPool.QueueUserWorkItem(t.ThreadPoolCallBack, i); strError = "#pending"; // 表示正在处理,希望前端稍后重新访问 goto ERROR1; } else { if (t.TaskState == TaskState.Processing) { if (t.ProgressRange != 0) { result_info.ProgressValue = (int)(((double)t.ProgressValue / (double)t.ProgressRange) * 100); } strError = "#pending"; // 表示正在处理,希望前端稍后重新访问 goto ERROR1; } if (string.IsNullOrEmpty(t.ErrorInfo) == false) { strError = t.ErrorInfo; goto ERROR1; } GC.Collect(); // 试着释放 Hashtable 等 long lHitCount = MyWebPage.GetServerResultCount(sessioninfo, strResultsetName); XmlDocument def_dom = GetFacetDefDom(out strError); if (def_dom == null) { goto ERROR1; } this.m_facetDom = def_dom; this.m_strLang = strLang; try { // 创建FilterInfo数组 result_info.Items = ResultsetFilter.BuildFilterInfos( strResultsetName, lHitCount, strSelected, GetKeyNameCaption, t.ResultItems, app.TempDir, // sessioninfo.GetTempDir(), 10); // GC.Collect(); // 担心 DpResultSet 未能回收 } catch (Exception ex) { strError = ExceptionUtil.GetAutoText(ex); goto ERROR1; } if (t.HitCount > 1000) { result_info.Comment = "分面导航只提取了当前结果集的前 1000 条记录"; } } // 返回一级节点的名字和包含记录数量 this.Response.Write(MyWebPage.GetResultString(result_info)); this.Response.End(); return; ERROR1: result_info.ErrorString = strError; this.Response.Write(MyWebPage.GetResultString(result_info)); this.Response.End(); }
// 根据特性的评注记录路径,获得一定范围的检索命中结果 // return: // -1 出错 // 0 没有找到 // 1 找到 public static int GetCommentsSearchResult( OpacApplication app, LibraryChannel channel, ItemLoadEventHandler itemLoadProc, SetStartEventHandler setStartProc, int nPerCount, string strCommentRecPath, bool bGetRecord, string strLang, // 2012/7/9 out int nStart, out string strError) { strError = ""; nStart = -1; long lHitCount = 0; bool bFound = false; List<string> aPath = null; for (int j = 0; ; j++) { nStart = j * nPerCount; // 只获得路径。确保所要的lStart lCount范围全部获得 long lRet = // this.Channel. channel.GetSearchResult( null, "default", nStart, // 0, nPerCount, // -1, strLang, out aPath, out strError); if (lRet == -1) goto ERROR1; lHitCount = lRet; if (lHitCount == 0) return 0; if (aPath.Count == 0) break; for (int i = 0; i < aPath.Count; i++) { if (aPath[i] == strCommentRecPath) { bFound = true; break; } } if (bFound == true) break; if (nStart >= lHitCount) break; } if (bFound == true) { if (// this.SetStart != null setStartProc != null) { SetStartEventArgs e = new SetStartEventArgs(); e.StartIndex = nStart; // this.SetStart(this, e); setStartProc(null, e); } for (int i = 0; i < aPath.Count; i++) { if (bGetRecord == true) { string strXml = ""; string strMetaData = ""; byte[] timestamp = null; string strOutputPath = ""; string strStyle = LibraryChannel.GETRES_ALL_STYLE; long lRet = // this.Channel. channel.GetRes( null, aPath[i], strStyle, out strXml, out strMetaData, out timestamp, out strOutputPath, out strError); if (lRet == -1) goto ERROR1; if (//this.ItemLoad != null itemLoadProc != null) { ItemLoadEventArgs e = new ItemLoadEventArgs(); e.Path = aPath[i]; e.Index = i; e.Count = aPath.Count; e.Xml = strXml; e.Timestamp = timestamp; e.TotalCount = (int)lHitCount; // this.ItemLoad(this, e); e.Channel = channel; itemLoadProc(null, e); } } else { if (//this.ItemLoad != null itemLoadProc != null) { ItemLoadEventArgs e = new ItemLoadEventArgs(); e.Path = aPath[i]; e.Index = i; e.Count = aPath.Count; e.Xml = ""; e.Timestamp = null; e.TotalCount = (int)lHitCount; // this.ItemLoad(this, e); e.Channel = channel; itemLoadProc(null, e); } } } return 1; // 找到 } nStart = -1; strError = "路径为 '" + strCommentRecPath + "' 的记录在结果集中没有找到"; return 0; // 没有找到 ERROR1: return -1; }
// 列出可用的查重方案名 public int ListProjectNames(string strPureRecPath, out string[] projectnames, out string strError) { strError = ""; projectnames = null; EnableControls(false); stop.OnStop += new StopEventHandler(this.DoStop); stop.Initial("正在获取可用的查重方案名 ..."); stop.BeginLoop(); try { // 获得server url if (String.IsNullOrEmpty(this.LibraryServerName) == true) { strError = "尚未指定服务器名"; goto ERROR1; } dp2Server server = this.MainForm.Servers.GetServerByName(this.LibraryServerName); if (server == null) { strError = "服务器名为 '" + this.LibraryServerName + "' 的服务器不存在..."; goto ERROR1; } string strServerUrl = server.Url; this.Channel = this.Channels.GetChannel(strServerUrl); DupProjectInfo[] dpis = null; string strBiblioDbName = dp2SearchForm.GetDbName(strPureRecPath); long lRet = Channel.ListDupProjectInfos( stop, strBiblioDbName, out dpis, out strError); if (lRet == -1) { goto ERROR1; } projectnames = new string[dpis.Length]; for (int i = 0; i < projectnames.Length; i++) { projectnames[i] = dpis[i].Name; } return((int)lRet); } finally { stop.EndLoop(); stop.OnStop -= new StopEventHandler(this.DoStop); stop.Initial(""); EnableControls(true); } ERROR1: return(-1); }
// 获得一系列册的摘要字符串 // // paramters: // strStyle 风格。逗号间隔的列表。如果包含html text表示格式。forcelogin // strOtherParams <a>命令中其余的参数。例如" target='_blank' "可以用来打开新窗口 public static string GetBarcodesSummary( OpacApplication app, // SessionInfo sessioninfo, LibraryChannel channel, string strBarcodes, string strArrivedItemBarcode, string strStyle, string strOtherParams) { string strSummary = ""; if (strOtherParams == null) strOtherParams = ""; string strDisableClass = ""; if (string.IsNullOrEmpty(strArrivedItemBarcode) == false) strDisableClass = "deleted"; bool bForceLogin = false; if (StringUtil.IsInList("forcelogin", strStyle) == true) bForceLogin = true; string strPrevBiblioRecPath = ""; string[] barcodes = strBarcodes.Split(new char[] { ',' }); for (int j = 0; j < barcodes.Length; j++) { string strBarcode = barcodes[j]; if (String.IsNullOrEmpty(strBarcode) == true) continue; // 获得摘要 string strOneSummary = ""; string strBiblioRecPath = ""; string strError = ""; long lRet = channel.GetBiblioSummary( null, strBarcode, null, strPrevBiblioRecPath, // 前一个path out strBiblioRecPath, out strOneSummary, out strError); if (lRet == -1 || lRet == 0) strOneSummary = strError; /* LibraryServerResult result = this.GetBiblioSummary(sessioninfo, strBarcode, null, strPrevBiblioRecPath, // 前一个path out strBiblioRecPath, out strOneSummary); if (result.Value == -1 || result.Value == 0) strOneSummary = result.ErrorInfo; * */ if (strOneSummary == "" && strPrevBiblioRecPath == strBiblioRecPath) strOneSummary = "(同上)"; if (StringUtil.IsInList("html", strStyle) == true) { string strBarcodeLink = "<a " + (string.IsNullOrEmpty(strDisableClass) == false && strBarcode != strArrivedItemBarcode ? "class='" + strDisableClass + "'" : "") + " href='book.aspx?barcode=" + strBarcode + (bForceLogin == true ? "&forcelogin=userid" : "") + "' " + strOtherParams + " >" + strBarcode + "</a>"; strSummary += strBarcodeLink + " : " + strOneSummary + "<br/>"; } else { strSummary += strBarcode + " : " + strOneSummary + "<br/>"; } strPrevBiblioRecPath = strBiblioRecPath; } return strSummary; }
int GetBrowseCols(List <string> pathlist, List <ListViewItem> itemlist, out string strError) { strError = ""; // 获得server url if (String.IsNullOrEmpty(this.LibraryServerName) == true) { strError = "尚未指定服务器名"; return(-1); } dp2Server server = this.MainForm.Servers.GetServerByName(this.LibraryServerName); if (server == null) { strError = "服务器名为 '" + this.LibraryServerName + "' 的服务器不存在..."; return(-1); } string strServerUrl = server.Url; this.Channel = this.Channels.GetChannel(strServerUrl); EnableControls(false); stop.OnStop += new StopEventHandler(this.DoStop); stop.Initial("正在填充浏览列 ..."); stop.BeginLoop(); this.Update(); this.MainForm.Update(); try { int nStart = 0; int nCount = 0; for (; ;) { nCount = pathlist.Count - nStart; if (nCount > 100) { nCount = 100; } if (nCount <= 0) { break; } Application.DoEvents(); // 出让界面控制权 if (stop != null) { if (stop.State != 0) { strError = "用户中断"; return(-1); } } stop.SetMessage("正在装入浏览信息 " + (nStart + 1).ToString() + " - " + (nStart + nCount).ToString()); string[] paths = new string[nCount]; pathlist.CopyTo(nStart, paths, 0, nCount); DigitalPlatform.LibraryClient.localhost.Record[] searchresults = null; long lRet = this.Channel.GetBrowseRecords( this.stop, paths, "id,cols", out searchresults, out strError); if (lRet == -1) { return(-1); } if (searchresults == null || searchresults.Length == 0) { strError = "searchresults == null || searchresults.Length == 0"; return(-1); } for (int i = 0; i < searchresults.Length; i++) { DigitalPlatform.LibraryClient.localhost.Record record = searchresults[i]; ListViewUtil.EnsureColumns(this.listView_browse, 2 + (record.Cols == null ? 0 : record.Cols.Length), 200); ListViewItem item = itemlist[nStart + i]; item.Text = record.Path; if (record.Cols != null) { for (int j = 0; j < record.Cols.Length; j++) { item.SubItems.Add(record.Cols[j]); } } } nStart += searchresults.Length; } } finally { stop.EndLoop(); stop.OnStop -= new StopEventHandler(this.DoStop); stop.Initial(""); EnableControls(true); } return(0); }
// 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; }
// 获得一条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); }
internal static int GetRemoteBiblioDbNames( string strUrl, string strUserName, string strPassword, out List<string> dbnames, out string strError) { strError = ""; dbnames = new List<string>(); string strValue = ""; LibraryChannel channel = new LibraryChannel(); channel.Url = strUrl; try { long lRet = channel.Login(strUserName, strPassword, "type=worker,client=dp2circulation|" + Program.ClientVersion, out strError); if (lRet != 1) { strError = "对服务器 '" + channel.Url + "' 以用户 '" + strUserName + "' 进行登录时发生错误: " + strError; return -1; } lRet = channel.GetSystemParameter(null, "system", "biblioDbGroup", out strValue, out strError); if (lRet == -1) { strError = "针对服务器 " + channel.Url + " 获得书目库信息过程发生错误:" + strError; return -1; } } finally { channel.Close(); } { // 解析 XML XmlDocument dom = new XmlDocument(); dom.LoadXml("<root />"); try { dom.DocumentElement.InnerXml = strValue; } catch (Exception ex) { strError = "category=system,name=biblioDbGroup 所返回的 XML 片段在装入 InnerXml 时出错: " + ex.Message; return -1; } XmlNodeList nodes = dom.DocumentElement.SelectNodes("database"); foreach (XmlNode node in nodes) { string strDbName = DomUtil.GetAttr(node, "biblioDbName"); dbnames.Add(strDbName); } } return 0; }
void Channels_BeforeLogin(object sender, BeforeLoginEventArgs e) { LibraryChannel channel = (LibraryChannel)sender; dp2Server server = this.MainForm.Servers[channel.Url]; if (server == null) { e.ErrorInfo = "没有找到 URL 为 " + channel.Url + " 的服务器对象"; e.Failed = true; e.Cancel = true; return; } if (e.FirstTry == true) { e.UserName = server.DefaultUserName; e.Password = server.DefaultPassword; e.Parameters = "location=dp2Catalog,type=worker"; /* * e.IsReader = false; * e.Location = "dp2Catalog"; * */ // 2014/9/13 e.Parameters += ",mac=" + StringUtil.MakePathList(SerialCodeForm.GetMacAddress(), "|"); #if SN // 从序列号中获得 expire= 参数值 string strExpire = this.MainForm.GetExpireParam(); if (string.IsNullOrEmpty(strExpire) == false) { e.Parameters += ",expire=" + strExpire; } #endif e.Parameters += ",client=dp2catalog|" + Program.ClientVersion; if (String.IsNullOrEmpty(e.UserName) == false) { return; // 立即返回, 以便作第一次 不出现 对话框的自动登录 } } // IWin32Window owner = this; ServerDlg dlg = SetDefaultAccount( e.LibraryServerUrl, null, e.ErrorInfo, owner); if (dlg == null) { e.Cancel = true; return; } e.UserName = dlg.UserName; e.Password = dlg.Password; e.SavePasswordShort = false; e.Parameters = "location=dp2Catalog,type=worker"; e.Parameters += ",client=dp2catalog|" + Program.ClientVersion; /* * e.IsReader = false; * e.Location = "dp2Catalog"; * */ e.SavePasswordLong = true; e.LibraryServerUrl = dlg.ServerUrl; }
// 检索出实体库全部可用的馆藏地名称 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; }
// 检索 // return: // -1 error // 0 succeed public int DoSearch(string strProjectName, string strRecPath, string strXml, out string strUsedProjectName, out string strError) { strError = ""; strUsedProjectName = ""; if (strProjectName == "<默认>" || strProjectName == "<default>") { strProjectName = ""; } EventFinish.Reset(); EnableControls(false); stop.OnStop += new StopEventHandler(this.DoStop); stop.Initial("正在进行查重 ..."); stop.BeginLoop(); this.Update(); this.MainForm.Update(); try { this.ClearDupState(true); this.listView_browse.Items.Clear(); // 获得server url if (String.IsNullOrEmpty(this.LibraryServerName) == true) { strError = "尚未指定服务器名"; goto ERROR1; } dp2Server server = this.MainForm.Servers.GetServerByName(this.LibraryServerName); if (server == null) { strError = "服务器名为 '" + this.LibraryServerName + "' 的服务器不存在..."; goto ERROR1; } this.SortColumns.Clear(); SortColumns.ClearColumnSortDisplay(this.listView_browse.Columns); string strBrowseStyle = "cols"; if (this.checkBox_includeLowCols.Checked == false) { strBrowseStyle += ",excludecolsoflowthreshold"; } string strServerUrl = server.Url; this.Channel = this.Channels.GetChannel(strServerUrl); long lRet = Channel.SearchDup( stop, strRecPath, strXml, strProjectName, "includeoriginrecord", // includeoriginrecord out strUsedProjectName, out strError); if (lRet == -1) { goto ERROR1; } long lHitCount = lRet; if (lHitCount == 0) { goto END1; // 查重发现没有命中 } long lStart = 0; long lPerCount = Math.Min(50, lHitCount); // 装入浏览格式 for (; ;) { Application.DoEvents(); // 出让界面控制权 if (stop != null) { if (stop.State != 0) { strError = "用户中断"; goto ERROR1; } } stop.SetMessage("正在装入浏览信息 " + (lStart + 1).ToString() + " - " + (lStart + lPerCount).ToString() + " (命中 " + lHitCount.ToString() + " 条记录) ..."); DupSearchResult[] searchresults = null; lRet = Channel.GetDupSearchResult( stop, lStart, lPerCount, strBrowseStyle, // "cols,excludecolsoflowthreshold", out searchresults, out strError); if (lRet == -1) { goto ERROR1; } if (lRet == 0) { break; } Debug.Assert(searchresults != null, ""); // 处理浏览结果 for (int i = 0; i < searchresults.Length; i++) { DupSearchResult result = searchresults[i]; ListViewUtil.EnsureColumns(this.listView_browse, 2 + (result.Cols == null ? 0 : result.Cols.Length), 200); if (this.checkBox_returnAllRecords.Checked == false) { // 遇到第一个权值较低的,就中断全部获取浏览过程 if (result.Weight < result.Threshold) { goto END1; } } /* * if (result.Cols == null) * { * strError = "返回的结果行错误 result.Cols == null"; * goto ERROR1; * } * * ListViewUtil.EnsureColumns(this.listView_browse, * 2 + result.Cols.Length, * 200); * */ ListViewItem item = new ListViewItem(); item.Text = result.Path; item.SubItems.Add(result.Weight.ToString()); if (result.Cols != null) { for (int j = 0; j < result.Cols.Length; j++) { item.SubItems.Add(result.Cols[j]); } } this.listView_browse.Items.Add(item); if (item.Text == this.RecordPath) { // 如果就是发起记录自己 2008/2/29 item.ImageIndex = ITEMTYPE_OVERTHRESHOLD; item.BackColor = Color.LightGoldenrodYellow; item.ForeColor = SystemColors.GrayText; // 表示就是发起记录自己 } else if (result.Weight >= result.Threshold) { item.ImageIndex = ITEMTYPE_OVERTHRESHOLD; item.BackColor = Color.LightYellow; item.Font = new Font(item.Font, FontStyle.Bold); } else { item.ImageIndex = ITEMTYPE_NORMAL; } } lStart += searchresults.Length; if (lStart >= lHitCount || lPerCount <= 0) { break; } } END1: this.SetDupState(); return((int)lHitCount); } finally { stop.EndLoop(); stop.OnStop -= new StopEventHandler(this.DoStop); stop.Initial(""); EventFinish.Set(); EnableControls(true); } ERROR1: return(-1); }
/// <summary> /// 准备进行检索 /// </summary> /// <returns>0: 没有成功; 1: 成功</returns> public int PrepareSearch() { if (String.IsNullOrEmpty(this.LibraryServerUrlList) == true) return 0; if (this.Channel == null) this.Channel = new LibraryChannel(); this.Channel.Url = GetFirstUrl(this.LibraryServerUrlList); this.Channel.BeforeLogin -= new DigitalPlatform.LibraryClient.BeforeLoginEventHandle(Channel_BeforeLogin); this.Channel.BeforeLogin += new DigitalPlatform.LibraryClient.BeforeLoginEventHandle(Channel_BeforeLogin); Stop = new DigitalPlatform.Stop(); Stop.Register(stopManager, true); // 和容器关联 return 1; }
// 处理一小批指纹数据的装入 // parameters: static void GetSomeFingerprintData( LibraryChannel channel, List <string> lines, CancellationToken token, out List <DigitalPlatform.LibraryClient.localhost.Record> records) { // strError = ""; records = new List <DigitalPlatform.LibraryClient.localhost.Record>(); for (; ;) { token.ThrowIfCancellationRequested(); DigitalPlatform.LibraryClient.localhost.Record[] searchresults = null; string[] paths = new string[lines.Count]; lines.CopyTo(paths); REDO_GETRECORDS: long lRet = channel.GetBrowseRecords( null, paths, "id,cols,format:cfgs/browse_fingerprint", out searchresults, out string strError); if (lRet == -1) { #if NO DialogResult temp_result = MessageBox.Show(this, strError + "\r\n\r\n是否重试?", "ReaderSearchForm", MessageBoxButtons.RetryCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); if (temp_result == DialogResult.Retry) { goto REDO_GETRECORDS; } return(-1); #endif if (Prompt != null) { MessagePromptEventArgs e = new MessagePromptEventArgs { // e.MessageText = "获得书目记录 '"+strCommand+"' ("+StringUtil.MakePathList(format_list)+") 时发生错误: " + strError; MessageText = strError + "\r\n\r\n是否重试?", Actions = "yes,no,cancel" }; Prompt(channel, e); if (e.ResultAction == "cancel") { throw new ChannelException(channel.ErrorCode, strError); } else if (e.ResultAction == "yes") { goto REDO_GETRECORDS; } else { // no 也是抛出异常。因为继续下一批代价太大 throw new ChannelException(channel.ErrorCode, strError); } } else { throw new ChannelException(channel.ErrorCode, strError); } } records.AddRange(searchresults); // 去掉已经做过的一部分 lines.RemoveRange(0, searchresults.Length); if (lines.Count == 0) { break; } } }
// 获得一个日志文件的尺寸 // 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; }
// 同步 // 注:中途遇到异常(例如 Loader 抛出异常),可能会丢失 INSERT_BATCH 条以内的日志记录写入 operlog 表 // parameters: // strLastDate 处理中断或者结束时返回最后处理过的日期 // last_index 处理或中断返回时最后处理过的位置。以后继续处理的时候可以从这个偏移开始 // return: // -1 出错 // 0 中断 // 1 完成 public static ReplicationResult DoReplication( LibraryChannel channel, string strStartDate, string strEndDate, LogType logType, CancellationToken token) { string strLastDate = ""; long last_index = -1; // -1 表示尚未处理 // bool bUserChanged = false; // strStartDate 里面可能会包含 ":1-100" 这样的附加成分 StringUtil.ParseTwoPart(strStartDate, ":", out string strLeft, out string strRight); strStartDate = strLeft; if (string.IsNullOrEmpty(strStartDate) == true) { return(new ReplicationResult { Value = -1, ErrorInfo = "DoReplication() 出错: strStartDate 参数值不应为空" }); } try { List <string> dates = null; int nRet = OperLogLoader.MakeLogFileNames(strStartDate, strEndDate, true, // 是否包含扩展名 ".log" out dates, out string strWarning, out string strError); if (nRet == -1) { return(new ReplicationResult { Value = -1, ErrorInfo = strError }); } if (dates.Count > 0 && string.IsNullOrEmpty(strRight) == false) { dates[0] = dates[0] + ":" + strRight; } channel.Timeout = new TimeSpan(0, 1, 0); // 一分钟 // using (SQLiteConnection connection = new SQLiteConnection(this._connectionString)) { ProgressEstimate estimate = new ProgressEstimate(); OperLogLoader loader = new OperLogLoader { Channel = channel, Stop = null, // this.Progress; // loader.owner = this; Estimate = estimate, Dates = dates, Level = 2, // Program.MainForm.OperLogLevel; AutoCache = false, CacheDir = "", LogType = logType, Filter = "setReaderInfo" }; loader.Prompt += Loader_Prompt; try { // int nRecCount = 0; string strLastItemDate = ""; long lLastItemIndex = -1; foreach (OperLogItem item in loader) { token.ThrowIfCancellationRequested(); //if (stop != null) // stop.SetMessage("正在同步 " + item.Date + " " + item.Index.ToString() + " " + estimate.Text + "..."); if (string.IsNullOrEmpty(item.Xml) == true) { goto CONTINUE; } XmlDocument dom = new XmlDocument(); try { dom.LoadXml(item.Xml); } catch (Exception ex) { #if NO DialogResult result = System.Windows.Forms.DialogResult.No; strError = logType.ToString() + "日志记录 " + item.Date + " " + item.Index.ToString() + " XML 装入 DOM 的时候发生错误: " + ex.Message; string strText = strError; this.Invoke((Action)(() => { result = MessageBox.Show(this, strText + "\r\n\r\n是否跳过此条记录继续处理?", "ReportForm", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); })); if (result == System.Windows.Forms.DialogResult.No) { return(-1); } // 记入日志,继续处理 this.GetErrorInfoForm().WriteHtml(strError + "\r\n"); continue; #endif if (Prompt != null) { strError = logType.ToString() + "日志记录 " + item.Date + " " + item.Index.ToString() + " XML 装入 DOM 的时候发生错误: " + ex.Message; MessagePromptEventArgs e = new MessagePromptEventArgs { MessageText = strError + "\r\n\r\n是否跳过此条继续处理?\r\n\r\n(确定: 跳过; 取消: 停止全部操作)", IncludeOperText = true, // + "\r\n\r\n是否跳过此条继续处理?", Actions = "yes,cancel" }; Prompt(channel, e); if (e.ResultAction == "cancel") { throw new ChannelException(channel.ErrorCode, strError); } else if (e.ResultAction == "yes") { continue; } else { // no 也是抛出异常。因为继续下一批代价太大 throw new ChannelException(channel.ErrorCode, strError); } } else { throw new ChannelException(channel.ErrorCode, strError); } } string strOperation = DomUtil.GetElementText(dom.DocumentElement, "operation"); if (strOperation == "setReaderInfo") { nRet = TraceSetReaderInfo( dom, out strError); } else { continue; } if (nRet == -1) { strError = "同步 " + item.Date + " " + item.Index.ToString() + " 时出错: " + strError; if (Prompt != null) { MessagePromptEventArgs e = new MessagePromptEventArgs { MessageText = strError + "\r\n\r\n是否跳过此条继续处理?\r\n\r\n(确定: 跳过; 取消: 停止全部操作)", IncludeOperText = true, // + "\r\n\r\n是否跳过此条继续处理?", Actions = "yes,cancel" }; Prompt(channel, e); if (e.ResultAction == "cancel") { throw new Exception(strError); } else if (e.ResultAction == "yes") { continue; } else { // no 也是抛出异常。因为继续下一批代价太大 throw new Exception(strError); } } else { throw new ChannelException(channel.ErrorCode, strError); } } // lProcessCount++; CONTINUE: // 便于循环外获得这些值 strLastItemDate = item.Date; lLastItemIndex = item.Index + 1; // index = 0; // 第一个日志文件后面的,都从头开始了 } // 记忆 strLastDate = strLastItemDate; last_index = lLastItemIndex; } finally { loader.Prompt -= Loader_Prompt; } } return(new ReplicationResult { Value = last_index == -1 ? 0 : 1, LastDate = strLastDate, LastIndex = last_index }); } catch (Exception ex) { string strError = "ReportForm DoReplication() exception: " + ExceptionUtil.GetDebugText(ex); return(new ReplicationResult { Value = -1, ErrorInfo = strError }); } }
// 装入书目记录 // 本函数在后期修改this.BiblioRecPath。如果中间出错,则不修改 // parameters: // strDirectionStyle prev/next/空 // bWarningNotSaved 是否警告装入前书目信息修改后尚未保存? // return: // -1 error // 0 not found // 1 found int LoadBiblioRecord( LibraryChannel channel, string strBiblioRecPath, string strDirectionStyle, bool bWarningNotSaved, bool bLoadSubrecords, out string strOutputBiblioRecPath, out string strXml, out string strSubRecords, out string strError) { strXml = ""; strSubRecords = ""; strOutputBiblioRecPath = ""; // 2008/6/24 if (String.IsNullOrEmpty(strDirectionStyle) == false) { if (strDirectionStyle != "prev" && strDirectionStyle != "next") { strError = "未知的strDirectionStyle参数值 '" + strDirectionStyle + "'"; return -1; } } if (bWarningNotSaved == true && this.Cataloging == true && this.BiblioChanged == true) { // 警告尚未保存 DialogResult result = MessageBox.Show(this, "当前有编目信息被修改后尚未保存。若此时装载新内容,现有未保存信息将丢失。\r\n\r\n确实要装入新内容? ", "EntityForm", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (result != DialogResult.Yes) { strError = "放弃装载书目记录"; return -1; } } #if NO LibraryChannel channel = this.GetChannel(); Progress.OnStop += new StopEventHandler(this.DoStop); Progress.Initial("正在装入书目记录 ..."); Progress.BeginLoop(); #endif Progress.Initial("正在装入书目记录 ..."); try { if (String.IsNullOrEmpty(strDirectionStyle) == false) { strBiblioRecPath += "$" + strDirectionStyle; } #if NO Global.SetHtmlString(this.webBrowser_biblioRecord, "(空白)"); #endif this.m_webExternalHost_biblio.SetHtmlString("(空白)", "entityform_error"); Progress.SetMessage("正在装入书目记录 " + strBiblioRecPath + " ..."); bool bCataloging = this.Cataloging; /* long lRet = Channel.GetBiblioInfo( stop, strBiblioRecPath, "html", out strHtml, out strError); * */ List<string> format_list = new List<string>(); format_list.Add("outputpath"); format_list.Add("html"); if (bCataloging == true) { format_list.Add("xml"); } if (bLoadSubrecords) { format_list.Add("subrecords:all" + (this.DisplayOtherLibraryItem == true ? "|getotherlibraryitem" : "")); } string[] results = null; byte[] baTimestamp = null; long lRet = channel.GetBiblioInfos( Progress, strBiblioRecPath, "", format_list.ToArray(), out results, out baTimestamp, out strError); if (lRet == 0) { // Global.SetHtmlString(this.webBrowser_biblioRecord, "路径为 '" + strBiblioRecPath + "' 的书目记录没有找到 ..."); this.m_webExternalHost_biblio.SetHtmlString("路径为 '" + strBiblioRecPath + "' 的书目记录没有找到 ...", "entityform_error"); return 0; // not found } string strHtml = ""; bool bError = false; string strErrorText = ""; if (results != null && results.Length >= 1) strOutputBiblioRecPath = results[0]; if (results != null && results.Length >= 2) strHtml = results[1]; if (lRet == -1) { // 暂时不报错 bError = true; strErrorText = strError; // 有报错的情况下不刷新时间戳 2008/11/28 changed } else { // 2014/11/5 if (string.IsNullOrEmpty(strError) == false) { bError = true; strErrorText = strError; } // 没有报错时,要对results进行严格检查 if (results == null) { strError = "results == null"; goto ERROR1; } if (results.Length != format_list.Count) { strError = "result.Length != formats.Length"; goto ERROR1; } // 没有报错的情况下才刷新时间戳 2008/11/28 changed this.BiblioTimestamp = baTimestamp; } #if NO Global.SetHtmlString(this.webBrowser_biblioRecord, strHtml, this.MainForm.DataDir, "entityform_biblio"); #endif this.m_webExternalHost_biblio.SetHtmlString(strHtml, "entityform_biblio"); // 如果没有修改BiblioRecPath,就不能把MARC编辑器中的书目记录修改,否则因BiblioChanged已经为true,可能会导致后面在原有书目记录上作错误的自动保存的副作用 this.BiblioRecPath = strOutputBiblioRecPath; // 2008/6/24 { // subrecords 后面可能带有冒号。需要前方一致匹配 int index = IndexOfFormat(format_list, "subrecords"); if (index != -1) { if (results != null && results.Length > index) strSubRecords = results[index]; } } if (bCataloging == true) { int index = format_list.IndexOf("xml"); Debug.Assert(index != -1, ""); if (results != null && results.Length > index) strXml = results[index]; if (bError == false) // 2008/6/24 { // return: // -1 error // 0 空的记录 // 1 成功 int nRet = SetBiblioRecordToMarcEditor(strXml, out strError); if (nRet == -1) goto ERROR1; // 2008/11/13 if (nRet == 0) MessageBox.Show(this, "警告:当前书目记录 '" + strOutputBiblioRecPath + "' 是一条空记录"); this.BiblioChanged = false; // 2009/10/24 // 根据998$t 兑现ReadOnly状态 string strTargetBiblioRecPath = this.m_marcEditor.Record.Fields.GetFirstSubfield("998", "t"); if (String.IsNullOrEmpty(strTargetBiblioRecPath) == false) { if (this.LinkedRecordReadonly == true) { // TODO: 装载目标记录,替代当前全部内容(除了998) this.m_marcEditor.ReadOnly = true; } } else { // 如果必要,恢复可编辑状态 if (this.m_marcEditor.ReadOnly != false) this.m_marcEditor.ReadOnly = false; } // 注:非采购工作库,也可以设定目标记录路径 // TODO: 未来可以增加“终点库”角色,这样的库才是不能设定目标记录路径的 /* // 根据当前库是不是采购工作库,决定“设置目标记录”按钮是否为Enabled if (this.MainForm.IsOrderWorkDb(this.BiblioDbName) == true) this.toolStripButton_setTargetRecord.Enabled = true; else this.toolStripButton_setTargetRecord.Enabled = false; * */ } } if (bError == true) { strError = strErrorText; goto ERROR1; } } finally { #if NO Progress.EndLoop(); Progress.OnStop -= new StopEventHandler(this.DoStop); Progress.Initial(""); this.ReturnChannel(channel); #endif Progress.Initial(""); } return 1; ERROR1: return -1; }
// 从服务器端得到XML数据,初始化若干变量 // parameters: // page 如果!=null,允许灵敏中断 // return: // -1 出错 // 0 正常结束 // 1 被用户中断 public int InitialInfo( System.Web.UI.Page page, LibraryChannel channel, out string strError) { strError = ""; Line line = this; if (this.m_bInfoInitilized == true) { return(0); } if (String.IsNullOrEmpty(this.m_strRecPath) == true) { strError = "m_strRecPath尚未初始化"; return(-1); } string strStyle = "content,data"; string strContent; string strMetaData; byte[] baTimeStamp; string strOutputPath; Debug.Assert(channel != null, "Channels.GetChannel 异常"); if (page != null && page.Response.IsClientConnected == false) // 灵敏中断 { return(1); } long nRet = channel.GetRes(null, this.m_strRecPath, strStyle, out strContent, out strMetaData, out baTimeStamp, out strOutputPath, out strError); if (nRet == -1) { strError = "获取记录 '" + this.m_strRecPath + "' 时出错: " + strError; return(-1); } if (page != null && page.Response.IsClientConnected == false) // 灵敏中断 { return(1); } // 处理数据 nRet = line.ProcessXml( page, strContent, out strError); if (nRet == -1) { return(-1); } this.m_bInfoInitilized = true; return(0); }
// 保存XML格式的书目记录到数据库 // parameters: // bResave 是否为删除后重新保存的模式。在这种模式下,使用 strAction == "new" int SaveXmlBiblioRecordToDatabase( LibraryChannel channel, string strPath, bool bResave, string strXml, byte[] baTimestamp, out string strOutputPath, out byte[] baNewTimestamp, out string strWarning, out string strError) { strError = ""; strWarning = ""; baNewTimestamp = null; strOutputPath = ""; #if NO Progress.OnStop += new StopEventHandler(this.DoStop); Progress.Initial("正在保存书目记录 ..."); Progress.BeginLoop(); #endif Progress.Initial("正在保存书目记录 ..."); try { string strAction = "change"; if (Global.IsAppendRecPath(strPath) == true || bResave == true) strAction = "new"; /* if (String.IsNullOrEmpty(strPath) == true) strAction = "new"; else { string strRecordID = Global.GetRecordID(strPath); if (String.IsNullOrEmpty(strRecordID) == true || strRecordID == "?") strAction = "new"; } */ REDO: long lRet = channel.SetBiblioInfo( Progress, strAction, strPath, "xml", strXml, baTimestamp, "", out strOutputPath, out baNewTimestamp, out strError); if (lRet == -1) { strError = "保存书目记录 '" + strPath + "' 时出错: " + strError; if (strAction == "change" && channel.ErrorCode == ErrorCode.NotFound) { strError = "保存书目记录 '" + strPath + "' 时出错: 原记录已经不存在"; DialogResult result = MessageBox.Show(this, strError + "\r\n\r\n请问是否改为重新创建此记录?", "EntityForm", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1); if (result == System.Windows.Forms.DialogResult.Yes) { strAction = "new"; // TODO: 此时也需要进一步保存下属的册记录等。而且对象资源不可能恢复了 goto REDO; } } goto ERROR1; } if (channel.ErrorCode == ErrorCode.PartialDenied) { strWarning = "书目记录 '" + strPath + "' 保存成功,但所提交的字段部分被拒绝 (" + strError + ")。请留意刷新窗口,检查实际保存的效果"; } } finally { #if NO Progress.EndLoop(); Progress.OnStop -= new StopEventHandler(this.DoStop); Progress.Initial(""); #endif Progress.Initial(""); } return 1; ERROR1: return -1; }
// 获得一个册的题名字符串 NormalResult GetEntityData(string pii, out string title, out string item_xml, out string item_recpath) { title = ""; item_xml = ""; item_recpath = ""; LibraryChannel channel = App.CurrentApp.GetChannel(); try { #if NO GetItemInfo( stop, "item", strBarcode, "", strResultType, out strResult, out strItemRecPath, out item_timestamp, strBiblioType, out strBiblio, out strBiblioRecPath, out strError); #endif long lRet = channel.GetItemInfo(null, "item", pii, "", "xml", out item_xml, out item_recpath, out byte[] item_timestamp, "", out string biblio_xml, out string biblio_recpath, out string strError); if (lRet == -1) { return new NormalResult { Value = -1, ErrorInfo = strError } } ; lRet = channel.GetBiblioSummary( null, pii, "", // strConfirmItemRecPath, null, out string strBiblioRecPath, out string strSummary, out strError); if (lRet == -1) { return new NormalResult { Value = -1, ErrorInfo = strError } } ; title = strSummary; return(new NormalResult()); } finally { App.CurrentApp.ReturnChannel(channel); } }