Пример #1
0
        /// <summary>
        /// 发送请求带返回
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="transfer"></param>
        /// <returns></returns>
        public T  Send <T>(DBTransfer transfer)
        {
            byte[] buf = SerializerFactory <CommonSerializer> .Serializer(transfer);

            //RequestServer request = new RequestServer();
            //request.Address = SrvControl.Instance.GetCureent();
            //byte[] rec= request.Request(buf);
            byte[] rec = SetRequest(transfer);

            if (rec == null)
            {
                return(default(T));
            }
            RequestResult result = SerializerFactory <CommonSerializer> .Deserialize <RequestResult>(rec);

            if (result.Error == ErrorCode.Sucess)
            {
                if (typeof(T) == typeof(DataTable) || typeof(T) == typeof(DataSet))
                {
                    //当前序列化不能对DataTable
                    //服务端转换为XML
                    if (result.Result != null)
                    {
                        DataSet ds    = new DataSet();
                        byte[]  bytes = SerializerFactory <CommonSerializer> .Serializer(result.Result);

                        DataSetModel dataSetModel = SerializerFactory <CommonSerializer> .Deserialize <DataSetModel>(bytes);

                        if (dataSetModel != null)
                        {
                            var stream = new StringReader(dataSetModel.Schema);
                            ds.ReadXmlSchema(stream);
                            //ds.ReadXml(dataSetModel.Content);
                            //从stream装载到XmlTextReader
                            stream = new StringReader(dataSetModel.Content);
                            var reader = new XmlTextReader(stream);
                            ds.ReadXml(reader);
                            if (typeof(T) == typeof(DataSet))
                            {
                                result.Result = ds;
                            }
                            else
                            {
                                result.Result = ds.Tables[0];
                            }
                        }
                    }
                }
                return((T)result.Result);
            }
            else if (result.ReslutMsg == "请登录")
            {
                CryptoClient.Singleton.IsLogin = false;
                throw new ServerException(result.ReslutMsg);
            }
            else
            {
                throw new ServerException(result.ReslutMsg);
            }
        }
Пример #2
0
        /// <summary>
        /// 从缓存文件中获取数据
        /// </summary>
        /// <param name="db"></param>
        /// <param name="queryID"></param>
        /// <param name="pageNum"></param>
        /// <param name="isModel"></param>
        /// <returns></returns>
        private object GetFile(string db, long queryID, int pageNum, bool isModel)
        {
            string flage = "T";

            if (isModel)
            {
                flage = "N";
            }
            string dir = Path.Combine(PageConfig.FileCacheDir, db);

            string[] files = Directory.GetFileSystemEntries(dir, queryID + "_" + pageNum + "_" + flage + CacheFileExtension);
            if (files.Length > 0)
            {
                foreach (string file in files)
                {
                    using (FileStream fs = new FileStream(file, FileMode.Open))
                    {
                        byte[] bytes = new byte[fs.Length];
                        fs.Read(bytes, 0, bytes.Length);
                        if (!isModel)
                        {
                            return(SerializerFactory <CommonSerializer> .Deserialize <DataTable>(bytes));
                        }
                        else
                        {
                            return(SerializerFactory <CommonSerializer> .Deserialize <List <object> >(bytes));
                        }
                    }
                }
            }
            return(null);
        }
Пример #3
0
        /// <summary>
        /// 发送请求无返回
        /// </summary>
        /// <param name="transfer"></param>
        public void Send(DBTransfer transfer)
        {
            byte[] buf = SerializerFactory <CommonSerializer> .Serializer(transfer);

            //RequestServer request = new RequestServer();
            //request.Address = SrvControl.Instance.GetCureent();
            //byte[] rec = request.Request(buf);
            byte[] rec = SetRequest(transfer);
            if (rec == null)
            {
                return;
            }
            RequestResult result = SerializerFactory <CommonSerializer> .Deserialize <RequestResult>(rec);

            if (result.Error == ErrorCode.Exception)
            {
                if (result.ReslutMsg == "请登陆")
                {
                    CryptoClient.Singleton.IsLogin = false;
                }
                else
                {
                    throw new ServerException(result.ReslutMsg);
                }
            }
        }
Пример #4
0
        public async Task <TValue> GetAsync <TValue>(string key, CancellationToken cancellation = default(CancellationToken))
        {
            CheckIfInitialized();

            try
            {
                byte[] blob = null;
                using (var activity = _activitySource?.StartActivity("Get from cache.", ActivityKind.Producer))
                {
                    activity?.AddTag("cacheKey", key);

                    blob = await DistributeCache?.GetAsync(key, cancellation);

                    if (null == blob)
                    {
                        return(default(TValue));
                    }

                    using (var serializerActivity = _activitySource?.StartActivity("Deserialize.", ActivityKind.Producer))
                        return(SerializerFactory.Deserialize <TValue>(blob));
                }
            }
            catch (Exception ex)
            {
                throw new DataCacheException(ex.Message);
            }
        }
Пример #5
0
        /// <summary>
        /// 通过导出RSAParameters值转换
        /// </summary>
        /// <param name="rsa"></param>
        /// <param name="param"></param>
        public static void FromRSAParameters(RSA rsa, string param)
        {
            byte[]        p      = Convert.FromBase64String(param);
            RSAParameters reslut = SerializerFactory <CommonSerializer> .Deserialize <RSAParameters>(p);

            //  RSAParameters reslut = BytesToStruct<RSAParameters>(p);
            rsa.ImportParameters(reslut);
        }
Пример #6
0
        private static void Session_OnDataReceived(object sender, AsyncUdpUserToken token)
        {
            RequestResult result = SerializerFactory <CommonSerializer> .Deserialize <RequestResult>(token.Data);

            if (result != null)
            {
                Console.WriteLine(result.ErrorMsg);
            }
        }
Пример #7
0
        /// <summary>
        /// 设置登录信息
        /// </summary>
        /// <param name="rec"></param>
        public void SetLogin(byte[] rec)
        {
            var response = SerializerFactory <CommonSerializer> .Deserialize <ServerResponse>(rec);

            Sessionid = response.Clientid;
            CipherReply.Singleton.RSAPublicKeys = response.RSAPublicKeys;
            if (response.IsSucess)
            {
                IsLogin = true;
            }
        }
Пример #8
0
        public Dictionary <object, T> GetKVS <T>(object[] keys)
        {
            Dictionary <object, T> dicResult = new Dictionary <object, T>(keys.Length);

            foreach (object key in keys)
            {
                byte[] data  = RedisHelper.GetBytes(key.ToString());
                T      value = SerializerFactory <CommonSerializer> .Deserialize <T>(data);

                dicResult[key] = value;
            }
            return(dicResult);
        }
Пример #9
0
        public TValue GetData(TKey key, Transaction txn = null)
        {
            TValue value = default(TValue);

            byte[] kdata = SerializerFactory <CommonSerializer> .Serializer(key);

            byte[] vdata = Get(kdata, null, txn);
            if (null != vdata)
            {
                value = SerializerFactory <CommonSerializer> .Deserialize <TValue>(vdata);
            }
            return(value);
        }
Пример #10
0
        /// <summary>
        /// 发送请求无返回
        /// </summary>
        /// <param name="transfer"></param>
        public void Send(DBTransfer transfer)
        {
            byte[] buf = SerializerFactory <CommonSerializer> .Serializer(transfer);

            RequestServer request = new RequestServer();

            request.Address = SrvControl.Instance.GetCureent();
            byte[]        rec    = request.Request(buf);
            RequestResult result = SerializerFactory <CommonSerializer> .Deserialize <RequestResult>(rec);

            if (result.Error == ErrorCode.Exception)
            {
                throw new ServerException(result.ReslutMsg);
            }
        }
Пример #11
0
        /// <summary>
        /// 发送请求带返回
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="transfer"></param>
        /// <returns></returns>
        public T  Send <T>(DBTransfer transfer)
        {
            byte[] buf = SerializerFactory <CommonSerializer> .Serializer(transfer);

            RequestServer request = new RequestServer();

            request.Address = SrvControl.Instance.GetCureent();
            byte[]        rec    = request.Request(buf);
            RequestResult result = SerializerFactory <CommonSerializer> .Deserialize <RequestResult>(rec);

            if (result.Error != ErrorCode.Exception)
            {
                if (typeof(T) == typeof(DataTable) || typeof(T) == typeof(DataSet))
                {
                    //当前序列化不能对DataTable
                    //服务端转换为XML
                    if (result.Result != null)
                    {
                        if (typeof(string) == result.Result.GetType())
                        {
                            DataSet ds     = new DataSet();
                            var     stream = new StringReader(result.Result.ToString());
                            //从stream装载到XmlTextReader
                            var reader = new XmlTextReader(stream);
                            ds.ReadXml(reader);
                            if (typeof(T) == typeof(DataSet))
                            {
                                result.Result = ds;
                            }
                            else
                            {
                                result.Result = ds.Tables[0];
                            }
                        }
                    }
                }
                return((T)result.Result);
            }
            else
            {
                throw new ServerException(result.ReslutMsg);
            }
        }
Пример #12
0
        /// <summary>
        /// 处理请求任务
        /// </summary>
        /// <param name="source"></param>
        /// <param name="client"></param>
        private void SubmitTask(SrvDataSource source, ClientRequest client)
        {
            Console.WriteLine("Submint:" + Thread.CurrentThread.ManagedThreadId);
            var data = source.Message as byte[];
            //获取传递的请求
            DBTransfer model = SerializerFactory <CommonSerializer> .Deserialize <DBTransfer>(data);

            if (model.TimeOut == 0)
            {
                //不超时
                var result = DBAcessSrv.Singleton.Execete(Interlocked.Increment(ref rspID), model);
                ResponseResult(source, result, model, client);
            }
            else
            {
                //超时请求
                var result = ExecuteTimeOut(source, client, model);
                ResponseResult(source, result, model, client);
            }
        }
Пример #13
0
 private void Send()
 {
     Task.Factory.StartNew(() =>
     {
         DBTransfer transfer = null;
         int num             = 0;
         int waitTime        = 300;//5分钟
         while (true)
         {
             if (queue.IsEmpty)
             {
                 Thread.Sleep(1000);
                 num++;
                 if (num > waitTime)
                 {
                     break;
                 }
                 continue;
             }
             num = 0;
             if (queue.TryDequeue(out transfer))
             {
                 semaphore.Wait();
                 Task.Factory.StartNew(() =>
                 {
                     byte[] buf            = SerializerFactory <CommonSerializer> .Serializer(transfer);
                     RequestServer request = new RequestServer();
                     request.Address       = SrvControl.Instance.GetCureent();
                     byte[] rec            = request.Request(buf);
                     RequestResult result  = SerializerFactory <CommonSerializer> .Deserialize <RequestResult>(rec);
                     if (SrvExecuteResult != null)
                     {
                         SrvExecuteResult(result.RequestID, result.Error == ErrorCode.Sucess, result.ReslutMsg);
                     }
                     semaphore.Release();
                 });
             }
         }
         Send();//递归更新线程
     });
 }
Пример #14
0
        private void Udp_OnDataReceived(object sender, AsyncUdpUserToken token)
        {
            byte[] buffer = null;
            if (token.Offset == 0 && (token.Length == 0 || token.Data.Length == token.Length))
            {
                buffer = token.Data;
            }
            else
            {
                buffer = new byte[token.Length];
                Array.Copy(buffer, 0, token.Data, token.Offset, token.Length);
            }
            DBTransfer transfer = SerializerFactory <CommonSerializer> .Deserialize <DBTransfer>(buffer);

            token.FreeCache();
            Task.Factory.StartNew(() =>
            {
                ProcessMonitor(transfer, token.Remote);
            });

            //
        }
Пример #15
0
        public IEnumerable <object> ReadAllObjects()
        {
            var types = TypeRegistry.GetDTOTypes().OrderBy(x => x.Name).ToList();

            if (!types.Any(x => x.Equals(typeof(Include))))
            {
                types.Add(typeof(Include));
            }

            types = types.Union(GetSubTypes(types)).ToList();

            using (ISerializer adapter = new SerializerFactory().GetSerializerByPath(Path))
            {
                try
                {
                    var result = new List <object>();

                    foreach (var o in adapter.Deserialize())
                    {
                        if (o is Include)
                        {
                            result.AddRange(ExpandInclude((Include)o));
                        }
                        else
                        {
                            result.Add(o);
                        }
                    }

                    return(result);
                }
                catch (Exception e)
                {
                    throw new IOException($"Exception occured when reading file {Path}\n{e.GetAllMessages()}", e);
                }
            }
        }
Пример #16
0
        private void Process(TCPUserToken token)
        {
            if (dBAcess == null)
            {
                lock (obj_lock)
                {
                    if (dBAcess == null)
                    {
                        dBAcess = new DBAcessSrv();
                    }
                }
            }
            Task.Factory.StartNew((req) =>
            {
                TCPUserToken userToken = req as TCPUserToken;
                DBTransfer model       = SerializerFactory <CommonSerializer> .Deserialize <DBTransfer>(userToken.Data);

                RequestResult result = null;
                if (model.TimeOut == 0)
                {
                    //不超时
                    result = dBAcess.Execete(Interlocked.Increment(ref rspID), model);
                }
                else
                {
                    int timeOut    = model.TimeOut < 0 ? TimeOut : model.TimeOut * 1000;
                    var taskResult = Executors.Submit(() =>
                    {
                        return(dBAcess.Execete(Interlocked.Increment(ref rspID), model));
                    }, timeOut);
                    result = taskResult.Result;
                    if (result == null)
                    {
                        result = new RequestResult();
                    }
                    if (ExecuteErrorCode.timeout == taskResult.ResultCode)
                    {
                        result.Error = ResultErrorCode.TimeOut;
                    }
                    else if (ExecuteErrorCode.exception == taskResult.ResultCode)
                    {
                        result.Error = ResultErrorCode.Exception;
                    }
                }
                //
                if (model.IsJson && result.Error == DBModel.ErrorCode.Sucess && model.IsQuery)
                {
                    CommonSerializer common = new CommonSerializer();
                    result.Result           = common.JSONObjectToString(result.Result);
                }
                byte[] buffer = null;
                try
                {
                    if (result.Result is DataTable)
                    {
                        DataTable dt  = result.Result as DataTable;
                        result.Result = dt.DataSet.GetXml();
                    }
                    buffer = SerializerFactory <CommonSerializer> .Serializer(result);
                }
                catch (Exception ex)
                {
                    result.Error     = ResultErrorCode.Exception;
                    result.ReslutMsg = "序列化失败," + ex.Message;
                    result.Result    = null;
                    buffer           = SerializerFactory <CommonSerializer> .Serializer(result);
                }
                userToken.Rsp(buffer);
            }, token);
        }
Пример #17
0
 /// <summary>
 /// Receive a deserialized object from the network. This method is blocking until a complete object is received.
 /// </summary>
 /// <typeparam name="T">Base type of object to deserialize.</typeparam>
 /// <returns>Deserialized object transmitted through network.</returns>
 /// <exception cref="ArgumentException">When an invalid type is passed as an argument.</exception>
 /// <exception cref="IOException">When an error occurs with an underlying NetworkStream read or deserialization operation.</exception>
 public T ReceiveObject <T>()
 {
     return(serializerFactory.Deserialize <T>(readMessageFromStream()));
 }
Пример #18
0
 /// <summary>
 ///
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="key"></param>
 /// <returns></returns>
 public T Get <T>(string key)
 {
     byte[] data = RedisHelper.GetBytes(key);
     return(SerializerFactory <CommonSerializer> .Deserialize <T>(data));
 }