Ejemplo n.º 1
0
        // 执行一些后台管理任务
        public static void BackgroundWork()
        {
            List <Task> tasks = new List <Task>();

            bool bOutputBegin = false;

            Instance first_instance = null;

            if (_instances.Count > 0)
            {
                first_instance = _instances[0];
            }
            foreach (Instance instance in _instances)
            {
                // 向 dp2mserver 发送心跳消息
                // instance.SendHeartBeat();

                bool bNeedCheck = NeedCheck(instance);

                if (bNeedCheck)
                {
                    instance.WriteErrorLog("<<< BackgroundWork 开始一轮处理\r\n状态:\r\n" + instance.GetDebugState());
                    bOutputBegin = true;
                }

                string strError = "";
                // 利用 dp2library API 获取一些配置信息
                if (string.IsNullOrEmpty(instance.dp2library.LibraryUID) == true)
                {
                    int nRet = instance.MessageConnection.GetConfigInfo(out strError);
                    if (nRet == -1)
                    {
                        // Program.WriteWindowsLog(strError);
                        instance.WriteErrorLog("获得 dp2library 配置时出错: " + strError);
                    }
                    else
                    {
#if NO
                        if (instance.MessageConnection.IsConnected == false)
                        {
                            tasks.Add(instance.BeginConnectTask()); // 2016/10/13 以前没有 if 语句,那样就容易导致重复 BeginConnect()
                        }
#endif
                        if (bNeedCheck)
                        {
                            Check(instance, tasks);
                        }
                        else
                        {
                            Echo(instance, false);
                        }
                    }
                }
                else
                {
#if NO
                    if (instance.MessageConnection.IsConnected == false)
                    {
                        // instance.BeginConnnect();
                        tasks.Add(instance.BeginConnectTask());
                    }
                    else
                    {
                        // TODO: 验证一次请求
                    }
#endif

                    if (bNeedCheck)
                    {
                        Check(instance, tasks);
                    }
                    else
                    {
                        Echo(instance, false);
                    }

                    // 每隔二十分钟清理一次闲置的 dp2library 通道
                    if (DateTime.Now - _lastCleanTime >= TimeSpan.FromMinutes(20))
                    {
                        try
                        {
                            instance.MessageConnection.CleanLibraryChannel();
                        }
                        catch (Exception ex)
                        {
                            instance.WriteErrorLog("CleanLibraryChannel() 异常: " + ExceptionUtil.GetExceptionText(ex));
                        }
                        _lastCleanTime = DateTime.Now;
                    }
                }
            }

            // 阻塞,直到全部任务完成。避免 BeginConnect() 函数被重叠调用
            if (tasks.Count > 0)
            {
                // test 这一句可以用来制造死锁测试场景
                // Thread.Sleep(60 * 60 * 1000);

                if (first_instance != null)
                {
                    first_instance.WriteErrorLog("-- BackgroundWork - 等待 " + tasks.Count + " 个 Connect 任务完成");
                }

                Task.WaitAll(tasks.ToArray());

                if (first_instance != null)
                {
                    first_instance.WriteErrorLog("-- BackgroundWork - " + tasks.Count + " 个 Connect 任务已经完成");
                }
            }

            if (bOutputBegin == true && first_instance != null)
            {
                first_instance.WriteErrorLog(">>> BackgroundWork 结束一轮处理\r\n");
            }
        }
Ejemplo n.º 2
0
        // 获得资源。包装版本 -- 返回字符串版本、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);
        }
Ejemplo n.º 3
0
        public ServiceResult <object> ShowRow(BusinessParam bp)
        {
            var  methodName = $".{new StackTrace().GetFrame(1).GetMethod().Name}";
            long entityId   = 0;

            foreach (var where in bp.Clause.Wheres.Where(where =>
                                                         where.Key.Equals("entityId") && where.Value != null && !where.Value.Equals("")))
            {
                entityId = long.Parse(where.Value);
            }

            try
            {
                if (entityId == 0)
                {
                    return(ExceptionUtil.ExceptionHandler("شناسه مورد نظر یافت نشد",
                                                          ClassDetails[0].Facade + methodName,
                                                          bp.UserInfo));
                }
                var tableNameComboval = Util.GetSqlServerTableName <DataLayer.Model.Core.ComboVal.ComboVal>();
                var tableNameUser     = Util.GetSqlServerTableName <Users>();
                var queryString       = "select main.EntityId,main.Name,main.Value,main.AdminOnly,main.Active," +
                                        "main.Created,main.Updated,main.Code,combo.EntityId,combo.Name,created.EntityId," +
                                        "created.Username,updated.EntityId,updated.Username from (" +
                                        "select EntityId, Name, Value, ParentId, AdminOnly, Active, Created, Updated, Code, CreateBy, UpdateBy from " +
                                        tableNameComboval + ") main " +
                                        "left join(select EntityId, Name from " + tableNameComboval +
                                        ") combo on combo.EntityId = main.ParentId " +
                                        "left join(select EntityId, Username from " + tableNameUser +
                                        ") created on created.EntityId = main.CreateBy " +
                                        "left join(select EntityId, Username from " + tableNameUser +
                                        ") updated on updated.EntityId = main.UpdateBy " +
                                        "where main.EntityId = " + entityId;
                using (var unitOfWork = new UnitOfWork())
                {
                    var comboVal = unitOfWork.ComboVal.CreateNativeQuery(queryString, x => new ComboValDto
                    {
                        EntityId  = Convert.ToInt64(x[0].ToString()),
                        Name      = x[1]?.ToString(),
                        Value     = x[2]?.ToString(),
                        AdminOnly = Convert.ToBoolean(x[3]?.ToString()),
                        Active    = Convert.ToBoolean(x[4]?.ToString()),
                        Created   = Util.GetTimeStamp(string.IsNullOrEmpty(x[5].ToString())
                            ? (DateTime?)null
                            : Convert.ToDateTime(x[5]?.ToString())),
                        Updated = Util.GetTimeStamp(string.IsNullOrEmpty(x[6].ToString())
                            ? (DateTime?)null
                            : Convert.ToDateTime(x[6]?.ToString())),
                        Code   = x[7]?.ToString(),
                        Parent = string.IsNullOrEmpty(x[8].ToString())
                            ? null
                            : new ComboValDto {
                            EntityId = Convert.ToInt64(x[8].ToString()), Name = x[9]?.ToString()
                        },
                        CreatedBy = string.IsNullOrEmpty(x[10].ToString())
                            ? null
                            : new UserDto {
                            EntityId = Convert.ToInt64(x[10].ToString()), Username = x[11]?.ToString()
                        },
                        UpdatedBy = string.IsNullOrEmpty(x[12].ToString())
                            ? null
                            : new UserDto {
                            EntityId = Convert.ToInt64(x[12].ToString()), Username = x[13]?.ToString()
                        }
                    });

                    return(comboVal == null
                        ? new ServiceResult <object>(Enumerator.ErrorCode.NotFound, "رکورد یافت نشد")
                        : new ServiceResult <object>(comboVal[0], 1));
                }
            }
            catch (Exception e)
            {
                return(ExceptionUtil.ExceptionHandler(e, ClassDetails[0].Facade + methodName, bp.UserInfo));
            }
        }
Ejemplo n.º 4
0
        // 填充全部内容
        int Fill(LibraryChannel channel_param,
                 TreeNode node,
                 out string strError)
        {
            strError = "";

            TreeNodeCollection children = null;

            if (node == null)
            {
                children = this.Nodes;
            }
            else
            {
                children = node.Nodes;
            }

            if (string.IsNullOrEmpty(this.Lang))
            {
                this.Lang = "zh";
            }

            LibraryChannel channel     = null;
            TimeSpan       old_timeout = new TimeSpan(0);

            if (channel_param != null)
            {
                channel = channel_param;
            }
            else
            {
                channel = this.CallGetChannel(true);

                old_timeout     = channel.Timeout;
                channel.Timeout = new TimeSpan(0, 5, 0);
            }

            bool restoreLoading = IsLoading(node);

            try
            {
                string start_path = GetNodePath(node);

                {
                    DirItemLoader loader = new DirItemLoader(channel,
                                                             null,
                                                             start_path,
                                                             "",
                                                             this.Lang);

                    children.Clear();

                    foreach (ResInfoItem item in loader)
                    {
                        // 2017/9/23
                        if (string.IsNullOrEmpty(item.Name))
                        {
                            continue;
                        }

                        TreeNode nodeNew = new TreeNode(item.Name, item.Type, item.Type);

                        nodeNew.Tag = item;
                        if (item.HasChildren)
                        {
                            SetLoading(nodeNew);
                        }

                        if (EnabledIndices != null &&
                            StringUtil.IsInList(nodeNew.ImageIndex, EnabledIndices) == false)
                        {
                            nodeNew.ForeColor = ControlPaint.LightLight(nodeNew.ForeColor);
                        }

                        if (HideIndices != null &&
                            StringUtil.IsInList(nodeNew.ImageIndex, HideIndices) == true)
                        {
                            continue;
                        }

                        children.Add(nodeNew);
                    }
                }

                // 在根级追加 '!' 下的 dp2library 本地文件或目录
                if (string.IsNullOrEmpty(start_path))
                {
                    ResInfoItem item = new ResInfoItem();
                    item.Name        = "!";
                    item.Type        = 4;
                    item.HasChildren = true;

                    TreeNode nodeNew = new TreeNode(item.Name, item.Type, item.Type);

                    nodeNew.Tag = item;
                    if (item.HasChildren)
                    {
                        SetLoading(nodeNew);
                    }

                    if (EnabledIndices != null &&
                        StringUtil.IsInList(nodeNew.ImageIndex, EnabledIndices) == false)
                    {
                        nodeNew.ForeColor = ControlPaint.LightLight(nodeNew.ForeColor);
                    }

                    if (HideIndices != null &&
                        StringUtil.IsInList(nodeNew.ImageIndex, HideIndices) == true)
                    {
                    }
                    else
                    {
                        children.Add(nodeNew);
                    }
                }

                restoreLoading = false;  // 防止 finally 复原
                return(0);
            }
            catch (ChannelException ex)
            {
                strError = ex.Message;
                return(-1);

#if NO
                if (ex.ErrorCode == ErrorCode.AccessDenied)
                {
                    strError = ex.Message;
                    return(-1);
                }
                strError = "Fill() 过程出现异常: " + ExceptionUtil.GetExceptionText(ex);
                return(-1);
#endif
            }
            catch (Exception ex)
            {
                strError = "Fill() 过程出现异常: " + ExceptionUtil.GetExceptionText(ex);
                return(-1);
            }
            finally
            {
                if (channel_param == null)
                {
                    channel.Timeout = old_timeout;

                    this.CallReturnChannel(channel, true);
                }

                if (restoreLoading)
                {
                    SetLoading(node);
                    if (node != null)
                    {
                        node.Collapse();
                    }
                }
            }
        }
Ejemplo n.º 5
0
        // 写入实例的错误日志文件
        public static void WriteErrorLog(string strText)
        {
            if (ConsoleMode == true)
            {
                Console.WriteLine(strText);
            }

            if (_errorLogError == true || // 先前写入实例的日志文件发生过错误,所以改为写入 Windows 日志。会加上实例名前缀字符串
                string.IsNullOrEmpty(LogDir) == true)
            {
                WriteWindowsLog(strText, EventLogEntryType.Error);
            }
            else
            {
                try
                {
                    _writeErrorLog(strText);
                }
                catch (Exception ex)
                {
                    WriteWindowsLog("因为原本要写入日志文件的操作发生异常, 所以不得不改为写入 Windows 日志(见后一条)。异常信息如下:'" + ExceptionUtil.GetDebugText(ex) + "'", EventLogEntryType.Error);
                    WriteWindowsLog(strText, EventLogEntryType.Error);
                }
            }
        }
Ejemplo n.º 6
0
 public void Warn(Exception exception)
 {
     Console.WriteLine("[WARN] " + ExceptionUtil.GetDetailMessage(exception));
 }
Ejemplo n.º 7
0
        // 初始化 dp2circulation_marc_autogen.cs 的 Assembly,并new DetailHost对象
        // return:
        //      -1  error
        //      0   没有重新初始化Assembly,而是直接用以前Cache的Assembly
        //      1   重新(或者首次)初始化了Assembly
        public int InitialAutogenAssembly(
            string strBiblioRecPath,
            out string strError)
        {
            strError = "";
            int nRet = 0;

#if NO
            // 2014/7/14
            if (string.IsNullOrEmpty(strBiblioRecPath) == true)
            {
                strBiblioRecPath = this.BiblioRecPath;
            }
#endif
            string strAutogenDataCfgFilename = "";

            string strFormat = "";
            if (StringUtil.HasHead(strBiblioRecPath, "format:") == true)
            {
                strFormat = strBiblioRecPath.Substring("format:".Length);
                strAutogenDataCfgFilename = Path.Combine(Program.MainForm.DataDir, strFormat + "_cfgs/" + this.ScriptFileName);
            }
            else
            {
                // 库名部分路径
                string strBiblioDbName = Global.GetDbName(strBiblioRecPath);

                if (string.IsNullOrEmpty(strBiblioDbName) == true)
                {
                    return(0);
                }

                strAutogenDataCfgFilename = strBiblioDbName + "/cfgs/" + this.ScriptFileName;
            }

            bool bAssemblyReloaded = false;

            // 如果必要,重新准备Assembly
            if (m_autogenDataAssembly == null ||
                m_strAutogenDataCfgFilename != strAutogenDataCfgFilename)
            {
                this.m_autogenDataAssembly = Program.MainForm.AssemblyCache.FindObject(strAutogenDataCfgFilename);
                this.m_detailHostObj       = null;

                // 如果Cache中没有现成的Assembly
                if (this.m_autogenDataAssembly == null)
                {
                    string strCode = "";
                    string strRef  = "";

#if NO
                    byte[] baCfgOutputTimestamp = null;
                    // return:
                    //      -1  error
                    //      0   not found
                    //      1   found
                    nRet = this._myForm.GetCfgFileContent(strAutogenDataCfgFilename,
                                                          out strCode,
                                                          out baCfgOutputTimestamp,
                                                          out strError);
                    if (nRet == -1)
                    {
                        goto ERROR1;
                    }
                    if (nRet == 0)
                    {
                        IDetailHost host = null;

                        if (this.DetailHostType != null)
                        {
                            host = (IDetailHost)DetailHostType.InvokeMember(null,
                                                                            BindingFlags.DeclaredOnly |
                                                                            BindingFlags.Public | BindingFlags.NonPublic |
                                                                            BindingFlags.Instance | BindingFlags.CreateInstance, null, null,
                                                                            null);
                        }
                        else
                        {
                            host = new DetailHost();
                        }

                        host.Assembly        = null;
                        host.Form            = this._myForm;
                        host.DetailWindow    = this._myForm as IBiblioItemsWindow;
                        this.m_detailHostObj = host;

                        m_strAutogenDataCfgFilename = strAutogenDataCfgFilename;

                        this.m_autogenDataAssembly = Assembly.GetAssembly(this.GetType());  // 充数

                        return(1);
                    }

                    string strCfgFilePath = strAutogenDataCfgFilename + ".ref"; // strBiblioDbName + "/cfgs/" + this.ScriptFileName + ".ref";
                    nRet = this._myForm.GetCfgFileContent(strCfgFilePath,
                                                          out strRef,
                                                          out baCfgOutputTimestamp,
                                                          out strError);
                    if (nRet == -1 /*|| nRet == 0*/)    // .ref 文件可以没有
                    {
                        goto ERROR1;
                    }
#endif
                    if (string.IsNullOrEmpty(strFormat) == false)
                    {
                        nRet = GetCodeFromLocal(
                            strAutogenDataCfgFilename,
                            out strCode,
                            out strRef,
                            out strError);
                    }
                    else
                    {
                        // 从服务器获得两个配置文件的内容
                        nRet = GetCode(
                            strAutogenDataCfgFilename,
                            out strCode,
                            out strRef,
                            out strError);
                    }
                    if (nRet == -1)
                    {
                        goto ERROR1;
                    }
                    if (nRet == 1)
                    {
                        return(1);
                    }

                    try
                    {
                        // 准备Assembly
                        Assembly assembly = null;
                        nRet = GetCsScriptAssembly(
                            strCode,
                            strRef,
                            out assembly,
                            out strError);
                        if (nRet == -1)
                        {
                            strError = "编译脚本文件 '" + strAutogenDataCfgFilename + "' 时出错:" + strError;
                            goto ERROR1;
                        }
                        // 记忆到缓存
                        Program.MainForm.AssemblyCache.SetObject(strAutogenDataCfgFilename, assembly);

                        this.m_autogenDataAssembly = assembly;

                        bAssemblyReloaded = true;
                    }
                    catch (Exception ex)
                    {
                        strError = "准备脚本代码过程中发生异常: \r\n" + ExceptionUtil.GetDebugText(ex);
                        goto ERROR1;
                    }
                }

                bAssemblyReloaded = true;

                m_strAutogenDataCfgFilename = strAutogenDataCfgFilename;

                // 至此,Assembly已经纯备好了
                Debug.Assert(this.m_autogenDataAssembly != null, "");
            }

            Debug.Assert(this.m_autogenDataAssembly != null, "");

            // 准备 host 对象
            if (this.m_detailHostObj == null ||
                bAssemblyReloaded == true)
            {
                try
                {
                    IDetailHost host = null;
                    nRet = NewHostObject(
                        out host,
                        out strError);
                    if (nRet == -1)
                    {
                        strError = "准备脚本文件 '" + m_strAutogenDataCfgFilename + "' 时出错:" + strError;
                        goto ERROR1;
                    }

                    this.m_detailHostObj = host;
                }
                catch (Exception ex)
                {
                    strError = "准备脚本代码过程中发生异常: \r\n" + ExceptionUtil.GetDebugText(ex);
                    goto ERROR1;
                }
            }

            Debug.Assert(this.m_detailHostObj != null, "");

            if (bAssemblyReloaded == true)
            {
                return(1);
            }
            return(0);

ERROR1:
            return(-1);
        }
        /// <summary>
        /// Sends an operation to the server while observing it's durability requirements
        /// </summary>
        /// <param name="operation">A binary memcached operation - must be a mutation operation.</param>
        /// <param name="deletion">True if mutation is a deletion.</param>
        /// <param name="replicateTo">The durability requirement for replication.</param>
        /// <param name="persistTo">The durability requirement for persistence.</param>
        /// <returns>The <see cref="IOperationResult"/> with it's <see cref="Durability"/> status.</returns>
        /// <exception cref="ServiceNotSupportedException">The cluster does not support Data services.</exception>
        public override IOperationResult SendWithDurability(IOperation operation, bool deletion, ReplicateTo replicateTo, PersistTo persistTo)
        {
            IOperationResult result;

            try
            {
                //Is the cluster configured for Data services?
                if (!ConfigInfo.IsDataCapable)
                {
                    throw new ServiceNotSupportedException(
                              ExceptionUtil.GetMessage(ExceptionUtil.ServiceNotSupportedMsg, "Data"));
                }

                result = SendWithRetry(operation);
                if (result.Success)
                {
                    var config = ConfigInfo.ClientConfig.BucketConfigs[BucketName];

                    if (ConfigInfo.SupportsEnhancedDurability)
                    {
                        var seqnoObserver = new KeySeqnoObserver(operation.Key, Pending, ConfigInfo, ClusterController,
                                                                 config.ObserveInterval, (uint)config.ObserveTimeout);

                        var observed = seqnoObserver.Observe(result.Token, replicateTo, persistTo);
                        result.Durability = observed ? Durability.Satisfied : Durability.NotSatisfied;
                    }
                    else
                    {
                        var observer = new KeyObserver(Pending, ConfigInfo, ClusterController, config.ObserveInterval, config.ObserveTimeout);
                        var observed = observer.Observe(operation.Key, result.Cas, deletion, replicateTo, persistTo);
                        result.Durability = observed ? Durability.Satisfied : Durability.NotSatisfied;
                    }
                }
                else
                {
                    result.Durability = Durability.NotSatisfied;
                }
            }
            catch (ReplicaNotConfiguredException e)
            {
                result = new OperationResult
                {
                    Id         = operation.Key,
                    Exception  = e,
                    Status     = ResponseStatus.NoReplicasFound,
                    Durability = Durability.NotSatisfied,
                    OpCode     = operation.OperationCode
                };
            }
            catch (DocumentMutationLostException e)
            {
                result = new OperationResult
                {
                    Id         = operation.Key,
                    Exception  = e,
                    Status     = ResponseStatus.DocumentMutationLost,
                    Durability = Durability.NotSatisfied,
                    OpCode     = operation.OperationCode
                };
            }
            catch (Exception e)
            {
                result = new OperationResult
                {
                    Id        = operation.Key,
                    Exception = e,
                    Status    = ResponseStatus.ClientFailure,
                    OpCode    = operation.OperationCode
                };
            }
            return(result);
        }
        /// <summary>
        /// Sends an operation to the server while observing it's durability requirements using async/await
        /// </summary>
        /// <typeparam name="T">The value for T.</typeparam>
        /// <param name="operation">A binary memcached operation - must be a mutation operation.</param>
        /// <param name="deletion">True if mutation is a deletion.</param>
        /// <param name="replicateTo">The durability requirement for replication.</param>
        /// <param name="persistTo">The durability requirement for persistence.</param>
        /// <returns>The <see cref="Task{IOperationResult}"/> to be awaited on with it's <see cref="Durability"/> status.</returns>
        /// <exception cref="ServiceNotSupportedException">The cluster does not support Data services.</exception>
        public override async Task <IOperationResult <T> > SendWithDurabilityAsync <T>(IOperation <T> operation, bool deletion, ReplicateTo replicateTo, PersistTo persistTo)
        {
            IOperationResult <T> result;

            try
            {
                //Is the cluster configured for Data services?
                if (!ConfigInfo.IsDataCapable)
                {
                    throw new ServiceNotSupportedException(
                              ExceptionUtil.GetMessage(ExceptionUtil.ServiceNotSupportedMsg, "Data"));
                }

                result = await SendWithRetryAsync(operation).ContinueOnAnyContext();

                if (result.Success)
                {
                    var config = ConfigInfo.ClientConfig.BucketConfigs[BucketName];
                    using (var cts = new CancellationTokenSource(config.ObserveTimeout))
                    {
                        if (ConfigInfo.SupportsEnhancedDurability)
                        {
                            var seqnoObserver = new KeySeqnoObserver(operation.Key, Pending, ConfigInfo,
                                                                     ClusterController,
                                                                     config.ObserveInterval, (uint)config.ObserveTimeout);

                            var observed = await seqnoObserver.ObserveAsync(result.Token, replicateTo, persistTo, cts)
                                           .ContinueOnAnyContext();

                            result.Durability = observed ? Durability.Satisfied : Durability.NotSatisfied;
                            ((OperationResult <T>)result).Success = result.Durability == Durability.Satisfied;
                        }
                        else
                        {
                            var observer = new KeyObserver(Pending, ConfigInfo, ClusterController,
                                                           config.ObserveInterval, config.ObserveTimeout);

                            var observed = await observer.ObserveAsync(operation.Key, result.Cas,
                                                                       deletion, replicateTo, persistTo, cts).ContinueOnAnyContext();

                            result.Durability = observed ? Durability.Satisfied : Durability.NotSatisfied;
                            ((OperationResult <T>)result).Success = result.Durability == Durability.Satisfied;
                        }
                    }
                }
                else
                {
                    result.Durability = Durability.NotSatisfied;
                    ((OperationResult <T>)result).Success = result.Durability == Durability.Satisfied;
                }
            }
            catch (TaskCanceledException e)
            {
                result = new OperationResult <T>
                {
                    Id         = operation.Key,
                    Exception  = e,
                    Status     = ResponseStatus.OperationTimeout,
                    Durability = Durability.NotSatisfied,
                    Success    = false
                };
            }
            catch (ReplicaNotConfiguredException e)
            {
                result = new OperationResult <T>
                {
                    Id         = operation.Key,
                    Exception  = e,
                    Status     = ResponseStatus.NoReplicasFound,
                    Durability = Durability.NotSatisfied,
                    Success    = false
                };
            }
            catch (DocumentMutationLostException e)
            {
                result = new OperationResult <T>
                {
                    Id         = operation.Key,
                    Exception  = e,
                    Status     = ResponseStatus.DocumentMutationLost,
                    Durability = Durability.NotSatisfied,
                    Success    = false
                };
            }
            catch (DocumentMutationException e)
            {
                result = new OperationResult <T>
                {
                    Id         = operation.Key,
                    Exception  = e,
                    Status     = ResponseStatus.DocumentMutationDetected,
                    Durability = Durability.NotSatisfied,
                    Success    = false
                };
            }
            catch (Exception e)
            {
                result = new OperationResult <T>
                {
                    Id        = operation.Key,
                    Exception = e,
                    Status    = ResponseStatus.ClientFailure,
                    Success   = false
                };
            }
            return(result);
        }
        private void btnLuu_Click(object sender, EventArgs e)
        {
            try
            {
                MonHoc mh = new MonHoc();
                if (!string.IsNullOrEmpty(txtMaMH.Text))
                {
                    mh.MaMH = txtMaMH.Text.Trim();
                }
                else
                {
                    MsgboxUtil.Exclamation("Mã môn học không được để trống");
                    txtMaMH.Focus();
                    return;
                }
                if (!string.IsNullOrEmpty(txtTenMH.Text))
                {
                    mh.TenMH = txtTenMH.Text.Trim();
                }
                else
                {
                    MsgboxUtil.Exclamation("Tên môn học không được để trống");
                    txtTenMH.Focus();
                    return;
                }
                if (numSTC.Value > 0)
                {
                    mh.STC = (byte)numSTC.Value;
                }
                else
                {
                    MsgboxUtil.Exclamation("Số tín chỉ không thể nhỏ hơn 0");
                    numSTC.Focus();
                    return;
                }

                if (numLyThuyet.Value > 0)
                {
                    mh.LyThuyet = (byte)numLyThuyet.Value;
                }
                else
                {
                    MsgboxUtil.Exclamation("Số tiết lý thuyết không thể nhỏ hơn 0");
                    numLyThuyet.Focus();
                    return;
                }

                if (numThucHanh.Value >= 0)
                {
                    mh.ThucHanh = (byte)numThucHanh.Value;
                }
                else
                {
                    MsgboxUtil.Exclamation("Số tiết thực hành không thể nhỏ hơn 0");
                    numThucHanh.Focus();
                    return;
                }
                MonHocBUS.Them(mh);
                StaticClass.LuuThayDoi();
                log.GhiFile("Thêm mới môn học: " + mh.MaMH);
                MsgboxUtil.Success("Thành công");
                btnHuy_Click(null, null);
            }
            catch (Exception ex)
            {
                ExceptionUtil.ThrowMsgBox(ex.Message);
            }
        }
Ejemplo n.º 11
0
    private void LoadOperationOrgTree()
    {
        Hashtable hashtable = new Hashtable();

        try
        {
            NavigateTree.Nodes.Clear();

            //机构类型 h 总公司;hd 总公司部门;b 分公司;bd 分公司部门;zgxmb 直管项目部;fgsxmb 分公司项目部

            ObjectQuery oq = new ObjectQuery();
            oq.AddCriterion(Expression.Eq("State", 1));

            Disjunction dis = new Disjunction();
            dis.Add(Expression.Eq("OperationType", "h"));
            dis.Add(Expression.Eq("OperationType", "b"));
            dis.Add(Expression.Eq("OperationType", "zgxmb"));
            dis.Add(Expression.Eq("OperationType", "fgsxmb"));
            //dis.Add(Expression.Eq("CategoryNodeType", VirtualMachine.Patterns.CategoryTreePattern.Domain.NodeType.RootNode));
            oq.AddCriterion(dis);

            oq.AddOrder(Order.Asc("Level"));
            oq.AddOrder(Order.Asc("OrderNo"));
            IList list = MGWBS.GWBSSrv.ObjectQuery(typeof(OperationOrg), oq);

            foreach (OperationOrg childNode in list)
            {
                if (childNode.State == 0)
                {
                    continue;
                }

                TreeNode tnTmp = new TreeNode();
                tnTmp.Text        = childNode.Name;
                tnTmp.Value       = childNode.Id;
                tnTmp.NavigateUrl = "/IRPWebClient/map/BaiduMap.aspx?ProjectId=" + childNode.Id + "&ProjectName=" + HttpUtility.UrlEncode(childNode.Name) + "&ProjectType=" + childNode.OperationType;

                if (childNode.Level == 2 && childNode.OperationType.ToLower() == "h")
                {
                    NavigateTree.Nodes.Add(tnTmp);
                    txtProjectId.Value = "ProjectId=" + childNode.Id;
                }
                else
                {
                    TreeNode tnp = null;
                    tnp = hashtable[childNode.ParentNode.Id.ToString()] as TreeNode;
                    if (tnp != null)
                    {
                        tnp.ChildNodes.Add(tnTmp);
                    }
                }
                hashtable.Add(tnTmp.Value, tnTmp);
            }
            if (list.Count > 0)
            {
                //this.NavigateTree.Nodes[0].Select();
                //this.tvwCategory.Nodes[0].Expand();
            }
        }
        catch (Exception e)
        {
            Response.Write("<script type='text/javascript'>alert('" + ExceptionUtil.ExceptionMessage(e) + "');</script>");
        }
    }
Ejemplo n.º 12
0
    protected void Page_Load(object sender, EventArgs e)
    {
        ///-----------------------------------------------------
        ///功    能: 儲存天然氣自評表答案
        ///說    明:
        /// * Request["cpid"]: 業者Guid
        ///-----------------------------------------------------

        XmlDocument xDoc = new XmlDocument();

        /// Transaction
        SqlConnection oConn = new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"].ToString());

        oConn.Open();
        SqlCommand oCmmd = new SqlCommand();

        oCmmd.Connection = oConn;
        SqlTransaction myTrans = oConn.BeginTransaction();

        oCmmd.Transaction = myTrans;
        try
        {
            #region 檢查登入資訊
            if (LogInfo.mGuid == "")
            {
                throw new Exception("請重新登入");
            }
            #endregion

            //string cpid = (string.IsNullOrEmpty(Request["cpid"])) ? LogInfo.companyGuid : Request["cpid"].ToString().Trim();
            string cpid = LogInfo.companyGuid;

            // for 3/16
            //if (LogInfo.competence == "01")
            //{
            //	switch (LogInfo.mGuid)
            //	{
            //		case "64BF9515-47C0-47A6-BC30-88C6EFD50D03":
            //			cpid = "A11B680E-4A42-45E0-BCE2-3B16679C0606";
            //			break;
            //		case "C80975D7-C35D-4A99-B784-5F2EFF2099C2":
            //                     cpid = "A11B680E-4A42-45E0-BCE2-3B16679C0606";
            //                     break;
            //                 case "39DF8B07-2F23-4D0E-8983-22AB7510DD3D":
            //                     cpid = "A11B680E-4A42-45E0-BCE2-3B16679C0606";
            //                     break;
            //                 case "B73B61B8-6CCF-4141-A858-9A8C4E403A9C":
            //                     cpid = "A11B680E-4A42-45E0-BCE2-3B16679C0606";
            //                     break;
            //             }
            //}
            //         else if (LogInfo.competence == "03")
            //         {
            //             cpid = "A11B680E-4A42-45E0-BCE2-3B16679C0606";
            //         }

            DataTable qdt = q_db.GetQuestionGuid();
            if (qdt.Rows.Count > 0)
            {
                for (int i = 0; i < qdt.Rows.Count; i++)
                {
                    string cAns  = (string.IsNullOrEmpty(Request["cg_" + qdt.Rows[i]["天然氣自評表題目guid"].ToString()])) ? "" : Request["cg_" + qdt.Rows[i]["天然氣自評表題目guid"].ToString()].ToString().Trim();
                    string mAns  = (string.IsNullOrEmpty(Request["mg_" + qdt.Rows[i]["天然氣自評表題目guid"].ToString()])) ? "" : Request["mg_" + qdt.Rows[i]["天然氣自評表題目guid"].ToString()].ToString().Trim();
                    string PsStr = (string.IsNullOrEmpty(Request["ps_" + qdt.Rows[i]["天然氣自評表題目guid"].ToString()])) ? "" : Request["ps_" + qdt.Rows[i]["天然氣自評表題目guid"].ToString()].ToString().Trim();
                    string vfStr = (string.IsNullOrEmpty(Request["vf_" + qdt.Rows[i]["天然氣自評表題目guid"].ToString()])) ? "" : Request["vf_" + qdt.Rows[i]["天然氣自評表題目guid"].ToString()].ToString().Trim();

                    if (LogInfo.competence == "02")                     // 業者
                    {
                        if (cAns != "")
                        {
                            ans_db._業者guid = cpid;
                            ans_db._答案     = cAns;
                            ans_db._委員意見   = "";

                            ans_db._題目guid = qdt.Rows[i]["天然氣自評表題目guid"].ToString();
                            ans_db._年度     = qdt.Rows[i]["天然氣自評表題目年份"].ToString();
                            ans_db._填寫人員類別 = LogInfo.competence;
                            ans_db._建立者    = LogInfo.mGuid;
                            ans_db._修改者    = LogInfo.mGuid;

                            ans_db.SaveAnswer(oConn, myTrans);
                        }
                    }
                    else if (LogInfo.competence == "01")
                    {
                        if (mAns != "")
                        {
                            #region 自評表答案
                            ans_db._業者guid = cpid;
                            ans_db._答案     = mAns;
                            ans_db._檢視文件   = vfStr;
                            string pStr = (mAns != "01") ? PsStr : "";
                            ans_db._委員意見 = pStr;


                            ans_db._題目guid = qdt.Rows[i]["天然氣自評表題目guid"].ToString();
                            ans_db._年度     = qdt.Rows[i]["天然氣自評表題目年份"].ToString();
                            ans_db._填寫人員類別 = LogInfo.competence;
                            ans_db._建立者    = LogInfo.mGuid;
                            ans_db._修改者    = LogInfo.mGuid;
                            #endregion

                            ans_db.SaveAnswer(oConn, myTrans);
                        }
                    }
                    else
                    {
                        if (mAns != "")
                        {
                            #region 自評表答案
                            ans_db._業者guid = cpid;
                            ans_db._答案     = mAns;
                            ans_db._檢視文件   = vfStr;
                            string pStr = (mAns != "01") ? PsStr : "";
                            ans_db._委員意見 = pStr;

                            ans_db._題目guid = qdt.Rows[i]["天然氣自評表題目guid"].ToString();
                            ans_db._年度     = qdt.Rows[i]["天然氣自評表題目年份"].ToString();
                            ans_db._填寫人員類別 = "01"; //for 0323
                            ans_db._建立者    = LogInfo.mGuid;
                            ans_db._修改者    = LogInfo.mGuid;
                            #endregion

                            #region 委員意見log
                            cs_db._委員guid = LogInfo.mGuid;
                            cs_db._委員     = LogInfo.name;
                            cs_db._業者guid = LogInfo.companyGuid;
                            cs_db._題目guid = qdt.Rows[i]["天然氣自評表題目guid"].ToString();
                            cs_db._年度     = qdt.Rows[i]["天然氣自評表題目年份"].ToString();
                            cs_db._答案     = mAns;
                            cs_db._檢視文件   = vfStr;
                            cs_db._委員意見   = pStr;
                            cs_db._建立者    = LogInfo.mGuid;
                            cs_db._修改者    = LogInfo.mGuid;
                            #endregion

                            ans_db.SaveAnswer(oConn, myTrans);
                        }
                    }
                }
            }

            myTrans.Commit();

            string xmlstr = string.Empty;
            xmlstr = "<?xml version='1.0' encoding='utf-8'?><root><Response>儲存完成</Response></root>";
            xDoc.LoadXml(xmlstr);
        }
        catch (Exception ex)
        {
            myTrans.Rollback();
            xDoc = ExceptionUtil.GetExceptionDocument(ex);
        }
        finally
        {
            oCmmd.Connection.Close();
            oConn.Close();
        }
        Response.ContentType = System.Net.Mime.MediaTypeNames.Text.Xml;
        xDoc.Save(Response.Output);
    }
Ejemplo n.º 13
0
        // return:
        //      -1  error
        //      0   canceled
        //      1   succeed
        public int GetNumber(
            Stop stop,
            System.Windows.Forms.IWin32Window parent,
            string strUrl,
            string strAuthor,
            bool bSelectPinyin,
            bool bSelectEntry,
            bool bOutputDebugInfo,
            BeforeLoginEventHandle e,
            out string strNumber,
            out string strDebugInfo,
            out string strError)
        {
            strError     = "";
            strDebugInfo = "";

            Channel channel = this;

            // this.parent = parent;

            // channel.BeforeLogin -= new BeforeLoginEventHandle(channel_BeforeLogin);
            // channel.BeforeLogin += new BeforeLoginEventHandle(channel_BeforeLogin);

            channel.BeforeLogin -= e;
            channel.BeforeLogin += e;

            channel.Url = strUrl;

            strNumber = "";

            int nRet = 0;

            try
            {
                channel.Clear();
            }
            catch (Exception ex)
            {
                strError = ExceptionUtil.GetAutoText(ex);
                return(-1);
            }

            for (; ;)
            {
                // 这个函数具有catch 通讯中 exeption的能力
                nRet = channel.GetNumber(
                    stop,
                    strAuthor,
                    bSelectPinyin,
                    bSelectEntry,
                    bOutputDebugInfo,
                    out strNumber,
                    out strDebugInfo,
                    out strError);
                if (nRet != -3)
                {
                    break;
                }

                Debug.Assert(nRet == -3, "");

                string strTitle = strError;

                string strQuestion = "";

                nRet = channel.GetQuestion(out strQuestion,
                                           out strError);
                if (nRet != 1)
                {
                    nRet = -1;
                    break;
                }

                QuestionDlg dlg = new QuestionDlg();
                GuiUtil.AutoSetDefaultFont(dlg);    // 2015/5/28
                dlg.StartPosition           = FormStartPosition.CenterScreen;
                dlg.label_messageTitle.Text = strTitle;
                dlg.textBox_question.Text   = strQuestion.Replace("\n", "\r\n");
                dlg.ShowDialog(parent);

                if (dlg.DialogResult != DialogResult.OK)
                {
                    nRet = 0;
                    break;
                }

                nRet = channel.Answer(strQuestion,
                                      dlg.textBox_result.Text,
                                      out strError);
                if (nRet != 1)
                {
                    nRet = -1;
                    break;
                }
            }

            if (nRet == -1)
            {
                return(-1);
            }

            return(1);
        }
        private void DoLongPollingRefresh(string appId, string cluster, string dataCenter)
        {
            Random     random         = new Random();
            ServiceDTO lastServiceDto = null;

            while (!m_longPollingStopped.ReadFullFence())
            {
                int    sleepTime = 50; //default 50 ms
                string url       = null;
                try
                {
                    if (lastServiceDto == null)
                    {
                        IList <ServiceDTO> configServices = ConfigServices;
                        lastServiceDto = configServices[random.Next(configServices.Count)];
                    }

                    url = AssembleLongPollRefreshUrl(lastServiceDto.HomepageUrl, appId, cluster, dataCenter);

                    logger.Debug(
                        string.Format("Long polling from {0}", url));
                    Com.Ctrip.Framework.Apollo.Util.Http.HttpRequest request = new Com.Ctrip.Framework.Apollo.Util.Http.HttpRequest(url);
                    //longer timeout - 10 minutes
                    request.Timeout = 600000;

                    HttpResponse <IList <ApolloConfigNotification> > response = m_httpUtil.DoGet <IList <ApolloConfigNotification> >(request);

                    logger.Debug(
                        string.Format("Long polling response: {0}, url: {1}", response.StatusCode, url));
                    if (response.StatusCode == 200 && response.Body != null)
                    {
                        UpdateNotifications(response.Body);
                        UpdateRemoteNotifications(response.Body);
                        Notify(lastServiceDto, response.Body);
                        m_longPollSuccessSchedulePolicyInMS.Success();
                    }
                    else
                    {
                        sleepTime = m_longPollSuccessSchedulePolicyInMS.Fail();
                    }

                    //try to load balance
                    if (response.StatusCode == 304 && random.NextDouble() >= 0.5)
                    {
                        lastServiceDto = null;
                    }

                    m_longPollFailSchedulePolicyInSecond.Success();
                }
                catch (Exception ex)
                {
                    lastServiceDto = null;

                    int sleepTimeInSecond = m_longPollFailSchedulePolicyInSecond.Fail();
                    logger.Warn(
                        string.Format("Long polling failed, will retry in {0} seconds. appId: {1}, cluster: {2}, namespace: {3}, long polling url: {4}, reason: {5}",
                                      sleepTimeInSecond, appId, cluster, AssembleNamespaces(), url, ExceptionUtil.GetDetailMessage(ex)));

                    sleepTime = sleepTimeInSecond * 1000;
                }
                finally
                {
                    Thread.Sleep(sleepTime);
                }
            }
        }
Ejemplo n.º 15
0
 public void Error(Exception exception)
 {
     Console.WriteLine("[ERROR] " + ExceptionUtil.GetDetailMessage(exception));
 }
        /// <summary>
        /// Sends a <see cref="IOperation{T}" /> to the Couchbase Server using the Memcached protocol.
        /// </summary>
        /// <typeparam name="T">The Type of the body of the request.</typeparam>
        /// <param name="operation">The <see cref="IOperation{T}" /> to send.</param>
        /// <returns>
        /// An <see cref="IOperationResult" /> with the status of the request.
        /// </returns>
        /// <exception cref="ServiceNotSupportedException">The cluster does not support Data services.</exception>
        public override IOperationResult <T> SendWithRetry <T>(IOperation <T> operation)
        {
            if (Log.IsDebugEnabled && TimingEnabled)
            {
                operation.Timer = Timer;
                operation.BeginTimer(TimingLevel.Three);
            }

            //Is the cluster configured for Data services?
            if (!ConfigInfo.IsDataCapable)
            {
                return(new OperationResult <T>
                {
                    Id = operation.Key,
                    Success = false,
                    Exception = new ServiceNotSupportedException(
                        ExceptionUtil.GetMessage(ExceptionUtil.ServiceNotSupportedMsg, "Data")),
                    Status = ResponseStatus.ClientFailure
                });
            }

            IOperationResult <T> operationResult = new OperationResult <T> {
                Success = false, OpCode = operation.OperationCode
            };

            do
            {
                IVBucket vBucket;
                var      server = GetServer(operation.Key, operation.LastConfigRevisionTried, out vBucket);
                if (server == null)
                {
                    continue;
                }
                operation.VBucket = vBucket;
                operation.LastConfigRevisionTried = vBucket.Rev;
                operationResult = server.Send(operation);

                if (operationResult.Success)
                {
                    Log.Debug(
                        m =>
                        m("Operation {0} succeeded {1} for key {2} : {3}", operation.GetType().Name,
                          operation.Attempts, operation.Key, operationResult.Value));
                    break;
                }
                if (CanRetryOperation(operationResult, operation) && !operation.TimedOut())
                {
                    LogFailure(operation, operationResult);
                    operation = (IOperation <T>)operation.Clone();
                    Thread.Sleep(VBucketRetrySleepTime);
                }
                else
                {
                    ((OperationResult)operationResult).SetException();
                    Log.Debug(m => m("Operation doesn't support retries for key {0}", operation.Key));
                    break;
                }
            } while (!operationResult.Success && !operation.TimedOut());

            if (!operationResult.Success)
            {
                if (operation.TimedOut())
                {
                    const string msg = "The operation has timed out.";
                    ((OperationResult)operationResult).Message = msg;
                    ((OperationResult)operationResult).Status  = ResponseStatus.OperationTimeout;
                }
                LogFailure(operation, operationResult);
            }

            if (Log.IsDebugEnabled && TimingEnabled)
            {
                operation.EndTimer(TimingLevel.Three);
            }

            return(operationResult);
        }
Ejemplo n.º 17
0
 public void Error(string message, Exception exception)
 {
     Console.WriteLine("[ERROR] " + message + " - " + ExceptionUtil.GetDetailMessage(exception));
 }
        /// <summary>
        /// Sends a N1QL query to the server to be executed using the <see cref="IQueryRequest"/> object using async/await.
        /// </summary>
        /// <typeparam name="T">The Type T of the body of each result row.</typeparam>
        /// <param name="queryRequest">The <see cref="IQueryRequest"/> object to send to the server.</param>
        /// <returns>An <see cref="Task{IQueryResult}"/> object to be awaited on that is the result of the query.</returns>
        /// <exception cref="ServiceNotSupportedException">The cluster does not support Query services.</exception>
        public override async Task <IQueryResult <T> > SendWithRetryAsync <T>(IQueryRequest queryRequest)
        {
            IQueryResult <T> queryResult = null;

            try
            {
                //Is the cluster configured for Query services?
                if (!ConfigInfo.IsQueryCapable)
                {
                    throw new ServiceNotSupportedException(
                              ExceptionUtil.GetMessage(ExceptionUtil.ServiceNotSupportedMsg, "Query"));
                }

                queryRequest.Lifespan = new Lifespan
                {
                    CreationTime = DateTime.UtcNow,
                    Duration     = ConfigInfo.ClientConfig.QueryRequestTimeout
                };

                using (var cancellationTokenSource = new CancellationTokenSource(ConfigInfo.ClientConfig.ViewRequestTimeout))
                {
                    queryResult = await RetryQueryEveryAsync(async (e, c) =>
                    {
                        var attempts = 0;
                        IServer server;
                        while ((server = c.GetQueryNode()) == null)
                        {
                            if (attempts++ > 10)
                            {
                                throw new TimeoutException("Could not acquire a server.");
                            }
                            Thread.Sleep((int)Math.Pow(2, attempts));
                        }

                        var result = await server.SendAsync <T>(queryRequest).ContinueOnAnyContext();
                        if (!result.Success)
                        {
                            //if this is too loose, we may need to constrain it to HttpRequestException or another exception later on
                            var exception = result.Exception;
                            if (exception != null)
                            {
                                lock (_syncObj)
                                {
                                    Log.Trace("Request failed checking config:", exception);
                                    UpdateConfig();
                                }
                            }
                        }
                        return(result);
                    },
                                                             queryRequest, ConfigInfo, cancellationTokenSource.Token).ConfigureAwait(false);
                }
            }
            catch (Exception e)
            {
                Log.Info(e);
                const string message = "The Query request failed, check Error and Exception fields for details.";
                queryResult = new QueryResult <T>
                {
                    Message   = message,
                    Status    = QueryStatus.Fatal,
                    Success   = false,
                    Exception = e
                };
            }
            return(queryResult);
        }
Ejemplo n.º 19
0
        void RecvCallback(IAsyncResult ar)
        {
            try
            {
                if (client == null)
                {
                    m_strAsycError = "用户中断";
                    goto ERROR1;
                }
                Debug.Assert(client != null, "");

                // TODO: 是否要关闭 NetworkStream !!!
                NetworkStream stream = client.GetStream();
                Debug.Assert(stream != null, "");

                int nReaded = stream.EndRead(ar);
                if (nReaded == 0)
                {
                    m_strAsycError = "通道被对方切断";
                    goto ERROR1;
                }

                m_baRecv = ByteArray.Add(m_baRecv, m_baTempRecv, nReaded);
                Debug.Assert(m_baRecv != null, "");

                long remainder = 0;
                bool bRet      = BerNode.IsCompleteBER(m_baRecv,
                                                       0,
                                                       m_baRecv.Length,
                                                       out remainder);
                if (bRet == true)
                {
                    // 发送和接收完成
                    if (SendRecvComplete != null)
                    {
                        SendRecvComplete(this, new EventArgs());
                    }
                    return;
                }


                // 否则继续接收
                try
                {
                    m_baTempRecv = new byte[4096];

                    IAsyncResult result = stream.BeginRead(m_baTempRecv,
                                                           0,
                                                           4096,
                                                           new AsyncCallback(RecvCallback),
                                                           null);
                }
                catch (Exception ex)
                {
                    m_strAsycError = "接收出错: " + ex.Message;

                    goto ERROR1;
                }
            }
            // System.ObjectDisposedException
            catch (Exception ex)
            {
                m_strAsycError = "RecvCallback()出错: " + ExceptionUtil.GetDebugText(ex);

                goto ERROR1;
            }
            return;

ERROR1:
            // 发送和接收完成
            if (SendRecvComplete != null)
            {
                SendRecvComplete(this, new EventArgs());
            }
            return;
        }
Ejemplo n.º 20
0
        // listview imageindex 0:尚未初始化 1:已经初始化 2:出错

        // 工作线程每一轮循环的实质性工作
        void Worker()
        {
            try
            {
                string strError = "";

                for (int i = this.m_nTail; i < this.listView_list.Items.Count; i++)
                {
                    // ListViewItem item = this.listView_list.Items[i];
                    ListViewItem item = GetItem(i);

                    if (item.ImageIndex == 1)
                    {
                        continue;
                    }

                    // string strBarcode = item.Text;
                    ReaderInfo info       = (ReaderInfo)item.Tag;
                    string     strBarcode = info.ReaderBarcode;

                    stop.OnStop += new StopEventHandler(this.DoStop);
                    stop.Initial("正在初始化浏览器组件 ...");
                    stop.BeginLoop();

                    string strTypeList = "xml";
                    int    nTypeCount  = 1;

                    if (this.checkBox_displayReaderDetailInfo.Checked == true)
                    {
                        strTypeList += ",html";

                        if (StringUtil.CompareVersion(this.MainForm.ServerVersion, "2.25") >= 0)
                        {
                            strTypeList += ":noborrowhistory";
                        }

                        nTypeCount = 2;
                    }

                    try
                    {
                        string[] results = null;
                        long     lRet    = Channel.PassGate(stop,
                                                            strBarcode,
                                                            this.textBox_gateName.Text, // strGateName
                                                            strTypeList,
                                                            out results,
                                                            out strError);
                        if (lRet == -1)
                        {
                            OnError(item, strError);
                            goto CONTINUE;
                        }

                        // this.textBox_counter.Text = lRet.ToString();
                        SetCounterText(lRet);

                        if (results.Length != nTypeCount)
                        {
                            strError = "results error...";
                            OnError(item, strError);
                            goto CONTINUE;
                        }

                        string strXml = results[0];

                        string strReaderName = "";
                        string strState      = "";
                        int    nRet          = GetRecordInfo(strXml,
                                                             out strReaderName,
                                                             out strState,
                                                             out strError);
                        if (nRet == -1)
                        {
                            OnError(item, strError);
                            goto CONTINUE;
                        }

                        info.ReaderName = strReaderName;

                        if (this.checkBox_hideReaderName.Checked == true)
                        {
                            string strText = "";
                            // item.SubItems[1].Text = strText.PadLeft(strReaderName.Length, '*');
                            SetItemText(item, 1, strText.PadLeft(strReaderName.Length, '*'));
                        }
                        else
                        {
                            // item.SubItems[1].Text = strReaderName;
                            SetItemText(item, 1, strReaderName);
                        }

                        // item.SubItems[2].Text = strState;
                        SetItemText(item, 2, strState);

                        // item.ImageIndex = 1;    // error
                        SetItemImageIndex(item, 1);

                        if (this.checkBox_displayReaderDetailInfo.Checked == true &&
                            results.Length == 2)
                        {
                            this.m_webExternalHost.StopPrevious();
                            this.webBrowser_readerInfo.Stop();

                            // this.HtmlString = results[1];

                            // API.PostMessage(this.Handle, WM_SETHTML, 0, 0);
                            StartSetHtml(results[1]);
                        }
                    }
                    finally
                    {
                        stop.EndLoop();
                        stop.OnStop -= new StopEventHandler(this.DoStop);
                        stop.Initial("");
                    }

CONTINUE:
                    this.m_nTail = i;
                }
            }
            catch (Exception ex)
            {
                string strErrorText = "PassGateForm Worker() 出现异常: " + ExceptionUtil.GetDebugText(ex);
                this.MainForm.WriteErrorLog(strErrorText);
            }
        }
Ejemplo n.º 21
0
        // 自动加工数据
        // parameters:
        //      sender    从何处启动? MarcEditor EntityEditForm BindingForm
        public void AutoGenerate(object sender,
                                 GenerateDataEventArgs e,
                                 string strBiblioRecPath,
                                 bool bOnlyFillMenu = false)
        {
            int    nRet              = 0;
            string strError          = "";
            bool   bAssemblyReloaded = false;

            // 防止重入
            if (bOnlyFillMenu == true && this.m_nInFillMenu > 0)
            {
                return;
            }

            this.m_nInFillMenu++;
            try
            {
                // 初始化 dp2circulation_marc_autogen.cs 的 Assembly,并new DetailHost对象
                // return:
                //      -1  error
                //      0   没有重新初始化Assembly,而是直接用以前Cache的Assembly
                //      1   重新(或者首次)初始化了Assembly
                nRet = InitialAutogenAssembly(strBiblioRecPath, // null,
                                              out strError);
                if (nRet == -1)
                {
                    goto ERROR1;
                }
                if (nRet == 0)
                {
                    if (this.m_detailHostObj == null)
                    {
                        return; // 库名不具备,无法初始化
                    }
                }
                if (nRet == 1)
                {
                    bAssemblyReloaded = true;
                }

                Debug.Assert(this.m_detailHostObj != null, "");

                if (this.AutoGenNewStyle == true)
                {
                    bool bDisplayWindow = Program.MainForm.PanelFixedVisible == false ? true : false;
                    if (bDisplayWindow == true)
                    {
                        if (String.IsNullOrEmpty(e.ScriptEntry) != true &&
                            e.ScriptEntry != "Main")
                        {
                            bDisplayWindow = false;
                        }
                    }

                    if (sender is EntityEditForm &&
                        (String.IsNullOrEmpty(e.ScriptEntry) == true ||
                         e.ScriptEntry == "Main"))
                    {
                        bDisplayWindow = true;
                    }
                    else if (sender is BindingForm &&
                             (String.IsNullOrEmpty(e.ScriptEntry) == true ||
                              e.ScriptEntry == "Main"))
                    {
                        bDisplayWindow = true;
                    }

                    DisplayAutoGenMenuWindow(bDisplayWindow);   // 可能会改变 .ActionTable以及 .Count
                    if (bOnlyFillMenu == false)
                    {
                        if (Program.MainForm.PanelFixedVisible == true &&
                            e.Parameter == null)    // 2015/6/5
                        {
                            Program.MainForm.ActivateGenerateDataPage();
                        }
                    }

                    if (this.m_genDataViewer != null)
                    {
                        this.m_genDataViewer.sender = sender;
                        this.m_genDataViewer.e      = e;
                    }

                    // 清除残留菜单事项
                    if (m_autogenSender != sender ||
                        bAssemblyReloaded == true)
                    {
                        if (this.m_genDataViewer != null &&
                            this.m_genDataViewer.Count > 0)
                        {
                            this.m_genDataViewer.Clear();
                        }
                    }
                }
                else // 旧的风格
                {
#if NO
                    if (this.m_genDataViewer != null)
                    {
                        this.m_genDataViewer.Close();
                        this.m_genDataViewer = null;
                    }
#endif
                    CloseGenDataViewer();

                    if (this._myForm.Focused == true
                        // || this.m_marcEditor.Focused TODO: 这里要研究一下如何实现
                        )
                    {
                        Program.MainForm.CurrentGenerateDataControl = null;
                    }

                    // 如果意图仅仅为填充菜单
                    if (bOnlyFillMenu == true)
                    {
                        return;
                    }
                }

                try
                {
                    // 旧的风格
                    if (this.AutoGenNewStyle == false)
                    {
                        this.m_detailHostObj.Invoke(String.IsNullOrEmpty(e.ScriptEntry) == true ? "Main" : e.ScriptEntry,
                                                    sender,
                                                    e);
                        // this.SetSaveAllButtonState(true); TODO: 应该没有必要。MARC 编辑器内容修改自然会引起保存按钮状态变化
                        return;
                    }

                    // 初始化菜单
                    try
                    {
                        if (this.m_genDataViewer != null)
                        {
                            // 出现菜单界面
                            if (this.m_genDataViewer.Count == 0)
                            {
                                dynamic o = this.m_detailHostObj;
                                o.CreateMenu(sender, e);

                                this.m_genDataViewer.Actions = this.m_detailHostObj.ScriptActions;
                            }

                            // 根据当前插入符位置刷新加亮事项
                            this.m_genDataViewer.RefreshState();
                        }

                        if (String.IsNullOrEmpty(e.ScriptEntry) == false)
                        {
                            this.m_detailHostObj.Invoke(e.ScriptEntry,
                                                        sender,
                                                        e);
                        }
                        else
                        {
                            if (Program.MainForm.PanelFixedVisible == true &&
                                bOnlyFillMenu == false &&
                                Program.MainForm.CurrentGenerateDataControl != null)
                            {
                                TableLayoutPanel table = (TableLayoutPanel)Program.MainForm.CurrentGenerateDataControl;
                                for (int i = 0; i < table.Controls.Count; i++)
                                {
                                    Control control = table.Controls[i];
                                    if (control is DpTable)
                                    {
                                        control.Focus();
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception /*ex*/)
                    {
                        /*
                         * // 被迫改用旧的风格
                         * this.m_detailHostObj.Invoke(String.IsNullOrEmpty(e.ScriptEntry) == true ? "Main" : e.ScriptEntry,
                         * sender,
                         * e);
                         * this.SetSaveAllButtonState(true);
                         * return;
                         * */
                        throw;
                    }
                }
                catch (Exception ex)
                {
                    strError = "执行脚本文件 '" + m_strAutogenDataCfgFilename + "' 过程中发生异常: \r\n" + ExceptionUtil.GetDebugText(ex);
                    goto ERROR1;
                }

                this.m_autogenSender = sender;  // 记忆最近一次的调用发起者

                if (bOnlyFillMenu == false &&
                    this.m_genDataViewer != null)
                {
                    this.m_genDataViewer.TryAutoRun();
                }
                return;

ERROR1:
                // TODO: 报错是否要直接显示在 dpTable 中?
                // MessageBox.Show(this._myForm, strError);
                DisplayAutoGenMenuWindow(false);
                if (this.m_genDataViewer != null)
                {
                    this.m_genDataViewer.DisplayError(strError);
                }
            }
            finally
            {
                this.m_nInFillMenu--;
            }
        }
Ejemplo n.º 22
0
        public void LoadPhoto(string photo_path)
        {
            if (string.IsNullOrEmpty(photo_path))
            {
                App.Invoke(new Action(() =>
                {
                    this.SetPhoto((Stream)null);
                }));
                return;
            }

            // TODO: 照片可以缓存到本地。每次只需要获取 timestamp 即可。如果 timestamp 和缓存的不一致再重新获取一次

            Stream stream = null;

            try
            {
                // 先尝试从缓存获取

                /*
                 * string cacheDir = Path.Combine(WpfClientInfo.UserDir, "photo");
                 * PathUtil.CreateDirIfNeed(cacheDir);
                 * string fileName = Path.Combine(cacheDir, GetPath(photo_path));
                 */
                string fileName = GetCachePhotoPath(photo_path);
                if (File.Exists(fileName))
                {
                    try
                    {
                        stream = new MemoryStream(File.ReadAllBytes(fileName));
                        // stream = File.OpenRead(fileName);
                    }
                    catch (Exception ex)
                    {
                        WpfClientInfo.WriteErrorLog($"从读者照片本地缓存文件 {fileName} 读取内容时出现异常:{ExceptionUtil.GetDebugText(ex)}");
                        stream = null;
                    }
                }

                if (stream == null)
                {
                    stream = new MemoryStream();
                    var      channel     = App.CurrentApp.GetChannel();
                    TimeSpan old_timeout = channel.Timeout;
                    channel.Timeout = TimeSpan.FromSeconds(30);
                    try
                    {
                        long lRet = channel.GetRes(
                            null,
                            photo_path,
                            stream,
                            "data,content", // strGetStyle,
                            null,           // byte [] input_timestamp,
                            out string strMetaData,
                            out byte[] baOutputTimeStamp,
                            out string strOutputPath,
                            out string strError);
                        if (lRet == -1)
                        {
                            // SetGlobalError("patron", $"获取读者照片时出错: {strError}");
                            // return;
                            throw new Exception($"获取读者照片(path='{photo_path}')时出错: {strError}");
                        }

                        // 顺便存储到本地
                        {
                            bool suceed = false;
                            stream.Seek(0, SeekOrigin.Begin);
                            try
                            {
                                using (var file = File.OpenWrite(fileName))
                                {
                                    StreamUtil.DumpStream(stream, file);
                                }

                                suceed = true;
                            }
                            catch (Exception ex)
                            {
                                WpfClientInfo.WriteErrorLog($"读者照片写入本地缓存文件 {fileName} 时出现异常:{ExceptionUtil.GetDebugText(ex)}");
                            }
                            finally
                            {
                                if (suceed == false)
                                {
                                    File.Delete(fileName);
                                }
                            }
                        }

                        stream.Seek(0, SeekOrigin.Begin);
                    }
                    finally
                    {
                        channel.Timeout = old_timeout;
                        App.CurrentApp.ReturnChannel(channel);
                    }
                }

                App.Invoke(new Action(() =>
                {
                    this.SetPhoto(stream);
                }));
                stream = null;
            }
            finally
            {
                if (stream != null)
                {
                    stream.Dispose();
                }
            }
        }
Ejemplo n.º 23
0
        // 尝试写入实例的错误日志文件
        // return:
        //      false   失败
        //      true    成功
        public static bool DetectWriteErrorLog(string strText)
        {
            _errorLogError = false;
            try
            {
                _writeErrorLog(strText);
            }
            catch (Exception ex)
            {
                WriteWindowsLog("尝试写入目录 " + LogDir + " 的日志文件发生异常, 后面将改为写入 Windows 日志。异常信息如下:'" + ExceptionUtil.GetDebugText(ex) + "'", EventLogEntryType.Error);
                _errorLogError = true;
                return(false);
            }

            WriteWindowsLog("日志文件检测正常。从此开始关于 dp2MServer 的日志会写入目录 " + LogDir + " 中当天的日志文件",
                            EventLogEntryType.Information);
            return(true);
        }
Ejemplo n.º 24
0
        // 根据数据库定义文件,创建若干数据库
        // 注: 如果发现同名数据库已经存在,先删除再创建
        // parameters:
        //      strTempDir  临时目录路径。调用前要创建好这个临时目录。调用后需要删除这个临时目录
        public static int CreateDatabases(
            Stop stop,
            RmsChannel channel,
            string strDbDefFileName,
            string strTempDir,
            out string strError)
        {
            strError = "";
            int nRet = 0;

            // 展开压缩文件
            if (stop != null)
            {
                stop.SetMessage("正在展开压缩文件 " + strDbDefFileName);
            }
            try
            {
                using (ZipFile zip = ZipFile.Read(strDbDefFileName))
                {
                    foreach (ZipEntry e in zip)
                    {
                        Debug.WriteLine(e.ToString());
                        e.Extract(strTempDir, ExtractExistingFileAction.OverwriteSilently);
                    }
                }
            }
            catch (Exception ex)
            {
                strError = "展开压缩文件 '" + strDbDefFileName + "' 到目录 '" + strTempDir + "' 时出现异常: " + ExceptionUtil.GetAutoText(ex);
                return(-1);
            }

            DirectoryInfo di = new DirectoryInfo(strTempDir);

            DirectoryInfo[] dis = di.GetDirectories();

            int i = 0;

            foreach (DirectoryInfo info in dis)
            {
                // 跳过 '_datadir'
                if (info.Name == "_datadir")
                {
                    continue;
                }

                string strTemplateDir  = Path.Combine(info.FullName, "cfgs");
                string strDatabaseName = info.Name;
                // 数据库是否已经存在?
                // return:
                //      -1  error
                //      0   not exist
                //      1   exist
                //      2   其他类型的同名对象已经存在
                nRet = DatabaseUtility.IsDatabaseExist(
                    channel,
                    strDatabaseName,
                    out strError);
                if (nRet == -1)
                {
                    return(-1);
                }
                if (nRet == 1)
                {
                    if (stop != null)
                    {
                        stop.SetMessage("正在删除数据库 " + strDatabaseName);
                    }

                    // 如果发现同名数据库已经存在,先删除
                    long lRet = channel.DoDeleteDB(strDatabaseName, out strError);
                    if (lRet == -1)
                    {
                        if (channel.ErrorCode != ChannelErrorCode.NotFound)
                        {
                            return(-1);
                        }
                    }
                }

                if (stop != null)
                {
                    stop.SetMessage("正在创建数据库 " + strDatabaseName + " (" + (i + 1) + ")");
                }

                // 根据数据库模板的定义,创建一个数据库
                // parameters:
                //      strTempDir  将创建数据库过程中,用到的配置文件会自动汇集拷贝到此目录。如果 == null,则不拷贝
                nRet = DatabaseUtility.CreateDatabase(channel,
                                                      strTemplateDir,
                                                      strDatabaseName,
                                                      null,
                                                      out strError);
                if (nRet == -1)
                {
                    return(-1);
                }

                i++;
            }

            return(0);
        }
Ejemplo n.º 25
0
        // 同步
        // 注:中途遇到异常(例如 Loader 抛出异常),可能会丢失 INSERT_BATCH 条以内的日志记录写入 operlog 表
        // parameters:
        //      strLastDate   处理中断或者结束时返回最后处理过的日期
        //      last_index  处理或中断返回时最后处理过的位置。以后继续处理的时候可以从这个偏移开始
        // return:
        //      -1  出错
        //      0   中断
        //      1   完成
        public 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 (this.HasLoaderPrompt())
                                {
                                    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"
                                    };
                                    Loader_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 (this.HasLoaderPrompt())
                                {
                                    MessagePromptEventArgs e = new MessagePromptEventArgs
                                    {
                                        MessageText     = strError + "\r\n\r\n是否跳过此条继续处理?\r\n\r\n(确定: 跳过;  取消: 停止全部操作)",
                                        IncludeOperText = true,
                                        // + "\r\n\r\n是否跳过此条继续处理?",
                                        Actions = "yes,cancel"
                                    };
                                    Loader_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 (ChannelException ex)
            {
                return(new ReplicationResult {
                    Value = -1, ErrorInfo = ex.Message
                });
            }
            catch (Exception ex)
            {
                string strError = "ReportForm DoReplication() exception: " + ExceptionUtil.GetDebugText(ex);
                return(new ReplicationResult {
                    Value = -1, ErrorInfo = strError
                });
            }
        }
Ejemplo n.º 26
0
        public static NormalResult GetState(string style)
        {
            try
            {
                // 因为 GetState 是可有可无的请求,如果 Url 为空就算了
                if (string.IsNullOrEmpty(Base.Url))
                {
                    return(new NormalResult());
                }

                BaseChannel <IRfid> channel = null;
                bool old_checkState         = _checkState;
                _checkState = false;
                try
                {
                    channel = Base.GetChannel();
                }
                finally
                {
                    _checkState = old_checkState;
                }

                try
                {
                    var result = channel.Object.GetState(style);
                    if (result.Value == -1)
                    {
                        Base.TriggerSetError(result,
                                             new SetErrorEventArgs {
                            Error = result.ErrorInfo
                        });
                    }
                    else
                    {
                        Base.TriggerSetError(result,
                                             new SetErrorEventArgs {
                            Error = null
                        });                                          // 清除以前的报错
                    }
                    return(result);
                }
                finally
                {
                    Base.ReturnChannel(channel);
                }
            }
            catch (Exception ex)
            {
                Base.TriggerSetError(ex,
                                     new SetErrorEventArgs
                {
                    Error = $"RFID 中心出现异常: {ExceptionUtil.GetAutoText(ex)}"
                });
                return(new NormalResult
                {
                    Value = -1,
                    ErrorInfo = ex.Message,
                    ErrorCode = NotResponseException.GetErrorCode(ex)
                });
            }
        }
Ejemplo n.º 27
0
        public void Received(Packet p, int packetId)
        {
            try
            {
                if (p is PingPacket)
                {
                    lightClient.startPingStopwatch();

                    lightClient.sendObject(new PongPacket(), false);
                }
                else if (p is PingReceive)
                {
                    lightClient.endPingStopwatch();


                    lightClient.LoggerInstance.Debug("Ping: {0}", lightClient.getPingTime().Milliseconds + "ms");
                }
                else if (p is IllegalConnectionPacket)
                {
                    lightClient.LoggerInstance.Info(((IllegalConnectionPacket)p).message);
                    lightClient.disconnect(ServerDisconnectEvent.DisconnectStatus.CONNECTION_LOST);
                }
                else if (p is InitialHandshakePacket)
                {
                    // Handles object encryption key sharing
                    var packet = (InitialHandshakePacket)p;

                    var versionData = packet.getVersionData();

                    var versionRange = StaticHandler.getVersionRangeStatus(versionData);

                    if (versionRange == StaticHandler.VersionRange.MATCH_REQUIREMENTS)
                    {
                        lightClient.LoggerInstance.Info("Version range requirements match Server version.");
                    }
                    else
                    {
                        // Current version is smaller than the server's required minimum
                        if (versionRange == StaticHandler.VersionRange.WE_ARE_LOWER)
                        {
                            lightClient.LoggerInstance
                            .Info(
                                "The client version ({0}) does not meet server's minimum version ({1}) requirements. Expect incompatibility issues",
                                StaticHandler.VERSION_DATA.Version.ToString(), versionData.MinVersion.ToString());
                        }

                        // Current version is larger than server's minimum version
                        if (versionRange == StaticHandler.VersionRange.WE_ARE_HIGHER)
                        {
                            lightClient.LoggerInstance
                            .Info(
                                "The server version ({0}) does not meet client's minimum version ({1}) requirements. Expect incompatibility issues",
                                versionData.Version.ToString(), StaticHandler.VERSION_DATA.MinVersion.ToString());
                        }
                    }

                    var secretKey = EncryptionUtil.generateAESProvider();

                    // TODO: Remove this debug
                    string debug = "Using key " + string.Join(",", secretKey.Key) + " base64:" + Convert.ToBase64String(secretKey.Key);
                    StaticHandler.Core.Logger.Debug(debug);

                    lightClient.setSecretKey(secretKey);


                    var responsePacket = new KeyResponsePacket(secretKey, packet.getPublicKey());

                    lightClient.sendObject(responsePacket, false);


                    lightClient.callEvent(new ServerConnectHandshakeEvent(lightClient.Channel));
                }
                else if (p is RequestConnectInfoPacket)
                {
                    var connectedPacket = lightClient.buildConnectedPacket();

                    lightClient.sendObject(connectedPacket).ConfigureAwait(false);
                    StaticHandler.Core.Logger.Info("Sent the connection Packet for request");
                }
                else if (p is SelfMessagePacket)
                {
                    switch (((SelfMessagePacket)p).type)
                    {
                    case SelfMessagePacket.MessageType.TIMED_OUT_REGISTRATION:
                        lightClient.LoggerInstance.Info("Timed out on registering.");
                        lightClient.disconnect(ServerDisconnectEvent.DisconnectStatus.TIMEOUT);
                        break;

                    case SelfMessagePacket.MessageType.REGISTER_PACKET:
                        lightClient.registered = true;
                        lightClient.LoggerInstance.Info("Successfully connected to server");
                        lightClient.callEvent(new ServerConnectFinishEvent(lightClient.Channel));
                        break;

                    case SelfMessagePacket.MessageType.LOST_SERVER_CONNECTION:
                        lightClient.LoggerInstance.Info("Lost connection to server! Must have shutdown!");
                        lightClient.disconnect(ServerDisconnectEvent.DisconnectStatus.CONNECTION_LOST);
                        break;
                    }
                }

                foreach (var iPacketHandler in lightClient.getPacketHandlers())
                {
                    Task.Run(() =>
                    {
                        try
                        {
                            iPacketHandler.handlePacket(p, packetId);
                        }
                        catch (Exception e)
                        {
                            throw ExceptionUtil.throwParsePacketException(e, p);
                        }
                    });
                }
            }
            catch (ParsePacketException ignored)
            {
                throw;
            }
            catch (Exception e)
            {
                throw ExceptionUtil.throwParsePacketException(e, p);
            }
        }
Ejemplo n.º 28
0
        public static bool PrepareEnvironment(Page page,
                                              ref OpacApplication app,
                                              ref SessionInfo sessioninfo)
        {
            string strErrorInfo = "";

            // 获得app对象
            // 并检查系统错误字符串

            // 2008/6/6
            // 错误信息采用两级存放策略。
            // 如果LibraryAppliation对象已经存在,则采用其ErrorInfo成员的值;
            // 否则,采用Application["errorinfo"]值
            app = (OpacApplication)page.Application["app"];
            if (app == null)
            {
                strErrorInfo = (string)page.Application["errorinfo"];

                if (String.IsNullOrEmpty(strErrorInfo) == true)
                {
                    strErrorInfo = "app == null";
                }

                page.Response.Write(HttpUtility.HtmlEncode(strErrorInfo).Replace("\r\n", "<br/>"));
                page.Response.End();
                return(false);
            }
            else
            {
                strErrorInfo = app.GlobalErrorInfo;
                if (String.IsNullOrEmpty(strErrorInfo) == false)
                {
                    page.Response.Write(HttpUtility.HtmlEncode(strErrorInfo).Replace("\r\n", "<br/>"));
                    page.Response.End();
                    return(false);
                }

                if (app.XmlLoaded == false)
                {
                    strErrorInfo =
                        "<html><body><pre>" +
                        HttpUtility.HtmlEncode("OPAC 初始化时装载 XmlDefs 失败,可能的原因是:OPAC 所依赖的 dp2Library 服务模块尚未启动,或 OPAC 代理帐户不存在、权限不够或密码被修改...。\r\n具体出错原因请察看 dp2OPAC 数据目录 log 子目录下的当日日志文件(log_????????.txt),并及时排除故障。OPAC 系统将在稍后自动重试装载 XmlDefs。");
                    page.Response.Write(strErrorInfo);

                    if (page.Request.UserHostAddress == "localhost" ||
                        page.Request.UserHostAddress == "::1")
                    {
                        page.Response.Write("\r\n\r\n");
                        // 输出当天日志文件内容
                        app.DumpErrorLog(page);
                    }

                    page.Response.Write("</pre></body></html>");
                    page.Response.End();
                    return(false);
                }
            }

            /*
             * string strErrorInfo = (string)page.Application["errorinfo"];
             *
             * if (String.IsNullOrEmpty(strErrorInfo) == false)
             * {
             *  page.Response.Write(HttpUtility.HtmlEncode(strErrorInfo).Replace("\r\n","<br/>"));
             *  page.Response.End();
             *  return false;   // error
             * }*/

            // 获得SessionInfo
            sessioninfo = (SessionInfo)page.Session["sessioninfo"];
            if (sessioninfo == null)
            {
                /*
                 * strErrorInfo = "sessioninfo == null";
                 * page.Response.Write(strErrorInfo);
                 * page.Response.End();
                 * return false;
                 * */

                // 2013/12/7
                string strClientIP = HttpContext.Current.Request.UserHostAddress.ToString();
                // 增量计数
                if (app != null)
                {
                    long v = app.IpTable.IncIpCount(strClientIP, 1);
                    if (v >= app.IpTable.MAX_SESSIONS_PER_IP)
                    {
                        app.IpTable.IncIpCount(strClientIP, -1);
                        strErrorInfo             = "同一 IP 前端数量超过配额 " + app.IpTable.MAX_SESSIONS_PER_IP.ToString() + "。请稍后再试。";
                        page.Response.StatusCode = 403;
                        // page.Response.StatusDescription = strErrorInfo;
                        page.Response.Write(strErrorInfo);
                        page.Response.End();
                        // TODO: 也可以 redirect 引导到一个说明性的页面
                        return(false);
                    }
                }

                try
                {
                    sessioninfo                 = new SessionInfo(app);
                    sessioninfo.ClientIP        = strClientIP;
                    page.Session["sessioninfo"] = sessioninfo;
                }
                catch (Exception ex)
                {
                    strErrorInfo = "PrepareEnvironment()创建Session出现异常: " + ExceptionUtil.GetDebugText(ex);
                    page.Response.Write(strErrorInfo);
                    page.Response.End();
                    return(false);
                }
            }

            string strLang = (string)page.Session["lang"];

            sessioninfo.ChannelLang = strLang;

            if (page is MyWebPage)
            {
                (page as MyWebPage).LoadCookiesLoginToSession();
            }

            return(true);
        }
Ejemplo n.º 29
0
        public unsafe string Format(Entry entry)
        {
            int len = 25 + entry.Tag.Length + entry.Message.Length;

            // This fallback is needed because of possible huge stack allocation.
            if (len > 100 * 1024)
            {
                return(FormatSlow(entry));
            }

            string categoryString  = null;
            string exceptionString = null;

            if (_categoryFormatter != null)
            {
                categoryString = _categoryFormatter.GetString(entry.Category);

                len += categoryString.Length + 1;
            }

            if (entry.Exception != null)
            {
                exceptionString = entry.Exception.ToString();

                if (_doAsyncExceptionCleanup)
                {
                    exceptionString = ExceptionUtil.CleanStackTrace(exceptionString);
                }

                len += exceptionString.Length + 5;
            }

            char *charBuffer = stackalloc char[len];
            char *ptr        = charBuffer;

            var dt = entry.TimeStamp;

            AppendDigitsFast(ref ptr, dt.Hour, 2);
            Append(&ptr, ':');
            AppendDigitsFast(ref ptr, dt.Minute, 2);
            Append(&ptr, ':');
            AppendDigitsFast(ref ptr, dt.Second, 2);
            Append(&ptr, ':');
            AppendDigitsFast(ref ptr, dt.Millisecond, 3);
            Append(&ptr, '|');

            Append(&ptr, LogLevels.Levels[(int)entry.Level]);

            Append(&ptr, '|');
            AppendDigitsFast(ref ptr, LogEnvironment.CurrentManagedThreadId, 2, ' ');
            Append(&ptr, '|');
            Append(&ptr, entry.Tag);
            Append(&ptr, '|');

            if (_categoryFormatter != null)
            {
                Append(&ptr, categoryString);
                Append(&ptr, '|');
            }

            Append(&ptr, entry.Message);

            if (entry.Exception != null)
            {
                Append(&ptr, " --> ");
                Append(&ptr, exceptionString);
            }

            Append(&ptr, '\r');
            Append(&ptr, '\n');

            return(new string(charBuffer, 0, len));
        }
Ejemplo n.º 30
0
        public static IPara GetPara(object obj, string field)
        {
            if (obj == null)
            {
                return(null);
            }
            FieldInfo    f    = GetField(obj, field);
            AbstractPara para = null;

            if (f != null)
            {
                string type = f.FieldType.Name;

                if (ParseUtility.IsInt64(type))
                {
                    para = new LongPara(field);
                }
                if (ParseUtility.IsInt32(type))
                {
                    para = new IntPara(field);
                }
                if (ParseUtility.IsSingle(type))
                {
                    para = new FloatPara(field);
                }
                if (ParseUtility.IsDouble(type))
                {
                    para = new DoublePara(field);
                }
                if (ParseUtility.IsString(type))
                {
                    para = new StringPara(field);
                }
                if (ParseUtility.IsBoolean(type))
                {
                    para = new BoolPara(field);
                }
                try
                {
                    if (para != null)
                    {
                        para.SetValue(f.GetValue(obj));
                    }
                }
                catch (Exception e)
                {
                    throw new GameConfigExpception(field + " is not a valid field.\n" + ExceptionUtil.GetExceptionContent(e));
                }
            }
            return(para);
        }