Ejemplo n.º 1
0
        public void ConnectCommand_ExecuteRequest_2()
        {
            int    returnCode            = 0;
            string configuration         = "Some=Text";
            Mock <IIrbisConnection> mock = GetConnectionMock();

            mock.SetupGet(c => c.Connected).Returns(true);
            IIrbisConnection connection = mock.Object;
            ConnectCommand   command    = new ConnectCommand(connection)
            {
                Username = "******",
                Password = "******"
            };
            ResponseBuilder builder = new ResponseBuilder()
                                      .AppendAnsi(CommandCode.RegisterClient).NewLine()
                                      .AppendAnsi("12345678").NewLine()
                                      .AppendAnsi("1").NewLine()
                                      .AppendAnsi("123").NewLine()
                                      .AppendAnsi("64.2014").NewLine()
                                      .NewLine()
                                      .NewLine()
                                      .NewLine()
                                      .NewLine()
                                      .NewLine()
                                      .Append(returnCode).NewLine()
                                      .AppendAnsi("30").NewLine()
                                      .AppendAnsi(configuration);
            TestingSocket socket = (TestingSocket)connection.Socket;

            socket.Response = builder.Encode();
            ClientQuery query = command.CreateQuery();

            command.Execute(query);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Connects this instance and properly sets the
        /// client stream to Use Ssl if it is specified.
        /// </summary>
        public void Connect()
        {
            if (_client == null)
            {
                _client = new TcpClient();
            } //If a previous quit command was issued, the client would be disposed of.

            _client.ReceiveTimeout = (int)TimeSpan.FromMinutes(Timeout).TotalMilliseconds;
            _client.SendTimeout    = (int)TimeSpan.FromMinutes(Timeout).TotalMilliseconds;

            if (_client.Connected)
            {
                return;
            } //if the connection already is established no need to reconnect.

            SetState(Pop3State.Unknown);
            ConnectResponse response;

            using (ConnectCommand command = new ConnectCommand(_client, Hostname, Port, UseSsl))
            {
                TraceCommand <ConnectCommand, ConnectResponse>(command);
                response = command.Execute(CurrentState);
                EnsureResponse(response);
            }

            SetClientStream(response.NetworkStream);

            SetState(Pop3State.Authorization);
        }
Ejemplo n.º 3
0
 /// <summary>
 ///
 /// </summary>
 public void CheckAutoConnect()
 {
     if (!string.IsNullOrEmpty(ServerAddress))
     {
         ConnectCommand.Execute(null);
     }
 }
        public FlightDisplayVM(IMainModel main, ISettingsModel settings)
        {
            MainModel     = main;
            SettingsModel = settings;

            // connect the server and client upon initialization
            ConnectCommand.Execute(null);
        }
Ejemplo n.º 5
0
        async Task Initialize()
        {
            var accounts = accountDataRepository?.GetAccounts();

            if (accounts != null && accounts.Any())
            {
                Accounts = accounts;
                if (accounts.Count == 1)
                {
                    CurrentAccount = accounts[0];
#warning "Optimistic: any account/cookies is supposed valid, proper implementation needed (cookies timeout check)"
                    await ThreadUI.Invoke(() =>
                    {
                        Loc.NavigationService.Navigate(View.Connect);
                        Loc.Main.AccountManager.CurrentAccount.ConnectionErrorStatus = "Connecting";
                        Loc.Main.AccountManager.CurrentAccount.IsConnecting          = true;
                    });

                    bool success = await CurrentAccount.BeginAuthentication(false);

                    if (success)
                    {
                        await ThreadUI.Invoke(() =>
                        {
                            Loc.Main.AccountManager.CurrentAccount.IsConnected = false;
                            Loc.NavigationService.Navigate(View.Main);
                        });
                    }
                    else
                    {
                        Debug.WriteLine("Login failed");
                    }
                }
                else
                {
                    // Handle selection of one of the multi accounts
                }
            }
            else
            {
                // navigate to connectpage
                await ThreadUI.Invoke(() =>
                {
                    CurrentAccount = new Account();
                    Loc.NavigationService.Navigate(View.Connect);
                    // Trying to detect login and password stored in RoamingSettings
                    if (ApplicationSettingsHelper.Contains(nameof(CurrentAccount.Pseudo), false) && ApplicationSettingsHelper.Contains(nameof(CurrentAccount.Password), false))
                    {
                        ToastHelper.Simple("Connexion automatique ...");
                        var pseudo              = ApplicationSettingsHelper.ReadSettingsValue(nameof(CurrentAccount.Pseudo), false).ToString();
                        var password            = ApplicationSettingsHelper.ReadSettingsValue(nameof(CurrentAccount.Password), false).ToString();
                        CurrentAccount.Pseudo   = pseudo;
                        CurrentAccount.Password = password;
                        ConnectCommand.Execute(null);
                    }
                });
            }
        }
Ejemplo n.º 6
0
        public LobbyViewModel(GTTcpClient client, PlayerListViewModel playerList)
        {
            SelectedGameStage = GameStage.First;
            _playerList       = playerList;
            IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());

            HostIp            = ipHostInfo.AddressList.Where(ip => ip.AddressFamily == AddressFamily.InterNetwork).First().ToString();
            ConnectInProgress = false;
            Port    = DefaultPort;
            Ip      = HostIp;
            _client = client;
            _client.BuildingBegun      += Client_BuildingBegun;
            _playerList.LostConnection += PlayerList_LostConnection;

            HostCommand = new DelegateCommand(param => Server == null, param =>
            {
                try
                {
                    Server = new GTTcpListener(Port, SelectedGameStage);
                    Task.Factory.StartNew(() => Server.Start(), TaskCreationOptions.RunContinuationsAsynchronously | TaskCreationOptions.LongRunning);
                    Ip = "127.0.0.1";
                    ConnectCommand.Execute(null);
                }
                catch (SocketException)
                {
                    Error = "Az adott port már használatban van!";
                }
            });

            ConnectCommand = new DelegateCommand(param => !ConnectInProgress && !IsConnected, param => Connect());

            ReadyCommand = new DelegateCommand(param =>
            {
                try
                {
                    _client.ToggleReady(ServerStage.Lobby);
                }
                catch (Exception e)
                {
                    Error = $"Hiba a szerverrel való kommunikáció közben:\n{e.Message}";
                }
            });

            BackToMenuCommand = new DelegateCommand(param =>
            {
                UnsubscribeFromEvents();
                BackToMenu?.Invoke(this, Server != null);
            });

            StartBuildingCommand = new DelegateCommand(param => Server != null && !Server.NotReadyPlayers.Any() && _client.PlayerInfos.Count > 1,
                                                       param =>
            {
                Task.Factory.StartNew(() => Server.StartBuildStage(), TaskCreationOptions.LongRunning);
            });
        }
Ejemplo n.º 7
0
        public ConnectionSetupViewModel(IConnectionService connectionService, IMeasurementManager measurementManager)
        {
            _connectionService = connectionService;

            measurementManager.PositionSource
            .Subscribe(pos => { Position = pos; });

            _connectionService.DiagnosticEventsStream
            .Subscribe(dE => { ConnectionStatus = (ConnectionStatus)dE.Message; });

            ConnectCommand.Execute(null);
        }
Ejemplo n.º 8
0
 /// <summary>
 ///     Occurs when the board collection changed
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 protected override void Boards_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
 {
     foreach (var board in Boards)
     {
         if (board.SerialNumber == AutoConnectSerialNumber)
         {
             Application.Current.Dispatcher.Invoke(() =>
             {
                 SelectedBoard = board;
                 ConnectCommand.Execute(null);
             });
         }
     }
 }
Ejemplo n.º 9
0
        private void StartPortsDiscovery()
        {
            if (!_DiscoveringPorts)
            {
                LogMessage("COM ports discovery started...");

                _DiscoveringPorts = true;
                Task.Run(() =>
                {
                    while (true)
                    {
                        string[] ports = SerialPort.GetPortNames();
                        if (ports?.Length > 0)
                        {
                            Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.DataBind, new Action(() =>
                            {
                                var port = PortName;
                                Ports    = new List <string>(ports);
                                if (!string.IsNullOrEmpty(port) && ports.Contains(port))
                                {
                                    PortName = port;
                                }
                                else
                                {
                                    PortName = Ports.FirstOrDefault();
                                }
                            }));
                        }
                        else
                        {
                            if (Connected && !_Emulation)
                            {
                                ConnectCommand.Execute(null);
                            }

                            Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.DataBind, new Action(() =>
                            {
                                Ports = new List <string> {
                                    NO_PORTS
                                };
                                PortName = NO_PORTS;
                            }));
                        }

                        Thread.Sleep(1000);
                    }
                });
            }
        }
Ejemplo n.º 10
0
        public Task <bool> ExecuteAsync(object data)
        {
            var result = _store.GetBool(UserSettingKeys.Builtin.ShowConnectOnStart);

            if (result == null)
            {
                return(Task.FromResult(false));
            }

            if (result.Value)
            {
                _command.Execute();
            }

            return(Task.FromResult(true));
        }
        /// <summary>
        ///     Construct a view model used to power a XAML Selector view
        /// </summary>
        public SelectorDesignTimeViewModel(bool selectBoard            = true,
                                           DesignTimeTestData testData = DesignTimeTestData.None) : base(new DesignTimeConnectionService())
        {
            if (selectBoard)
            {
                SelectedBoard = Boards[0];
                ConnectCommand.Execute(this);
            }

            //switch(testData)
            //{
            //    case DesignTimeTestData.Analog:
            //        SelectedBoard.GenerateAnalogDemoData();
            //        break;
            //    case DesignTimeTestData.Digital:
            //        SelectedBoard.GenerateDigitalTestData();
            //        break;

            //}
        }
Ejemplo n.º 12
0
        public void ConnectCommand_ExecuteRequest_1()
        {
            int    returnCode                  = 0;
            string configuration               = "Some=Text";
            Mock <IIrbisConnection> mock       = GetConnectionMock();
            IIrbisConnection        connection = mock.Object;
            ConnectCommand          command    = new ConnectCommand(connection)
            {
                Username = "******",
                Password = "******"
            };
            ResponseBuilder builder = new ResponseBuilder()
                                      .AppendAnsi(CommandCode.RegisterClient).NewLine()
                                      .AppendAnsi("12345678").NewLine()
                                      .AppendAnsi("1").NewLine()
                                      .AppendAnsi("123").NewLine()
                                      .AppendAnsi("64.2014").NewLine()
                                      .NewLine()
                                      .NewLine()
                                      .NewLine()
                                      .NewLine()
                                      .NewLine()
                                      .Append(returnCode).NewLine()
                                      .AppendAnsi("30").NewLine()
                                      .AppendAnsi(configuration);
            TestingSocket socket = (TestingSocket)connection.Socket;

            socket.Response = builder.Encode();
            ClientQuery    query    = command.CreateQuery();
            ServerResponse response = command.Execute(query);

            Assert.AreEqual(returnCode, response.ReturnCode);
            Assert.AreEqual(configuration, command.Configuration);
            Assert.AreEqual(30, command.ConfirmationInterval);
            Assert.AreEqual("64.2014", command.ServerVersion);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// dataObjectに格納されたデータを復元したeditorのリストを返す.
        /// </summary>
        public static IEnumerable <IEditor> RestoreDataObject(IDataObject dataObject, IControllerFactory factory)
        {
            Contract.Requires(dataObject != null);

            var ret = new List <IEditor>();

            var editorFormat = EditorConsts.DataEditorFormat;

            if (!dataObject.GetDataPresent(editorFormat.Name))
            {
                return(ret);
            }

            var idToEditor = new Dictionary <string, IEditor>();
            var trees      = dataObject.GetData(editorFormat.Name) as List <TransferContentTree>;

            if (trees != null)
            {
                var externalizer = new Externalizer();

                foreach (var tree in trees)
                {
                    var editor = RestoreEditorStructure(tree.Root, externalizer, factory);
                    ret.Add(editor);
                    idToEditor.Add(tree.Root.Value.Id, editor);
                }
            }

            /// editor間の接続
            var connFormat = EditorConsts.DataConnectionFormat;

            if (!dataObject.GetDataPresent(editorFormat.Name))
            {
                return(ret);
            }

            var conns = dataObject.GetData(connFormat.Name) as List <TransferConnection>;

            if (conns != null)
            {
                foreach (var conn in conns)
                {
                    if (idToEditor.ContainsKey(conn.ConnectionId))
                    {
                        var connEditor = idToEditor[conn.ConnectionId];
                        var connFig    = connEditor.Figure as IEdge;
                        if (connEditor != null && connFig != null)
                        {
                            if (!string.IsNullOrEmpty(conn.SourceId) && idToEditor.ContainsKey(conn.SourceId))
                            {
                                var srcEditor = idToEditor[conn.SourceId];
                                if (srcEditor != null)
                                {
                                    /// command executorは通さない
                                    var cmd = new ConnectCommand(
                                        connEditor,
                                        connFig.SourceAnchor,
                                        srcEditor,
                                        connFig.SourcePoint
                                        );
                                    cmd.Execute();
                                }
                            }
                            if (!string.IsNullOrEmpty(conn.TargetId) && idToEditor.ContainsKey(conn.TargetId))
                            {
                                var tgtEditor = idToEditor[conn.TargetId];
                                if (tgtEditor != null)
                                {
                                    /// command executorは通さない
                                    var cmd = new ConnectCommand(
                                        connEditor,
                                        connFig.TargetAnchor,
                                        tgtEditor,
                                        connFig.TargetPoint
                                        );
                                    cmd.Execute();
                                }
                            }
                        }
                    }
                }
            }

            return(ret);
        }
Ejemplo n.º 14
0
        ConnectResponse IEasConnection.Connect(ConnectRequest connectRequest, IServerCapabilities capabilities)
        {
            ConnectCommand connectCommand = new ConnectCommand(this.EasConnectionSettings);

            return(connectCommand.Execute(connectRequest, capabilities ?? EasConnection.DefaultCapabilities));
        }
Ejemplo n.º 15
0
        public MainViewModel()
        {
            // ファイルから読む体で
            userDict.Add("111", new UserModel("111", "社会人P")
            {
                Color = Colors.LightGreen
            });
            userDict.Add("222", new UserModel("222", "八百屋"));

            Comments = model.Comments.ToReadOnlyReactiveCollection(comment =>
            {
                if (!userDict.TryGetValue(comment.ID, out var user))
                {
                    user = new UserModel(comment.ID);
                    userDict.Add(user.ID, user);
                }

                return(new CommentViewModel(comment, user));
            }).AddTo(disposable);

            #region Command
            NameChangeCommand.Subscribe(obj =>
            {
                var menuItem = obj as MenuItem;
                var comment  = menuItem.DataContext as CommentViewModel;
                var ib       = new InputBox
                {
                    DataContext = comment,
                    Text        = comment.Name.Value,
                };

                if (ib.ShowDialog() == true)
                {
                    comment.Name.Value = ib.Text;
                }
            });

            ColorChangeCommand.Subscribe(obj =>
            {
                var menuItem        = obj as MenuItem;
                var comment         = menuItem.DataContext as CommentViewModel;
                comment.Color.Value = (Color)menuItem.Tag;
            });

            ConnectCommand = IsRunning.Select(x => !x).ToAsyncReactiveCommand();
            ConnectCommand.Subscribe(async _ =>
            {
                await model.ConnectAsync("lv1234567");
                IsRunning.Value = true;
            }).AddTo(disposable);

            DisconnectCommand = IsRunning.ToReactiveCommand();
            DisconnectCommand.Subscribe(_ =>
            {
                model.Disconnect();
                IsRunning.Value = false;
            }).AddTo(disposable);
            #endregion

            ConnectCommand.Execute();
        }
Ejemplo n.º 16
0
        public MainWindowViewModel()
        {
            Locator.CurrentMutable.RegisterConstant(this);
            User = new CurrentUserViewModel();
            Locator.CurrentMutable.RegisterConstant <ICurrentUser>(User);
            configuration = Locator.Current.GetService <IConfiguration>();
            settings      = configuration?.GetSection("ChatClientSettings")?.Get <ChatClientSettings>();

            var mapper = Locator.Current.GetService <IMapper>();

            if (settings == null)
            {
                settings = new ChatClientSettings();
            }

            if (settings.HostUrl.IsNullOrEmpty())
            {
                settings.HostUrl = "http://localhost:5000";
            }

            if (settings.AttachmentDefaultPath.IsNullOrEmpty())
            {
                settings.AttachmentDefaultPath = "\\Download";
            }

            serviceClient = new JsonServiceClient(settings.HostUrl);

            ProfileViewModel = new ProfileViewModel(serviceClient);
            Locator.CurrentMutable.RegisterConstant <IProfile>(ProfileViewModel);
            ProfileViewModel.IsOpenProfileEvent += () => WindowStates(WindowState.OpenProfile);

            AttachmentViewModel = new SendAttachmentsViewModel(serviceClient);

            SettingsViewModel = new SettingsViewModel(serviceClient);
            SettingsViewModel.OpenSettingsActiveEvent        += (e) => { WindowStates(WindowState.WindowSettings); };
            SettingsViewModel.TypeEnterEvent                 += (e) => { KeySendMessage = e; };
            SettingsViewModel.ContextMenuSettingsActiveEvent += (e) => { WindowStates(WindowState.HeaderMenuPopup); };
            SettingsViewModel.SetSelectedOnSettingsItemEvent += e => { TextHeaderMenuInSettings = SettingsViewModel.SettingsMenuActiveMain ? "Сообщения и чаты" : "Аудит входа"; };

            Width(false);
            User.UserName = settings.UserName;
            Tokens        = new TokenResult {
                AccessToken = settings.AccessToken, RefreshToken = settings.RefreshToken
            };

            Messages = new ObservableCollection <IMessagesContainerViewModel>();

            var bits            = Environment.Is64BitOperatingSystem ? "PC 64bit, " : "PC 32bit, ";
            var operatingSystem = bits + RuntimeInformation.OSDescription;

            string ipAddress = "";

            try
            {
                ipAddress = new WebClient().DownloadString("https://api.ipify.org");
            }
            catch (Exception e)
            {
                try
                {
                    IPHostEntry ipHost = Dns.GetHostEntry("localhost");
                    if (ipHost.AddressList.Length > 0)
                    {
                        ipAddress = ipHost.AddressList.Last().ToString();
                    }
                }
                catch (Exception exception) { }
            }
            var nameVersionClient = "SkillChat Avalonia Client 1.0";

            ConnectCommand = ReactiveCommand.CreateFromTask(async() =>
            {
                try
                {
                    _connection = new HubConnectionBuilder()
                                  .WithUrl(settings.HostUrl + "/ChatHub")
                                  .Build();

                    _hub = _connection.CreateHub <IChatHub>();
                    ProfileViewModel.SetChatHub(_hub);
                    AttachmentViewModel.SetChatHub(_hub);

                    if (Tokens == null || Tokens.AccessToken.IsNullOrEmpty())
                    {
                        Tokens = await serviceClient.PostAsync(new AuthViaPassword
                        {
                            Login = User.UserName, Password = User.Password
                        });
                        settings.AccessToken  = Tokens.AccessToken;
                        settings.RefreshToken = Tokens.RefreshToken;
                        settings.UserName     = User.UserName;
                        configuration.GetSection("ChatClientSettings").Set(settings);
                    }

                    serviceClient.BearerToken = Tokens.AccessToken;
                    this.ObservableForProperty(m => m.ExpireTime).Subscribe(change =>
                    {
                        if (change.Value != null)
                        {
                            //TODO запуск обновления токена
                        }
                    });

                    _connection.Subscribe <LogOn>(async data =>
                    {
                        if (data.Error)
                        {
                            IsSignedIn = false;
                            serviceClient.BearerToken = Tokens.RefreshToken;
                            try
                            {
                                Tokens = await serviceClient.PostAsync(new PostRefreshToken());
                                settings.AccessToken  = Tokens.AccessToken;
                                settings.RefreshToken = Tokens.RefreshToken;
                                configuration.GetSection("ChatClientSettings").Set(configuration);
                                await _hub.Login(Tokens.AccessToken, operatingSystem, ipAddress, nameVersionClient);
                            }
                            catch (Exception e)
                            {
                                Tokens = null;
                            }
                        }
                        else
                        {
                            IsSignedIn = true;
                            User.Id    = data.Id;
                            User.Login = data.UserLogin;
                            ExpireTime = data.ExpireTime;
                            var chats  = await serviceClient.GetAsync(new GetChatsList());
                            var chat   = chats.Chats.FirstOrDefault();
                            ChatId     = chat?.Id;
                            ChatName   = chat?.ChatName;
                            LoadMessageHistoryCommand.Execute(null);
                            //Получаем настройки
                            SettingsViewModel.ChatSettings = await serviceClient.GetAsync(new GetMySettings());
                            KeySendMessage = SettingsViewModel.ChatSettings.SendingMessageByEnterKey;
                        }
                    });

                    _connection.Subscribe <UpdateUserDisplayName>(async user =>
                    {
                        try
                        {
                            var updateMessages = Messages.Where(s => s is UserMessagesContainerViewModel);
                            foreach (var message in updateMessages)
                            {
                                foreach (var item in message.Messages.Where(s => s.UserId == user.Id))
                                {
                                    item.UserNickname = user.DisplayName;
                                }
                            }

                            ProfileViewModel.UpdateUserProfile(user.DisplayName, user.Id);
                        }
                        catch (Exception e)
                        {
                            SignOutCommand.Execute(null);
                        }
                    });

                    _connection.Subscribe <ReceiveMessage>(async data =>
                    {
                        var isMyMessage    = User.Id == data.UserId;
                        var hasAttachments = data.Attachments != null && data.Attachments.Count > 0;

                        MessageViewModel newMessage;

                        if (isMyMessage)
                        {
                            newMessage = hasAttachments ? new MyAttachmentViewModel() : new MyMessageViewModel();
                        }
                        else
                        {
                            newMessage = hasAttachments ? new UserAttachmentViewModel() : new UserMessageViewModel();
                        }

                        newMessage.Id           = data.Id;
                        newMessage.Text         = data.Message;
                        newMessage.PostTime     = data.PostTime;
                        newMessage.UserNickname = data.UserNickname ?? data.UserLogin;
                        newMessage.UserId       = data.UserId;

                        newMessage.Attachments = data.Attachments?
                                                 .Select(s =>
                        {
                            var attah = mapper?.Map <AttachmentMold>(s);
                            return(new AttachmentMessageViewModel(attah));
                        }).ToList();

                        var container = Messages.LastOrDefault();

                        if (isMyMessage)
                        {
                            if (!(container is MyMessagesContainerViewModel))
                            {
                                container = new MyMessagesContainerViewModel();
                                Messages.Add(container);
                            }
                        }
                        else
                        {
                            if (container is UserMessagesContainerViewModel)
                            {
                                var lastMessage = container.Messages.LastOrDefault();
                                if (lastMessage?.UserId != newMessage.UserId)
                                {
                                    container = new UserMessagesContainerViewModel();
                                    Messages.Add(container);
                                }
                            }
                            else
                            {
                                container = new UserMessagesContainerViewModel();
                                Messages.Add(container);
                            }

                            if (!windowIsFocused || SettingsViewModel.IsOpened)
                            {
                                Notify.NewMessage(newMessage.UserNickname, newMessage.Text.Replace("\r\n", " "));
                            }
                        }

                        container.Messages.Add(newMessage);
                        if (container.Messages.First() == newMessage)
                        {
                            newMessage.ShowNickname = true;
                        }

                        MessageReceived?.Invoke(new ReceivedMessageArgs(newMessage));
                    });

                    _connection.Closed += connectionOnClosed();
                    await _connection.StartAsync();
                    await _hub.Login(Tokens.AccessToken, operatingSystem, ipAddress, nameVersionClient);
                    //Messages.Add("Connection started");
                    IsShowingLoginPage    = false;
                    IsShowingRegisterPage = false;
                    ValidationError       = "";
                    IsConnected           = true;
                    User.Password         = "";
                }
                catch (Exception ex)
                {
                    //Изменение параеметров TextBox в случае ошибки
                    User.Error("неверный логин или пароль");
                    ErrorBe?.Invoke();
                    IsShowingLoginPage = _connection.State != HubConnectionState.Connected ? true : false;
                    //Messages.Add(ex.Message);
                }
            });

            if (Tokens.AccessToken.IsNullOrEmpty() == false)
            {
                ConnectCommand.Execute(null);
            }

            SendCommand = ReactiveCommand.CreateFromTask(async() =>
            {
                try
                {
                    await _hub.SendMessage(new HubMessage(ChatId, MessageText));
                    MessageText = null;
                }
                catch (Exception ex)
                {
                    SignOutCommand.Execute(null);
                }
            },
                                                         this.WhenAnyValue(m => m.IsConnected, m => m.MessageText,
                                                                           (b, m) => b == true && !string.IsNullOrEmpty(m)));

            LoadMessageHistoryCommand = ReactiveCommand.CreateFromTask(async() =>
            {
                try
                {
                    var first   = Messages.FirstOrDefault()?.Messages.FirstOrDefault();
                    var request = new GetMessages {
                        ChatId = ChatId, BeforePostTime = first?.PostTime
                    };

                    // Логика выбора сообщений по id чата
                    var result = await serviceClient.GetAsync(request);
                    foreach (var item in result.Messages)
                    {
                        var isMyMessage    = User.Id == item.UserId;
                        var hasAttachments = item.Attachments != null && item.Attachments.Count > 0;

                        MessageViewModel newMessage;

                        if (isMyMessage)
                        {
                            newMessage = hasAttachments ? new MyAttachmentViewModel() : new MyMessageViewModel();
                        }
                        else
                        {
                            newMessage = hasAttachments ? new UserAttachmentViewModel() : new UserMessageViewModel();
                        }

                        newMessage.Id           = item.Id;
                        newMessage.Text         = item.Text;
                        newMessage.PostTime     = item.PostTime;
                        newMessage.UserNickname = item.UserNickName;
                        newMessage.UserId       = item.UserId;

                        newMessage.Attachments = item.Attachments?.Select(s => new AttachmentMessageViewModel(s)).ToList();

                        var container = Messages.FirstOrDefault();

                        if (isMyMessage)
                        {
                            if (!(container is MyMessagesContainerViewModel))
                            {
                                container = new MyMessagesContainerViewModel();
                                Messages.Insert(0, container);
                            }
                        }
                        else
                        {
                            if (container is UserMessagesContainerViewModel)
                            {
                                var firstMessage = container.Messages.FirstOrDefault();
                                if (firstMessage?.UserId != newMessage.UserId)
                                {
                                    container = new UserMessagesContainerViewModel();
                                    Messages.Insert(0, container);
                                }
                            }
                            else
                            {
                                container = new UserMessagesContainerViewModel();
                                Messages.Insert(0, container);
                            }
                        }

                        container.Messages.Insert(0, newMessage);

                        var firstInBlock = container.Messages.First();
                        foreach (var message in container.Messages)
                        {
                            message.ShowNickname = firstInBlock == message;
                        }
                    }
                }
                catch (Exception e)
                {
                }
            });

            SignOutCommand = ReactiveCommand.CreateFromTask(async() =>
            {
                try
                {
                    Messages.Clear();
                    MessageText = null;
                    Tokens      = null;
                    IsSignedIn  = false;
                    IsConnected = false;
                    serviceClient.BearerToken = null;
                    if (_connection != null)
                    {
                        _connection.Closed -= connectionOnClosed();
                        await _connection.StopAsync();
                    }

                    _connection = null;
                    _hub        = null;

                    settings.AccessToken  = null;
                    settings.RefreshToken = null;
                    configuration.GetSection("ChatClientSettings").Set(settings);

                    WindowStates(WindowState.SignOut);
                }
                catch (Exception ex)
                {
                }
                finally
                {
                    IsShowingLoginPage = true;
                }
            });
            IsShowingLoginPage = true;

            // Скрывает окно регистрации
            IsShowingRegisterPage = false;
            IsShowingLoginPage    = true;
            GoToRegisterCommand   = ReactiveCommand.Create <object>(_ =>
            {
                IsShowingRegisterPage = true;
                IsShowingLoginPage    = false;
                RegisterUser.Login    = User.UserName;
                User.Password         = "";
            });

            RegisterUser = new RegisterUserViewModel();
            RegisterUser.GoToLoginCommand = ReactiveCommand.Create <object>(_ =>
            {
                IsShowingRegisterPage = false;
                IsShowingLoginPage    = true;
                RegisterUser.Password = "";
                User.UserName         = RegisterUser.Login;
            });
            IsConnected     = false; //Скрывает окно чата
            RegisterCommand = ReactiveCommand.CreateFromTask(async() =>
            {
                var request = new RegisterNewUser();
                try
                {
                    ValidationError = "";
                    if (string.IsNullOrWhiteSpace(RegisterUser.Login) ||
                        string.IsNullOrWhiteSpace(RegisterUser.Password))
                    {
                        throw new Exception("Не заполнены логин и/или пароль");
                    }
                    request.Login    = RegisterUser.Login;
                    request.Password = RegisterUser.Password;
                    request.UserName = RegisterUser.UserName;

                    Tokens = await serviceClient.PostAsync(request);

                    settings.AccessToken  = Tokens.AccessToken;
                    settings.RefreshToken = Tokens.RefreshToken;
                    settings.UserName     = RegisterUser.Login;
                    configuration.GetSection("ChatClientSettings").Set(settings);
                    ConnectCommand.Execute(null);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"Ошибка регистрации {ex.Message}");
                    ValidationError = ex.Message;
                }
            });

            NotifyCommand = ReactiveCommand.Create <object>(obj =>
            {
                if (obj is IHaveIsActive win)
                {
                    windowIsFocused = win.IsActive;
                }
            });
            PointerPressedCommand = ReactiveCommand.Create <object>(obj =>
            {
                ProfileViewModel.ContextMenuClose();
                SettingsViewModel.CloseContextMenu();
            });

            ProfileViewModel.SignOutCommand            = SignOutCommand;
            ProfileViewModel.LoadMessageHistoryCommand = LoadMessageHistoryCommand;
        }
Ejemplo n.º 17
0
        private void SetUp(IEditor createdEditor, object model)
        {
            _newStyledText = null;
            _oldStyledText = null;

            /// 親controllerへの通知
            var containerCtrl = _target.Controller as IContainerController;

            Contract.Requires(
                containerCtrl != null && containerCtrl.CanContainChild(_modelFactory.ModelDescriptor)
                );

            var createdConnectionCtrl = createdEditor.Controller as IConnectionController;
            var createdEdge           = createdEditor.Figure as IEdge;

            if (createdEditor == null || createdConnectionCtrl == null || createdEdge == null)
            {
                /// rollback
                containerCtrl.RemoveChild(model);
                _target.RemoveChildEditor(createdEditor);
                throw new ArgumentException();
            }

            var srcConnectableCtrl = _edgeSourceEditor == null?
                                     null:
                                     _edgeSourceEditor.Controller as IConnectableController;
            var srcConnectableFig = _edgeSourceEditor == null?
                                    null:
                                    _edgeSourceEditor.Figure as IConnectable;
            var tgtConnectableCtrl = _edgeTargetEditor == null?
                                     null:
                                     _edgeTargetEditor.Controller as IConnectableController;
            var tgtConnectableFig = _edgeTargetEditor == null?
                                    null:
                                    _edgeTargetEditor.Figure as IConnectable;

            /// パラメタの妥当性検査
            var isValidSrcConnect =
                _edgeSourceEditor != null &&
                srcConnectableFig != null &&
                createdConnectionCtrl.CanConnectSource(_edgeSourceEditor.Model);
            var isValidSrcDisconnect =
                (_edgeSourceEditor == null ||
                 srcConnectableCtrl == null ||
                 !createdConnectionCtrl.CanConnectSource(_edgeSourceEditor.Model)
                ) &&
                createdConnectionCtrl.CanDisconnectSource;
            var isValidSrc = isValidSrcConnect || isValidSrcDisconnect;

            var isValidTgtConnect =
                _edgeTargetEditor != null &&
                tgtConnectableCtrl != null &&
                createdConnectionCtrl.CanConnectTarget(_edgeTargetEditor.Model);
            var isValidTgtDisconnect =
                (_edgeTargetEditor == null ||
                 tgtConnectableCtrl == null ||
                 !createdConnectionCtrl.CanConnectTarget(_edgeTargetEditor.Model)
                ) &&
                createdConnectionCtrl.CanDisconnectTarget;
            var isValidTgt = isValidTgtConnect || isValidTgtDisconnect;

            if (!isValidSrc || !isValidTgt)
            {
                /// rollback
                containerCtrl.RemoveChild(model);
                _target.RemoveChildEditor(createdEditor);
                throw new ArgumentException();
            }

            /// controllerの通知
            if (isValidSrcConnect)
            {
                createdConnectionCtrl.ConnectSource(_edgeSourceEditor.Model);
                srcConnectableCtrl.ConnectOutgoing(model);
            }
            if (isValidTgtConnect)
            {
                createdConnectionCtrl.ConnectTarget(_edgeTargetEditor.Model);
                tgtConnectableCtrl.ConnectIncoming(model);

                var node  = _edgeTargetEditor.Figure as INode;
                var mtext = _edgeTargetEditor.Model as MemoText;
                _oldStyledText = mtext.StyledText.CloneDeeply() as StyledText.Core.StyledText;
                _newStyledText = mtext.StyledText;

                var charIndex = node.GetCharIndexAt(_edgePoints.Last());

                var inline = node.StyledText.GetInlineAt(charIndex);
                var anc    = default(Anchor);
                if (inline.IsAnchorCharacter)
                {
                    anc = inline as Anchor;
                }
                else
                {
                    /// nodeのcharIndex位置にAnchor追加
                    anc = new Anchor();
                    var insertAnchorCommand = new InsertInlineCommand(_newStyledText, charIndex, anc);
                    insertAnchorCommand.Execute();
                }

                var edge = createdEdge;
                _newTargetAnchorId          = anc.Id;
                _oldTargetAnchorId          = edge.TargetConnectionOption as string;
                edge.TargetConnectionOption = _newTargetAnchorId;

                var connectCommand = new ConnectCommand(createdEditor, createdEdge.TargetAnchor, _edgeTargetEditor, _edgePoints.Last());
                connectCommand.Execute();
            }

            /// figureの編集
            createdEdge.SetEdgePoints(_edgePoints);
            createdEdge.Route();
            if (isValidSrcConnect)
            {
                createdEdge.Source = srcConnectableFig;
            }
            if (isValidTgtConnect)
            {
                createdEdge.Target = tgtConnectableFig;
            }

            createdEditor.Enable();
        }