//------------------ helper methods ------------------- private static long GetTimeTrade(string url, out int id) { Thread.Sleep(100); var requester = new PublicKeyRequiredRequester(); var response = requester.Request(url, Resources.PUBLIC_KEY); using (Stream stream = response.GetResponseStream()) { StreamReader sr = new StreamReader(stream); string s = sr.ReadToEnd(); List <StockExchenge.MarketTradesHistory.Trade> trades = null; try { trades = JConverter.JsonConver <List <StockExchenge.MarketTradesHistory.Trade> >(s); } catch (Exception) { Console.WriteLine($"Response: {s}"); } if (trades?.Count > 0) { var tradeFirst = trades.First(); id = tradeFirst.ID; return(tradeFirst.Time); } else { Console.WriteLine($"NOT FOUND"); } id = 0; return(0); } }
private void GetHistoryCandle() { try { var klineString = kline.GetHistory(); var klines = JConverter.JsonConver <List <object[]> >(klineString); foreach (var k in klines) { var ohlcPoint = new OhlcPoint() { Open = Convert.ToDouble(k[1], new CultureInfo("en-US")), High = Convert.ToDouble(k[2], new CultureInfo("en-US")), Low = Convert.ToDouble(k[3], new CultureInfo("en-US")), Close = Convert.ToDouble(k[4], new CultureInfo("en-US")) }; OhclValues.Add(ohlcPoint); LabelsX.Add(Convert.ToInt64(k[0]).UnixToDateTime().ToString(formatX)); } } catch (Exception ex) { // запись логов в БД } }
public override void ExecuteCommand(ChatSession session, BinaryRequestInfo requestInfo) { session.Logger.DebugFormat("Cmd: SignUp, RemoteEndPoint: {0}", session.RemoteEndPoint); string content = Encoding.UTF8.GetString(requestInfo.Body, 0, requestInfo.Body.Length); session.Logger.DebugFormat("消息内容:{0}", content); ArraySegmentWrapper segmentWrapper = null; ResultInfo <User> result = null; try { //解析Json字符串 var json = JsonDict.Parse(content); string name = json["Name"]; string email = json["Email"]; string pwd = json["Pwd"]; //数据库验证 result = BizManager.AutofacBootstrapper.Resolve <IAuthBiz>().SignUp(name, email, pwd); } catch (Exception ex) { result = new ResultInfo <User>(ex); } //发送注册响应消息 segmentWrapper = new ArraySegmentWrapper(Constants.SIGNUP_RESPONSE_KEY, JConverter.SerializeToBytes(result)); session.SendData(session, segmentWrapper.Wrapper()); }
public override void ExecuteCommand(ChatSession session, BinaryRequestInfo requestInfo) { session.Logger.DebugFormat("Cmd: EditProfile, RemoteEndPoint: {0}", session.RemoteEndPoint); string content = Encoding.UTF8.GetString(requestInfo.Body, 0, requestInfo.Body.Length); session.Logger.DebugFormat("消息内容:{0}", content); ResultInfo result = null; try { //解析Json字符串 var user = JConverter.Deserialize <User>(content); result = BizManager.AutofacBootstrapper.Resolve <IUserBiz>().UpdateUser(user); } catch (Exception ex) { result = new ResultInfo(ex); } ArraySegmentWrapper segmentWrapper = new ArraySegmentWrapper(Constants.EDIT_PROFILE_RESPONSE_KEY, JConverter.SerializeToBytes(result)); session.SendData(session, segmentWrapper.Wrapper()); }
public OrderResponse OrderLimit(string paramOrd, string publicKey, string secretKey) { string correctParam = paramOrd.Replace("_", ""); var privateApi = new SecretKeyRequiredRequester(); string response = string.Empty; Regex my_reg = new Regex(@"\D"); string serverTime = string.Empty; try { serverTime = my_reg.Replace(ServiceRequests.ServerTime(), ""); } catch (Exception ex) { // TODO: loging } string url_order = "https://api.binance.com/api/v3/order?" + correctParam + "&type=LIMIT&recvWindow=5000&timeInForce=GTC×tamp=" + serverTime; string api_parametrs = correctParam + "&type=LIMIT&recvWindow=5000&timeInForce=GTC×tamp=" + serverTime; try { response = privateApi.GetWebRequest(url_order, api_parametrs, publicKey, secretKey, "POST"); } catch (Exception ex) { // TODO: ВЫВЕСТИ НА МОРДУ } return(JConverter.JsonConver <OrderResponse>(response)); }
private void GetHistoryCandle() { try { candles.Clear(); kline = new Kline(SelectedPair, SelectedInterval); var klineString = kline.GetHistory(); var klines = JConverter.JsonConver <List <object[]> >(klineString); foreach (var k in klines) { var ohlcPoint = new Charts.Models.Candle( Convert.ToInt64(k[0], new CultureInfo("en-US")), Convert.ToDouble(k[2], new CultureInfo("en-US")), Convert.ToDouble(k[3], new CultureInfo("en-US")), Convert.ToDouble(k[1], new CultureInfo("en-US")), Convert.ToDouble(k[4], new CultureInfo("en-US"))); candles.Add(ohlcPoint); } } catch (Exception ex) { // запись логов в БД } }
private void GetExchangeInfo(ExchangeInfo exchangeInfo, string simbol) { exchangeSettingsPair = new ExchangeSettingsPair(); try { var jsonString = exchangeInfo.Info; dynamic entity = JConverter.JsonConvertDynamic(jsonString); foreach (var symbol in entity.symbols) { if (symbol.symbol == simbol) { exchangeSettingsPair.QuotePrecision = symbol.quotePrecision; exchangeSettingsPair.BasePrecision = symbol.baseAssetPrecision; foreach (var filter in symbol.filters) { if (filter.filterType == "LOT_SIZE") { decimal stepSize; decimal.TryParse(filter.stepSize.ToString(), NumberStyles.Number, new CultureInfo("en-US"), out stepSize); exchangeSettingsPair.LotSizeFilter.StepSize = stepSize; } } break; } } } catch (Exception ex) { throw ex; } }
private void GetPairs(string data) { if (!string.IsNullOrWhiteSpace(data)) { try { var jsonString = data; dynamic entity = JConverter.JsonConvertDynamic(jsonString); foreach (var symbol in entity.symbols) { if (symbol.status == STATUS_TRADING) { MarketPairs.Add(new MarketPair() { BaseAsset = symbol.baseAsset, QuoteAsset = symbol.quoteAsset, Pair = symbol.symbol, Status = symbol.status }); } } } catch (Exception ex) { // TODO: запись лога в БД throw ex; } } else { throw new ArgumentException("Value IsNullOrWhiteSpace", "data"); } }
public async Task <int> Rquest1() { try { HttpWebRequest reqGET = (HttpWebRequest)WebRequest.Create(@"https://api.binance.com/api/v3/historicalTrades?symbol=BTCUSDT&fromId=1&limit=10"); reqGET.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; reqGET.UserAgent = "Mozilla/5.0 (Windows NT 5.1; rv:5.0) Gecko/20100101 Firefox/5.0"; reqGET.ContentType = "application/x-www-form-urlencoded"; reqGET.Headers.Add("X-MBX-APIKEY", "33SB2WjAtgVzFjcSGLE4fuvxzBQD8sz475bmC29UI8WCwtOVmdKwzqu78zVD6pqx"); HttpWebResponse response = (HttpWebResponse)await reqGET.GetResponseAsync(); var status = (int)response.StatusCode; countRequest++; Console.Clear(); Console.WriteLine($"{status} count: {countRequest}"); WebHeaderCollection headers = response.Headers; for (int i = 0; i < headers.Count; i++) { //Console.WriteLine("{0}: {1}", headers.GetKey(i), headers[i]); } Stream stream = response.GetResponseStream(); StreamReader sr = new StreamReader(stream); string s = sr.ReadToEnd(); var trades = JConverter.JsonConver <List <StockExchenge.MarketTradesHistory.Trade> >(s); //Console.WriteLine(s); return(status); } catch (WebException ex) { var resp = (HttpWebResponse)ex.Response; if (resp != null) { var status = (int)resp.StatusCode; Console.WriteLine(status); return(status); } else { Console.WriteLine(ex.Message); return(-1); } } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine(-2); return(-2); } }
public void Init() { var random = new Random(123); _dataset = new BigObject[Count]; for (var i = 0; i < _dataset.Length; i++) { _dataset[i] = SerializationBuilder.CreateBigObject(random); } _converter = SerializationBuilder.BuildVeloJsonConverter(); }
//public List<Trade> RequestedTrades(string publicKey, string secretKey, TradeConfiguration configuration) //{ // var trades = TradesRequest(publicKey, secretKey, $"{configuration.MainCoin}{configuration.AltCoin}"); // if (trades != null) // { // foreach (var trade in trades) // { // tradeRepository.Create(new DataBaseWork.Models.Trade() // { // FK_PublicKey = publicKey, // Symbol = trade.symbol, // TradeID = trade.id, // OrderID = trade.orderId, // OrderListID = trade.orderListId, // Price = trade.price, // Qty = trade.qty, // QuoteQty = trade.quoteQty, // Commission = trade.commission, // CommissionAsset = trade.commissionAsset, // Time = trade.time, // IsBuyer = trade.isBuyer, // IsMaker = trade.isMaker, // IsBestMatch = trade.isBestMatch // }); // } // } // return trades; //} private List <Trade> TradesRequest(string key, string secret, string pair, long fromId) { logService.Write("***********TradesRequest START***********", true); logService.Write($"\tTradesRequest Public key: {key}"); logService.Write($"\tTradesRequest pair: {pair}"); List <Trade> result = null; var privateApi = new SecretKeyRequiredRequester(); var my_reg = new Regex(@"\D"); var serverTime = ""; var response = ""; try { serverTime = my_reg.Replace(ServiceRequests.ServerTime(), ""); logService.Write($"\tTradesRequest get serverTime successful: {serverTime}"); } catch (Exception ex) { logService.Write($"\tAccount get serverTime error: Exception: {ex.Message} Innerexception: {ex.InnerException?.Message}"); } try { var request = CreatRequest(pair, serverTime, out string requestParams, fromId); response = privateApi.GetWebRequest(request, requestParams, key, secret, "GET"); logService.Write($"\tTradesRequest {Resources.DOMAIN_V3}myTrades... successful: response = {response}"); } catch (Exception ex) { logService.Write($"\tTradesRequest {Resources.DOMAIN_V3}myTrades... error: Exception: {ex.Message} Innerexception: {ex.InnerException?.Message}"); } try { result = JConverter.JsonConver <List <Trade> >(response); logService.Write($"\tTradesRequest JConverter successful."); } catch (Exception ex) { logService.Write($"\tTradesRequest JConverter error: Exception: {ex.Message} Innerexception: {ex.InnerException?.Message}"); } if (result != null) { var tradeForRemove = result.FirstOrDefault(x => x.id == fromId); if (tradeForRemove != null) { result.Remove(tradeForRemove); } } logService.Write("***********TradesRequest END***********", true); return(result); }
public void Init() { var random = new Random(123); _dataset = new string[Count]; for (var i = 0; i < _dataset.Length; i++) { var instance = SerializationBuilder.CreateBigObject(random); _dataset[i] = JsonConvert.SerializeObject(instance); } _converter = new JConverter(); }
public LastPriceResponse GetInfo(string pair) { try { var response = publicRequester.RequestPublicApi($"https://api.binance.com/api/v3/ticker/price?symbol={pair}"); return(JConverter.JsonConver <LastPriceResponse>(response)); } catch (Exception ex) { // TODO: Сохранеие логово } return(null); }
private void Kline_MessageEvent(object sender, KlineEventArgs e) { try { Candle candle = JConverter.JsonConver <Candle>(e.Message); var ohlcPoint = new OhlcPoint() { Open = candle.k.o, High = candle.k.h, Low = candle.k.l, Close = candle.k.c }; var firstCandle = OhclValues.FirstOrDefault(); if (isClose) { OhclValues.Add(ohlcPoint); OhclValues.Remove(firstCandle); LabelsX.Add(candle.k.t.UnixToDateTime().ToString(formatX)); isClose = false; } else { if (OhclValues.Count > 0) { var lastOhlc = OhclValues.Last(); lastOhlc.Open = ohlcPoint.Open; lastOhlc.High = ohlcPoint.High; lastOhlc.Low = ohlcPoint.Low; lastOhlc.Close = ohlcPoint.Close; } else { OhclValues.Add(ohlcPoint); LabelsX.Add(candle.k.t.UnixToDateTime().ToString(formatX)); } } if (candle.k.x) // проверка должна быть после добавления, иначе добавим закрытую свечу { isClose = true; } } catch (Exception ex) { //TODO: запись логов в БД } //CreateChartValuesLines(); }
public Tests() { _jsonConverter = new DependencyCollection() .AddECS() .BuildProvider() .GetRequired <JConverter>(); _converter = _jsonConverter.Converters.Get(typeof(TestAsset)); var reference = CreateAsset(6); var assets = new LocalList <Asset>( new TestAsset(7, new IComponent[] { Fixture.Create <TestComponent1>() }) { Array = Fixture.CreateMany <int>().ToArray(), Reference = reference }, CreateAsset(4, Fixture.Create <TestComponent1>()), CreateAsset(3, Fixture.Create <TestComponent2>()), CreateAsset(2), reference); var components = new IComponent[] { Fixture.Create <TestComponent1>(), Fixture.Create <TestComponent2>(), new TestComponent3 { Asset = (TestAsset)assets[0], AssetsArray = assets.ToArray(), AssetsList = assets.ToList() } }; _asset = new TestAsset(1, components) { Array = Fixture.CreateMany <int>().ToArray() }; assets.Add(_asset); assets.Reverse(); _assets = assets.ToArray(); _actors = new[] { BuildActor(1), new TestActor(2) { Prototype = reference } }; }
public void GetDateTrade() { var requester = new PublicKeyRequiredRequester(); var fromIdStart = 0L; var isFoundtrades = true; while (isFoundtrades) { var response = requester.Request(GetUrl(PAIR, fromIdStart), Resources.PUBLIC_KEY); using (Stream stream = response.GetResponseStream()) { StreamReader sr = new StreamReader(stream); string s = sr.ReadToEnd(); List <StockExchenge.MarketTradesHistory.Trade> trades = null; try { trades = JConverter.JsonConver <List <StockExchenge.MarketTradesHistory.Trade> >(s); } catch (Exception) { Console.WriteLine($"Response: {s}"); break; } if (trades?.Count > 0) { var tradeFirst = trades.First(); var tradesLast = trades.Last(); Console.WriteLine($"STSRT TIME {tradeFirst.ID}: {tradeFirst.Time.UnixToDateTime()}"); Console.WriteLine($"FINISH TIME {tradesLast.ID}: {tradesLast.Time.UnixToDateTime()}"); } else { Console.WriteLine($"NOT FOUND"); isFoundtrades = false; } } fromIdStart += LIMIT; Thread.Sleep(1000); } }
public override void ExecuteCommand(ChatSession session, BinaryRequestInfo requestInfo) { session.Logger.DebugFormat("Cmd: SignIn, RemoteEndPoint: {0}", session.RemoteEndPoint); string content = Encoding.UTF8.GetString(requestInfo.Body, 0, requestInfo.Body.Length); session.Logger.DebugFormat("消息内容:{0}", content); ArraySegmentWrapper segmentWrapper = null; ResultInfo <User> result = null; try { //解析Json字符串 var json = JsonDict.Parse(content); string account = json["Account"]; string pwd = json["Pwd"]; //数据库验证 result = BizManager.AutofacBootstrapper.Resolve <IAuthBiz>().SignIn(account, pwd); if (result.Success) { result.RData.Password = string.Empty; session.User = result.RData; session.User.ConnectState = EConnectState.Online; UserLogin model = new UserLogin() { UserId = result.RData.Id, IP = session.RemoteEndPoint.ToString(), CustomId = session.SessionID, ConnectState = EConnectState.Online }; BizManager.AutofacBootstrapper.Resolve <IAuthBiz>().SaveStatus(model); //通知有客户端连入 session.NotifyOnline(session.SessionID, account); } } catch (Exception ex) { result = new ResultInfo <User>(ex); } //发送登录响应消息 segmentWrapper = new ArraySegmentWrapper(Constants.SIGNIN_RESPONSE_KEY, JConverter.SerializeToBytes(result)); session.SendData(session, segmentWrapper.Wrapper()); }
private void GetLastPrice(string data) { var aggTrade = JConverter.JsonConver <AggTrade>(data); var lastPrice = PrimitiveConverter.ToDouble(aggTrade.p); if (!previosPrices.ContainsKey(aggTrade.s)) { previosPrices.Add(aggTrade.s, lastPrice); OnLastPriceEvent(aggTrade.s, lastPrice); } else { var previosPrice = previosPrices[aggTrade.s]; if (lastPrice != previosPrice) { previosPrices[aggTrade.s] = lastPrice; OnLastPriceEvent(aggTrade.s, lastPrice); } } }
private Account Account(string key, string secret) { logService.Write("***********Account START***********", true); logService.Write($"\tPublic key: {key}"); Account result = null; SecretKeyRequiredRequester privateApi = new SecretKeyRequiredRequester(); string response = string.Empty; Regex my_reg = new Regex(@"\D"); string serverTime = string.Empty; try { serverTime = my_reg.Replace(ServiceRequests.ServerTime(), ""); logService.Write($"\tAccount get serverTime successful: {serverTime}"); } catch (Exception ex) { logService.Write($"\tAccount get serverTime error: Exception: {ex.Message} Innerexception: {ex.InnerException?.Message}"); } try { response = privateApi.GetWebRequest($"{Resources.DOMAIN_V3}account?recvWindow=5000×tamp=" + serverTime, "recvWindow=5000×tamp=" + serverTime, key, secret, "GET"); logService.Write($"\tAccount {Resources.DOMAIN_V3}account... successful: response = {response.Substring(0, 500)}"); } catch (Exception ex) { logService.Write($"\tAccount {Resources.DOMAIN_V3}account... error: Exception: {ex.Message} Innerexception: {ex.InnerException?.Message}"); } try { result = JConverter.JsonConver <Account>(response); logService.Write($"\tAccount JConverter successful."); } catch (Exception ex) { logService.Write($"\tAccount JConverter error: Exception: {ex.Message} Innerexception: {ex.InnerException?.Message}"); } logService.Write("***********Account END***********", true); return(result); }
/* * { * "timezone": "UTC", * "serverTime": 1508631584636, * "rateLimits": [{ * "rateLimitType": "REQUESTS", * "interval": "MINUTE", * "limit": 1200 * }, * { * "rateLimitType": "ORDERS", * "interval": "SECOND", * "limit": 10 * }, * { * "rateLimitType": "ORDERS", * "interval": "DAY", * "limit": 100000 * } * ], * "exchangeFilters": [], * "symbols": [{ * "symbol": "ETHBTC", * "status": "TRADING", * "baseAsset": "ETH", * "baseAssetPrecision": 8, * "quoteAsset": "BTC", * "quotePrecision": 8, * "orderTypes": ["LIMIT", "MARKET"], * "icebergAllowed": false, * "filters": [{ * "filterType": "PRICE_FILTER", * "minPrice": "0.00000100", * "maxPrice": "100000.00000000", * "tickSize": "0.00000100" * }, { * "filterType": "LOT_SIZE", * "minQty": "0.00100000", * "maxQty": "100000.00000000", * "stepSize": "0.00100000" * }, { * "filterType": "MIN_NOTIONAL", * "minNotional": "0.00100000" * }] * }] * } */ #endregion private void GetExchangeInfo() { try { var jsonString = MainWindow.ExchangeInfo.Info; dynamic entity = JConverter.JsonConvertDynamic(jsonString); foreach (var symbol in entity.symbols) { if (symbol.symbol == selectedPair) { quotePrecision = symbol.quotePrecision; break; } } } catch (Exception ex) { throw ex; // TODO: запись лога в БД } }
private void UpdateBalance(string data) { var balance = JConverter.JsonConver <BalanceInfo>(data); if (balance != null) { if (balance.B != null) { foreach (var b in balance.B) { if (b.f != 0 || b.l != 0) { repositories.BalanceRepository.Update(new DataBaseWork.Models.Balance() { FK_PublicKey = key.PublicKey, Asset = b.a, Free = b.f, Locked = b.l }); } } } } }
public DeserializationTests() { _converter = new JConverter(BuildConvertersCollection()); }
public void DownloadAvatar(long userId) { var json = new JsonDict(); json.AddLong("UserId", userId); ArraySegmentWrapper segmentWrapper = new ArraySegmentWrapper(Constants.DOWNLOAD_AVATAR_REQUEST_KEY, JConverter.SerializeToBytes(json)); this.Send(segmentWrapper); }
public void UploadAvatar(long userId, string extName, byte[] data) { var json = new JsonDict(); json.AddLong("UserId", userId); json.Add("ExtName", extName); json.Add("Data", Convert.ToBase64String(data)); ArraySegmentWrapper segmentWrapper = new ArraySegmentWrapper(Constants.UPLOAD_AVATAR_REQUEST_KEY, JConverter.SerializeToBytes(json)); this.Send(segmentWrapper); }
public void EditProfile(User user) { ArraySegmentWrapper segmentWrapper = new ArraySegmentWrapper(Constants.EDIT_PROFILE_REQUEST_KEY, JConverter.SerializeToBytes(user)); this.Send(segmentWrapper); }
public void SignUp(SignUpReq req) { ArraySegmentWrapper segmentWrapper = new ArraySegmentWrapper(Constants.SIGNUP_REQUEST_KEY, JConverter.SerializeToBytes(req)); this.Send(segmentWrapper); }
private void DataAnalyze(string cmd, string msg) { JsonDict json = null; JsonDictCollection jsons = null; switch (cmd) { case Constants.CONNECTED_RESPONSE_KEY: //建立连接响应报文 var res1 = JConverter.Deserialize <ResultInfo>(msg); this.ConnectedCallbackHandler?.Invoke(res1); break; case Constants.SIGNIN_RESPONSE_KEY: //用户登录响应报文 var res2 = JConverter.Deserialize <ResultInfo <User> >(msg); this.SignInCallbackHandler?.Invoke(res2); break; case Constants.SIGNUP_RESPONSE_KEY: //用户注册 var res3 = JConverter.Deserialize <ResultInfo>(msg); this.SignUpCallbackHandler?.Invoke(res3); break; case Constants.ONLINE_LIST_RESPONSE_KEY: //获取在线用户列表 var res4 = JConverter.Deserialize <ResultInfo <IEnumerable <User> > >(msg); this.GetOnlineListCallbackHandler?.Invoke(res4); break; case Constants.TALK_RESPONSE_KEY: //对话 var res5 = JConverter.Deserialize <ResultInfo <Message> >(msg); this.TalkCallbackHandler?.Invoke(res5); break; case Constants.SEARCH_USER_RESPONSE_KEY: //搜索用户 var res6 = JConverter.Deserialize <ResultInfo <IEnumerable <User> > >(msg); this.SearchUserCallbackHandler?.Invoke(res6); break; case Constants.SAVE_CONTACTS_RESPONSE_KEY: //保存通讯录 var res7 = JConverter.Deserialize <ResultInfo>(msg); this.SaveContactsCallbackHandler?.Invoke(res7); break; case Constants.GET_CONTACTS_RESPONSE_KEY: //获取通讯录 var res8 = JConverter.Deserialize <ResultInfo <IEnumerable <Contacts> > >(msg); this.GetContactsCallbackHandler?.Invoke(res8); break; case Constants.EDIT_PROFILE_RESPONSE_KEY: //修改个人资料 var res9 = JConverter.Deserialize <ResultInfo>(msg); this.EditProfileCallbackHandler?.Invoke(res9); break; case Constants.UPLOAD_AVATAR_RESPONSE_KEY: //上传头像 var res10 = JConverter.Deserialize <ResultInfo>(msg); this.UploadAvatarCallbackHandler?.Invoke(res10); break; case Constants.DOWNLOAD_AVATAR_RESPONSE_KEY: //下载头像 var res11 = JConverter.Deserialize <ResultInfo <Tuple <long, byte[]> > >(msg); this.DownloadAvatarCallbackHandler?.Invoke(res11); break; case Constants.NOTIFY_ONLINE_RESPONSE_KEY: case Constants.NOTIFY_OFFLINE_RESPONSE_KEY: this.GetOnlineList(); break; default: var res99 = new ReceivedRes() { FromUser = "******", ToUser = "******", Content = msg }; this.ReceivedCallbackHandler?.Invoke(res99); break; } }
public override void ExecuteCommand(ChatSession session, BinaryRequestInfo requestInfo) { session.Logger.DebugFormat("Cmd: UploadAvatar, RemoteEndPoint: {0}", session.RemoteEndPoint); string content = Encoding.UTF8.GetString(requestInfo.Body, 0, requestInfo.Body.Length); //session.Logger.DebugFormat("消息内容:{0}", content); ResultInfo result = null; try { //解析Json字符串 var json = JsonDict.Parse(content); long userId = json.GetLong("UserId"); string extName = json["ExtName"]; string dataStr = json["Data"]; byte[] data = Convert.FromBase64String(dataStr); var result2 = BizManager.AutofacBootstrapper.Resolve <IUserBiz>().FindById(userId); if (result2.Success) { string dir = Path.Combine("Users", "Avatar", result2.RData.Name); string path = Path.Combine(dir, $"{DateTime.Now.ToString("yyyyMMdd")}_{Guid.NewGuid()}{extName}"); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate)) { fs.Write(data, 0, data.Length); } var result3 = BizManager.AutofacBootstrapper.Resolve <IUserBiz>().UpdateUserAvatar(userId, path); if (result3.Success) { result = new ResultInfo() { RMsg = "用户头像上传成功" }; } else { result = new ResultInfo() { RCode = "1002", RMsg = "用户头像上传失败", Success = false }; } } else { result = new ResultInfo() { RCode = "1001", RMsg = "用户不存在,上传用户头像失败", Success = false }; } } catch (Exception ex) { result = new ResultInfo(ex); } ArraySegmentWrapper segmentWrapper = new ArraySegmentWrapper(Constants.UPLOAD_AVATAR_RESPONSE_KEY, JConverter.SerializeToBytes(result)); session.SendData(session, segmentWrapper.Wrapper()); }
public override void OnCommandExecuting(CommandExecutingContext commandContext) { var session = commandContext.Session as ChatSession; //If the session is not logged in, cancel the executing of the command if (session.User == null) { ResultInfo result = new ResultInfo() { RMsg = $"未登陆,命令执行失败。" }; ArraySegmentWrapper segmentWrapper = new ArraySegmentWrapper(Constants.ERROR_PERMIT_RESPONSE_KEY, JConverter.SerializeToBytes(result)); session.Send(segmentWrapper.Wrapper()); session.Close(); commandContext.Cancel = true; } }
public override void ExecuteCommand(ChatSession session, BinaryRequestInfo requestInfo) { session.Logger.DebugFormat("Cmd: SearchUser, RemoteEndPoint: {0}", session.RemoteEndPoint); string content = Encoding.UTF8.GetString(requestInfo.Body, 0, requestInfo.Body.Length); session.Logger.DebugFormat("消息内容:{0}", content); ResultInfo <IEnumerable <User> > result = null; try { //解析Json字符串 var json = JsonDict.Parse(content); string account = json["Account"]; result = BizManager.AutofacBootstrapper.Resolve <IUserBiz>().SearchUser(account); } catch (Exception ex) { result = new ResultInfo <IEnumerable <User> >(ex); } ArraySegmentWrapper segmentWrapper = new ArraySegmentWrapper(Constants.SEARCH_USER_RESPONSE_KEY, JConverter.SerializeToBytes(result)); session.SendData(session, segmentWrapper.Wrapper()); }