public static void Write(string messageType, int time, int transportId, TransportType type, Location location, Location?destination, int?duration, IReadOnlyList <Cargo> store) { var departEvent = new TransportEvent { Type = messageType, Time = time, TransportId = transportId, Kind = type.ToString().ToUpper(), Location = location.ToString().ToUpper(), Destination = destination?.ToString().ToUpper(), Duration = duration }; foreach (var cargo in store) { departEvent.Cargo.Add(new TransportCargo { Id = cargo.Id, Origin = cargo.Origin.ToString().ToUpper(), Destination = cargo.Destination.ToString().ToUpper() }); } Write(departEvent); }
public async Task CreateClientTranslatesTheTransportType(TransportType connectionType) { var options = new EventHubClientOptions { TransportType = connectionType }; var host = "my.eventhub.com"; var eventHubPath = "some-path"; var signature = new SharedAccessSignature(options.TransportType, host, eventHubPath, "keyName", "KEY", TimeSpan.FromHours(1)); var credential = new SharedAccessSignatureCredential(signature); var client = (AmqpEventHubClient)TrackOneEventHubClient.CreateClient(host, eventHubPath, credential, options); try { if (connectionType.ToString().ToLower().Contains("websockets")) { Assert.That(client.ConnectionStringBuilder.TransportType.ToString().ToLower(), Contains.Substring("websockets"), "The transport type should be based on WebSockets."); } else { Assert.That(client.ConnectionStringBuilder.TransportType.ToString().ToLower(), Does.Not.Contain("websockets"), "The transport type should be based on TCP."); } } finally { await client?.CloseAsync(); } }
public static void TransportDisabledByClient(ILogger logger, TransportType transport) { if (logger.IsEnabled(LogLevel.Debug)) { _transportDisabledByClient(logger, transport.ToString(), null); } }
static async Task <int> MainAsync() { Console.WriteLine($"[{DateTime.UtcNow.ToString("MM/dd/yyyy hh:mm:ss.fff tt", CultureInfo.InvariantCulture)}] Main()"); IConfiguration configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("config/appsettings.json", optional: true) .AddEnvironmentVariables() .Build(); TimeSpan dmDelay = configuration.GetValue("DMDelay", TimeSpan.FromSeconds(5)); string targetModuleId = configuration.GetValue("TargetModuleId", "DirectMethodReceiver"); // Get deviced id of this device, exposed as a system variable by the iot edge runtime string targetDeviceId = configuration.GetValue <string>("IOTEDGE_DEVICEID"); TransportType transportType = configuration.GetValue("ClientTransportType", TransportType.Amqp_Tcp_Only); Console.WriteLine($"Using transport {transportType.ToString()}"); ModuleClient moduleClient = await InitModuleClient(transportType); (CancellationTokenSource cts, ManualResetEventSlim completed, Option <object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), null); Console.WriteLine($"Target device Id = [{targetDeviceId}], Target module Id = [{targetModuleId}]"); await CallDirectMethod(moduleClient, dmDelay, targetDeviceId, targetModuleId, cts).ConfigureAwait(false); await moduleClient.CloseAsync(); completed.Set(); handler.ForEach(h => GC.KeepAlive(h)); return(0); }
public static void StartingTransport(ILogger logger, TransportType transportType, Uri url) { if (logger.IsEnabled(LogLevel.Debug)) { _startingTransport(logger, transportType.ToString(), url, null); } }
public async Task HubConnectionCanSendAndReceiveGroupMessages(TransportType transportType, IHubProtocol protocol) { using (StartLog(out var loggerFactory, testName: $"{nameof(HubConnectionCanSendAndReceiveGroupMessages)}_{transportType.ToString()}_{protocol.Name}")) { var connection = CreateConnection(_serverFixture.FirstServer.Url + "/echo", transportType, protocol, loggerFactory); var secondConnection = CreateConnection(_serverFixture.SecondServer.Url + "/echo", transportType, protocol, loggerFactory); var tcs = new TaskCompletionSource <string>(); connection.On <string>("Echo", message => tcs.TrySetResult(message)); var tcs2 = new TaskCompletionSource <string>(); secondConnection.On <string>("Echo", message => tcs2.TrySetResult(message)); await secondConnection.StartAsync().OrTimeout(); await connection.StartAsync().OrTimeout(); await connection.InvokeAsync("AddSelfToGroup", "Test").OrTimeout(); await secondConnection.InvokeAsync("AddSelfToGroup", "Test").OrTimeout(); await connection.InvokeAsync("EchoGroup", "Test", "Hello, World!").OrTimeout(); Assert.Equal("Hello, World!", await tcs.Task.OrTimeout()); Assert.Equal("Hello, World!", await tcs2.Task.OrTimeout()); await connection.DisposeAsync().OrTimeout(); } }
public async Task Initialize() { var twin = await client.GetTwinAsync(); await client.OpenAsync(); TwinCollection properties = new TwinCollection(); properties[TransportTypeProperty] = transportType.ToString(); properties[TypeProperty] = deviceModel.DeviceType; properties[SupportedMethodsProperty] = String.Join(",", deviceModel.SupportedMethods.Select(x => x.Item1)); properties[TelemetryProperty] = deviceModel.TelemetrySchema; foreach (var property in deviceModel.InitialProperties) { properties[property.Item1] = property.Item2; } await client.UpdateReportedPropertiesAsync(properties); foreach (var method in deviceModel.SupportedMethods) { await client.SetMethodHandlerAsync(method.Item1, method.Item2, null); } await client.SetDesiredPropertyUpdateCallbackAsync(deviceModel.DesiredPropertyUpdateCallbackProperty, null); initialized = true; }
public AgentAction(TransportType transport, int choicesCount, double totalReward, double averageReward) { Transport = transport.ToString(); ChoicesCount = choicesCount; TotalReward = totalReward; AverageReward = averageReward; }
static async Task <int> MainAsync() { Console.WriteLine($"[{DateTime.UtcNow.ToString("MM/dd/yyyy hh:mm:ss.fff tt", CultureInfo.InvariantCulture)}] Main()"); IConfiguration configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("config/appsettings.json", optional: true) .AddEnvironmentVariables() .Build(); TransportType transportType = configuration.GetValue("ClientTransportType", TransportType.Amqp_Tcp_Only); Console.WriteLine($"Using transport {transportType.ToString()}"); await InitModuleClient(transportType); // Wait until the app unloads or is cancelled var cts = new CancellationTokenSource(); AssemblyLoadContext.Default.Unloading += (ctx) => cts.Cancel(); Console.CancelKeyPress += (sender, cpe) => cts.Cancel(); await WhenCancelled(cts.Token); return(0); }
public static void TransportDoesNotSupportTransferFormat(ILogger logger, TransportType transport, TransferFormat transferFormat) { if (logger.IsEnabled(LogLevel.Debug)) { _transportDoesNotSupportTransferFormat(logger, transport.ToString(), transferFormat.ToString(), null); } }
public static void TransportFailed(ILogger logger, TransportType transport, Exception ex) { if (logger.IsEnabled(LogLevel.Debug)) { _transportFailed(logger, transport.ToString(), ex); } }
static void Main() { Console.WriteLine($"[{DateTime.UtcNow.ToString("MM/dd/yyyy hh:mm:ss.fff tt", CultureInfo.InvariantCulture)}] Main()"); IConfiguration configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("config/appsettings.json", optional: true) .AddEnvironmentVariables() .Build(); TransportType transportType = configuration.GetValue("ClientTransportType", TransportType.Mqtt_Tcp_Only); Console.WriteLine($"Using transport {transportType.ToString()}"); var retryPolicy = new RetryPolicy(TimeoutErrorDetectionStrategy, TransientRetryStrategy); retryPolicy.Retrying += (_, args) => { Console.WriteLine($"Init failed with exception {args.LastException}"); if (args.CurrentRetryCount < RetryCount) { Console.WriteLine("Retrying..."); } }; retryPolicy.ExecuteAsync(() => Init(transportType)).Wait(); // Wait until the app unloads or is cancelled var cts = new CancellationTokenSource(); AssemblyLoadContext.Default.Unloading += (ctx) => cts.Cancel(); Console.CancelKeyPress += (sender, cpe) => cts.Cancel(); WhenCancelled(cts.Token).Wait(); }
static async Task <int> MainAsync() { Console.WriteLine($"[{DateTime.UtcNow.ToString("MM/dd/yyyy hh:mm:ss.fff tt", CultureInfo.InvariantCulture)}] Main()"); IConfiguration configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("config/appsettings.json", optional: true) .AddEnvironmentVariables() .Build(); TimeSpan messageDelay = configuration.GetValue("MessageDelay", TimeSpan.FromSeconds(5)); int messageCount = configuration.GetValue(MessageCountConfigKey, 500); bool sendForever = messageCount < 0; var sim = new SimulatorParameters { MachineTempMin = configuration.GetValue <double>("machineTempMin", 21), MachineTempMax = configuration.GetValue <double>("machineTempMax", 100), MachinePressureMin = configuration.GetValue <double>("machinePressureMin", 1), MachinePressureMax = configuration.GetValue <double>("machinePressureMax", 10), AmbientTemp = configuration.GetValue <double>("ambientTemp", 21), HumidityPercent = configuration.GetValue("ambientHumidity", 25) }; string messagesToSendString = sendForever ? "unlimited" : messageCount.ToString(); Console.WriteLine( $"Initializing simulated temperature sensor to send {messagesToSendString} messages, at an interval of {messageDelay.TotalSeconds} seconds.\n" + $"To change this, set the environment variable {MessageCountConfigKey} to the number of messages that should be sent (set it to -1 to send unlimited messages)."); TransportType transportType = configuration.GetValue("ClientTransportType", TransportType.Amqp_Tcp_Only); Console.WriteLine($"Using transport {transportType.ToString()}"); var retryPolicy = new RetryPolicy(TimeoutErrorDetectionStrategy, TransientRetryStrategy); retryPolicy.Retrying += (_, args) => { Console.WriteLine($"Creating ModuleClient failed with exception {args.LastException}"); if (args.CurrentRetryCount < RetryCount) { Console.WriteLine("Retrying..."); } }; ModuleClient moduleClient = await retryPolicy.ExecuteAsync(() => InitModuleClient(transportType)); ModuleClient userContext = moduleClient; await moduleClient.SetInputMessageHandlerAsync("control", ControlMessageHandle, userContext); (CancellationTokenSource cts, ManualResetEventSlim completed, Option <object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), null); await SendEvents(moduleClient, messageDelay, sendForever, messageCount, sim, cts); await cts.Token.WhenCanceled(); completed.Set(); handler.ForEach(h => GC.KeepAlive(h)); return(0); }
Settings( string deviceId, string iotHubConnectionString, string moduleId, string gatewayHostName, string workloadUri, string apiVersion, string moduleGenerationId, string iotHubHostName, CloudToDeviceMessageTesterMode testMode, string trackingId, TransportType transportType, TimeSpan messageDelay, Uri reportingEndpointUrl, TimeSpan testDuration, TimeSpan testStartDelay) { Preconditions.CheckRange(testDuration.Ticks, 0); Preconditions.CheckRange(testStartDelay.Ticks, 0); Preconditions.CheckArgument(Enum.IsDefined(typeof(TransportType), transportType)); Preconditions.CheckArgument(Enum.IsDefined(typeof(CloudToDeviceMessageTesterMode), testMode)); Preconditions.CheckNonWhiteSpace(deviceId, nameof(deviceId)); this.TestMode = testMode; this.ReportingEndpointUrl = Preconditions.CheckNotNull(reportingEndpointUrl, nameof(reportingEndpointUrl)); this.SharedSettings = new C2DTestSharedSettings() { IotHubConnectionString = Preconditions.CheckNonWhiteSpace(iotHubConnectionString, nameof(iotHubConnectionString)), DeviceId = deviceId + "-" + transportType.ToString() + "-leaf", ModuleId = Preconditions.CheckNonWhiteSpace(moduleId, nameof(moduleId)), }; if (testMode == CloudToDeviceMessageTesterMode.Receiver) { this.ReceiverSettings = new C2DTestReceiverSettings() { GatewayHostName = Preconditions.CheckNonWhiteSpace(gatewayHostName, nameof(gatewayHostName)), WorkloadUri = Preconditions.CheckNonWhiteSpace(workloadUri, nameof(workloadUri)), ApiVersion = Preconditions.CheckNonWhiteSpace(apiVersion, nameof(apiVersion)), ModuleGenerationId = Preconditions.CheckNonWhiteSpace(moduleGenerationId, nameof(moduleGenerationId)), IotHubHostName = Preconditions.CheckNonWhiteSpace(iotHubHostName, nameof(iotHubHostName)), TransportType = transportType, EdgeDeviceId = deviceId }; } else { this.SenderSettings = new C2DTestSenderSettings() { TrackingId = Preconditions.CheckNonWhiteSpace(trackingId, nameof(trackingId)), MessageDelay = messageDelay, TestStartDelay = testStartDelay, TestDuration = testDuration }; } }
private async Task RunConnection(TransportType transportType) { var userId = "C#" + transportType.ToString(); _tokens[userId] = await GetJwtToken(userId); var hubConnection = new HubConnectionBuilder() .WithUrl(ServerUrl + "/broadcast") .WithTransport(transportType) .WithAccessToken(() => _tokens[userId]) .Build(); var closedTcs = new TaskCompletionSource <object>(); hubConnection.Closed += e => closedTcs.SetResult(null); hubConnection.On <string, string>("Message", (sender, message) => Console.WriteLine($"[{userId}] {sender}: {message}")); await hubConnection.StartAsync(); Console.WriteLine($"[{userId}] Connection Started"); var ticks = 0; var nextMsgAt = 3; try { while (!closedTcs.Task.IsCompleted) { await Task.Delay(1000); ticks++; if (ticks % 15 == 0) { // no need to refresh the token for websockets if (transportType != TransportType.WebSockets) { _tokens[userId] = await GetJwtToken(userId); Console.WriteLine($"[{userId}] Token refreshed"); } } if (ticks % nextMsgAt == 0) { await hubConnection.SendAsync("Broadcast", userId, $"Hello at {DateTime.Now.ToString()}"); nextMsgAt = _random.Next(2, 5); } } } catch (Exception ex) { Console.WriteLine($"[{userId}] Connection terminated with error: {ex}"); } }
public ITransportInterface TransportSource(TransportType type) { switch (type) { case TransportType.Metro: return new MetroSource(); case TransportType.Train: return new TrainSource(); default: throw new NotSupportedException("TransportType: " + type.ToString()); } }
public static string GetTypeString(this TransportType type) { switch (type) { case TransportType.Bus: return(Bus); case TransportType.Trolleybus: return(Trolleybus); case TransportType.Tram: return(Tram); default: throw new ArgumentOutOfRangeException(type.ToString(), "Unknown transport type"); } }
public Transport GetTransport(TransportType type) { // A BoatPlane is worth 500k, otherwise it is worth 100k var transportValue = type == TransportType.BoatPlane ? 500000 : 100000; const int carSize = 6; var transportString = type.ToString(); var normalGraphic = _content.Load<Texture2D>(String.Concat("Images/Transport/", transportString)); var glowGraphic = _content.Load<Texture2D>(String.Concat("Images/Transport/", transportString, "_glow")); var newTransport = new Transport(type, transportString, carSize, normalGraphic, glowGraphic, transportValue); return newTransport; }
public Transport GetTransport(TransportType type) { // A BoatPlane is worth 500k, otherwise it is worth 100k var transportValue = type == TransportType.BoatPlane ? 500000 : 100000; const int carSize = 6; var transportString = type.ToString(); var normalGraphic = _content.Load <Texture2D>(String.Concat("Images/Transport/", transportString)); var glowGraphic = _content.Load <Texture2D>(String.Concat("Images/Transport/", transportString, "_glow")); var newTransport = new Transport(type, transportString, carSize, normalGraphic, glowGraphic, transportValue); return(newTransport); }
public void Display() { Console.WriteLine("*** Day Trip ***"); Console.WriteLine($"Morning: {_activities[0].ToString()}"); Console.WriteLine($"Lunch: {_lunch.ToString()}"); Console.WriteLine($"Afternoon: {_activities[1].ToString()}"); Console.WriteLine($"Dinner: {_dinner.ToString()}"); if (_accommodation != null) { Console.WriteLine($"Hotel: {_accommodation.ToString()}"); } Console.WriteLine($"Evening: {_activities[2].ToString()}"); Console.WriteLine($"Transport: {_transport.ToString()}"); Console.WriteLine($"Client: {_client.ToString()}"); }
static async Task <int> MainAsync() { Console.WriteLine($"[{DateTime.UtcNow.ToString("MM/dd/yyyy hh:mm:ss.fff tt", CultureInfo.InvariantCulture)}] Main()"); IConfiguration configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("config/appsettings.json", optional: true) .AddEnvironmentVariables() .Build(); TimeSpan messageDelay = configuration.GetValue("MessageDelay", TimeSpan.FromSeconds(5)); var sim = new SimulatorParameters { MachineTempMin = configuration.GetValue <double>("machineTempMin", 21), MachineTempMax = configuration.GetValue <double>("machineTempMax", 100), MachinePressureMin = configuration.GetValue <double>("machinePressureMin", 1), MachinePressureMax = configuration.GetValue <double>("machinePressureMax", 10), AmbientTemp = configuration.GetValue <double>("ambientTemp", 21), HumidityPercent = configuration.GetValue("ambientHumidity", 25) }; TransportType transportType = configuration.GetValue("ClientTransportType", TransportType.Amqp_Tcp_Only); Console.WriteLine($"Using transport {transportType.ToString()}"); var retryPolicy = new RetryPolicy(TimeoutErrorDetectionStrategy, TransientRetryStrategy); retryPolicy.Retrying += (_, args) => { Console.WriteLine($"Creating ModuleClient failed with exception {args.LastException}"); if (args.CurrentRetryCount < RetryCount) { Console.WriteLine("Retrying..."); } }; ModuleClient moduleClient = await retryPolicy.ExecuteAsync(() => InitModuleClient(transportType)); ModuleClient userContext = moduleClient; await moduleClient.SetInputMessageHandlerAsync("control", ControlMessageHandle, userContext).ConfigureAwait(false); (CancellationTokenSource cts, ManualResetEventSlim completed, Option <object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), null); await SendEvents(moduleClient, messageDelay, sim, cts).ConfigureAwait(false); completed.Set(); handler.ForEach(h => GC.KeepAlive(h)); return(0); }
public async Task HubConnectionCanSendAndReceiveMessages(TransportType transportType, IHubProtocol protocol) { using (StartLog(out var loggerFactory, testName: $"{nameof(HubConnectionCanSendAndReceiveMessages)}_{transportType.ToString()}_{protocol.Name}")) { var connection = CreateConnection(_serverFixture.FirstServer.Url + "/echo", transportType, protocol, loggerFactory); await connection.StartAsync().OrTimeout(); var str = await connection.InvokeAsync <string>("Echo", "Hello, World!").OrTimeout(); Assert.Equal("Hello, World!", str); await connection.DisposeAsync().OrTimeout(); } }
static async Task <int> MainAsync() { Console.WriteLine($"[{DateTime.UtcNow.ToString("MM/dd/yyyy hh:mm:ss.fff tt", CultureInfo.InvariantCulture)}] Main()"); IConfiguration configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("config/appsettings.json", optional: true) .AddEnvironmentVariables() .Build(); TimeSpan messageDelay = configuration.GetValue("MessageDelay", TimeSpan.FromMilliseconds(500)); int messageCount = configuration.GetValue(MessageCountConfigKey, 5000); bool sendForever = messageCount < 0; string messagesToSendString = sendForever ? "unlimited" : messageCount.ToString(); TransportType transportType = configuration.GetValue("ClientTransportType", TransportType.Amqp_Tcp_Only); Console.WriteLine($"Using transport {transportType.ToString()}"); var retryPolicy = new RetryPolicy(TimeoutErrorDetectionStrategy, TransientRetryStrategy); retryPolicy.Retrying += (_, args) => { Console.WriteLine($"Creating ModuleClient failed with exception {args.LastException}"); if (args.CurrentRetryCount < RetryCount) { Console.WriteLine("Retrying..."); } }; ModuleClient moduleClient = await retryPolicy.ExecuteAsync(() => InitModuleClient(transportType)); ModuleClient userContext = moduleClient; await moduleClient.SetInputMessageHandlerAsync("control", ControlMessageHandle, userContext); (CancellationTokenSource cts, ManualResetEventSlim completed, Option <object> handler) = ShutdownHandler.Init(TimeSpan.FromSeconds(5), null); await SendEvents(moduleClient, messageDelay, sendForever, messageCount, cts); //await cts.Token.WhenCanceled(); completed.Set(); handler.ForEach(h => GC.KeepAlive(h)); return(0); }
/// <summary> /// Create DeviceClient from the specified connection string using the specified transport type /// (WinRT) Only Http transport is allowed /// </summary> /// <param name="connectionString">Connection string for the IoT hub (including DeviceId)</param> /// <param name="transportType">Specifies whether Amqp or Http transport is used</param> /// <returns>DeviceClient</returns> public static DeviceClient CreateFromConnectionString(string connectionString, TransportType transportType) { if (connectionString == null) { throw new ArgumentNullException("connectionString"); } var iotHubConnectionString = IotHubConnectionString.Parse(connectionString); if (transportType == TransportType.Http1) { return new DeviceClient(new HttpDeviceClient(iotHubConnectionString)); } else { throw new NotImplementedException(); } throw new InvalidOperationException("Unsupported Transport Type " + transportType.ToString()); }
static string TransportName(TransportType type) { switch (type) { case TransportType.Amqp_Tcp_Only: return("AMQP"); case TransportType.Amqp_WebSocket_Only: return("AMQP over WebSockets"); case TransportType.Mqtt_Tcp_Only: return("MQTT"); case TransportType.Mqtt_WebSocket_Only: return("MQTT over WebSockets"); default: return(type.ToString()); } }
/// <summary> /// Create DeviceClient from the specified connection string using the specified transport type /// (WinRT) Only Http transport is allowed /// </summary> /// <param name="connectionString">Connection string for the IoT hub (including DeviceId)</param> /// <param name="transportType">Specifies whether Amqp or Http transport is used</param> /// <returns>DeviceClient</returns> public static DeviceClient CreateFromConnectionString(string connectionString, TransportType transportType) { if (connectionString == null) { throw new ArgumentNullException("connectionString"); } var iotHubConnectionString = IotHubConnectionString.Parse(connectionString); if (transportType == TransportType.Http1) { return(new DeviceClient(new HttpDeviceClient(iotHubConnectionString))); } else { throw new NotImplementedException(); } throw new InvalidOperationException("Unsupported Transport Type " + transportType.ToString()); }
public override string ToHtml() { string result = Visualisation.HtmlReceiptNotAcknowledgedMessage; result = result.Replace( ":ElectronicServiceProvider:", (ElectronicServiceProvider == null) ? string.Empty : ElectronicServiceProvider.ToHtml()); result += "\n"; result = result.Replace( ":DocumentURI:", (MessageURI == null) ? string.Empty : MessageURI.ToHtml()); result += "\n"; result = result.Replace( ":TransportType:", (TransportType == null) ? string.Empty : TransportType.GetDisplay(TransportType.ToString())); result += "\n"; result = result.Replace( ":Discrepancies:", (Discrepancies == null) ? string.Empty : Discrepancies.GetDisplayList()); result += "\n"; result = result.Replace( ":Applicant:", (Applicant == null) ? string.Empty : Applicant.ToHtml()); result += "\n"; result = result.Replace( ":DocumentTypeURI:", (DocumentTypeURI == null) ? string.Empty : DocumentTypeURI.ToHtml()); result += "\n"; result = result.Replace( ":DocumentTypeName:", (DocumentTypeName == null) ? string.Empty : DocumentTypeName.ToString()); result += "\n"; result = result.Replace( ":ReceiptTime:", (MessageCreationTime == null) ? string.Empty : MessageCreationTime.ToString("dd.MM.yyyy hh:mm:ss")); result += "\n"; //result = result.Replace( // ":Signature:", // (Signature == null) ? string.Empty : Signature.ToHtml()); return(result); }
/// <summary> /// Creates a new instance of OscServer. /// </summary> /// <param name="transportType">The underlying transport protocol.</param> /// <param name="ipAddress">The local IP address to bind to.</param> /// <param name="port">The UDP port to bind to.</param> /// <param name="multicastAddress">The multicast IP address to join.</param> /// <param name="transmissionType">The transmission type for the server to use.</param> /// <param name="consumeParsingExceptions">Specifies the behavior of handling parsing exceptions.</param> /// <remarks>If ipAddress is specified, Unicast; otherwise, if multicastAddress is specified, Multicast.</remarks> private OscServer(TransportType transportType, IPAddress ipAddress, int port, IPAddress multicastAddress, TransmissionType transmissionType, bool consumeParsingExceptions = true) { Assert.IsTrue(transportType == TransportType.Udp || transportType == TransportType.Tcp); if ((transportType == TransportType.Tcp) && (transmissionType != TransmissionType.Unicast)) { throw new InvalidOperationException("TCP must be used with TransmissionType.Unicast."); } mTransportType = transportType; mIPAddress = ipAddress; mPort = port; mIPEndPoint = new IPEndPoint(ipAddress, port); mTransmissionType = transmissionType; if (mTransmissionType == TransmissionType.Multicast) { Assert.ParamIsNotNull(multicastAddress); mMulticastAddress = multicastAddress; } mRegisteredMethods = new List <string>(); mFilterRegisteredMethods = true; mConsumeParsingExceptions = consumeParsingExceptions; switch (mTransportType) { case TransportType.Udp: mUdpServer = new UdpServer(mIPAddress, mPort, mMulticastAddress, mTransmissionType); mUdpServer.DataReceived += new EventHandler <UdpDataReceivedEventArgs>(mUdpServer_DataReceived); break; case TransportType.Tcp: mTcpServer = new TcpServer(mIPAddress, mPort, true, OscPacket.LittleEndianByteOrder); mTcpServer.DataReceived += new EventHandler <TcpDataReceivedEventArgs>(mTcpServer_DataReceived); break; default: throw new InvalidOperationException("Invalid transport type: " + mTransportType.ToString()); } }
static async Task <int> MainAsync() { Console.WriteLine($"[{DateTime.UtcNow.ToString("MM/dd/yyyy hh:mm:ss.fff tt", CultureInfo.InvariantCulture)}] Main()"); IConfiguration configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("config/appsettings.json", optional: true) .AddEnvironmentVariables() .Build(); TransportType transportType = configuration.GetValue("ClientTransportType", TransportType.Amqp_Tcp_Only); Console.WriteLine($"Using transport {transportType.ToString()}"); var retryPolicy = new RetryPolicy(TimeoutErrorDetectionStrategy, TransientRetryStrategy); retryPolicy.Retrying += (_, args) => { Console.WriteLine($"Creating ModuleClient failed with exception {args.LastException}"); if (args.CurrentRetryCount < RetryCount) { Console.WriteLine("Retrying..."); } }; Tuple <ModuleClient, ModuleConfig> moduleclientAndConfig = await retryPolicy.ExecuteAsync(() => InitModuleClient(transportType)); Tuple <ModuleClient, ModuleConfig> userContext = moduleclientAndConfig; await moduleclientAndConfig.Item1.SetInputMessageHandlerAsync("input1", PrintAndFilterMessages, userContext).ConfigureAwait(false); // Wait until the app unloads or is cancelled var cts = new CancellationTokenSource(); AssemblyLoadContext.Default.Unloading += (ctx) => cts.Cancel(); Console.CancelKeyPress += (sender, cpe) => cts.Cancel(); WhenCancelled(cts.Token).Wait(); return(0); }
public void SaveStateReward(string previousAgentState, string currentAgentState, double reward, TransportType previousAction) { var item = collection.Find(x => x.State == previousAgentState).FirstOrDefault(); if (item != null) { var allTransportTypes = item.AgentActions; var current = allTransportTypes.Find(x => x.Transport == previousAction.ToString()); current.AddReward(reward); var updateDef = Builders <MongoAgentStateInfo> .Update.Set(o => o.AgentActions, allTransportTypes); collection.UpdateOne(x => x.State == previousAgentState, updateDef); } else { collection.InsertOne( new MongoAgentStateInfo { State = previousAgentState, AgentActions = StorageHelpers.CreateFirstAgentActions(previousAction, reward) }); } }
public async Task InvokeAsync(HttpContext context) { StringValues TransportType; if (!context.Request.Headers.TryGetValue(BasicConfig.TransportType, out TransportType)) { context.Response.StatusCode = (int)HttpStatusCode.NotFound; return; } using (var Reader = new StreamReader(context.Request.Body)) { var body = await Reader.ReadToEndAsync(); if (!body.IsEmpty()) { await Save(HttpUtility.HtmlDecode(body), TransportType.ToString()); } } await context.Response.WriteAsync("Collect Success"); }
public override string ToString() { string result = Visualisation.ReceiptAcknowledgedMessage; result = result.Replace( ":ElectronicServiceProvider:", (ElectronicServiceProvider == null) ? string.Empty : ElectronicServiceProvider.ToString()); result = result.Replace( ":DocumentURI:", (DocumentURI == null) ? string.Empty : DocumentURI.ToString()); result = result.Replace( ":TransportType:", (TransportType == null) ? string.Empty : TransportType.GetDisplay(TransportType.ToString())); result = result.Replace( ":Applicant:", (Applicant == null) ? string.Empty : Applicant.ToString()); result = result.Replace( ":DocumentTypeURI:", (DocumentTypeURI == null) ? string.Empty : DocumentTypeURI.ToString()); result = result.Replace( ":DocumentTypeName:", (DocumentTypeName == null) ? string.Empty : DocumentTypeName.ToString()); result = result.Replace( ":CaseAccessIdentifier:", (CaseAccessIdentifier == null) ? string.Empty : CaseAccessIdentifier.ToString()); result = result.Replace( ":ReceiptTime:", (ReceiptTime == null) ? string.Empty : ReceiptTime.ToString("dd.MM.yyyy hh:mm:ss")); result = result.Replace( ":RegisteredBy:", (RegisteredBy == null) ? string.Empty : RegisteredBy.ToString()); //result = result.Replace( // ":Signature:", // (Signature== null) ? string.Empty : Signature.ToString()); return(result); }
public static void ConnectedWithTransport(TransportType transport) { Log.LogInformation((int)EventIds.Connected, $"Edge agent connected to IoT Hub via {transport.ToString()}."); }
public IVoIPTransport CreateTransport(TransportType transportType) { return _container.Get<IVoIPTransport>(transportType.ToString()); }
/// <summary> /// Creates a new instance of OscServer. /// </summary> /// <param name="transportType">The underlying transport protocol.</param> /// <param name="ipAddress">The local IP address to bind to.</param> /// <param name="port">The UDP port to bind to.</param> /// <param name="multicastAddress">The multicast IP address to join.</param> /// <param name="transmissionType">The transmission type for the server to use.</param> /// <param name="consumeParsingExceptions">Specifies the behavior of handling parsing exceptions.</param> /// <remarks>If ipAddress is specified, Unicast; otherwise, if multicastAddress is specified, Multicast.</remarks> public OscServer(TransportType transportType, IPAddress ipAddress, int port, IPAddress multicastAddress, TransmissionType transmissionType, bool consumeParsingExceptions) { Assert.IsTrue(transportType == TransportType.Udp || transportType == TransportType.Tcp); if ((transportType == TransportType.Tcp) && (transmissionType != TransmissionType.Unicast)) { throw new InvalidOperationException("TCP must be used with TransmissionType.Unicast."); } mTransportType = transportType; mIPAddress = ipAddress; mPort = port; mIPEndPoint = new IPEndPoint(ipAddress, port); mTransmissionType = transmissionType; if (mTransmissionType == TransmissionType.Multicast) { Assert.ParamIsNotNull(multicastAddress); mMulticastAddress = multicastAddress; } mRegisteredMethods = new List<string>(); mFilterRegisteredMethods = true; mConsumeParsingExceptions = consumeParsingExceptions; switch (mTransportType) { case TransportType.Udp: mUdpServer = new UdpServer(mIPAddress, mPort, mMulticastAddress, mTransmissionType); mUdpServer.DataReceived += new UdpDataReceivedHandler(mUdpServer_DataReceived); break; case TransportType.Tcp: mTcpServer = new TcpServer(mIPAddress, mPort, true, false, OscPacket.LittleEndianByteOrder); mTcpServer.DataReceived += new TcpDataReceivedHandler(mTcpServer_DataReceived); break; default: throw new InvalidOperationException("Invalid transport type: " + mTransportType.ToString()); } }