Esempio n. 1
0
        void NewTransaction(object sender, KJFramework.EventArgs.LightSingleArgEventArgs <IMessageTransaction <MetadataContainer> > e)
        {
            NewProcessorObject         obj;
            MetadataMessageTransaction transaction = (MetadataMessageTransaction)e.Target;

            if (!transaction.Request.IsAttibuteExsits(0x00))
            {
                throw new KeyHasNullException();
            }
            MessageIdentity identity = transaction.Request.GetAttribute(0x00).GetValue <MessageIdentity>();

            lock (_processorLockObj)
            {
                if (!_processors.TryGetValue(new Protocols {
                    ProtocolId = identity.ProtocolId, ServiceId = identity.ServiceId, DetailsId = identity.DetailsId
                }, out obj))
                {
                    _tracing.Error("#Schedule message failed, because cannot find processor. #P:{0}, S{1}, D{2}", identity.ProtocolId, identity.ServiceId, identity.DetailsId);
                    return;
                }
            }
            try
            {
                obj.Processor.Process(transaction);
            }
            catch (System.Exception ex) { _tracing.Error(ex, null); }
        }
Esempio n. 2
0
        public void BeginReceive()
        {
            Socket s = _socket;

            if (s != null)
            {
                try
                {
                    s.BeginReceive(_recvBuffer, 0, _recvBufferSize, SocketFlags.None, new AsyncCallback(BeginReceiveCallback), _socket);
                }
                catch (SocketException ex)
                {
                    Socket sEx = _socket;
                    _tracing.ErrorFmt(ex, "SocketDataTransceiver接收数据发生异常,SocketErrorCode:{0},RemoteEndPoint:{1},SocketDataTransceiver将被迫关闭!", ex.SocketErrorCode, sEx == null ? "null" : ((IPEndPoint)(_socket.RemoteEndPoint)).ToString());
                    Close();
                }
                catch (ObjectDisposedException ex)
                {
                    _tracing.Error(ex, "因为socket已释放,SocketDataTransceiver接收数据发生异常,SocketDataTransceiver将被迫关闭!");
                    Close();
                }
                catch (Exception ex)
                {
                    _tracing.Error(ex, "SocketDataTransceiver接收数据发生异常,SocketDataTransceiver将被迫关闭!");
                    Close();
                }
            }
        }
Esempio n. 3
0
        public static string GetOneCom()
        {
            if (SerialPortTran.IsTheDevice(FirstCom))
            {
                return(FirstCom);
            }

            {
                string[] sValues = SerialPort.GetPortNames(); // keyCom.GetValueNames();
                foreach (string sValue in sValues)
                {
                    if (sValue != FirstCom)
                    {
                        try
                        {
                            bool b = SerialPortTran.IsTheDevice(sValue);
                            if (b)
                            {
                                FirstCom = sValue;
                                return(sValue);
                            }
                        }
                        catch (Exception ex) {
                            _tracing.Error(ex, "failed to try connect and send test ." + sValue);
                        }
                    }
                }
            }
            return("");
        }
Esempio n. 4
0
        /// <summary>
        /// Read from stream
        /// </summary>
        /// <param name="type"></param>
        /// <param name="stream"></param>
        /// <param name="contentHeaders"></param>
        /// <param name="formatterContext"></param>
        /// <returns></returns>
        public override Task <object> ReadFromStreamAsync(Type type, Stream stream, System.Net.Http.HttpContent contentHeaders, IFormatterLogger formatterContext)
        {
            var task = Task <object> .Factory.StartNew(() =>
            {
                try
                {
                    var settings = new JsonSerializerSettings
                    {
                        NullValueHandling = NullValueHandling.Ignore,
                    };

                    var sr      = new StreamReader(stream);
                    var jreader = new JsonTextReader(sr);

                    var ser = new JsonSerializer();
                    ser.Converters.Add(new IsoDateTimeConverter());
                    object val = ser.Deserialize(jreader, type);
                    return(val);
                }
                catch (Exception ex)
                {
                    _tracing.Error(ex, null);
                    return(null);
                }
            });

            return(task);
        }
Esempio n. 5
0
 /// <summary>
 ///     开始接收数据
 /// </summary>
 private void StartReceive()
 {
     if (!_state)
     {
         return;
     }
     try
     {
         IFixedCacheStub <SocketBuffStub> stub = ChannelConst.BuffAsyncStubPool.Rent();
         if (stub == null)
         {
             throw new System.Exception("#Cannot rent an async recv io-stub for socket recv async action.");
         }
         SocketAsyncEventArgs e = stub.Cache.Target;
         //set callback var = receiver
         stub.Tag       = this;
         e.AcceptSocket = _socket;
         e.UserToken    = stub;
         bool result = e.AcceptSocket.ReceiveAsync(e);
         //Sync process data.
         if (!result)
         {
             ProcessReceive(stub);
         }
     }
     catch (System.Exception ex)
     {
         _tracing.Error(ex, null);
         Stop();
     }
 }
Esempio n. 6
0
 /// <summary>
 ///     正常新建Account进入BC落地
 /// </summary>
 /// <param name="userId">用户ID</param>
 /// <param name="accountId">账户ID</param>
 /// <param name="sourceId">账户来源编号</param>
 /// <returns>结果</returns>
 public IExecuteResult CreateAccountNormal(uint userId, uint accountId, ushort sourceId)
 {
     if (userId == 0)
     {
         return(ExecuteResult.Fail(SystemErrors.Malformed, "#Illegal user id."));
     }
     if (accountId == 0)
     {
         return(ExecuteResult.Fail(SystemErrors.Malformed, "#Illegal account id."));
     }
     try
     {
         //获取参数的值
         object[] parameterValues = new object[] { accountId, userId, sourceId };
         int      count           = _masterDB.SpExecuteNonQuery(SpName.SpAddAccount, ParametersObject.SpAddAccount, parameterValues);
         return(count == 0
                       ? ExecuteResult.Fail(SystemErrors.NotFound, SpName.SpAddAccount + ":Executed count = 0")
                       : ExecuteResult.Succeed(true));
     }
     catch (Exception ex)
     {
         _tracing.Error(ex, null);
         return(ExecuteResult.Fail(SystemErrors.Unknown, ex.Message));
     }
 }
Esempio n. 7
0
 /// <summary>
 ///    连接容器内部方法,子类可以重写此方法。
 ///    <para>*此方法主要用于确保在使用指定算法获取容器中连接之前,连接容器内部拥有足够多的连接</para>
 ///    <para>*具体策略为优先保证在同步执行代码的情况下,当前连接容器中最少有一个存活的连接,至于剩下的连接需要异步进行创建</para>
 /// </summary>
 protected virtual bool MakeSureConnections()
 {
     if (_connections.Count >= _min || _connections.Count == 1)
     {
         return(true);
     }
     lock (_lockObj)
     {
         try
         {
             IServerConnectionAgent <T> agent = _createFunc(_tuple.Item1, _tuple.Item2, _tuple.Item3);
             //如果当前时间点无法正常创建一个连接代理器,则放弃此次同步机会并改为异步进行
             if (agent == null || !agent.GetChannel().IsConnected)
             {
                 return(false);
             }
             Register(agent);
             return(true);
         }
         catch (System.Exception ex)
         {
             _tracing.Error(ex);
             return(false);
         }
         finally
         {
             if (_connections.Count < _max && Interlocked.CompareExchange(ref _usedBackendThread, 1, 0) == 0)
             {
                 CreateAgentAsync();
             }
         }
     }
 }
Esempio n. 8
0
 /// <summary>
 ///     获取指定活动所绑定的标签信息集合
 /// </summary>
 /// <param name="campaignId">活动编号</param>
 /// <returns>执行结果</returns>
 public IExecuteResult <SimpleUserTag[]> GetUserTagsByCampaignId(ulong campaignId)
 {
     try
     {
         //获取参数的值
         object[] parameterValues = new object[] { campaignId };
         //验证CampaignId和AccountId从属关系
         DataTable dt = _slaveDB.SpExecuteTable(SpName.SpGetUserTagsByCampaignId, ParametersObject.GetUserTagsByCampaignId, parameterValues);
         if (dt.Rows.Count <= 0)
         {
             return(ExecuteResult <SimpleUserTag[]> .Succeed(null));
         }
         SimpleUserTag[] tags = new SimpleUserTag[dt.Rows.Count];
         for (int i = 0; i < dt.Rows.Count; i++)
         {
             tags[i] = _convertor.ConvertToDomain(dt.Rows[i]);
         }
         return(ExecuteResult <SimpleUserTag[]> .Succeed(tags));
     }
     catch (Exception ex)
     {
         _tracing.Error(ex, null);
         return(ExecuteResult <SimpleUserTag[]> .Fail(SystemErrors.Unknown, ex.Message));
     }
 }
Esempio n. 9
0
        /// <summary>
        /// 启动接受客户端连接
        /// </summary>
        private void StartAccept()
        {
            if (isListening)
            {
                bool asyAccept = false;
                try
                {
                    asyAccept = listener.AcceptAsync(accpetEventArgs);
                }
                catch (SocketException ex)
                {
                    _tracing.ErrorFmt(ex, "AcceptAsync发生Sokcet异常,ErrorCode:{0},StartAccept被迫中止", ex.ErrorCode);
                    return;
                }
                catch (ObjectDisposedException ex)
                {
                    _tracing.Error(ex, "AcceptAsync发生异常,监听socket已释放,StartAccept被迫中止");
                    return;
                }
                catch (Exception ex)
                {
                    _tracing.Error(ex, "AcceptAsync发生异常,StartAccept被迫中止");
                    return;
                }

                if (!asyAccept)
                {
                    ProcessAccept(accpetEventArgs);
                }
            }
        }
        /// <summary>
        ///     解析元数据
        /// </summary>
        /// <param name="data">总BUFF长度</param>
        /// <param name="offset">可用偏移量</param>
        /// <param name="count">可用长度</param>
        /// <returns>
        ///     返回能否解析的一个标示
        /// </returns>
        public override List <T> Parse <T>(byte[] data, int offset, int count)
        {
            int      totalLength;
            List <T> messages = new List <T>();

            try
            {
                while (count > 0)
                {
                    totalLength = BitConverter.ToInt32(data, offset);
                    if (totalLength > data.Length)
                    {
                        _tracing.Error("#Parse message failed, illegal total length. #length: " + totalLength);
                        return(messages);
                    }
                    int markRangeCount  = BitConverter.ToUInt16(data, offset + 4);
                    int markRangeLength = markRangeCount * 5 + offset;
                    int protocolId      = data[markRangeLength + 6];
                    int serviceId       = data[markRangeLength + 7];
                    int detailsId       = data[markRangeLength + 8];
                    MetadataContainer message;
                    try
                    {
                        message = MetadataObjectEngine.GetObject(data, (uint)offset, (uint)totalLength);
                        if (message == null)
                        {
                            _tracing.Error(
                                "#Parse message failed, parse result = null. #protocol id={0}, service id={1}, detalis id={2}: ",
                                protocolId, serviceId, detailsId);
                            return(messages);
                        }
                    }
                    catch (System.Exception ex)
                    {
                        _tracing.Error(ex, "#Parse message failed.");
                        continue;
                    }
                    finally
                    {
                        offset += totalLength;
                        count  -= totalLength;
                    }
                    messages.Add((T)(object)message);
                    if (data.Length - offset < 4)
                    {
                        break;
                    }
                }
                return(messages);
            }
            catch (System.Exception ex)
            {
                _tracing.Error(ex, "#Parse message failed.");
                return(messages);
            }
        }
        private static void RecycleProc()
        {
            while (true)
            {
                try {
                    Thread.Sleep(1000);

                    List <RpcTcpSimplexConnectionWrapper> keys = new List <RpcTcpSimplexConnectionWrapper>();
                    lock (_syncRoot) {
                        foreach (var k in _connections)
                        {
                            keys.Add(k.Key);
                        }
                    }

                    //
                    // 尝试回收一个连接
                    foreach (var k in keys)
                    {
                        k.TryRecycle();
                    }

                    //
                    // 关闭延时Queue中的Socket
                    while (_closeQueue.Count > 0)
                    {
                        ComboClass <DateTime, RpcTcpSocketConnection> a;
                        lock (_syncRoot) {
                            a = _closeQueue.Peek();
                            if (DateTime.Now > a.V1)
                            {
                                a = _closeQueue.Dequeue();
                            }
                            else
                            {
                                break;
                            }
                        }
                        try {
                            RpcTcpSocketConnection sock = a.V2;
                            _tracing.InfoFmt("delay close connection: {0}", sock.RemoteUri);
                            sock.Disconnect();
                            _tracing.InfoFmt("delay close connection ok {0}", sock.RemoteUri);
                        } catch (Exception ex) {
                            _tracing.Error(ex, "delay close connection failed");
                        }
                    }
                } catch (ThreadAbortException) {
                    Thread.ResetAbort();
                } catch (Exception ex) {
                    _tracing.Error(ex, "RecycleProc Failed");
                }
            }
        }
Esempio n. 12
0
        private void FormLoad()
        {
            this.btnFinish.Visible = false;
            string localXmlFile  = string.Concat(Application.StartupPath, "\\UpdateList.xml");
            string serverXmlFile = string.Empty;

            try
            {
                _UpdaterXmlFiles = new XmlFiles(localXmlFile);
            }
            catch (Exception e)
            {
                _tracing.Error(e, "the config xml is reading failed.");
                this.Close();
                return;
            }
            //获取更新服务器地址
            _UpdateUri = _UpdaterXmlFiles.GetNodeValue("//Url");
            AppUpdater appupdater = AppUpdater.GetInstance();

            appupdater.UpdaterUrl = _UpdateUri + "/UpdateList.xml";
            //与服务器连接获取配置文件
            try
            {
                _TempUpatePath = Environment.GetEnvironmentVariable("Temp") + "\\_" + _UpdaterXmlFiles.FindNode("//Application").Attributes["applicationId"].Value + "_y_x_m_\\";
                appupdater.DownAutoUpdateFile(_TempUpatePath);
            }
            catch (Exception e)
            {
                _tracing.Error(e, "Connect to server failed");
                Utils.ShowMessageBox(Messages.ConnectServerFailed, Messages.TitleNotification);
                this.Close();
                return;
            }
            //获取文件列表
            serverXmlFile = _TempUpatePath + "\\UpdateList.xml";
            if (!File.Exists(serverXmlFile))
            {
                return;
            }
            Hashtable htUpdateFile = new Hashtable();

            availableUpdate = appupdater.CheckForUpdate(serverXmlFile, localXmlFile, out htUpdateFile);
            if (availableUpdate > 0)
            {
                for (int i = 0; i < htUpdateFile.Count; i++)
                {
                    string[] fileArray = (string[])htUpdateFile[i];
                    //lvUpdateList.Items.Add(new ListViewItem(fileArray));
                    lvUpdateList.Items.Add(new  ListViewItem(fileArray));
                }
            }
        }
Esempio n. 13
0
 /// <summary>
 ///     内部执行
 /// </summary>
 protected void Proc()
 {
     try
     {
         InnerProc();
     }
     catch (System.Exception ex)
     {
         _tracing.Error(ex, null);
         EndWork();
     }
 }
Esempio n. 14
0
 /// <summary>
 /// 保存设备信息
 /// </summary>
 /// <returns></returns>
 public bool SaveDeviceInfomation(Device device, PointInfo points, LogConfig log, List <AlarmConfig> alarm, List <DigitalSignature> ds)
 {
     using (System.Data.SQLite.SQLiteConnection conn = SQLiteHelper.SQLiteHelper.CreateConn())
     {
         PointTempBLL        _point   = new PointTempBLL();
         LogConfigBLL        _log     = new LogConfigBLL();
         AlarmConfigBLL      _alarm   = new AlarmConfigBLL();
         ReportEditorBLL     _report  = new ReportEditorBLL();
         DigitalSignatureBLL _digital = new DigitalSignatureBLL();
         if (conn.State != System.Data.ConnectionState.Open)
         {
             conn.Open();
         }
         System.Data.Common.DbTransaction tran = conn.BeginTransaction();
         try
         {
             //保存设备信息
             if (InsertDevice(device, tran) &&
                 //保存温度点信息
                 _point.InsertPoint(points, tran) &&
                 //保存log信息
                 _log.InsertLogConfig(log, tran) &&
                 //保存alarm信息
                 _alarm.InsertAlarmConfig(alarm, tran) &&
                 _digital.InsertDigitalSignature(ds, tran)
                 )
             {
                 tran.Commit();
             }
             else
             {
                 tran.Rollback();
             }
         }
         catch (Exception ex)
         {
             tran.Rollback();
             conn.Close();
             _tracing.Error(ex, "save data to db failed!");
             return(false);
         }
         finally
         {
             if (conn.State == ConnectionState.Open)
             {
                 conn.Close();
             }
         }
     }
     return(true);
 }
        public IEnumerable <Rates> GetRates()
        {
            _myTracing.Debug(string.Format("{0} --- {1}", nameof(DataManager), nameof(GetRates)));
            string endpoint = ConfigurationManager.AppSettings["RatesUrl"];

            if (string.IsNullOrEmpty(endpoint))
            {
                _myTracing.Error(string.Format("Rates Url could not be found in config"));
                throw new NullReferenceException();
            }

            string json = _jsonProvider.GetDataFromUri(endpoint);

            try
            {
                RatesList = new List <Rates>();
                RatesList = JsonConvert.DeserializeObject <List <Rates> >(json);
            }
            catch (Exception ex)
            {
                _myTracing.Error(string.Format("Error when DeserializeObject was invoke : {0}", ex.Message));
                throw ex;
            }
            Task.Run(() => _fileProvider.Write(RatesList));
            return(RatesList);
        }
Esempio n. 16
0
        /// <summary>
        /// 解析元数据
        /// </summary>
        /// <param name="data">元数据</param>
        /// <returns>
        /// 返回能否解析的一个标示
        /// </returns>
        public override List <T> Parse <T>(byte[] data)
        {
            int      offset = 0;
            int      totalLength;
            List <T> messages = new List <T>();

            try
            {
                while (offset < data.Length)
                {
                    totalLength = BitConverter.ToInt32(data, offset);
                    if (totalLength > data.Length)
                    {
                        _tracing.Error("#Parse message failed, illegal total length. #length: " + totalLength);
                        return(messages);
                    }
                    byte[] messageData = totalLength == data.Length
                                             ? data
                                             : ByteArrayHelper.GetReallyData(data, offset, totalLength);
                    int  protocolId  = messageData[5];
                    int  serviceId   = messageData[6];
                    int  detailsId   = messageData[7];
                    Type messageType = GetMessageType(protocolId, serviceId, detailsId);
                    if (messageType == null)
                    {
                        _tracing.Error("#Parse message failed, illegal message protocol. #protocol id={0}, service id={1}, detalis id={2}\r\nTarget protocol stack: {3} ", protocolId, serviceId, detailsId, this);
                        return(messages);
                    }
                    offset += messageData.Length;
                    BaseMessage message;
                    try
                    {
                        //使用智能对象引擎进行解析
                        message = IntellectObjectEngine.GetObject <BaseMessage>(messageType, messageData);
                        if (message == null)
                        {
                            _tracing.Error("#Parse message failed, parse result = null. #protocol id={0}, service id={1}, detalis id={2}: ", protocolId, serviceId, detailsId);
                            return(messages);
                        }
                    }
                    catch (System.Exception ex)
                    {
                        _tracing.Error(ex, "#Parse message failed.");
                        continue;
                    }
                    messages.Add((T)(object)message);
                    if (data.Length - offset < 4)
                    {
                        break;
                    }
                }
                return(messages);
            }
            catch (System.Exception ex)
            {
                _tracing.Error(ex, "#Parse message failed.");
                return(messages);
            }
        }
Esempio n. 17
0
        /// <summary>
        ///     从OKcoin平台获取Ticker数据
        /// </summary>
        public IExecuteResult GetBTCTickerFromOkCoin()
        {
            try
            {
                string         responseText = null;
                HttpWebRequest request      = (HttpWebRequest)WebRequest.Create("http://okcoin.com/api/ticker.do");
                request.Method = "Get";
                request.Headers.Clear();
                request.ContentType   = "application/json; charset=UTF-8";
                request.ContentLength = 0;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    Stream stream = response.GetResponseStream();
                    if (stream != null)
                    {
                        StreamReader read = null;
                        using (read = new StreamReader(stream, Encoding.UTF8))
                            responseText += read.ReadToEnd();
                    }
                }
                JObject o      = (JObject)JsonConvert.DeserializeObject(responseText);
                Ticker  ticker = new Ticker
                {
                    BuyPrice  = double.Parse(o["ticker"]["buy"].ToString()),
                    HignPrice = double.Parse(o["ticker"]["high"].ToString()),
                    LastPrice = double.Parse(o["ticker"]["last"].ToString()),
                    LowPrice  = double.Parse(o["ticker"]["low"].ToString()),
                    SellPrice = double.Parse(o["ticker"]["sell"].ToString()),
                    Vol       = double.Parse(o["ticker"]["vol"].ToString()),
                };

                string sqlStr = string.Format("INSERT INTO `coin`.`trades`(`CoinId`,`PlatformId`,`BuyPrice`,`SellPrice`,`HighPrice`,`LowPrice`,`TradeVol`,`NowTime`,`LastPrice`)VALUE({0},{1},{2},{3},{4},{5},{6},{7},{8})",
                                              (int)CoinTypes.BTC, (int)PlatformTypes.OKCoin, ticker.BuyPrice, ticker.SellPrice, ticker.HignPrice, ticker.LowPrice, ticker.Vol, string.Format("'{0}'", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")), ticker.LastPrice);

                int count = InsertData(sqlStr);
                if (count == 0)
                {
                    return(ExecuteResult.Fail(SystemErrors.Unknown, "插入数据库时出错"));
                }
                return(ExecuteResult.Succeed(ticker));
            }
            catch (Exception ex)
            {
                _tracing.Error(ex, null);
                return(ExecuteResult.Fail(SystemErrors.Unknown, ex.Message));
            }
        }
Esempio n. 18
0
 protected virtual void Split()
 {
     if (_url == null)
     {
         throw new System.Exception("×ÊÔ´µØÖ·±êʾ²»ÄÜΪ¿Õ¡£");
     }
     if (_url.Trim() == "")
     {
         return;
     }
     try
     {
         int flagStartOffset;
         if ((flagStartOffset = _url.IndexOf(_splitFlag)) == -1)
         {
             throw new System.Exception("·Ç·¨µÄ×ÊÔ´µØÖ·±êʾ¡£");
         }
         String prefix  = _url.Substring(0, flagStartOffset);
         String address = _url.Substring(flagStartOffset + _splitFlag.Length, _url.Length - (flagStartOffset + _splitFlag.Length));
         if (String.IsNullOrEmpty(prefix) || String.IsNullOrEmpty(address))
         {
             throw new System.Exception("·Ç·¨µÄ×ÊÔ´µØÖ·±êʾ¡£");
         }
         _prefix  = prefix;
         _address = address;
     }
     catch (System.Exception ex)
     {
         _tracing.Error(ex, null);
         throw new System.Exception("·Ç·¨µÄ×ÊÔ´µØÖ·±êʾ¡£");
     }
 }
        public string GetDataFromUri(string endpoint)
        {
            try
            {
                #region WebRequest

                WebRequest request = WebRequest.Create(endpoint);
                request.Method = "GET";
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                #endregion

                #region Deserialize

                Stream       sr     = response.GetResponseStream();
                StreamReader reader = new StreamReader(sr);
                string       json   = reader.ReadToEnd();
                reader.Close();
                sr.Close();
                response.Close();
                return(json);

                #endregion
            }
            catch (Exception ex)
            {
                _myTracing.Error(string.Format(ex.Message));
                throw ex;
            }
        }
Esempio n. 20
0
        /// <summary>
        ///     获得登录端的IPv4
        /// <para>*当返回值为空则说明ip不合法或者为线程调用</para>
        /// </summary>
        /// <returns>ip</returns>
        private static IPEndPoint GetLoginClientIPv4()
        {
            IPEndPoint ipEndPoint;

            try
            {
                string ip = string.Empty;
                if (HttpContext.Current != null)
                {
                    if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
                    {
                        if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] == null)
                        {
                            if (HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"] != null)
                            {
                                ip = HttpContext.Current.Request.ServerVariables["HTTP_CLIENT_IP"];
                            }
                            else
                            if (HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] != null)
                            {
                                ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                            }
                        }
                        else
                        {
                            ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                        }
                    }
                    else if (HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] != null)
                    {
                        ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                    }
                }
                else
                {
                    string      hostName  = Dns.GetHostName();
                    IPHostEntry ipEntry   = Dns.GetHostEntry(hostName);
                    IPAddress   ipAddress = null;
                    for (int i = 0; i < ipEntry.AddressList.Length; i++)
                    {
                        if (ipEntry.AddressList[i].AddressFamily.ToString() == "InterNetwork")
                        {
                            ipAddress = ipEntry.AddressList[i];
                            break;
                        }
                    }
                    if (ipAddress != null)
                    {
                        ip = ipAddress.Address.ToString();
                    }
                }
                ipEndPoint = string.IsNullOrEmpty(ip) ? null : new IPEndPoint(IPAddress.Parse(ip).MapToIPv4(), 0);
            }
            catch (Exception ex)
            {
                ipEndPoint = null;
                _tracing.Error(ex, null);
            }
            return(ipEndPoint);
        }
Esempio n. 21
0
 /// <summary>
 ///     ֹͣ
 /// </summary>
 public void Abort()
 {
     try
     {
         _communicationState = CommunicationStates.Closing;
         InnerAbort();
         _communicationState = CommunicationStates.Closed;
     }
     catch (System.Exception ex)
     {
         _communicationState = CommunicationStates.Faulte;
         _tracing.Error(ex, null);
         FaultedHandler(null);
         throw;
     }
 }
Esempio n. 22
0
        /// <summary>
        ///   第三方用户使用的方法,意在使用自己的方式提取有用的数据
        /// </summary>
        /// <returns/>
        protected override List <byte[]> PickupData(ref int nextOffset, int offset)
        {
            int totalRecLength = offset;

            try
            {
                List <byte[]> bytes = new List <byte[]>();
                while (nextOffset < offset)
                {
                    int length = BitConverter.ToInt32(_buffer, nextOffset);
                    //not long enough.
                    if (totalRecLength - length < 0)
                    {
                        return(bytes);
                    }
                    byte[] newData = new byte[length];
                    System.Buffer.BlockCopy(_buffer, nextOffset, newData, 0, length);
                    nextOffset = nextOffset + length;
                    bytes.Add(newData);
                    totalRecLength -= length;
                }
                return(bytes);
            }
            catch (System.Exception ex)
            {
                _tracing.Error(ex, null);
                return(null);
            }
        }
 public void Write(object instance)
 {
     try
     {
         _myTracing.Debug(string.Format("{0} --- {1}", nameof(PersistentManager), nameof(Write)));
         string directoryPath = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
         if (instance is IEnumerable <Rates> rateList)
         {
             using (StreamWriter file = File.CreateText(directoryPath + @"/rates.json"))
             {
                 JsonSerializer serializer = new JsonSerializer();
                 serializer.Serialize(file, rateList);
             }
         }
         else if (instance is IEnumerable <Transaction> transactionList)
         {
             using (StreamWriter file = File.CreateText(directoryPath + @"/transactions.json"))
             {
                 JsonSerializer serializer = new JsonSerializer();
                 serializer.Serialize(file, transactionList);
             }
         }
     }
     catch (Exception ex)
     {
         _myTracing.Error(string.Format("Error when the data had been saving in disk : {0}", ex.Message));
     }
 }
Esempio n. 24
0
 public bool connectDevice()
 {
     if (Code == 11)
     {
         return(false);
     }
     try
     {
         string comname = SerialHelper.GetOneCom();
         ReadDone = false;
         if (comname.Length > 0)
         {
             SerialPortFixer.Execute(comname);
             spt = new SerialPortTran(comname, false);
             return(true);
         }
         else
         {
             //throw new Exception("can not found any device connected");
             _tracing.Error("can not found any device connected");
             return(false);
         }
     }
     catch {
         return(false);
     }
 }
Esempio n. 25
0
 /// <summary>
 ///   处理接收到的数据
 /// </summary>
 /// <param name="args">异步SOCKET事件</param>
 private void ProcessRecv(SocketAsyncEventArgs args)
 {
     if (args.BytesTransferred == 0 || args.SocketError != SocketError.Success)
     {
         Stop();
         return;
     }
     try
     {
         int    count   = args.BytesTransferred;
         string content = Encoding.UTF8.GetString(args.Buffer, 0, count);
         CommonBoradcastProtocol obj = JsonConvert.DeserializeObject <CommonBoradcastProtocol>(content);
         //discard current boradcast object directly when it was an illegal object.
         if (string.IsNullOrEmpty(obj.Key))
         {
             return;
         }
         //dispatch it.
         Action <CommonBoradcastProtocol> callback;
         if (!_callbacks.TryGetValue(obj.Key, out callback))
         {
             _tracing.Warn("#We had to discared current boradcast object, because of it hasn't any dispatcher in there.");
             return;
         }
         callback(obj);
     }
     catch (System.Exception ex) { _tracing.Error(ex, null); }
     finally { StartRecv(args); }
 }
Esempio n. 26
0
        void NewTransaction(object sender, KJFramework.EventArgs.LightSingleArgEventArgs <IMessageTransaction <BaseMessage> > e)
        {
            BusinessMessageTransaction transaction = (BusinessMessageTransaction)e.Target;
            IMessageProcessor          processor;
            MessageIdentity            identity = transaction.Request.MessageIdentity;

            if (!_processors.TryGetValue(new Protocols {
                ProtocolId = identity.ProtocolId, ServiceId = identity.ServiceId, DetailsId = identity.DetailsId
            }, out processor))
            {
                _tracing.Error("#Schedule message failed, because cannot find processor. #P:{0}, S{1}, D{2}", identity.ProtocolId, identity.ServiceId, identity.DetailsId);
                return;
            }
            try { processor.Process(transaction); }
            catch (Exception ex) { _tracing.Error(ex, null); }
        }
Esempio n. 27
0
 public IExecuteResult GetValue(CoinTypes coinType, PlatformTypes platformType)
 {
     try
     {
         KeyParse keyParse = new KeyParse {
             CoinType = coinType, PlatformType = platformType
         };
         string key     = keyParse.ToString();
         string content = m_Cache[key] as string;
         if (content == null)
         {
             CacheItemPolicy policy = new CacheItemPolicy();
             policy.AbsoluteExpiration = DateTime.Now.AddMilliseconds(25000);
             IExecuteResult <Ticker> result = _remoteApiService.GetDataFromDataBase(key);
             if (result.State != ExecuteResults.Succeed)
             {
                 return(ExecuteResult.Fail(SystemErrors.Unknown, null));
             }
             content = result.GetResult().ToString();
             m_Cache.Set(key, content, policy);
         }
         return(ExecuteResult.Succeed(JsonConvert.DeserializeObject <Ticker>(content)));
     }
     catch (Exception ex)
     {
         _tracing.Error(ex, null);
         return(ExecuteResult.Fail(SystemErrors.NotFound, null));
     }
 }
Esempio n. 28
0
 public unsafe static bool TryParse(string value, out KeyParse key)
 {
     if (string.IsNullOrEmpty(value))
     {
         key = null;
         return(false);
     }
     try
     {
         byte[] preData = Convert.FromBase64String(value);
         byte[] deData  = EncryptTEAHelper.Decrypt(preData);
         fixed(byte *pByte = deData)
         {
             key = new KeyParse {
                 CoinType = (CoinTypes)(*(pByte)), PlatformType = (PlatformTypes)(*(pByte + 1))
             };
             return(true);
         }
     }
     catch (Exception ex)
     {
         _tracing.Error(ex, null);
         key = null;
         return(false);
     }
 }
Esempio n. 29
0
        /// <summary>
        ///     连接到远程终结点
        /// </summary>
        /// <param name="channel">基于流的通讯信道</param>
        /// <exception cref="NullReferenceException">远程终结点地址不能为空</exception>
        public void Connect(IRawTransportChannel channel)
        {
            try
            {
                #region Clear resource before.

                //get clear for org channel.
                if (_channel != null)
                {
                    _channel.Buffer        = null;
                    _channel.Disconnected -= RawChannelDisconnected;
                    _channel.ReceivedData -= RawChannelReceivedData;
                    if (_channel.IsConnected)
                    {
                        _channel.Disconnect();
                    }
                    _channel = null;
                }

                #endregion

                if (channel == null)
                {
                    throw new ArgumentNullException("channel");
                }
                channel.Connect();
                if (_connected = channel.IsConnected)
                {
                    _channel = channel;
                    if (_channel.Buffer == null)
                    {
                        _channel.Buffer = new ReceiveBuffer(102400);
                    }
                    _logicalAddress        = _channel.LogicalAddress;
                    _address               = _channel.Address;
                    _channel.Disconnected += RawChannelDisconnected;
                    _channel.ReceivedData += RawChannelReceivedData;
                    ChannelConnectedHandler(null);
                }
            }
            catch (System.Exception ex)
            {
                _tracing.Error(ex, null);
                throw;
            }
        }
 /// <summary>
 ///     注册一个智能类型处理器
 ///     <para>* 如果该类型的处理器已经存在,则进行替换操作。</para>
 /// </summary>
 /// <param name="processor">智能类型处理器</param>
 public void Regist(IIntellectTypeProcessor processor)
 {
     if (processor == null)
     {
         return;
     }
     try
     {
         if (_processor.ContainsKey(processor.SupportedType))
         {
             _processor[processor.SupportedType] = processor;
             return;
         }
         _processor.Add(processor.SupportedType, processor);
     }
     catch (System.Exception ex) { _tracing.Error(ex, null); }
 }