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(); }
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); } }
protected virtual void OnRecieve(string message) { AsyncConsole.WriteLine(message); if (!client.IsConnected()) { cancellationToken.Cancel(); return; } }
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(); }
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; } }
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); } }
public static void LogWarn(object s) { AsyncConsole.WriteLine("[" + DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" + DateTime.Now.Second + "] " + "[WARN]: " + s.ToString()); }
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; } }
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; } }
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; } }
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); }
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(); }
static void client_ChannelListReceived(object sender, ChannelListEventArgs e) { _channel = e; PrintTidTs(DateTime.Now); console.OutputForegroundColor = ConsoleColor.Yellow; console.WriteLine("Available channels:"); console.OutputForegroundColor = ConsoleColor.Cyan; foreach (string name in e.Channels) { console.WriteLine(" - {0}", name); } }