Esempio n. 1
0
        /// <summary>
        /// 获取预约到书数据库名称
        /// </summary>
        /// <param name="strError"></param>
        /// <returns></returns>
        public int InitialArrivedDbProperties(out string strError)
        {
            strError = "";

            RestChannel channel = this.GetChannel();

            try
            {
                GetSystemParameterResponse response = channel.GetSystemParameter("arrived",
                                                                                 "dbname");

                long lRet = response.GetSystemParameterResult.Value;
                strError = response.GetSystemParameterResult.ErrorInfo;
                if (lRet == -1)
                {
                    strError = "针对服务器 " + channel.Url + " 获得预约到书库名过程发生错误:" + strError;
                    return(-1);
                }

                this.ArrivedDbName = response.strValue;
            }
            finally
            {
                this.ReturnChannel(channel);
            }

            return(0);
        }
Esempio n. 2
0
        private async Task NotifyCaughtExceptionsAsync()
        {
            RestChannel chan = await this.DiscordRestClient.GetChannelAsync(Config.Instance.Discord.BugReportChannelID);

            if (chan == null)
            {
                return;
            }

            IEnumerable <IGrouping <Exception, EventHandlerException> > exs = this.ServiceManager.TakeCaughtExceptions();

            foreach (IGrouping <Exception, EventHandlerException> grouping in exs)
            {
                EventHandlerException ex = grouping.FirstOrDefault();
                if (ex == null)
                {
                    continue;
                }

                EmbedBuilder builder = new EmbedBuilder();
                builder
                .WithField("Message", ex.Error.Message)
                .WithField("File", ex.FileName)
                .WithField("Method", ex.MethodName)
                .WithField("Line", ex.Line)
                .WithField("Occurences", grouping.Count())
                .WithColorType(EmbedColorType.Warning)
                .WithFooter("event handler error");

                await this.MessageSender.SendAsync(chan, builder.Build());
            }
        }
Esempio n. 3
0
        /// <summary>
        /// 获得图书馆名称
        /// </summary>
        /// <returns>
        /// -1 出错
        /// 0 成功
        /// </returns>
        public int GetLibraryInfo(out string strError)
        {
            strError = "";

            RestChannel channel = this.GetChannel();

            try
            {
                GetSystemParameterResponse response = channel.GetSystemParameter("library", "name");

                long lRet = response.GetSystemParameterResult.Value;
                strError = response.GetSystemParameterResult.ErrorInfo;
                if (lRet == -1)
                {
                    strError = "针对服务器 " + channel.Url + " 获得图书馆名称发生错误:" + strError;
                    return(-1);
                }

                this.LibraryName = response.strValue;
            }
            finally
            {
                this.ReturnChannel(channel);
            }

            return(0);
        }
Esempio n. 4
0
        private void Initialize()
        {
            _securitiesForSubscribeMarketDepth = new JsonArray();
            _securitiesForSubscribe            = new JsonArray();

            _orderCreator.NewMyTrade += OrderCreatorOnNewMyTrade;

            _cancelTokenSource = new CancellationTokenSource();

            _publicKey = ((ServerParameterString)ServerParameters[0]).Value;
            _secretKey = ((ServerParameterPassword)ServerParameters[1]).Value;

            if (string.IsNullOrEmpty(_publicKey) || string.IsNullOrEmpty(_secretKey))
            {
                throw new ArgumentException("Invalid key, connection terminated!");
            }

            StartMessageReader();

            _restChannel = new RestChannel();

            _wsSource = new WsSource(WsUri);
            _wsSource.MessageEvent += WsSourceOnMessageEvent;
            _wsSource.Start();
        }
Esempio n. 5
0
 internal static TwitchChannelEntity ToEntity(this RestChannel channel)
 {
     return(new TwitchChannelEntity
     {
         Id = channel.Id.ToString(),
         Followers = channel.Followers
     });
 }
Esempio n. 6
0
        private Stream GetStream(string url)
        {
            RestRequest request = new RestRequest()
            {
                Method = "GET", Url = url
            };

            return(RestChannel.GetStream(request));
        }
Esempio n. 7
0
        public Task <PaginatedResult <Message> > HistoryAsync(HistoryRequestParams query, bool untilAttach = false)
        {
            query = query ?? new HistoryRequestParams();
            if (untilAttach)
            {
                AddUntilAttachParameter(query);
            }

            return(RestChannel.HistoryAsync(query));
        }
Esempio n. 8
0
        private void UnInitialize()
        {
            _orderCreator.NewMyTrade -= OrderCreatorOnNewMyTrade;

            _restChannel = null;

            _wsSource.Dispose();
            _wsSource.MessageEvent -= WsSourceOnMessageEvent;
            _wsSource = null;
        }
Esempio n. 9
0
        // 查找指定URL的LibraryChannel对象
        ChannelWrapper GetChannelInternel(RestChannel inner_channel)
        {
            foreach (ChannelWrapper channel in this)
            {
                if (channel.Channel == inner_channel)
                {
                    return(channel);
                }
            }

            return(null);
        }
Esempio n. 10
0
        /// <summary>
        /// 获取预约到书数据库名称
        /// </summary>
        /// <param name="strError"></param>
        /// <returns></returns>
        public int InitialArrivedDbProperties(out string strError)
        {
            strError = "";

            RestChannel channel = this.GetChannel();

            try
            {
                GetSystemParameterResponse response = channel.GetSystemParameter("arrived",
                                                                                 "dbname");

                long lRet = response.GetSystemParameterResult.Value;
                strError = response.GetSystemParameterResult.ErrorInfo;
                if (lRet == -1)
                {
                    strError = "针对服务器 " + channel.Url + " 获得预约到书库名过程发生错误:" + strError;
                    return(-1);
                }

                this.ArrivedDbName = response.strValue;

                // 2021/2/20 增加
                // 获取预约保留天数
                //    <arrived dbname="预约到书" reserveTimeSpan="1day" outofReservationThreshold="10"
                //  canReserveOnshelf="true" notifyTypes="dpmail,email,mq" />
                response = channel.GetSystemParameter("system",
                                                      "arrived");
                lRet     = response.GetSystemParameterResult.Value;
                strError = response.GetSystemParameterResult.ErrorInfo;
                if (lRet == -1)
                {
                    strError = "针对服务器 " + channel.Url + " 获得预约参数发生错误:" + strError;
                    return(-1);
                }
                string      arrivedXml = response.strValue;
                XmlDocument dom        = new XmlDocument();
                dom.LoadXml(arrivedXml);
                if (dom.DocumentElement != null)
                {
                    this.ReserveTimeSpan = DomUtil.GetAttr(dom.DocumentElement, "reserveTimeSpan");
                }


                //DomUtil.GetElementAttr(dom.DocumentElement, "", "reserveTimeSpan");
            }
            finally
            {
                this.ReturnChannel(channel);
            }

            return(0);
        }
Esempio n. 11
0
        /// <summary>
        /// 最多通道数
        /// </summary>
        //public int MaxCount = 50;

        /// <summary>
        /// 征用一个通道
        /// </summary>
        /// <param name="strUrl">服务器 URL</param>
        /// <param name="strUserName">用户名</param>
        /// <returns>返回通道对象</returns>
        public RestChannel GetChannel(string strUrl,
                                      string strUserName)
        {
            ChannelWrapper wrapper = null;

            if (this.m_lock.TryEnterWriteLock(m_nLockTimeout) == false)
            {
                throw new LockException("锁定尝试中超时");
            }

            try
            {
                // 先从池中查找存在此url的空闭通道
                wrapper = this.GetChannelInternel(strUrl, strUserName, true);
                if (wrapper != null)
                {
                    return(wrapper.Channel);
                }

                ////超出数量,需清理不用的通道
                //if (this.Count >= MaxCount)
                //{
                //    // 清理不用的通道
                //    int nDeleteCount = CleanChannel(false);
                //    if (nDeleteCount == 0)
                //    {
                //        // 全部都在使用
                //        throw new Exception("通道池已满,请稍候重试获取通道");
                //    }
                //}

                // 如果没有找到
                RestChannel inner_channel = new RestChannel();
                inner_channel.Url          = strUrl;
                inner_channel.UserName     = strUserName;
                inner_channel.BeforeLogin -= new BeforeLoginEventHandle(channel_BeforeLogin);
                inner_channel.BeforeLogin += new BeforeLoginEventHandle(channel_BeforeLogin);

                wrapper         = new ChannelWrapper();
                wrapper.Channel = inner_channel;
                wrapper.InUsing = true;

                this.Add(wrapper);
                return(inner_channel);
            }
            finally
            {
                this.m_lock.ExitWriteLock(); //释放锁
            }
        }
Esempio n. 12
0
        /// <summary>
        /// 获取通道
        /// </summary>
        /// <param name="strServerUrl"></param>
        /// <param name="strUserName"></param>
        /// <returns></returns>
        public RestChannel GetChannel(string strServerUrl = ".",
                                      string strUserName  = "******")
        {
            if (strServerUrl == ".")
            {
                strServerUrl = this.Setting.Url;//Properties.Settings.Default.cfg_library_url;
            }
            strServerUrl = this.GetPurlUrl(strServerUrl);

            if (strUserName == ".")
            {
                strUserName = this.Setting.UserName;//Properties.Settings.Default.cfg_library_username;
            }
            RestChannel channel = this._channelPool.GetChannel(strServerUrl, strUserName);

            return(channel);
        }
Esempio n. 13
0
        public void DeleteReservation(string noteId)
        {
            RestChannel channel = this._mainForm.GetChannel();

            try
            {
                string strError = "";

                List <ReservationItem> items = DbManager.Instance.GetItemsByNoteId(noteId);
                foreach (ReservationItem item in items)
                {
                    //this.AppendNewLine(this.listView_items, item);

                    ReservationResponse response = channel.Reservation("delete",
                                                                       item.PatronBarcode,
                                                                       item.ItemBarcode);
                    if (response.ReservationResult.ErrorCode != ErrorCode.NoError)
                    {
                        strError += response.ReservationResult.ErrorInfo + "\r\n";
                    }

                    // 更新一下本地库的预约记录状态,与服务器保持一致,
                    // 但界面还不会立即反应出来,需要点一下上方的备书单,再显示出来的详细信息就为outof状态了
                    item.State = "outof";
                    DbManager.Instance.UpdateItem(item);
                }


                if (strError != "")
                {
                    // 用Invoke线程安全的方式来调
                    this.Invoke((Action)(() =>
                    {
                        MessageBox.Show(this, "调服务器取消预约出错:" + strError);
                        return;
                    }
                                         ));
                }
            }
            finally
            {
                this._mainForm.ReturnChannel(channel);
            }
        }
Esempio n. 14
0
        /// <summary>
        /// 归还一个通道
        /// </summary>
        /// <param name="channel">通道对象</param>
        public void ReturnChannel(RestChannel channel)
        {
            ChannelWrapper wrapper = null;

            if (this.m_lock.TryEnterReadLock(m_nLockTimeout) == false)
            {
                throw new LockException("锁定尝试中超时");
            }
            try
            {
                wrapper = GetChannelInternel(channel);
                if (wrapper != null)
                {
                    wrapper.InUsing = false;
                }
            }
            finally
            {
                this.m_lock.ExitReadLock();
            }
        }
Esempio n. 15
0
        private void button_notice_Click(object sender, EventArgs e)
        {
            if (this.listView_note.SelectedItems.Count == 0)
            {
                MessageBox.Show(this, "尚未选择备书单");
                return;
            }

            ListViewItem viewItem = this.listView_note.SelectedItems[0];
            string       noteId   = viewItem.SubItems[0].Text;

            // 2021/3/2加,检查处理过程中有没有变化
            // 检查备书单中册的到书状态在服务器端有无变成outof的?如果变为outof可能是读者放弃取书或者超过的保留期
            bool boutof = this.GetRecordState(noteId, out string checkinfo);

            if (boutof == true)
            {
                MessageBox.Show(this, checkinfo);
                return;
            }

            // 显示电话通知内容
            string     info = this.GetResultInfo(noteId);
            noticeForm dlg  = new noticeForm();

            dlg.StartPosition = FormStartPosition.CenterScreen;
            dlg.Info          = info;
            DialogResult ret = dlg.ShowDialog(this);

            if (ret == DialogResult.Cancel)
            {
                // 用户取消操作,则不做什么事情
                return;
            }



            // 发送微信通知

            /*
             * <root>
             * <type>预约到书通知</type>
             * <itemBarcode>0000001</itemBarcode>
             * <onShelf>false</onShelf>
             * <accessNo>123</accessNo>
             * <requestDate>Wed, 23 Dec 2020 14:24:10 GMT</requestDate>
             * <today>2016/5/17 10:10:59</today>
             * <reserveTime>2天</reserveTime>
             * <location>星洲/书柜</location>
             * <summary>数学小报. -- ISBN 7</summary>
             * <patronName>张三</patronName>
             * <patronRecord>
             * <barcode>13862157150</barcode>
             * <name>张三</name>
             * <libraryCode></libraryCode>
             * </patronRecord>
             * </root>
             *
             * // http://123.57.163.11/dp2library/demo/rest/SetMessage
             *
             * {
             * "strAction":"send",
             * "strStyle":"",
             * "messages":[
             * {
             * "strRecipient":"!mq:13862157150",
             * "strMime": "xml",
             * "strBody": "<root><type>预约到书通知</type><itemBarcode>0000001</itemBarcode>
             * <onShelf>false</onShelf><accessNo>I247.5/5</accessNo><requestDate>Wed, 23 Dec 2020 14:24:10 GMT</requestDate><today>2016/5/17 10:10:59</today><reserveTime>2天</reserveTime><location>星洲/书柜</location><summary>数学小报. -- ISBN 7-...</summary><patronName>张三</patronName><patronRecord><barcode>13862157150</barcode><name>张三</name><libraryCode></libraryCode></patronRecord></root>"
             * }]
             * }
             */

            // 用于写日志和报错
            string errorPatronName   = "";
            string errorItemBarcodes = "";



            RestChannel channel = this._mainForm.GetChannel();

            try
            {
                string strError = "";

                int    foundCount    = 0;
                int    notfoundCount = 0;
                string foundInfo     = "";
                string notfoundInfo  = "";


                List <ReservationItem> items = DbManager.Instance.GetItemsByNoteId(noteId);
                if (items.Count == 0)
                {
                    MessageBox.Show(this, "该备书单没有详细信息");
                    return;
                }

                foreach (ReservationItem item in items)
                {
                    string   requestTime = item.RequestTime;
                    DateTime dt          = DateTime.Parse(requestTime);
                    string   rfcDate     = DateTimeUtil.Rfc1123DateTimeString(dt); //.Date8toRfc1123(requestTime.Substring(0, 8),out rfcDate,out strError);

                    // 如果是找到的图书,给读者发送预约到书通知
                    if (item.CheckResult == "Y")
                    {
                        // 找到的数量和名称
                        foundCount++;
                        if (foundInfo != "")
                        {
                            foundInfo += ",";
                        }
                        foundInfo += item.Title + "(" + item.ItemBarcode + ")";



                        MessageData message = new MessageData();
                        message.strRecipient = "!mq:" + item.PatronBarcode;
                        message.strMime      = "xml";
                        string strBody = "<root>"
                                         + "<type>预约到书通知</type>"
                                         + "<source>dp2mini</source>"
                                         + "<itemBarcode>" + item.ItemBarcode + "</itemBarcode>"
                                         + "<onShelf>" + item.OnShelf + "</onShelf>"
                                         + "<accessNo>" + item.AccessNo + "</accessNo>"
                                         + "<requestDate>" + rfcDate + "</requestDate>"
                                         + "<today>" + item.ArrivedTime + "</today>"                           //2016/5/17 10:10:59
                                         + "<reserveTime>" + this._mainForm.ReserveTimeSpan + "</reserveTime>" //2天
                                         + "<location>" + item.Location + "</location>"
                                         + "<summary>" + item.Title + "</summary>"
                                         + "<patronName>" + item.PatronName + "</patronName>"
                                         + "<patronRecord>"
                                         + "<barcode>" + item.PatronBarcode + "</barcode>"
                                         + "<name>" + item.PatronName + "</name>"
                                         + "<libraryCode>" + item.LibraryCode + "</libraryCode>"
                                         + "</patronRecord>"
                                         + "</root>";
                        XmlDocument dom = new XmlDocument();
                        dom.LoadXml(strBody);
                        message.strBody = dom.DocumentElement.OuterXml;

                        SetMessageResponse response = channel.SetMessage("send",
                                                                         "",
                                                                         message);
                        if (response.SetMessageResult.ErrorCode != ErrorCode.NoError)
                        {
                            // 同一个备书单的读者是同一位
                            errorPatronName = item.PatronName + "(" + item.PatronBarcode + ")";

                            Log.Error("给'" + errorPatronName + "'发送册'" + item.ItemBarcode + "'到书的微信通知出错:" + response.SetMessageResult.ErrorInfo);

                            if (errorItemBarcodes != "")
                            {
                                errorItemBarcodes += ",";
                            }
                            errorItemBarcodes += item.ItemBarcode;
                        }
                    }
                    else
                    {
                        // 未找到的数量和名称
                        notfoundCount++;
                        if (notfoundInfo != "")
                        {
                            notfoundInfo += ",";
                        }
                        notfoundInfo += item.Title + "(" + item.ItemBarcode + ")";
                    }
                }

                if (errorItemBarcodes != "")
                {
                    // 用Invoke线程安全的方式来调
                    this.Invoke((Action)(() =>
                    {
                        MessageBox.Show(this, "给'" + errorPatronName + "'发送册'" + errorItemBarcodes + "'到书的微信通知出错,详细请查看日志");
                    }));
                }


                // 发送找到和未找到总结信息的通知
                {
                    ReservationItem item = items[0];

                    string strcontent = "";
                    if (foundCount > 0)
                    {
                        strcontent = "备好" + foundCount.ToString() + "本图书:" + foundInfo + "。";
                    }
                    if (notfoundCount > 0)
                    {
                        strcontent += "未找到" + notfoundCount.ToString() + "本: " + notfoundInfo + "。";
                    }

                    MessageData message = new MessageData();
                    message.strRecipient = "!mq:" + item.PatronBarcode;
                    message.strMime      = "xml";
                    string strBody = "<root>"
                                     + "<type>预约备书结果</type>"
                                     + "<content>" + strcontent + "</content>"
                                     + "<patronName>" + item.PatronName + "</patronName>"
                                     + "<patronRecord>"
                                     + "<barcode>" + item.PatronBarcode + "</barcode>"
                                     + "<name>" + item.PatronName + "</name>"
                                     + "<libraryCode>" + item.LibraryCode + "</libraryCode>"
                                     + "</patronRecord>"
                                     + "</root>";
                    XmlDocument dom = new XmlDocument();
                    dom.LoadXml(strBody);
                    message.strBody = dom.DocumentElement.OuterXml;

                    SetMessageResponse response = channel.SetMessage("send",
                                                                     "",
                                                                     message);
                    if (response.SetMessageResult.ErrorCode != ErrorCode.NoError)
                    {
                        string error = "给'" + item.PatronName + "(" + item.PatronBarcode + ")" + "'发送备书结果微信通知出错:" + response.SetMessageResult.ErrorInfo;
                        //写日志
                        Log.Error(error);

                        // 用Invoke线程安全的方式来调
                        this.Invoke((Action)(() =>
                        {
                            MessageBox.Show(this, error);
                        }));
                    }
                }
            }
            finally
            {
                this._mainForm.ReturnChannel(channel);
            }


            Note   note       = DbManager.Instance.GetNote(noteId);
            string noticeTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

            note.NoticeTime  = noticeTime;
            note.NoticeState = "Y";
            note.Step        = Note.C_Step_Notice;

            // 更新本地数据库备书库打印状态和时间
            DbManager.Instance.UpdateNote(note);

            // 更新备书行的显示
            this.LoadOneNote(note, viewItem);
            this.SetOperateButton(note.Step);
        }
Esempio n. 16
0
 /// <summary>
 /// 释放通道
 /// </summary>
 /// <param name="channel"></param>
 public void ReturnChannel(RestChannel channel)
 {
     this._channelPool.ReturnChannel(channel);
 }
Esempio n. 17
0
        /// <summary>
        /// 获取记录详细信息
        /// </summary>
        /// <param name="channel"></param>
        /// <param name="strRecord"></param>
        /// <param name="cols"></param>
        /// <param name="strError"></param>
        /// <returns></returns>
        int GetDetailInfo(RestChannel channel,
                          string recPath,
                          string strRecordXml,
                          out ReservationItem reserItem,
                          out string strError)
        {
            strError = "";

            reserItem         = new ReservationItem();
            reserItem.RecPath = recPath;

            XmlDocument dom = new XmlDocument();

            dom.LoadXml(strRecordXml);
            XmlNode nodeRoot = dom.DocumentElement;

            reserItem.RecPath       = recPath;
            reserItem.State         = DomUtil.GetElementText(nodeRoot, "state");
            reserItem.ItemBarcode   = DomUtil.GetElementText(nodeRoot, "itemBarcode");
            reserItem.ItemRefID     = DomUtil.GetElementText(nodeRoot, "itemRefID");
            reserItem.PatronBarcode = DomUtil.GetElementText(nodeRoot, "readerBarcode");
            reserItem.LibraryCode   = DomUtil.GetElementText(nodeRoot, "libraryCode");
            reserItem.OnShelf       = DomUtil.GetElementText(nodeRoot, "onShelf");
            reserItem.NotifyTime    = DateTimeUtil.ToLocalTime(DomUtil.GetElementText(nodeRoot, "notifyDate"), "yyyy-MM-dd HH:mm:ss");
            reserItem.Location      = DomUtil.GetElementText(nodeRoot, "location");
            reserItem.AccessNo      = DomUtil.GetElementText(nodeRoot, "accessNo");

            // 以下字段为图书信息
            reserItem.ISBN   = "";
            reserItem.Title  = "";
            reserItem.Author = "";

            // 以下字段是读者信息
            reserItem.PatronName  = "";
            reserItem.Department  = "";
            reserItem.PatronTel   = "";
            reserItem.RequestTime = "";
            reserItem.ArrivedTime = "";

            // 备书产生的字段
            reserItem.PrintState  = DomUtil.GetElementText(nodeRoot, "printState");
            reserItem.CheckResult = "";// 是否找到图书,值为:找到/未找到

            // 过了保留期的数据,不再获取详细数据
            if (reserItem.State == C_State_outof)
            {
                strError = "因为过了保留期,不必再获取详细数据了。";
                return(0);
            }

            // 获取册信息以及书目信息
            if (!string.IsNullOrEmpty(reserItem.ItemBarcode))
            {
                GetItemInfoResponse response = channel.GetItemInfo(reserItem.ItemBarcode,
                                                                   "xml",
                                                                   "xml");
                if (response.GetItemInfoResult.Value == -1)
                {
                    strError = "获取册记录'" + reserItem.ItemBarcode + "'出错:" + response.GetItemInfoResult.ErrorInfo;
                    return(-1);
                }
                if (response.GetItemInfoResult.Value == 0)
                {
                    strError = "获取册记录'" + reserItem.ItemBarcode + "未命中";
                    return(-1);
                }

                string strOutMarcSyntax = "";
                string strMARC          = "";
                string strMarcXml       = response.strBiblio;
                int    nRet             = MarcUtil.Xml2Marc(strMarcXml,
                                                            false,
                                                            "", // 自动识别 MARC 格式
                                                            out strOutMarcSyntax,
                                                            out strMARC,
                                                            out strError);
                if (nRet == -1)
                {
                    return(-1);
                }

                MarcRecord marcRecord = new MarcRecord(strMARC);
                reserItem.ISBN   = marcRecord.select("field[@name='010']/subfield[@name='a']").FirstContent;
                reserItem.Title  = marcRecord.select("field[@name='200']/subfield[@name='a']").FirstContent;
                reserItem.Author = marcRecord.select("field[@name='200']/subfield[@name='f']").FirstContent;
            }

            // 获取读者信息
            if (string.IsNullOrEmpty(reserItem.PatronBarcode) == false)
            {
                GetReaderInfoResponse readerRet = channel.GetReaderInfo(reserItem.PatronBarcode,
                                                                        "xml:noborrowhistory");
                if (readerRet.GetReaderInfoResult.Value == -1)
                {
                    strError = "获取册记录'" + reserItem.ItemBarcode + "'出错:" + readerRet.GetReaderInfoResult.ErrorInfo;
                    return(-1);
                }
                if (readerRet.GetReaderInfoResult.Value == 0)
                {
                    strError = "获取册记录'" + reserItem.ItemBarcode + "'未命中。";// + readerRet.GetReaderInfoResult.ErrorInfo;
                    return(-1);
                }

                string strPatronXml = readerRet.results[0];
                dom.LoadXml(strPatronXml);
                XmlNode rootNode = dom.DocumentElement;
                reserItem.PatronName = DomUtil.GetElementText(rootNode, "name");
                reserItem.Department = DomUtil.GetElementText(rootNode, "department");
                reserItem.PatronTel  = DomUtil.GetElementText(rootNode, "tel");

                /*
                 * - <root expireDate="">
                 * <barcode>XZP10199</barcode>
                 * <readerType>学生</readerType>
                 * <name>李明</name>
                 * <overdues />
                 * - <reservations>
                 * <request items="XZ000101" requestDate="Tue, 11 Feb 2020 00:30:27 +0800"
                 *  operator="XZP10199" state="arrived" arrivedDate="Tue, 11 Feb 2020 00:31:45 +0800"
                 *  arrivedItemBarcode="XZ000101" notifyID="59abfc23-f44f-4b34-a22c-f8a8aa5e289e"
                 *  accessNo="K825.6=76/Z780" location="星洲学校/图书馆,#reservation" />
                 * </reservations>
                 * </root>
                 */
                XmlNodeList nodeList = rootNode.SelectNodes("reservations/request");
                foreach (XmlNode node in nodeList)
                {
                    string arrivedItemBarcode = DomUtil.GetAttr(node, "arrivedItemBarcode");
                    if (arrivedItemBarcode == reserItem.ItemBarcode)
                    {
                        reserItem.RequestTime = DateTimeUtil.ToLocalTime(DomUtil.GetAttr(node, "requestDate"), "yyyy-MM-dd HH:mm:ss");
                        reserItem.ArrivedTime = DateTimeUtil.ToLocalTime(DomUtil.GetAttr(node, "arrivedDate"), "yyyy-MM-dd HH:mm:ss");
                        break;
                    }
                }
            }

            return(0);
        }
Esempio n. 18
0
 public DiscordChannel(RestChannel channel)
 {
     ID = channel.Id;
 }
Esempio n. 19
0
        /// <summary>
        /// 检索做事的函数
        /// </summary>
        /// <param name="token"></param>
        private void doSearch(CancellationToken token,
                              string arrivedDbName,
                              string strQueryWord)
        {
            string strError = "";

            // 记下原来的光标
            Cursor oldCursor = Cursor.Current;

            // 用Invoke线程安全的方式来调
            this.Invoke((Action)(() =>
            {
                // 设置按钮状态
                EnableControls(false);

                //清空界面数据
                this.ClearInfo();

                // 鼠标设为等待状态
                oldCursor = this.Cursor;
                this.Cursor = Cursors.WaitCursor;
            }
                                 ));

            RestChannel channel = this._mainForm.GetChannel();

            try
            {
                string strFrom       = "读者证条码号"; // 检索途径
                string strMatchStyle = "exact";  //匹配方式
                // 如果检索词为空,则按__id检索出全部记录
                if (string.IsNullOrEmpty(strQueryWord))
                {
                    strFrom       = "__id";
                    strMatchStyle = "left";
                }

                // 拼装检索语句
                string strQueryXml = "<target list='" + arrivedDbName + ":" + strFrom + "'>" +
                                     "<item>" +
                                     "<word>" + strQueryWord + "</word>" +
                                     "<match>" + strMatchStyle + "</match>" +
                                     "<relation>=</relation>" +
                                     "<dataType>string</dataType>" +
                                     "</item>" +
                                     "<lang>zh</lang>" +
                                     "</target>";

                string         strOutputStyle = "";
                SearchResponse searchResponse = channel.Search(strQueryXml,
                                                               "arrived",
                                                               strOutputStyle);
                long lRet = searchResponse.SearchResult.Value;
                if (lRet == -1)
                {
                    strError = "检索发生错误:" + strError;
                    goto ERROR1;
                }
                if (lRet == 0)
                {
                    strError = "未命中";
                    goto ERROR1;
                }

                long todoCount   = 0; // 待做的
                long outofCount  = 0; // 超过保留期的
                long inNoteCount = 0; // 已创建到备书单的记录

                // 获取结果集记录
                long     lTotalCount   = lRet;
                long     lStart        = 0;
                long     lOnceCount    = lTotalCount;
                Record[] searchresults = null;
                while (token.IsCancellationRequested == false)
                {
                    lRet = channel.GetSearchResult("arrived",
                                                   lStart,
                                                   lOnceCount,
                                                   "id,xml",// cols,
                                                   "zh",
                                                   out searchresults,
                                                   out strError);
                    if (lRet == -1)
                    {
                        strError = "获得检索结果发生错误:" + strError;
                        goto ERROR1;
                    }
                    else if (lRet == 0)
                    {
                        strError = "获得0 条检索结果";
                        goto ERROR1;
                    }

                    // 处理每一条记录
                    int i = 0;
                    foreach (Record record in searchresults)
                    {
                        if (token.IsCancellationRequested == true)
                        {
                            break;
                        }

                        string strPath = record.Path;

                        // 2020/2/22 先检查一下这笔预约记录在本地库是否存在,
                        // 如果存在则表示是创建过备书单,不需要显示在这里了。
                        ReservationItem item = DbManager.Instance.GetItem(strPath);
                        if (item != null)
                        {
                            inNoteCount++;
                            this._mainForm.SetStatusMessage((lStart + i + 1).ToString() + " / " + lTotalCount);
                            continue;
                        }


                        // 把一条记录,解析成一个详细信息
                        // 注意此时不会保存临时信息,只有在创建预约单时才会在本地存储,因为中间可能读者会自己取消了预约,所以还是以实时查询出来的准
                        int nRet = GetDetailInfo(channel,
                                                 strPath,
                                                 record.RecordBody.Xml,
                                                 out item,
                                                 out strError);
                        if (nRet == -1)
                        {
                            goto ERROR1;
                        }

                        this.Invoke((Action)(() =>
                        {
                            // 状态为outof加到超过保存期时,注意有两种情况:一种是确实超过保留期的,一种是读者取消预约的情况。
                            if (item.State == C_State_outof)
                            {
                                // 增加一行到超过保留期的
                                AppendNewLine(this.listView_outof, item);

                                outofCount++;
                            }
                            else
                            {
                                // 增加一行到预约到书
                                AppendNewLine(this.listView_results, item);

                                // 为预约到书记录建立hashtable,方便后面保留到本地库。因为listviewitem的信息不全。
                                // 未处理的预约记录一般量不太大,放在内存hashtable应该可以的。
                                this.ItemHt[strPath] = item;

                                // 方便决定后面是否自动排序
                                todoCount++;
                            }

                            this._mainForm.SetStatusMessage((lStart + i + 1).ToString() + " / " + lTotalCount);

                            // 数量加1
                            i++;
                        }));
                    }

                    lStart += searchresults.Length;
                    if (lStart >= lTotalCount)
                    {
                        break;
                    }
                }
                this.Invoke((Action)(() =>
                {
                    if (todoCount > 0)
                    {
                        // 按证条码号排序
                        this.SortCol(1);
                    }
                    // 任务栏显示信息
                    this._mainForm.SetStatusMessage("命中总数'" + lTotalCount + "'条,"
                                                    + "其中预约到书'" + todoCount + "'条,"
                                                    + "超过保留期或读者自己取消'" + outofCount + "'条,"
                                                    + "已创建到备书单'" + inNoteCount + "'条。");
                }));
                return;
            }
            catch (Exception ex)
            {
                strError = ex.Message;
                goto ERROR1;
            }
            finally
            {
                // 设置按置状态
                this.Invoke((Action)(() =>
                {
                    EnableControls(true);
                    this.Cursor = oldCursor;

                    this._mainForm.ReturnChannel(channel);
                }
                                     ));
            }

ERROR1:
            this.Invoke((Action)(() =>
            {
                MessageBox.Show(strError);
            }
                                 ));
        }
Esempio n. 20
0
        /// <summary>
        /// 检查备书单中记录当前的预约到书状态,有没有变为outof。
        /// 如果变为outof,有可能是读者放弃取书或者已经超过了保留期限。需撤消备书单,重新处理。
        /// </summary>
        /// <param name="noteId"></param>
        /// <param name="info"></param>
        /// <returns></returns>
        public bool GetRecordState(string noteId, out string info)
        {
            info = "";
            bool bOutof    = false;
            bool bBorrowed = false;

            string outofBarcodes    = "";
            string borrowedBarcodes = "";

            RestChannel channel = this._mainForm.GetChannel();

            try
            {
                List <ReservationItem> items = DbManager.Instance.GetItemsByNoteId(noteId);
                foreach (ReservationItem item in items)
                {
                    GetRecordResponse response = channel.GetRecord(item.RecPath);

                    //记录 '0000000078' 在库中不存在
                    if (response.GetRecordResult.Value == -1)
                    {
                        bBorrowed = true;
                        if (borrowedBarcodes != "")
                        {
                            borrowedBarcodes += ",";
                        }
                        borrowedBarcodes += "'" + item.ItemBarcode + "'";
                        continue;
                    }


                    string xml = response.strXml;

                    XmlDocument dom = new XmlDocument();
                    dom.LoadXml(xml);
                    string state = DomUtil.GetElementText(dom.DocumentElement, "state");
                    if (state == PrepForm.C_State_outof)
                    {
                        bOutof = true;

                        if (outofBarcodes != "")
                        {
                            outofBarcodes += ",";
                        }
                        outofBarcodes += "'" + item.ItemBarcode + "'";
                        continue;
                    }
                }

                if (bOutof == true)
                {
                    if (info != "")
                    {
                        info += "\r\n";
                    }

                    info += "册条码为" + outofBarcodes + "的图书预约到书状态在服务器端已变为outof,原因可能是读者放弃取书或者已经超过了保留期限。";
                }

                if (bBorrowed == true)
                {
                    if (info != "")
                    {
                        info += "\r\n";
                    }

                    info += "册条码为" + borrowedBarcodes + "的预约到书记录在服务器端不存在,原因是读者已经办理了借书。";
                }

                if (string.IsNullOrEmpty(info) == false)
                {
                    info += "\r\n" + "请撤消备书单,重新处理。";
                }
            }
            finally
            {
                this._mainForm.ReturnChannel(channel);
            }

            if (bOutof == true || bBorrowed == true)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Esempio n. 21
0
        // 获得日志文件中记录的总数
        // parameters:
        //      strDate 日志文件的日期,8 字符
        // return:
        //      -2  此类型的日志在 dp2library 端尚未启用
        //      -1  出错
        //      0   日志文件不存在,或者记录数为 0
        //      >0  记录数
        public static long GetOperLogCount(
            Stop stop,
            RestChannel 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);
        }
Esempio n. 22
0
        // 获得一个日志文件的尺寸
        // return:
        //      -2  此类型的日志尚未启用
        //      -1  error
        //      0   file not found
        //      1   found
        static int GetFileSize(
            Stop stop,
            //LibraryChannel channel,
            RestChannel 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);
        }
Esempio n. 23
0
        private SecucardConnect(ClientConfiguration configuration)
        {
            _configuration = configuration;

            // Setup Trace if directory is there
            if (!string.IsNullOrWhiteSpace(configuration.TraceDir))
            {
                string dir = configuration.TraceDir;
                if (!Path.IsPathRooted(configuration.TraceDir))
                {
                    dir = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location),
                                       configuration.TraceDir);
                }
                if (!Directory.Exists(Path.GetDirectoryName(dir)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(dir));
                }
                var listener = new SecucardTraceListener(dir)
                {
                    Name = "SecucardTraceListener"
                };
                System.Diagnostics.Trace.Listeners.Add(listener);
                SecucardTrace.EmptyLine();
            }

            // Check if Data storage was passed. Otherwise create memory storage
            if (configuration.DataStorage == null)
            {
                configuration.DataStorage = new MemoryDataStorage();
            }

            var context = new ClientContext
            {
                AppId = _configuration.AppId,
            };


            _context = context;

            var authConfig  = _configuration.AuthConfig;
            var stompConfig = _configuration.StompConfig;
            var restConfig  = _configuration.RestConfig;

            SecucardTrace.Info(string.Format("Creating client with configuration: {0}", configuration));

            if (_configuration.ClientAuthDetails == null)
            {
                //TODO:
            }

            context.DefaultChannel = _configuration.DefaultChannel;

            var restChannel = new RestChannel(restConfig, context);

            context.Channels.Add(ChannelOptions.ChannelRest, restChannel);


            if (_configuration.StompEnabled)
            {
                var stompChannel = new StompChannel(stompConfig, context);
                context.Channels.Add(ChannelOptions.ChannelStomp, stompChannel);
                stompChannel.StompEventArrivedEvent += context.EventDispatcher.StompMessageArrivedEvent;
            }

            var restAuth = new RestAuth(authConfig)
            {
                UserAgentInfo =
                    "secucardconnect-net-" + Version + "/net:" + Environment.OSVersion + " " + Environment.Version
            };

            context.TokenManager = new TokenManager(authConfig, _configuration.ClientAuthDetails, restAuth);
            context.TokenManager.TokenManagerStatusUpdateEvent += TokenManagerOnTokenManagerStatusUpdateEvent;


            // Prepare resource downloader
            ResourceDownloader.Get().Cache       = configuration.DataStorage;
            ResourceDownloader.Get().RestChannel = restChannel;


            _serviceDict = ServiceFactory.CreateServices(context);
            WireServiceInstances();
        }
Esempio n. 24
0
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button_login_Click(object sender, EventArgs e)
        {
            MainForm mainForm = null;

            if (this.Owner is MainForm)
            {
                mainForm = this.Owner as MainForm;
            }

            Debug.Assert(mainForm != null, "登录对话框的父窗口为空");

            // 登录地址必须为rest.开头的地址
            string url = this.textBox_libraryUrl.Text;

            if (url.Length < 5 ||
                (url.Substring(0, 5).ToLower() != "rest."))
            {
                MessageBox.Show(this, "服务器仅支持rest.开头的地址,请重新输入服务器地址或咨询管理员");
                return;
            }


            RestChannel channel = mainForm.GetChannel();

            try
            {
                string pureUrl = this._mainFrom.GetPurlUrl(this.LibraryUrl);// LibraryUrl.Substring(5);
                channel.Url = pureUrl;
                string strParameters = "type=worker"
                                       + ",client=dp2mini|" + ClientInfo.ClientVersion; //Program.ClientVersion;
                LoginResponse response = channel.Login(Username,
                                                       Password,
                                                       strParameters);
                if (response.LoginResult.Value == -1 || response.LoginResult.Value == 0)
                {
                    MessageBox.Show(this, response.LoginResult.ErrorInfo);
                    return;
                }

                // 保存配置信息
                SettingInfo info = new SettingInfo();
                info.Url            = LibraryUrl;
                info.UserName       = Username;
                info.Password       = Password;
                info.IsSavePassword = IsSavePassword;
                this._mainFrom.SaveSettings(info);

                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message);
                this.DialogResult = DialogResult.Cancel;
                this.Close();
            }
            finally
            {
                mainForm.ReturnChannel(channel);
            }
        }
Esempio n. 25
0
        public Command AddCmd(Command item)
        {
            Debug.Assert(item != null, "AddCmd传进的item不能为空。");
            Debug.Assert(String.IsNullOrEmpty(item.type) == false, "命令类型不能为空。");
            string strError = "";

            // 补充命令信息
            item.id          = this.cmdList.Count + 1;
            item.description = item.readerBarcode + "-" + item.type + "-" + item.itemBarcode;
            item.operTime    = DateTimeToString(DateTime.Now);
            item.typeString  = Command.getTypeString(item.type);

            if (item.type == Command.C_Command_Borrow ||
                item.type == Command.C_Command_VerifyRenew ||
                item.type == Command.C_Command_VerifyReturn)
            {
                if (String.IsNullOrEmpty(item.readerBarcode) == true)
                {
                    item.state      = -1;
                    item.resultInfo = "读者证条码号不能为空。";
                }
            }

            if (String.IsNullOrEmpty(item.itemBarcode) == true)
            {
                item.state      = -1;
                item.resultInfo = "册条码号不能为空。";
            }

            // 执行这个命令
            RestChannel channel = ilovelibraryServer.Instance.ChannelPool.GetChannel(ilovelibraryServer.Instance.dp2LibraryUrl, this.UserName);

            //2020/2/20 channel类不包括密码和参数,所以改在本地表中
            ilovelibraryServer.Instance._sessionTable[this.UserName] = this;
            //channel.Password = this.Password;
            //channel.Parameters = this.Parameters;
            try
            {
                long   lRet = -1;
                string strOutputReaderBarcode = "";
                string strReaderXml           = "";
                // 借书或续借
                if (item.type == Command.C_Command_Borrow ||
                    item.type == Command.C_Command_Renew ||
                    item.type == Command.C_Command_VerifyRenew)
                {
                    bool bRenew = false;
                    if (item.type == Command.C_Command_Renew ||
                        item.type == Command.C_Command_VerifyRenew)
                    {
                        bRenew = true;
                    }
                    DigitalPlatform.LibraryRestClient.BorrowInfo borrowInfo = null;
                    lRet = channel.Borrow(bRenew,
                                          item.readerBarcode,
                                          item.itemBarcode,
                                          out strOutputReaderBarcode,
                                          out strReaderXml,
                                          out borrowInfo,
                                          out strError);
                }
                else if (item.type == Command.C_Command_Return ||
                         item.type == Command.C_Command_VerifyReturn ||
                         item.type == Command.C_Command_Read)
                {
                    string strAction = "";
                    if (item.type == Command.C_Command_Return ||
                        item.type == Command.C_Command_VerifyReturn)
                    {
                        strAction = "return";
                    }
                    else
                    {
                        strAction = "read";
                    }


                    ReturnInfo returnInfo = null;
                    lRet = channel.Return(strAction,
                                          item.readerBarcode,
                                          item.itemBarcode,
                                          out strOutputReaderBarcode,
                                          out strReaderXml,
                                          out returnInfo,
                                          out strError);
                }



                // 设上实际的读者证条码
                item.readerBarcode = strOutputReaderBarcode;

                // 读者重复
                if (lRet == 2)
                {
                    item.state      = (int)lRet;
                    item.resultInfo = item.typeString + "书操作失败:" + strError;

                    //直接返回了,因为不会加到操作历史里
                    return(item);
                }

                // 册重复
                if (lRet == 3)
                {
                    item.state      = (int)lRet;
                    item.resultInfo = strError;//item.typeString + "书操作失败:" + strError;

                    //直接返回了,因为不会加到操作历史里
                    return(item);
                }


                if (lRet == -1)
                {
                    item.state      = -1;
                    item.resultInfo = item.typeString + "书操作失败:" + strError;
                }
                else if (lRet == 0)
                {
                    item.state      = 0;
                    item.resultInfo = item.typeString + "书操作成功。";
                }
                else
                {
                    item.state      = 1;
                    item.resultInfo = strError;
                }

                // 检索是否与前面同一个读者,不加要加线
                if (this.cmdList.Count > 0)
                {
                    Command firstCmd = this.cmdList[0];
                    if (firstCmd.readerBarcode != item.readerBarcode &&
                        String.IsNullOrEmpty(item.readerBarcode) == false &&
                        String.IsNullOrEmpty(firstCmd.readerBarcode) == false)
                    {
                        item.isAddLine = 1;
                    }
                }
                // 设链接地址
                if (item.itemBarcode.Contains("@biblioRecPath") == false && string.IsNullOrEmpty(ilovelibraryServer.Instance.dp2OpacUrl) == false)
                {
                    item.itemBarcodeUrl = ilovelibraryServer.Instance.dp2OpacUrl + "/book.aspx?barcode=" + HttpUtility.UrlEncode(item.itemBarcode) + "&borrower=" + item.readerBarcode;

                    item.itemBarcodeUrl = "<a href='" + item.itemBarcodeUrl + "' target='_blank'>" + item.itemBarcode + "</a>";
                }
                else
                {
                    item.itemBarcodeUrl = item.itemBarcode;
                }
                // 解析读者信息
                //PatronResult patronResult = ilovelibraryServer.Instance.GetPatronInfo(this, item.readerBarcode);
                //item.patronResult = patronResult;

                PatronResult patronResult = new PatronResult();
                patronResult.patron    = null;
                patronResult.apiResult = new ApiResult();
                if (String.IsNullOrEmpty(strReaderXml) == true)
                {
                    patronResult.apiResult.errorCode = -1;
                    patronResult.apiResult.errorInfo = "dp2服务端操作api返回的读者xml为空。";
                }
                else
                {
                    //解析返回的读者xml
                    ilovelibraryServer.Instance.ParseReaderXml(strReaderXml, patronResult);
                }
                item.patronResult = patronResult;


                // 加到集合里
                this.cmdList.Insert(0, item);

                return(item);
            }
            finally
            {
                ilovelibraryServer.Instance.ChannelPool.ReturnChannel(channel);
            }
        }