public void LoginByUsername_ThrowsChatException_IfSettingsTeamIdDoesNotMatchInitialLoadTeamId()
        {
            const string teamIdThatDoesNotMatchSettingsTeamId = "teamIdThatDoesNotMatch";
            const string SettingsTeamId = "settingsTeamId";
            const string url            = "http://localhost";
            const string userId         = "userId";
            const string teamGuid       = "teamGuid";
            const string username       = "******";
            const string password       = "******";
            var          token          = "token";
            var          login          = new Login {
                LoginId = username, Password = password, Token = string.Empty
            };
            var initialLoad = new InitialLoad {
                Teams = new[] { new Team {
                                    Id = teamGuid, Name = teamIdThatDoesNotMatchSettingsTeamId
                                } }
            };
            var user = new User {
                Id = userId
            };
            var restService = new Mock <IRestService>();

            restService.Setup(x => x.GetInitialLoad(new Uri(url), token)).Returns(initialLoad);
            restService.Setup(x => x.Login(new Uri(url), login, out token)).Returns(user);
            var session     = new Mock <ISession>();
            var chatFactory = new Mock <IChatFactory>();

            chatFactory.Setup(x => x.NewInstance(restService.Object, new Uri(url), token, userId, teamGuid)).Returns(session.Object);
            var sut = new ClientImpl(restService.Object, chatFactory.Object);

            NUnit.Framework.Constraints.ActualValueDelegate <ISession> performLogin = () => sut.LoginByUsername(url, SettingsTeamId, username, password);

            Assert.That(performLogin, Throws.TypeOf <ChatException>());
        }
Exemple #2
0
        private static async Task ConsumeMany(CancellationToken token)
        {
            const int start    = 10000;
            const int end      = 10010;
            var       tasks    = new List <Task>();
            var       clients  = new List <ClientImpl>();
            var       channels = new List <Channel>();

            Console.WriteLine($"Starting {nameof(ConsumeMany)} scenario");

            for (int i = start; i < end; i++)
            {
                var channel = new Channel("localhost", i, ChannelCredentials.Insecure);
                var client  = new ClientImpl(channel);
                channels.Add(channel);
                clients.Add(client);
            }

            foreach (ClientImpl client in clients)
            {
                tasks.Add(client.ConsumeMany(token));
            }

            await Task.Delay(-1, token);

            var shutdownTasks = new List <Task>();

            foreach (Channel c in channels)
            {
                shutdownTasks.Add(c.ShutdownAsync());
            }

            await Task.WhenAll(shutdownTasks);
        }
        public void LoginByUsername_UsesDataFromRestServiceToCreateSession()
        {
            const string url      = "http://localhost";
            const string userId   = "userId";
            const string teamId   = "teamId";
            const string teamGuid = "teamGuid";
            const string username = "******";
            const string password = "******";
            var          token    = "token";
            var          login    = new Login {
                LoginId = username, Password = password, Token = string.Empty
            };
            var initialLoad = new InitialLoad {
                Teams = new[] { new Team {
                                    Id = teamGuid, Name = teamId
                                } }
            };
            var user = new User {
                Id = userId
            };
            var restService = new Mock <IRestService>();

            restService.Setup(x => x.GetInitialLoad(new Uri(url), token)).Returns(initialLoad);
            restService.Setup(x => x.Login(new Uri(url), login, out token)).Returns(user);
            var session     = new Mock <ISession>();
            var chatFactory = new Mock <IChatFactory>();

            chatFactory.Setup(x => x.NewInstance(restService.Object, new Uri(url), token, userId, teamGuid))
            .Returns(session.Object);
            var sut = new ClientImpl(restService.Object, chatFactory.Object);

            var result = sut.LoginByUsername(url, teamId, username, password);

            result.ShouldBeEquivalentTo(session.Object, "because the correct session should be returned");
        }
Exemple #4
0
        private async Task <bool> PutRoomRest()
        {
            var relativeUri = $"/rooms/{CurrentRoom.RoomNumber}?newStatus={StatusContainer}&note={NoteContainer}";
            var response    = await ClientImpl.Put(FixedUri + relativeUri);

            return(response.IsSuccessStatusCode);
        }
Exemple #5
0
        private void LoadButton_Click(object sender, EventArgs e)
        {
            string directory = Path.Combine(PathUtils.ApplicationDirectory, "Input");

            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            if (this.client != null)
            {
                this.client.Dispose();
                this.client = null;
            }

            OpenTibia.Core.Version version = (OpenTibia.Core.Version) this.inputVersionComboBox.SelectedItem;
            string datPath = Path.Combine(directory, "Tibia.dat");
            string sprPath = Path.Combine(directory, "Tibia.spr");

            try
            {
                this.client = new ClientImpl();
                this.client.ClientLoaded    += new EventHandler(this.ClientLoaded_Handler);
                this.client.ProgressChanged += new ProgressHandler(this.ClientProgress_Handler);
                this.client.ClientCompiled  += new EventHandler(this.ClientCompiled_Handler);
                this.client.Load(datPath, sprPath, version);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Selected client: " + version + ".\n\n" + ex.Message);
                Application.Exit();
            }
        }
        public void AddClient(string name, string tier, bool isValid)
        {
            if (String.IsNullOrEmpty(name))
            {
                throw new ArgumentException("name");
            }

            if (String.IsNullOrEmpty(tier))
            {
                throw new ArgumentException("tier");
            }

            //TODO remove ++startingIdentifier
            var newClient = new ClientImpl()
            {
                Identifier = ++startingIdentifier, Name = name, IsValid = isValid, Tier = tier
            };

            // Add to collection
            Clients.Add(newClient);

            // Publish event for other observer view models
            eventAggregator.GetEvent <NewClientEvent>().Publish(new NewClientEventPayload()
            {
                NewClient = newClient
            });
        }
Exemple #7
0
        public MainForm()
        {
            m_versions                     = new VersionStorage();
            m_client                       = new ClientImpl();
            m_client.ClientLoaded         += new EventHandler(ClientLoaded_Handler);
            m_client.ProgressChanged      += new ProgressHandler(ClientProgressChanged_Handler);
            m_worker                       = new BackgroundWorker();
            m_worker.WorkerReportsProgress = true;
            m_worker.DoWork               += new DoWorkEventHandler(DoWork_Handler);
            m_worker.ProgressChanged      += new ProgressChangedEventHandler(ProgressChanged_Handler);
            m_worker.RunWorkerCompleted   += new RunWorkerCompletedEventHandler(RunWorkerCompleted_Handler);

            InitializeComponent();
            LoadVersions();

            obdVersionComboBox.Items.Add(ObdVersion.Version1);
            obdVersionComboBox.Items.Add(ObdVersion.Version2);
            obdVersionComboBox.SelectedIndex = 0;
            itemsListBox.Client     = m_client;
            outfitsListBox.Client   = m_client;
            effectsListBox.Client   = m_client;
            missilesListBox.Client  = m_client;
            thingTypeListBox.Client = m_client;
            saveButton.Enabled      = false;
        }
Exemple #8
0
        protected override void ChannelRead0(IChannelHandlerContext ctx, object msg)
        {
            base.ChannelRead0(ctx, msg);
            IEvent @event;

            switch (msg)
            {
            case TextWebSocketFrame textFrame:
                @event = textFrame.Text().JsonToObject <Event>();
                ClientImpl.HandleEvent(@event);
                ConsoleHelper.TestWriteLine($"接收到String[{textFrame.Text()}]");
                break;

            case BinaryWebSocketFrame binaryFrame:
                @event = binaryFrame.GetDefaultObject <Event>();
                ClientImpl.HandleEvent(@event);
                ConsoleHelper.TestWriteLine($"接收到Bytes[{@event.ToJson()}]");
                break;

            case PongWebSocketFrame _:
                ConsoleHelper.TestWriteLine("接收到心跳");
                break;

            case CloseWebSocketFrame _:
                ConsoleHelper.TestWriteLine("接收到关闭");
                ctx.Channel.CloseAsync();
                break;
            }
        }
Exemple #9
0
        private static async Task ConsumeTwoAsync(CancellationToken token)
        {
            Console.Write($"Starting {nameof(ConsumeTwoAsync)} scenario");
            var channel = new Channel("localhost", 10000, ChannelCredentials.Insecure);
            var client  = new ClientImpl(channel);

            Console.WriteLine(await client.ConsumeTwoAsync(token));
        }
Exemple #10
0
        private static async Task ConsumeOneAsync(CancellationToken token)
        {
            Console.Write($"Starting {nameof(ConsumeOneAsync)} scenario");
            var          channel = new Channel("localhost", 10000, ChannelCredentials.Insecure);
            var          client  = new ClientImpl(channel);
            BombResponse r       = await client.ConsumeOne(token);

            Console.WriteLine($"Recieved response: code='{r.Code}' detail='{r.Detail}'");
        }
Exemple #11
0
        public static void Test()
        {
            client1 = new ClientImpl();
            client2 = new ClientImpl();

            client1.List.Add(new Entity(Guid.NewGuid())
            {
                Data = "data1"
            });
            client2.List.Add(new Entity(Guid.NewGuid())
            {
                Data = "data2"
            });

            Console.WriteLine();
            Console.WriteLine("Before...");
            ToConsole();

            SyncEngine.PullAndPushChanges(client1, ServerProxy.Instance);
            SyncEngine.PullAndPushChanges(client2, ServerProxy.Instance);

            Console.WriteLine();
            Console.WriteLine("After sync (Client1 <-> Server, Client2 <-> Server) ...");
            ToConsole();

            Thread.Sleep(2000);

            client1.List[0].Data = "modified";
            client1.List[0].SetModified();
            Console.WriteLine();
            Console.WriteLine("Modified on client1...");
            ToConsole();

            SyncEngine.PullAndPushChanges(client1, ServerProxy.Instance);
            SyncEngine.PullAndPushChanges(client2, ServerProxy.Instance);

            Console.WriteLine();
            Console.WriteLine("After sync (Client1 <-> Server, Client2 <-> Server) ...");
            ToConsole();

            Thread.Sleep(2000);

            client1.List[0].IsDeleted = true;
            client1.List[0].SetModified();
            Console.WriteLine();
            Console.WriteLine("Deleted on client...");
            ToConsole();

            SyncEngine.PullAndPushChanges(client1, ServerProxy.Instance);
            SyncEngine.PullAndPushChanges(client2, ServerProxy.Instance);

            Console.WriteLine();
            Console.WriteLine("After sync (Client1 <-> Server, Client2 <-> Server) ...");
            ToConsole();
        }
Exemple #12
0
        private async Task <List <Room> > GetRoomsRest()
        {
            var relativeUri = $"/rooms?type={CurrentEmployee.EmployeeType}";
            var response    = await ClientImpl.Get(FixedUri + relativeUri);

            if (!response.IsSuccessStatusCode)
            {
                throw new Exception(response.StatusCode.ToString());
            }
            return(TransformHttpContent(response.Content));
        }
Exemple #13
0
        private async Task <RemoteService> TryStartProcess(CancellationToken cancellationToken)
        {
            Process newProcess   = null;
            int     newProcessId = -1;

            try {
#if HOST_DEBUG
                newProcess = Process.GetCurrentProcess();
                var currentProcessId = 0;
                var remotePort       = "RoslynPad-DEBUG";
#else
                var currentProcessId = Process.GetCurrentProcess().Id;
                var remotePort       = "RoslynPad-" + Guid.NewGuid();

                var processInfo = new ProcessStartInfo(HostPath)
                {
                    Arguments        = $"{HostArguments} {remotePort} 0 {currentProcessId}",
                    WorkingDirectory = _initializationParameters.WorkingDirectory,
                    CreateNoWindow   = true,
                    UseShellExecute  = false
                };

                newProcess = new Process {
                    StartInfo = processInfo
                };
                newProcess.Start();

                cancellationToken.ThrowIfCancellationRequested();

                try {
                    newProcessId = newProcess.Id;
                }
                catch {
                    newProcessId = 0;
                }

                if (!newProcess.IsAlive())
                {
                    return(null);
                }
#endif
                cancellationToken.ThrowIfCancellationRequested();

                ClientImpl client = null;
                // instantiate remote service
                try {
                    cancellationToken.ThrowIfCancellationRequested();
#if HOST_DEBUG
                    if (_debugClient == null)
                    {
                        client = new ClientImpl(remotePort, this);
                        await client.Connect(TimeSpan.FromSeconds(4)).ConfigureAwait(false);

                        await client.Initialize(new InitializationMessage { Parameters = _initializationParameters })
                        .ConfigureAwait(false);

                        _debugClient = client;
                    }
                    else
                    {
                        client = _debugClient;
                    }
#else
                    client = new ClientImpl(remotePort, this);
                    await client.Connect(TimeSpan.FromSeconds(4)).ConfigureAwait(false);

                    await client.Initialize(new InitializationMessage { Parameters = _initializationParameters })
                    .ConfigureAwait(false);
#endif
                }
                catch (Exception) {
                    client?.Dispose();
                    return(null);
                }

                return(new RemoteService(newProcess, newProcessId, client));
            }
            catch (OperationCanceledException) {
                if (newProcess != null)
                {
                    RemoteService.InitiateTermination(newProcess, newProcessId);
                }

                return(null);
            }
        }