Ejemplo n.º 1
0
        protected async override Task StartAsyncClient()
        {
            Console.Write("Enter your nickname:\n> ");
            string name = Console.ReadLine();

            Dictionary <string, string> credentianls = new Dictionary <string, string>()
            {
                ["name"] = name
            };

            string connectionResult = await client.SendRecieveAsync(JsonConvert.SerializeObject(credentianls));

            if (connectionResult != ChatServer.CONNECTION_ESTABLISHED)
            {
                Console.WriteLine("ERROR: Can't connect to the remote server.\nPress any key to continue...");
                Console.ReadKey();
                return;
            }

            cancellationToken = new CancellationTokenSource();

            AsyncConsole.Init();
            AsyncConsole.WriteLine("========= Welcome to the server =========");
            var OnInputTask = AsyncConsole.ReadLine(OnInput, cancellationToken.Token);
            await client.StartReceiving(OnRecieve, cancellationToken);

            AsyncConsole.WriteLine("ERROR: Server closed the connection.\nPress Enter to continue...");
            await OnInputTask;

            client.Disconnect();
        }
Ejemplo n.º 2
0
 public static void LogError(object s, bool viewMessage = false)
 {
     AsyncConsole.WriteLine("[" + DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" + DateTime.Now.Second + "] " + "[ERROR]: " + s.ToString());
     if (viewMessage)
     {
         MessageBox.Show(s.ToString() + "\n\nFor help, please visit the BordeX Steam forums!", "BordeX public Error", MessageBoxButton.OK, MessageBoxImage.Error);
     }
 }
Ejemplo n.º 3
0
 protected virtual void OnRecieve(string message)
 {
     AsyncConsole.WriteLine(message);
     if (!client.IsConnected())
     {
         cancellationToken.Cancel();
         return;
     }
 }
Ejemplo n.º 4
0
        protected async virtual Task StartAsyncClient()
        {
            cancellationToken = new CancellationTokenSource();

            AsyncConsole.Init();
            var OnInputTask = AsyncConsole.ReadLine(OnInput, cancellationToken.Token);
            await client.StartReceiving(OnRecieve, cancellationToken);

            AsyncConsole.WriteLine("ERROR: Server closed the connection.\nPress Enter to continue...");
            await OnInputTask;

            client.Disconnect();
        }
Ejemplo n.º 5
0
        //  start of the file upload task
        public static async Task <int> Main(string[] args)
        {
            try
            {
                // ActionBlock sends the audio files into the buffer and the buffer sends the audio files
                // to Azure destination such as storage container or event hub
                var(BlobStorageConnectionString, MillisecondsToRun, AudioFiles) = ParseArguments();

                cts = MillisecondsToRun == 0 ? new CancellationTokenSource() : new CancellationTokenSource(MillisecondsToRun);

                Console.CancelKeyPress += (s, e) =>
                {
                    Console.WriteLine("Cancelling data upload");
                    cts.Cancel();
                    e.Cancel = true;
                };

                AsyncConsole console = new AsyncConsole(cts.Token);

                var blobServiceClient = new  BlobServiceClient(BlobStorageConnectionString);
                var containerClient   = blobServiceClient.GetBlobContainerClient(BlobInputContainerName);
                await containerClient.CreateIfNotExistsAsync().ConfigureAwait(false);

                var blobServiceClientPool = new ObjectPool <BlobServiceClient>(() => new BlobServiceClient(BlobStorageConnectionString), 10);

                var tasks = new List <Task>();

                tasks.Add(UploadAudioFilesAsync <AudioFile>(AudioFiles, AudioFile.GetAudioFile, blobServiceClientPool, 100, console, SimulatedDelayBetweenUploads, 1000));
                tasks.Add(console.WriterTask);

                await Task.WhenAll(tasks.ToArray());

                Console.WriteLine("Audio data upload complete");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine("Audio data upload failed");
                return(1);
            }

            return(0);
        }
Ejemplo n.º 6
0
        protected override void OnRecieve(string message)
        {
            try
            {
                message = ParseResponse(message);
            }
            catch (Exception e)
            {
                AsyncConsole.WriteLine(e.Message);
                return;
            }

            AsyncConsole.WriteLine(message);

            if (!client.IsConnected())
            {
                cancellationToken.Cancel();
                return;
            }
        }
Ejemplo n.º 7
0
        public void Start()
        {
            bool success = true;

            try
            {
                _server.Start();
            } catch (Exception ex)
            {
                AsyncConsole.WriteLine("Error starting TCP server on port " + Port + ": " + ex.Message);
                success = false;
            }

            if (success)
            {
                //Globals.SystemManager.LogApplicationEvent(this, "", "Listening for TCP connections on port " + _listeningPort);
                _timer = new System.Threading.Timer(OnTick);
                _timer.Change(_tickRate, Timeout.Infinite);
            }
        }
Ejemplo n.º 8
0
        //  start of the telemetry generation task
        public static async Task <int> Main(string[] args)
        {
            try
            {
                var(EventHubConnectionString, MillisecondsToRun, GenerateKeyframeGap, NumberOfDevices) = ParseArguments();
                var eventHubClient = EventHubClient.CreateFromConnectionString(EventHubConnectionString);
                cts = MillisecondsToRun == 0 ? new CancellationTokenSource() : new CancellationTokenSource(MillisecondsToRun);

                Console.CancelKeyPress += (s, e) =>
                {
                    Console.WriteLine("Cancelling data generation");
                    cts.Cancel();
                    e.Cancel = true;
                };

                AsyncConsole console = new AsyncConsole(cts.Token);

                var eventHubClientPool = new ObjectPool <EventHubClient>(() => EventHubClient.CreateFromConnectionString(EventHubConnectionString), 100);

                var tasks = new List <Task>();
                for (int i = 0; i < NumberOfDevices; i++)
                {
                    tasks.Add(GenerateTelemetryAsync(TelemetryGenerator.GetTimeElapsedTelemetry, eventHubClientPool, new TelemetrySerializer <DroneState>(), 100, console, GenerateKeyframeGap, SimulatedDelayBetweenMessages, 1000, DevicesPrefix + i));
                }

                tasks.Add(console.WriterTask);

                await Task.WhenAll(tasks.ToArray());

                Console.WriteLine("Data generation complete");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine("Data generation failed");
                return(1);
            }

            return(0);
        }
Ejemplo n.º 9
0
 public static void LogWarn(object s)
 {
     AsyncConsole.WriteLine("[" + DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" + DateTime.Now.Second + "] " + "[WARN]: " + s.ToString());
 }
Ejemplo n.º 10
0
        private static async Task GenerateTelemetryAsync <T>(Func <T, string, bool, T> factory,
                                                             ObjectPool <EventHubClient> pool, TelemetrySerializer <T> serializer, int randomSeed, AsyncConsole console, int generateKeyframeGap, int simulatedDelayInMs, int waittime, string deviceId) where T : class
        {
            if (factory == null)
            {
                throw new ArgumentNullException(nameof(factory));
            }

            if (pool == null)
            {
                throw new ArgumentNullException(nameof(pool));
            }

            if (console == null)
            {
                throw new ArgumentNullException(nameof(console));
            }

            if (waittime > 0)
            {
                TimeSpan span = TimeSpan.FromMilliseconds(waittime);
                await Task.Delay(span);
            }

            if (deviceId == null)
            {
                throw new ArgumentNullException(nameof(deviceId));
            }

            Random random = new Random(randomSeed);

            // buffer block that holds the messages . consumer will fetch records from this block asynchronously.
            BufferBlock <T> buffer = new BufferBlock <T>(new DataflowBlockOptions()
            {
                BoundedCapacity = 100000
            });

            // consumer that sends the data to event hub asynchronoulsy.
            var consumer = new ActionBlock <T>(
                action: (t) =>
            {
                using (var client = pool.GetObject())
                {
                    return(client.Value.SendAsync(new EventData(serializer.Serialize(t))).ContinueWith(
                               async task =>
                    {
                        cts.Cancel();
                        await console.WriteLine(task.Exception.InnerException.Message);
                        await console.WriteLine($"event hub client failed for {deviceId}");
                    }, TaskContinuationOptions.OnlyOnFaulted
                               ));
                }
            },
                new ExecutionDataflowBlockOptions
            {
                BoundedCapacity        = 100000,
                CancellationToken      = cts.Token,
                MaxDegreeOfParallelism = 100,
            }
                );

            // link the buffer to consumer .
            buffer.LinkTo(consumer, new DataflowLinkOptions()
            {
                PropagateCompletion = true
            });

            long messages = 0;

            List <Task> taskList                    = new List <Task>();
            T           telemetryObject             = null;
            T           lastKeyFrameTelemetryObject = null;
            bool        keyFrame                    = true;
            var         generateTask                = Task.Factory.StartNew(
                async() =>
            {
                // generate telemetry records and send them to buffer block
                for (; ;)
                {
                    telemetryObject = factory(lastKeyFrameTelemetryObject, deviceId, keyFrame);
                    await buffer.SendAsync(telemetryObject).ConfigureAwait(false);

                    // Save the last key frame for stateful generation
                    if (keyFrame)
                    {
                        lastKeyFrameTelemetryObject = telemetryObject;

                        // Turn key frame off after sending a key frame
                        keyFrame = false;
                    }

                    if (++messages % generateKeyframeGap == 0)
                    {
                        await console.WriteLine($"Created records for {deviceId} - generating key frame").ConfigureAwait(false);

                        // since rec is changing, makes sense to generate a key frame
                        keyFrame = true;
                    }
                    else
                    {
                        await console.WriteLine($"Created {messages} records for {deviceId}").ConfigureAwait(false);

                        // Wait for given number of milliseconds after each messaage
                        await Task.Delay(simulatedDelayInMs).ConfigureAwait(false);
                    }

                    // Every few messages, send a key frame randomly
                    if (messages % random.Next(10, 100) == 0)
                    {
                        keyFrame = true;
                    }


                    if (cts.IsCancellationRequested)
                    {
                        break;
                    }
                }

                buffer.Complete();
                await Task.WhenAll(buffer.Completion, consumer.Completion);
                await console.WriteLine($"Created total {messages} records for {deviceId}").ConfigureAwait(false);
            }
                ).Unwrap().ContinueWith(
                async task =>
            {
                cts.Cancel();
                await console.WriteLine($"failed to generate telemetry for {deviceId}").ConfigureAwait(false);
                await console.WriteLine(task.Exception.InnerException.Message).ConfigureAwait(false);
            }, TaskContinuationOptions.OnlyOnFaulted
                );

            // await on consumer completion. Incase if sending is failed at any moment ,
            // exception is thrown and caught . This is used to signal the cancel the reading operation and abort all activity further

            try
            {
                await Task.WhenAll(consumer.Completion, generateTask);
            }
            catch (Exception ex)
            {
                cts.Cancel();
                await console.WriteLine(ex.Message).ConfigureAwait(false);

                await console.WriteLine($"failed to generate telemetry").ConfigureAwait(false);

                throw;
            }
        }
Ejemplo n.º 11
0
        //  start of the read task
        public static async Task <int> Main(string[] args)
        {
            try
            {
                var arguments  = ParseArguments();
                var rideClient = EventHubClient.CreateFromConnectionString(
                    arguments.RideConnectionString
                    );
                var fareClient = EventHubClient.CreateFromConnectionString(
                    arguments.FareConnectionString
                    );

                cts = arguments.MillisecondsToRun == 0 ? new CancellationTokenSource() : new CancellationTokenSource(arguments.MillisecondsToRun);

                Console.CancelKeyPress += (s, e) =>
                {
                    //Console.WriteLine("Cancelling data generation");
                    cts.Cancel();
                    e.Cancel = true;
                };


                AsyncConsole console = new AsyncConsole(cts.Token);

                var rideClientPool = new ObjectPool <EventHubClient>(() => EventHubClient.CreateFromConnectionString(arguments.RideConnectionString), 100);
                var fareClientPool = new ObjectPool <EventHubClient>(() => EventHubClient.CreateFromConnectionString(arguments.FareConnectionString), 100);


                var numberOfMillisecondsToLead = arguments.MillisecondsToLead;
                var pushRideDataFirst          = arguments.sendRideDataFirst;

                var rideTaskWaitTime = 0;
                var fareTaskWaitTime = 0;

                if (numberOfMillisecondsToLead > 0)
                {
                    if (!pushRideDataFirst)
                    {
                        rideTaskWaitTime = numberOfMillisecondsToLead;
                    }
                    else
                    {
                        fareTaskWaitTime = numberOfMillisecondsToLead;
                    }
                }


                var rideTask = ReadData <TaxiRide>(arguments.RideDataFiles,
                                                   TaxiRide.FromString, rideClientPool, 100, console,
                                                   rideTaskWaitTime, DataFormat.Json);

                var fareTask = ReadData <TaxiFare>(arguments.TripDataFiles,
                                                   TaxiFare.FromString, fareClientPool, 200, console,
                                                   fareTaskWaitTime, DataFormat.Csv);


                await Task.WhenAll(rideTask, fareTask, console.WriterTask);

                Console.WriteLine("Data generation complete");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine("Data generation failed");
                return(1);
            }

            return(0);
        }
Ejemplo n.º 12
0
        private static async Task ReadData <T>(ICollection <string> pathList, Func <string, string, T> factory,
                                               ObjectPool <EventHubClient> pool, int randomSeed, AsyncConsole console, int waittime, DataFormat dataFormat)
            where T : TaxiData
        {
            if (pathList == null)
            {
                throw new ArgumentNullException(nameof(pathList));
            }

            if (factory == null)
            {
                throw new ArgumentNullException(nameof(factory));
            }

            if (pool == null)
            {
                throw new ArgumentNullException(nameof(pool));
            }

            if (console == null)
            {
                throw new ArgumentNullException(nameof(console));
            }

            if (waittime > 0)
            {
                TimeSpan span = TimeSpan.FromMilliseconds(waittime);
                await Task.Delay(span);
            }

            string typeName = typeof(T).Name;
            Random random   = new Random(randomSeed);

            // buffer block that holds the messages . consumer will fetch records from this block asynchronously.
            BufferBlock <T> buffer = new BufferBlock <T>(new DataflowBlockOptions()
            {
                BoundedCapacity = 100000
            });

            // consumer that sends the data to event hub asynchronoulsy.
            var consumer = new ActionBlock <T>(
                (t) =>
            {
                using (var client = pool.GetObject())
                {
                    return(client.Value.SendAsync(new EventData(Encoding.UTF8.GetBytes(
                                                                    t.GetData(dataFormat))), t.PartitionKey).ContinueWith(
                               async task =>
                    {
                        cts.Cancel();
                        await console.WriteLine(task.Exception.InnerException.Message);
                        await console.WriteLine($"event hub client failed for {typeName}");
                    }
                               , TaskContinuationOptions.OnlyOnFaulted
                               ));
                }
            },
                new ExecutionDataflowBlockOptions
            {
                BoundedCapacity        = 100000,
                CancellationToken      = cts.Token,
                MaxDegreeOfParallelism = 100,
            }
                );

            // link the buffer to consumer .
            buffer.LinkTo(consumer, new DataflowLinkOptions()
            {
                PropagateCompletion = true
            });

            long messages = 0;

            List <Task> taskList = new List <Task>();

            var readTask = Task.Factory.StartNew(
                async() =>
            {
                // iterate through the path list and act on each file from here on
                foreach (var path in pathList)
                {
                    using (var archive = new ZipArchive(File.OpenRead(path),
                                                        ZipArchiveMode.Read))
                    {
                        foreach (var entry in archive.Entries)
                        {
                            using (var reader = new StreamReader(entry.Open()))
                            {
                                var header = reader.ReadLines()
                                             .First();
                                // Start consumer
                                var lines = reader.ReadLines()
                                            .Skip(1);


                                // for each line , send to event hub
                                foreach (var line in lines)
                                {
                                    // proceed only if previous send operation is succesful.
                                    // cancelation is requested in case if send fails .
                                    if (cts.IsCancellationRequested)
                                    {
                                        break;
                                    }
                                    await buffer.SendAsync(factory(line, header)).ConfigureAwait(false);
                                    if (++messages % 10000 == 0)
                                    {
                                        // random delay every 10000 messages are buffered ??
                                        await Task.Delay(random.Next(100, 1000))
                                        .ConfigureAwait(false);
                                        await console.WriteLine($"Created {messages} records for {typeName}").ConfigureAwait(false);
                                    }
                                }
                            }

                            if (cts.IsCancellationRequested)
                            {
                                break;
                            }
                        }

                        if (cts.IsCancellationRequested)
                        {
                            break;
                        }
                    }

                    buffer.Complete();
                    await Task.WhenAll(buffer.Completion, consumer.Completion);
                    await console.WriteLine($"Created total {messages} records for {typeName}").ConfigureAwait(false);
                }
            }
                ).Unwrap().ContinueWith(
                async task =>
            {
                cts.Cancel();
                await console.WriteLine($"failed to read files for {typeName}").ConfigureAwait(false);
                await console.WriteLine(task.Exception.InnerException.Message).ConfigureAwait(false);
            }
                , TaskContinuationOptions.OnlyOnFaulted
                );


            // await on consumer completion. Incase if sending is failed at any moment ,
            // execption is thrown and caught . This is used to signal the cancel the reading operation and abort all activity further

            try
            {
                await Task.WhenAll(consumer.Completion, readTask);
            }
            catch (Exception ex)
            {
                cts.Cancel();
                await console.WriteLine(ex.Message).ConfigureAwait(false);

                await console.WriteLine($"failed to send files for {typeName}").ConfigureAwait(false);

                throw;
            }
        }
Ejemplo n.º 13
0
        private static async Task UploadAudioFilesAsync <T>(ICollection <string> pathList, Func <string, T> factory,
                                                            ObjectPool <BlobServiceClient> pool, int randomSeed, AsyncConsole console, int simulatedDelay, int waittime) where T : AudioFile
        {
            if (factory == null)
            {
                throw new ArgumentNullException(nameof(factory));
            }

            if (pool == null)
            {
                throw new ArgumentNullException(nameof(pool));
            }

            if (console == null)
            {
                throw new ArgumentNullException(nameof(console));
            }

            if (waittime > 0)
            {
                TimeSpan span = TimeSpan.FromMilliseconds(waittime);
                await Task.Delay(span);
            }

            Random random = new Random(randomSeed);

            // buffer block that holds the messages . consumer will fetch records from this block asynchronously.
            BufferBlock <T> buffer = new BufferBlock <T>(new DataflowBlockOptions()
            {
                BoundedCapacity = 100000
            });

            // consumer that sends the data to blob storage asynchronoulsy.
            var consumer = new ActionBlock <T>(
                (t) =>
            {
                using (var client = pool.GetObject())
                {
                    var containerClient = client.Value.GetBlobContainerClient(BlobInputContainerName);
                    return(containerClient.UploadBlobAsync(Path.Combine(t.ParentFolderName, t.FileName),
                                                           File.OpenRead(t.FullPath),
                                                           cts.Token).ContinueWith(
                               async task =>
                    {
                        cts.Cancel();
                        await console.WriteLine(task.Exception.InnerException.Message);
                        await console.WriteLine($"Container client failed for {t}");
                    }, TaskContinuationOptions.OnlyOnFaulted
                               ));
                }
            },
                new ExecutionDataflowBlockOptions
            {
                BoundedCapacity        = ObjectPoolBoundedCapacity,
                CancellationToken      = cts.Token,
                MaxDegreeOfParallelism = MaxDegreeOfParallelism,
            }
                );

            // link the buffer to consumer .
            buffer.LinkTo(consumer, new DataflowLinkOptions()
            {
                PropagateCompletion = true
            });

            long files = 0;

            var taskList = new List <Task>();

            var uploadTask = Task.Factory.StartNew(
                async() =>
            {
                // generate telemetry records and send them to buffer block
                foreach (var path in pathList)
                {
                    if (cts.IsCancellationRequested)
                    {
                        break;
                    }
                    await buffer.SendAsync <T>(factory(path)).ConfigureAwait(false);

                    if (++files % simulatedDelay == 0)
                    {
                        // random delay every 10 files
                        await Task.Delay(random.Next(100, 1000)).ConfigureAwait(false);
                        await console.WriteLine($"Uploaded {files} audiofiles").ConfigureAwait(false);
                    }
                }

                buffer.Complete();
                await Task.WhenAll(buffer.Completion, consumer.Completion).ConfigureAwait(false);
                await console.WriteLine($"Uploaded total {files} audiofiles").ConfigureAwait(false);
            }
                ).Unwrap().ContinueWith(
                async task =>
            {
                cts.Cancel();
                await console.WriteLine($"failed to upload audiofiles").ConfigureAwait(false);
                await console.WriteLine(task.Exception.InnerException.Message).ConfigureAwait(false);
            }, TaskContinuationOptions.OnlyOnFaulted
                );

            // await on consumer completion. Incase if sending is failed at any moment ,
            // exception is thrown and caught . This is used to signal the cancel the reading operation and abort all activity further

            try
            {
                await Task.WhenAll(consumer.Completion, uploadTask);
            }
            catch (Exception ex)
            {
                cts.Cancel();
                await console.WriteLine(ex.Message).ConfigureAwait(false);

                await console.WriteLine($"failed to upload audiofiles").ConfigureAwait(false);

                throw;
            }
        }
Ejemplo n.º 14
0
        private static async Task ReadData <T>(ICollection <string> pathList, Func <string, string, T> factory,
                                               ObjectPool <EventHubClient> pool, int randomSeed, AsyncConsole console,
                                               CancellationToken cancellationToken, int waittime, DataFormat dataFormat)
            where T : TaxiData
        {
            if (pathList == null)
            {
                throw new ArgumentNullException(nameof(pathList));
            }

            if (factory == null)
            {
                throw new ArgumentNullException(nameof(factory));
            }

            if (pool == null)
            {
                throw new ArgumentNullException(nameof(pool));
            }

            if (console == null)
            {
                throw new ArgumentNullException(nameof(console));
            }

            if (waittime > 0)
            {
                TimeSpan span = TimeSpan.FromMilliseconds(waittime);
                await Task.Delay(span);
            }

            string typeName = typeof(T).Name;
            Random random   = new Random(randomSeed);

            // buffer block that holds the messages . consumer will fetch records from this block asynchronously.
            BufferBlock <T> buffer = new BufferBlock <T>(new DataflowBlockOptions()
            {
                BoundedCapacity = 100000
            });

            // consumer that sends the data to event hub asynchronoulsy.
            var consumer = new ActionBlock <T>(
                (t) =>
            {
                using (var client = pool.GetObject())
                {
                    return(client.Value.SendAsync(new EventData(Encoding.UTF8.GetBytes(
                                                                    t.GetData(dataFormat))), t.PartitionKey));
                }
            },
                new ExecutionDataflowBlockOptions
            {
                BoundedCapacity        = 100000,
                CancellationToken      = cancellationToken,
                MaxDegreeOfParallelism = 100,
            }
                );

            // link the buffer to consumer .
            buffer.LinkTo(consumer, new DataflowLinkOptions()
            {
                PropagateCompletion = true
            });

            long messages = 0;

            // iterate through the path list and act on each file from here on
            foreach (var path in pathList)
            {
                ZipArchive archive = new ZipArchive(
                    File.OpenRead(path),
                    ZipArchiveMode.Read);

                foreach (var entry in archive.Entries)
                {
                    using (var reader = new StreamReader(entry.Open()))
                    {
                        var header = reader.ReadLines()
                                     .First();
                        // Start consumer
                        var lines = reader.ReadLines()
                                    .Skip(1);


                        // for each line , send to event hub
                        foreach (var line in lines)
                        {
                            await buffer.SendAsync(factory(line, header)).ConfigureAwait(false);

                            if (++messages % 10000 == 0)
                            {
                                // random delay every 10000 messages are buffered ??
                                await Task.Delay(random.Next(100, 1000))
                                .ConfigureAwait(false);

                                await console.WriteLine($"Created {messages} records for {typeName}").ConfigureAwait(false);
                            }
                        }
                    }
                }
            }

            buffer.Complete();
            await Task.WhenAll(buffer.Completion, consumer.Completion);

            await console.WriteLine($"Created total {messages} records for {typeName}").ConfigureAwait(false);
        }
Ejemplo n.º 15
0
        private static async void MainThread()
        {
            console = new AsyncConsole(200, 300);
            console.InputForegroundColor  = ConsoleColor.White;
            console.OutputBackgroundColor = ConsoleColor.Black;
            console.OutputForegroundColor = ConsoleColor.White;
            console.InputBackgroundColor  = ConsoleColor.Black;
            console.WindowWidth           = 200;
            console.Clear();

            var client = new BattleNetClient(_settings);

            client.Connected             += Client_Connected;
            client.Disconnected          += Client_Disconnected;
            client.ClientCheckPassed     += client_ClientCheckPassed;
            client.ClientCheckFailed     += client_ClientCheckFailed;
            client.LoginSucceeded        += client_LoginSucceeded;
            client.LoginFailed           += client_LoginFailed;
            client.AccountCreated        += client_AccountCreated;
            client.AccountCreationFailed += client_AccountCreationFailed;

            client.Channel.UserJoined       += Client_UserJoinedChannel;
            client.Channel.UserLeft         += Client_UserLeftChannel;
            client.Channel.UserShown        += Client_UserWasInChannel;
            client.Channel.UserSpoke        += Client_UserSpoke;
            client.Channel.UserEmoted       += Client_UserEmoted;
            client.Channel.NewChannelJoined += Channel_NewChannelJoined;

            client.ServerError         += client_ServerError;
            client.ServerInformation   += client_ServerInformation;
            client.Broadcast           += client_Broadcast;
            client.WhisperReceived     += client_WhisperReceived;
            client.WhisperSent         += client_WhisperSent;
            client.ChannelListReceived += client_ChannelListReceived;

            client.ConnectAsync();

            string lastInput;

            do
            {
                lastInput = await console.ReadLineAsync();

                switch (lastInput)
                {
                case "/clear":
                    console.Clear();
                    break;

                case "/channel-list":
                case "/cl":
                    if (_channel != null)
                    {
                        client_ChannelListReceived(client, _channel);
                    }
                    else
                    {
                        console.OutputForegroundColor = ConsoleColor.Red;
                        console.WriteLine("The channel list has not yet been received.");
                    }
                    break;

                case "/quit":
                    client.Disconnect();
                    break;

                default:
                    client.Send(lastInput);
                    break;
                }
            }while (lastInput != "/quit");

            _ended.Set();
        }
Ejemplo n.º 16
0
        private static void TCPServer_DataAvailable(object sender, TCPServer.TCPCommandEventArgs e)
        {
            string receivedStr = Encoding.UTF8.GetString(e.Data);

            string[] commands = receivedStr.Split("\0", StringSplitOptions.RemoveEmptyEntries); // break up multiple commands that came in together

            //string trimmedCommand;
            foreach (string command in commands)
            {
                // if the command is null terminated, remove the null so that the command is recognized in the switch statement below

                //if (command.EndsWith("\0"))
                //{
                //    trimmedCommand = command.Substring(0, command.Length - 1); // Encoding.UTF8.GetString(e.Data, 0, e.Data.Length - 1);
                //}

                switch (command.ToUpper())
                {
                case "PING":
                    _FDAControlServer.Send(e.ClientID, "OK");
                    break;

                case "SHUTDOWN":
                    Globals.SystemManager?.LogApplicationEvent(Globals.FDANow(), "FDA Application", "", "Shutdown command received");
                    _FDAControlServer.Send(e.ClientID, "OK");

                    // give the TCP server a second to send the response before starting the shutdown
                    Thread.Sleep(1000);

                    shutdownWorker         = new BackgroundWorker();
                    shutdownWorker.DoWork += DoShutdown;
                    shutdownWorker.RunWorkerAsync();
                    //DoShutdown();
                    break;

                case "TOTALQUEUECOUNT":
                    //LogEvent("Getting queue counts");
                    int count = -1;
                    if (_dataAquisitionManager != null)
                    {
                        count = _dataAquisitionManager.GetTotalQueueCounts();
                    }
                    //LogEvent("Replying with the count (" + count.ToString() + ")");
                    _FDAControlServer.Send(e.ClientID, count.ToString());
                    break;

                case "STATUS":
                    string jsonStatus = GetFDAStatus().JSON();
                    _FDAControlServer.Send(e.ClientID, jsonStatus);
                    break;

                case "VERSION":
                    // return the FDA version number and the database type
                    _FDAControlServer.Send(e.ClientID, Globals.FDAVersion);
                    break;

                case "DBTYPE":
                    _FDAControlServer.Send(e.ClientID, DBType);
                    break;

                case "RUNMODE":
                    if (Globals.ConsoleMode)
                    {
                        _FDAControlServer.Send(e.ClientID, "debug (console)");
                    }
                    else
                    {
                        _FDAControlServer.Send(e.ClientID, "background");
                    }
                    break;

                case "UPTIME":
                    string   sendString = "";
                    TimeSpan uptime;
                    if (Globals.ExecutionTime != DateTime.MinValue)
                    {
                        uptime     = Globals.FDANow().Subtract(Globals.ExecutionTime);
                        sendString = uptime.Ticks.ToString();
                    }
                    _FDAControlServer.Send(e.ClientID, sendString);
                    break;

                case "PAUSE":
                    Globals.SystemManager.LogApplicationEvent(Globals.FDANow(), "FDA Application", "", "Pause command received", false, true);
                    AsyncConsole.Flush();
                    Globals.FDAStatus = Globals.AppState.Pausing;
                    break;

                case "RESUME":
                    Globals.FDAStatus = Globals.AppState.Normal;
                    Globals.SystemManager.LogApplicationEvent(Globals.FDANow(), "FDA Application", "", "Resume command received", false, true);
                    break;

                default:
                    Globals.SystemManager.LogApplicationEvent(Globals.FDANow(), "FDA Application", "", "Unrecognized command received over TCP '" + receivedStr + "'");
                    _FDAControlServer.Send(e.ClientID, "Unrecognized command '" + receivedStr + "'");
                    break;
                }
            }
        }