public void GetUserInfo() { dbInfo = new UserInfoEx { Id = 1, AvatarBigFileName = "AvatarBig.png", AvatarSmallFileName = "AvatarSmall.png", AboutFileName = "About.rtf", Contacts = "*****@*****.**", AvatarBig = SystemIcons.Information.ToBitmap(), AvatarSmall = SystemIcons.Warning.ToBitmap(), About = "About" }; cache = new UserInfoExCache(source.Object); var path = ExecutablePath.ExecPath + "\\files"; Assert.IsTrue(Directory.Exists(path), "cache directory " + path + " not found"); // 1st test // db with 3 files, cache is empty calls.Clear(); cache.GetUserInfo(1); Assert.AreEqual(4, calls.Count, "1: request count mismatch"); Assert.IsTrue(calls.Contains("GetUserBriefInfo 1"), "1: GetUserBriefInfo not found"); Assert.IsTrue(calls.Contains("ReadFile " + dbInfo.AvatarBigFileName), "1: ReadFile AvatarBigFileName not found"); Assert.IsTrue(calls.Contains("ReadFile " + dbInfo.AvatarSmallFileName), "1: ReadFile AvatarSmallFileName not found"); Assert.IsTrue(calls.Contains("ReadFile " + dbInfo.AboutFileName), "1: ReadFile AboutFileName not found"); // 2nd test // db with 3 files, cache is filled calls.Clear(); cache.GetUserInfo(1); Assert.AreEqual(1, calls.Count, "2: request count mismatch"); Assert.IsTrue(calls.Contains("GetUserBriefInfo 1"), "2: GetUserBriefInfo not found"); // 3rd test // 1 file is changed in db, cache is filled dbInfo.AvatarBig = SystemIcons.Error.ToBitmap(); calls.Clear(); cache.GetUserInfo(1); Assert.AreEqual(2, calls.Count, "3: request count mismatch"); Assert.IsTrue(calls.Contains("GetUserBriefInfo 1"), "3: GetUserBriefInfo not found"); Assert.IsTrue(calls.Contains("ReadFile " + dbInfo.AvatarBigFileName), "3: ReadFile AvatarBigFileName not found"); // 4th test // 1 file deleted from db, then added, cache is filled dbInfo.AvatarBigFileName = null; dbInfo.AvatarBig = null; calls.Clear(); cache.GetUserInfo(1); Assert.AreEqual(1, calls.Count, "4.1: request count mismatch"); Assert.IsTrue(calls.Contains("GetUserBriefInfo 1"), "4.1: GetUserBriefInfo not found"); calls.Clear(); dbInfo.AvatarBigFileName = "AvatarBig.png"; dbInfo.AvatarBig = SystemIcons.Error.ToBitmap(); cache.GetUserInfo(1); Assert.AreEqual(1, calls.Count, "4.2: request count mismatch"); Assert.IsTrue(calls.Contains("GetUserBriefInfo 1"), "4.2: GetUserBriefInfo not found"); }
public void GetUserInfoException() { cache = new UserInfoExCache(null); calls.Clear(); cache.GetUserInfo(1); Assert.AreEqual(0, calls.Count, "1: request count mismatch"); }
public void SetUserInfo() { cache = new UserInfoExCache(source.Object); dbInfo = new UserInfoEx {Id = 1}; var info = new UserInfoEx { Id = 1, Contacts = "*****@*****.**", AvatarBig = SystemIcons.Information.ToBitmap(), AvatarSmall = SystemIcons.Warning.ToBitmap(), About = "About" }; // 1st test // db is empty, cache is empty calls.Clear(); cache.SetUserInfo(info); // info with 3 files Assert.AreEqual(2, calls.Count, "1: request count mismatch"); Assert.IsTrue(calls.Contains("GetUserBriefInfo 1"), "1: GetUserBriefInfo not found"); Assert.IsTrue(calls.Contains("SetUserInfo 1"), "1: SetUserInfo not found"); // 2nd test // db with 3 files, cache is filled info.AvatarBig = SystemIcons.Error.ToBitmap(); calls.Clear(); cache.SetUserInfo(info); // info with 3 files, 1 file changed Assert.AreEqual(3, calls.Count, "2: request count mismatch"); Assert.IsTrue(calls.Contains("GetUserBriefInfo 1"), "2: GetUserBriefInfo not found"); Assert.IsTrue(calls.Contains("WriteFile " + dbInfo.AvatarBigFileName), "2: GetUserBriefInfo not found"); Assert.IsTrue(calls.Contains("SetUserInfo 1"), "2: SetUserInfo not found"); // 3rd test // db with 3 files, cache is filled info.AvatarBig = null; info.AvatarSmall = null; info.About = null; calls.Clear(); cache.SetUserInfo(info); // info with no files Assert.AreEqual(1, calls.Count, "3: request count mismatch"); Assert.IsTrue(calls.Contains("SetUserInfo 1"), "3: SetUserInfo not found"); }
public void SetVoidUserInfo() { var sourceVoid1 = new Mock<IAccountStatistics>(); sourceVoid1.Setup(s => s.GetUserInfo(It.IsAny<int>())).Returns<int>(GetUserInfo); sourceVoid1.Setup(s => s.GetUsersBriefInfo(It.IsAny<List<int>>())).Returns<List<int>>(ids => { calls.Add(string.Format("GetUserBriefInfo {0}", 1)); return null; }); sourceVoid1.Setup(s => s.SetUserInfo(It.IsAny<UserInfoEx>())).Returns<UserInfoEx>(SetUserInfo); sourceVoid1.Setup(s => s.ReadFiles(It.IsAny<List<string>>())).Returns<List<string>>(names => null); sourceVoid1.Setup(s => s.WriteFile(It.IsAny<string>(), It.IsAny<byte[]>())).Returns<string, byte[]>(WriteFile); cache = new UserInfoExCache(sourceVoid1.Object); calls.Clear(); cache.SetUserInfo(new UserInfoEx { Id = 1, Contacts = "*****@*****.**", AvatarBig = SystemIcons.Information.ToBitmap(), AvatarSmall = SystemIcons.Warning.ToBitmap(), About = "About" }); Assert.IsTrue(calls.Contains("GetUserBriefInfo 1"), "2: GetUserBriefInfo not found"); dbInfo = new UserInfoEx { Id = 1, AvatarBigFileName = "AvatarBig.png", AboutFileName = "About.rtf", Contacts = "*****@*****.**", AvatarBig = SystemIcons.Information.ToBitmap(), AvatarSmall = SystemIcons.Warning.ToBitmap(), About = "About" }; sourceVoid1.Setup(s => s.GetUsersBriefInfo(It.IsAny<List<int>>())).Returns<List<int>>(GetUsersBriefInfo); cache = new UserInfoExCache(sourceVoid1.Object); cache.SetUserInfo(new UserInfoEx { Id = 1, Contacts = "*****@*****.**", AvatarBig = SystemIcons.Information.ToBitmap(), AvatarSmall = SystemIcons.Warning.ToBitmap(), About = "About" }); }
public void GetVoidUserInfo() { var sourceVoid = new Mock<IAccountStatistics>(); sourceVoid.Setup(s => s.GetUserInfo(It.IsAny<int>())).Returns<int>(GetUserInfo); sourceVoid.Setup(s => s.GetUsersBriefInfo(It.IsAny<List<int>>())).Returns<List<int>>(ids => { calls.Add(string.Format("GetUserBriefInfo {0}", 1)); return new List<UserInfoEx> { null }; }); sourceVoid.Setup(s => s.SetUserInfo(It.IsAny<UserInfoEx>())).Returns<UserInfoEx>(SetUserInfo); sourceVoid.Setup(s => s.ReadFiles(It.IsAny<List<string>>())).Returns<List<string>>(names => null); sourceVoid.Setup(s => s.WriteFile(It.IsAny<string>(), It.IsAny<byte[]>())).Returns<string, byte[]>(WriteFile); cache = new UserInfoExCache(sourceVoid.Object); //TODO Эти тесты почти ничего не тестируют calls.Clear(); var res1 = cache.GetUsersInfo(new List<int> { 1 }); Assert.IsNull(res1); Assert.IsTrue(calls.Contains("GetUserBriefInfo 1"), "GetUserBriefInfo not found"); calls.Clear(); var res2 = cache.GetUsersInfo(null); Assert.IsNull(res2); Assert.AreEqual(0, calls.Count); }
private void DoSend() { Chat = new ChatClientStable(chatCallback, TerminalBindings.Chat); Chat.Connected += () => { if (Connected != null) Connected(); }; Chat.Disconnected += () => { if (Disconnected != null) Disconnected(); }; UserInfoSource = new UserInfoExCache(TradeSharpAccountStatistics.Instance.proxy); while (!isStopping) { bool timeoutFlag; var allRequests = requests.ExtractAll(lockTimeout, out timeoutFlag); if (timeoutFlag) continue; // флаг повтора запроса; // перезапросы возникают из-за ошибок сети; // в этом случае ожидание между запросами увеличено, чтобы не загружать проц без пользы var repeatRequest = false; foreach (var request in allRequests) { try { switch (request.Code) { case RequestCode.GetAllUsers: request.Id = Chat.GetAllUsers((string) request.Arguments[0]); break; case RequestCode.Enter: request.Id = Chat.Enter((User) request.Arguments[0]); break; case RequestCode.Exit: request.Id = Chat.Exit(); break; case RequestCode.GetRooms: request.Id = Chat.GetRooms(); break; case RequestCode.EnterRoom: request.Id = Chat.EnterRoom((string) request.Arguments[0], (string) request.Arguments[1]); break; case RequestCode.MoveToRoom: request.Id = Chat.MoveToRoom((int) request.Arguments[0], (string) request.Arguments[1], (string) request.Arguments[2]); break; case RequestCode.LeaveRoom: request.Id = Chat.LeaveRoom((string) request.Arguments[0]); break; case RequestCode.CreateRoom: request.Id = Chat.CreateRoom((Room) request.Arguments[0]); break; case RequestCode.DestroyRoom: request.Id = Chat.DestroyRoom((string) request.Arguments[0]); break; case RequestCode.SendPrivateMessage: request.Id = Chat.SendPrivateMessage((int) request.Arguments[0], (string) request.Arguments[1]); break; case RequestCode.SendMessage: request.Id = Chat.SendMessage((string) request.Arguments[0], (string) request.Arguments[1]); break; case RequestCode.GetPendingMessages: request.Id = Chat.GetPendingMessages((DateTime) request.Arguments[0], (string) request.Arguments[1]); break; case RequestCode.GetPendingPrivateMessages: request.Id = Chat.GetPendingPrivateMessages((DateTime) request.Arguments[0], (int) request.Arguments[1]); break; case RequestCode.Ping: Chat.Ping(); break; case RequestCode.GetUserInfoEx: var userinfo = UserInfoSource.GetUserInfo((int) request.Arguments[0]); if (UserInfoExReceived != null) UserInfoExReceived(userinfo ?? new UserInfoEx {Id = (int) request.Arguments[0]}); break; case RequestCode.SetUserInfoEx: UserInfoSource.SetUserInfo((UserInfoEx)request.Arguments[0]); break; } if (request.Id == 0) { QueueRequest(request); // if server refused request - try again repeatRequest = true; } else if (request.Id != -1) // skip Ping, GetUserInfoEx, SetUserInfoEx { request.Status = ChatResultCode.InProgress; pendingRequests.UpdateValues(request.Id, request); /*if (pendingRequestsLock.TryEnterWriteLock(lockTimeout)) { pendingRequests.Add(request.Id, request); pendingRequestsLock.ExitWriteLock(); } else Console.WriteLine("ChatSender.DoSend: pendingRequestsWriteLock timeout");*/ var requestCopy = new ChatRequest(request); if (RequestQueuedOnServer != null) RequestQueuedOnServer(requestCopy); if (forwardAnswers.ContainsKey(request.Id)) { pendingRequests.Remove(request.Id); requestCopy.Status = forwardAnswers.ReceiveValue(request.Id); if (RequestProcessed != null) RequestProcessed(requestCopy); forwardAnswers.Remove(request.Id); } } } catch (Exception ex) // probably communication error { Logger.ErrorFormat("DoSend exception: {0}", ex); if (request.Code != RequestCode.Ping) QueueRequest(request); repeatRequest = true; } } //проверка соединения - ping if (allRequests.Count == 0) { if (DateTime.Now.Subtract(lastConnectionCheck.GetLastHit()).TotalSeconds > 15) { var request = new ChatRequest(RequestCode.Ping, new List<object>(), -1); QueueRequest(request); lastConnectionCheck.Touch(); } } Thread.Sleep(repeatRequest ? 1000 : 100); } }
private void LoadData() { // загрузить данные о пользователе и счете editedAccount = AccountStatus.Instance.AccountData; if (editedAccount == null) return; // валюта... var indexCurx = cbCurrency.Items.IndexOf(editedAccount.Currency); if (indexCurx < 0) indexCurx = cbCurrency.Items.Add(editedAccount.Currency); cbCurrency.SelectedIndex = indexCurx; // баланс... cbDepoSize.Text = editedAccount.Equity.ToStringUniformMoneyFormat(false); // макс плечо... tbMaxLeverage.Text = editedAccount.MaxLeverage.ToStringUniform(); // получить данные о пользователе... var login = AccountStatus.Instance.Login; if (string.IsNullOrEmpty(login)) return; var password = UserSettings.Instance.GetPasswordForLogin(login); oldPassword = password; var passwordPrompt = Localizer.GetString("MessageEnterOldPassword"); while (true) { if (string.IsNullOrEmpty(password)) { DialogResult rst; password = Dialogs.ShowInputDialog(passwordPrompt, "", true, out rst); if (rst == DialogResult.Cancel) return; oldPassword = password; } var resp = MainForm.serverProxyTrade.proxy.GetUserDetail(login, password, out editedUser); if (resp == AuthenticationResponse.AccountInactive || resp == AuthenticationResponse.InvalidAccount || resp == AuthenticationResponse.ServerError) { MessageBox.Show(EnumFriendlyName<AuthenticationResponse>.GetString(resp)); return; } if (resp == AuthenticationResponse.WrongPassword) { password = string.Empty; passwordPrompt = Localizer.GetString("MessageWrongPwrdEnterAgain"); continue; } if (editedUser != null) break; } // показать данные пользователя tbEmail.Text = editedUser.Email; tbLogin.Text = editedUser.Login; tbPatronym.Text = editedUser.Patronym; tbName.Text = editedUser.Name; tbSurname.Text = editedUser.Surname; tbPhone1.Text = editedUser.Phone1; tbPhone2.Text = editedUser.Phone2; tbDescription.Text = editedUser.Description; tbPassword.Text = editedUser.Password; ShowSignallerOptions(editedUser); // получить дополнительные данные о пользователе try { var userInfoExSource = new UserInfoExCache(TradeSharpAccountStatistics.Instance.proxy, TerminalEnvironment.FileCacheFolder); var info = userInfoExSource.GetUserInfo(editedUser.ID); if (info != null) { bigAvatarPanel.BackgroundImage = info.AvatarBig; smallAvatarPanel.BackgroundImage = info.AvatarSmall; aboutRichTextBox.Text = info.About; ContactListUtils.UnpackContacts(info.Contacts, contactsListView); } } catch (Exception ex) { MessageBox.Show(Localizer.GetString("TitleServerError"), Localizer.GetString("TitleError"), MessageBoxButtons.OK, MessageBoxIcon.Error); Logger.Info("Ошбика при чтении дополнительной информации о пользователе", ex); } }
private void EditExisting() { var login = AccountStatus.Instance.Login; if (string.IsNullOrEmpty(login)) return; if (string.IsNullOrEmpty(oldPassword)) return; if (editedUser == null) return; if (editedAccount == null) return; // собрать данные var user = new PlatformUser { Email = tbEmail.Text, Login = tbLogin.Text, Name = tbName.Text, Surname = tbSurname.Text, Patronym = tbPatronym.Text, Phone1 = tbPhone1.Text, Phone2 = tbPhone2.Text, Description = tbDescription.Text, Password = tbPassword.Text }; var maxLeverage = tbMaxLeverage.Text.ToFloatUniform(); bool loginIsBusy; var resp = MainForm.serverProxyTrade.proxy.ModifyUserAndAccount(login, oldPassword, user, editedAccount.ID, maxLeverage, out loginIsBusy); if (loginIsBusy) { MessageBox.Show(string.Format(Localizer.GetString("MessageLoginInUse"), user.Login)); return; } if (resp == AuthenticationResponse.AccountInactive || resp == AuthenticationResponse.InvalidAccount || resp == AuthenticationResponse.WrongPassword || resp == AuthenticationResponse.ServerError) { var msg = Localizer.GetString("MessageUnableToUpdate") + " - " + EnumFriendlyName<AuthenticationResponse>.GetString(resp); MessageBox.Show(msg, Localizer.GetString("TitleError")); } // обновить дополнительные данные о пользователе try { var userInfoExSource = new UserInfoExCache(TradeSharpAccountStatistics.Instance.proxy, TerminalEnvironment.FileCacheFolder); var info = new UserInfoEx { Id = editedUser.ID, AvatarBig = bigAvatarPanel.BackgroundImage as Bitmap, AvatarSmall = smallAvatarPanel.BackgroundImage as Bitmap, About = aboutRichTextBox.Text, Contacts = ContactListUtils.PackContacts(contactsListView) }; userInfoExSource.SetUserInfo(info); } catch (Exception ex) { MessageBox.Show(Localizer.GetString("TitleServerError"), Localizer.GetString("TitleError")); Logger.Info("Ошбика при записи дополнительной информации о пользователе", ex); return; } MessageBox.Show(Localizer.GetString("MessageDataSuccessfulyUpdated"), Localizer.GetString("TitleConfirmation"), MessageBoxButtons.OK, MessageBoxIcon.Asterisk); }
/// <summary> /// Завершение асинхронной загрузки данных статистики с сервера /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void WorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (Parent == null) return; var userInfoExSource = new UserInfoExCache(TradeSharpAccountStatistics.Instance.proxy); var userInfo = userInfoExSource.GetUserInfo(Performer.UserId); if (userInfo != null) { photoPanel.BackgroundImageLayout = ImageLayout.Center; photoPanel.BackgroundImage = userInfo.AvatarBig; ContactListUtils.UnpackContacts(userInfo.Contacts, contactsList); aboutRichTextBox.Text = userInfo.About; } if (Efficiency == null) { profit1000tabPage.Enabled = false; profitTabPage.Enabled = false; openedDealsTabPage.Enabled = false; currenciesTabPage.Enabled = false; if (DataBindCompleted != null) DataBindCompleted(); return; } // суммарная статистика BindSummaryStatistics(gridSummaryStat, Performer, Efficiency, true); gridSummaryStat.CheckSize(true); var height = gridSummaryStat.CellHeight * gridSummaryStat.rows.Count + 1; gridSummaryStat.Height = height; summaryStatPanel.MinimumSize = new Size(0, (IsSubscribed ? 30 : 60) + height); // обычная статистика RebindStatisticsFastGrid(singleParametersFastGrid, Performer, null); singleParametersFastGrid.CheckSize(true); // подписать стоимость сигналов lblFee.Text = Performer.FeeUSD <= 0 ? Localizer.GetString("TitleFree") : Performer.FeeUSD.ToStringUniformMoneyFormat() + " / " + PaidService.GetMonthFeeFromDailyFee(Performer.FeeUSD).ToStringUniformMoneyFormat() + " USD"; lblFee.ForeColor = Performer.FeeUSD <= 0 ? SystemColors.ControlText : Color.Blue; // график доходности chartProfit.Graphs[0].Series[0].Clear(); chartProfit.Graphs[0].Series[1].Clear(); if (Efficiency.listEquity != null) { foreach (var pt in Efficiency.listEquity) chartProfit.Graphs[0].Series[0].Add(new TimeBalans(pt.time, pt.equity)); var hwm = GetHighWaterMarks(Efficiency.listEquity, Efficiency.listTransaction); foreach (var pt in hwm) chartProfit.Graphs[0].Series[1].Add(new TimeBalans(pt.time, pt.equity)); } chartProfit.Initialize(); // график доходности на 1000 chartProfit1000.Graphs[0].Series[0].Clear(); chartProfit1000.Graphs[0].Series[1].Clear(); if (Efficiency.listProfit1000 != null) { foreach (var pt in Efficiency.listProfit1000) chartProfit1000.Graphs[0].Series[0].Add(new TimeBalans(pt.time, pt.equity)); var hwm = GetHighWaterMarks(Efficiency.listProfit1000); foreach (var pt in hwm) chartProfit1000.Graphs[0].Series[1].Add(new TimeBalans(pt.time, pt.equity)); } chartProfit1000.Initialize(); // таблицы сделок if (Efficiency != null && Efficiency.openedDeals != null) BindDeals(true); if (Parent == null) return; try { var blank = new DealCountBySymbol(); chartCountByTicker.Series[0].Points.DataBind(GetDealCountBySymbol(Efficiency), blank.Property(p => p.Title), blank.Property(p => p.DealCount), null); } catch (Exception ex) { Logger.Info("PerformerStatistics.WorkerRunWorkerCompleted: error binding GetDealCountBySymbol to chart", ex); return; } // "Совокупные позиции" if (Efficiency != null) BindSummaryPositions(Efficiency, tickersAndVolumesBarControl); // прочие визуальные параметры txtSignalTitle.Text = SignalTitle; subscribeButton.Text = SubscriptionButtonTitle; btnInvest.Visible = !IsSubscribed; if (DataBindCompleted != null) DataBindCompleted(); }