public AddressSpaceValueReadArrayTests(TestServerFixture server) { _server = server; _hostEntry = Try.Op(() => Dns.GetHostEntry(Utils.GetHostName())) ?? Try.Op(() => Dns.GetHostEntry("localhost")); }
private static void mainThreadRunner() { try { screenCapturer = new AdvScreenCapture(); dxgiDuplicator = new DxgiOutputDuplicator(0, 0); inputEmulator = new InputEmulator(); Logger.Info("Application start shared memory id " + streamerArgs.SharedMemoryId); int ownerPID = streamerArgs.ServiceProcessId == null ? 0 : streamerArgs.ServiceProcessId.Value; using (SharedMemoryStream sm = SharedMemoryStream.OpenSharedMemoryStream(streamerArgs.SharedMemoryId, ownerPID)) { try { static_sm = sm; thrDesktopCapture.Start(); while (!isExiting) { Command commandCode = (Command)sm.ReadByte(); // Handle switch (commandCode) { case Command.GetScreenCapture: ImgFlags imgFlags = (ImgFlags)sm.ReadByte(); byte jpegQuality = (byte)sm.ReadByte(); desktopCaptureTasks.Enqueue(new DesktopCaptureTask(imgFlags, jpegQuality)); break; //case Command.CaptureCompressedDesktopImage: // CaptureCompressedDesktopImage(sm); // break; case Command.ReproduceUserInput: inputEmulator.EmulateInput(sm); break; case Command.GetDesktopInfo: lock (sm) { desktopInfo.WriteToDataStream(sm); } break; case Command.KeepAlive: break; default: Logger.Debug("Unsupported command code received: " + commandCode); lock (sm) { sm.WriteByte((byte)Command.Error_CommandCodeUnknown); } break; } } } finally { static_sm = null; } } } catch (ThreadAbortException) { } catch (StreamDisconnectedException ex) { Logger.Info("Exiting because: " + ex.Message); } catch (Exception ex) { Logger.Debug(ex); Logger.Info("Exiting due to main thread runner exception"); } finally { Try.Catch(() => { dxgiDuplicator?.Dispose(); }); Try.Catch(() => { screenCapturer?.Dispose(); }); //Try.Catch(() => { inputEmulator?.Dispose(); }); RobustExit(); } }
public async Task InvokeMethodLateSubscriptionTest() { // Create a mock endpoint capable of returning a mock processor var processor = Mock.Of <IProcessor>(); var endpoint = new Mock <Endpoint>("myId"); endpoint.Setup(ep => ep.CreateProcessor()).Returns(processor); endpoint.SetupGet(ep => ep.Id).Returns("myId"); // Create a mock endpoint executor factory to create the endpoint executor to verify invocation var endpointExecutor = Mock.Of <IEndpointExecutor>(); Mock.Get(endpointExecutor).SetupGet(ee => ee.Endpoint).Returns(() => endpoint.Object); var endpointExecutorFactory = Mock.Of <IEndpointExecutorFactory>(); Mock.Get(endpointExecutorFactory).Setup(eef => eef.CreateAsync(It.IsAny <Endpoint>())).ReturnsAsync(endpointExecutor); // Create a route to map to the message var endpoints = new HashSet <Endpoint> { endpoint.Object }; var route = new Route("myRoute", "true", "myIotHub", TelemetryMessageSource.Instance, endpoints); // Create a router var routerConfig = new RouterConfig(new[] { route }); Router router = await Router.CreateAsync("myRouter", "myIotHub", routerConfig, endpointExecutorFactory); // Create mock message converter to generate a message with source matching the route var messageConverter = Mock.Of <Core.IMessageConverter <Devices.Routing.Core.IMessage> >(); var methodRequest = new DirectMethodRequest("device1/module1", "shutdown", null, TimeSpan.FromSeconds(2), TimeSpan.FromSeconds(20)); // Mock of twin manager var twinManager = Mock.Of <ITwinManager>(); // DeviceListener var identity = Mock.Of <IModuleIdentity>(m => m.DeviceId == "device1" && m.ModuleId == "module1" && m.Id == "device1/module1"); var cloudProxy = new Mock <ICloudProxy>(); // ICloudConnectionProvider var cloudConnection = Mock.Of <ICloudConnection>(c => c.IsActive && c.CloudProxy == Option.Some(cloudProxy.Object)); var cloudConnectionProvider = new Mock <ICloudConnectionProvider>(); cloudConnectionProvider.Setup(c => c.Connect(It.IsAny <IIdentity>(), It.IsAny <Action <string, CloudConnectionStatus> >())) .ReturnsAsync(Try.Success(cloudConnection)); var connectionManager = new ConnectionManager(cloudConnectionProvider.Object, Mock.Of <ICredentialsCache>(), new IdentityProvider("myIotHub")); IInvokeMethodHandler invokeMethodHandler = new InvokeMethodHandler(connectionManager); // RoutingEdgeHub var routingEdgeHub = new RoutingEdgeHub(router, messageConverter, connectionManager, twinManager, "testEdgeDevice", invokeMethodHandler, Mock.Of <IDeviceConnectivityManager>()); var deviceMessageHandler = new DeviceMessageHandler(identity, routingEdgeHub, connectionManager); var underlyingDeviceProxy = new Mock <IDeviceProxy>(); // Arrange Message message = new EdgeMessage.Builder(new byte[0]).Build(); message.Properties[SystemProperties.CorrelationId] = methodRequest.CorrelationId; message.Properties[SystemProperties.StatusCode] = "200"; underlyingDeviceProxy.Setup(d => d.InvokeMethodAsync(It.IsAny <DirectMethodRequest>())) .Callback(() => deviceMessageHandler.ProcessMethodResponseAsync(message)) .ReturnsAsync(default(DirectMethodResponse)); underlyingDeviceProxy.SetupGet(d => d.IsActive).Returns(true); // Act deviceMessageHandler.BindDeviceProxy(underlyingDeviceProxy.Object); Task <DirectMethodResponse> responseTask = routingEdgeHub.InvokeMethodAsync(identity.Id, methodRequest); // Assert Assert.False(responseTask.IsCompleted); // Act await routingEdgeHub.AddSubscription(identity.Id, DeviceSubscription.Methods); await Task.Delay(TimeSpan.FromSeconds(5)); // Assert Assert.True(responseTask.IsCompleted); Assert.Equal(methodRequest.CorrelationId, responseTask.Result.CorrelationId); Assert.Equal(200, responseTask.Result.Status); Assert.False(responseTask.Result.Exception.HasValue); Assert.Equal(HttpStatusCode.OK, responseTask.Result.HttpStatusCode); }
protected internal virtual void TraverseTry(Try @try) { @try.Unsupported(); }
public static Try <B> SelectMany <A, B>(this Try <A> t, Fn <A, Try <B> > f) => t.flatMap(f);
private void AddExceptionHandlers(Try Try, Block tryStartBlock, Block blockAfterTryBody, Block blockAfterHandlers) { Block blockAfterLastCatchEnd = blockAfterTryBody; for (int i = 0, n = Try.Catchers == null ? 0 : Try.Catchers.Count; i < n; i++) { Catch catcher = Try.Catchers[i]; TypeNode catcherType = this.VisitTypeReference(catcher.Type); if (catcherType == null) catcherType = SystemTypes.Object; ExceptionHandler cb = new ExceptionHandler(); cb.TryStartBlock = tryStartBlock; cb.BlockAfterTryEnd = blockAfterTryBody; cb.HandlerStartBlock = new Block(new StatementList(3)); if (catcher.Variable == null) catcher.Variable = new Local(Identifier.Empty, catcherType); else catcher.Variable = this.VisitTargetExpression(catcher.Variable); if (catcher.Variable is Local) cb.HandlerStartBlock.Statements.Add(new AssignmentStatement(catcher.Variable, new Expression(NodeType.Pop))); else { Local loc = new Local(Identifier.Empty, catcherType); if (catcher.Variable == null) catcher.Variable = loc; cb.HandlerStartBlock.Statements.Add(new AssignmentStatement(loc, new Expression(NodeType.Pop))); cb.HandlerStartBlock.Statements.Add(new AssignmentStatement(catcher.Variable, loc)); } this.currentExceptionBlock = catcher.Block; cb.HandlerStartBlock.Statements.Add(this.VisitBlock(catcher.Block)); cb.HandlerStartBlock.Statements.Add(new Branch(null, blockAfterHandlers, false, false, true)); cb.BlockAfterHandlerEnd = new Block(null); cb.HandlerStartBlock.Statements.Add(cb.BlockAfterHandlerEnd); cb.FilterType = catcherType; cb.HandlerType = NodeType.Catch; this.currentMethod.ExceptionHandlers.Add(cb); tryStartBlock.Statements.Add(cb.HandlerStartBlock); blockAfterLastCatchEnd = cb.BlockAfterHandlerEnd; } //TODO: handle filters and fault blocks if (Try.Finally != null && Try.Finally.Block != null && Try.Finally.Block.Statements.Count > 0) { ExceptionHandler fb = new ExceptionHandler(); fb.TryStartBlock = tryStartBlock; fb.BlockAfterTryEnd = blockAfterLastCatchEnd; this.currentExceptionBlock = Try.Finally.Block; fb.HandlerStartBlock = this.VisitBlock(Try.Finally.Block); fb.HandlerStartBlock.Statements.Add(new EndFinally()); fb.BlockAfterHandlerEnd = new Block(null); fb.HandlerStartBlock.Statements.Add(fb.BlockAfterHandlerEnd); fb.HandlerType = NodeType.Finally; this.currentMethod.ExceptionHandlers.Add(fb); tryStartBlock.Statements.Add(fb.HandlerStartBlock); } }
public override Statement VisitTry(Try Try) { throw new ApplicationException("unimplemented"); }
public async Task AuthenticateFailureTest() { // Arrange var deviceIdentity = Mock.Of <IDeviceIdentity>(d => d.Id == "d1" && d.DeviceId == "d1"); IClientCredentials credentials = new TokenCredentials(deviceIdentity, Guid.NewGuid().ToString(), string.Empty, Option.None <string>(), false); var connectionManager = Mock.Of <IConnectionManager>(c => c.CreateCloudConnectionAsync(credentials) == Task.FromResult(Try <ICloudProxy> .Failure(new TimeoutException()))); IAuthenticator cloudAuthenticator = new CloudTokenAuthenticator(connectionManager, IotHubHostName); // Act bool isAuthenticated = await cloudAuthenticator.AuthenticateAsync(credentials); // Assert Assert.False(isAuthenticated); }
public void TryExpression_AppliesMappingFunctionIfNoExceptionsAreThrown() { var result = Try.Expression(() => 4 + 6); Assert.Equal(10, result.Success); }
/// <inheritdoc/> public async Task <Certificate> NewRootCertificateAsync(string certificateName, X500DistinguishedName subjectName, DateTime?notBefore, TimeSpan lifetime, CreateKeyParams keyParams, IssuerPolicies policies, Func <byte[], IEnumerable <X509Extension> > extensions, CancellationToken ct) { if (string.IsNullOrEmpty(certificateName)) { throw new ArgumentNullException(nameof(certificateName)); } // Validate policies policies = policies.Validate(null, keyParams); string caTempCertIdentifier = null; try { // (1) Create key in key vault and get CSR. // policy self signed, new key, not exportable key var policySelfSignedNewKey = CreateCertificatePolicy( subjectName.Name, keyParams, true, _keyStoreIsHsm, false, false); var tempAttributes = CreateCertificateAttributes( DateTime.UtcNow.AddMinutes(-10), TimeSpan.FromMinutes(10), DateTime.MaxValue); await CreateCertificateAsync(certificateName, policySelfSignedNewKey, tempAttributes, null, ct); // We have the cert - get it and key identifier to do the signing var createdCertificateBundle = await _keyVaultClient.GetCertificateAsync( _vaultBaseUrl, certificateName, ct); caTempCertIdentifier = createdCertificateBundle.CertificateIdentifier.Identifier; // policy unknown issuer, reuse key - not exportable var policyUnknownReuse = CreateCertificatePolicy( subjectName.Name, keyParams, false, _keyStoreIsHsm, true, false); var attributes = CreateCertificateAttributes(notBefore, lifetime, DateTime.MaxValue); // create the CSR var createResult = await CreateCertificateAsync(certificateName, policyUnknownReuse, attributes, null, ct); if (createResult.Csr == null) { throw new CryptographicUnexpectedOperationException( "Failed to read CSR from CreateCertificate."); } // decode the CSR and verify consistency var info = createResult.Csr.ToCertificationRequest(); // (2) - Issue root X509 Certificate with the csr. var signedcert = await _factory.CreateCertificateAsync(this, new KeyVaultKeyHandle(createdCertificateBundle), subjectName, info.PublicKey, attributes.NotBefore.Value, attributes.Expires.Value, policies.SignatureType.Value, true, extensions, ct); // (3) - Complete certificate creation with merger of X509 Certificate. var mergeResult = await _keyVaultClient.MergeCertificateAsync( _vaultBaseUrl, certificateName, new X509Certificate2Collection(signedcert), null, null, ct); // (4) - Get merged certificate and key identifier var mergedCert = await _keyVaultClient.GetCertificateAsync( mergeResult.CertificateIdentifier.Identifier, ct); var cert = CertificateEx.Create(mergedCert.Cer, new KeyVaultKeyHandle(mergedCert), policies); await _certificates.AddCertificateAsync(certificateName, cert, mergedCert.CertificateIdentifier.Identifier, ct); return(cert); } catch (KeyVaultErrorException kex) { throw new ExternalDependencyException( "Failed to create new Root CA certificate", kex); } finally { if (caTempCertIdentifier != null) { // disable the temp cert for self signing operation var attr = new CertificateAttributes { Enabled = false }; await Try.Async(() => _keyVaultClient.UpdateCertificateAsync( caTempCertIdentifier, null, attr)); } } }
/// <inheritdoc/> public async Task <Certificate> CreateCertificateAndPrivateKeyAsync(string rootCertificate, string certificateName, X500DistinguishedName subjectName, DateTime?notBefore, CreateKeyParams keyParams, Func <byte[], IEnumerable <X509Extension> > extensions, CancellationToken ct) { try { // (0) Retrieve issuer certificate var caCertBundle = await _keyVaultClient.GetCertificateAsync( _vaultBaseUrl, rootCertificate, ct); if (caCertBundle == null) { throw new ResourceNotFoundException("Issuer cert not found."); } var caCert = await _certificates.FindCertificateAsync( caCertBundle.CertificateIdentifier.Identifier); if (caCert?.IssuerPolicies == null) { throw new ArgumentException("Certificate cannot issue."); } // (1) Create key in key vault and get CSR. // policy unknown issuer, new key, exportable key var policyUnknownNewExportable = CreateCertificatePolicy( subjectName.Name, keyParams, false, _keyStoreIsHsm, false, true); var attributes = CreateCertificateAttributes(notBefore, caCert.IssuerPolicies.IssuedLifetime.Value, caCert.NotAfterUtc); var createResult = await CreateCertificateAsync(certificateName, policyUnknownNewExportable, attributes, null, ct); if (createResult.Csr == null) { throw new CryptographicUnexpectedOperationException( "Failed to read CSR from CreateCertificate."); } // decode the CSR and verify consistency var info = createResult.Csr.ToCertificationRequest(); try { // (2) - Issue X509 Certificate with csr and root certificate. // create signed cert var signedcert = await _factory.CreateCertificateAsync(this, caCert, subjectName, info.PublicKey, attributes.NotBefore.Value, attributes.Expires.Value, caCert.IssuerPolicies.SignatureType.Value, false, extensions, ct); // (3) - Complete certificate creation with merger of X509 Certificate. var mergeResult = await _keyVaultClient.MergeCertificateAsync( _vaultBaseUrl, certificateName, new X509Certificate2Collection(signedcert), null, null, ct); // (4) - Get merged certificate and key identifier var mergedCert = await _keyVaultClient.GetCertificateAsync( mergeResult.CertificateIdentifier.Identifier, ct); var cert = CertificateEx.Create(mergedCert.Cer, new KeyVaultKeyHandle(mergedCert)); System.Diagnostics.Debug.Assert(!cert.IsIssuer()); await _certificates.AddCertificateAsync(certificateName, cert, mergedCert.CertificateIdentifier.Identifier, ct); return(cert); } catch { await _keyVaultClient.DeleteCertificateAsync( _vaultBaseUrl, certificateName, ct); await Try.Async(() => _keyVaultClient.PurgeDeletedCertificateAsync( _vaultBaseUrl, certificateName, ct)); throw; } } catch (KeyVaultErrorException ex) { throw new ExternalDependencyException( "Failed to create new key pair certificate", ex); } }
public static Validation <Fail, Try <B> > Sequence <Fail, A, B>(this Try <A> ta, Func <A, Validation <Fail, B> > f) => ta.Map(f).Sequence();
/// <inheritdoc/> public async Task ProcessEventsAsync(PartitionContext context, IEnumerable <EventData> messages) { if (messages == null || !messages.Any()) { return; } var messagesCount = 0; foreach (var eventData in messages) { messagesCount++; if (_outer._config.SkipEventsOlderThan != null && eventData.SystemProperties.TryGetValue("x-opt-enqueued-time", out var enqueued) && (DateTime)enqueued + _outer._config.SkipEventsOlderThan < DateTime.UtcNow) { kOldEvent.WithLabels(_processorId, context.EventHubPath, context.ConsumerGroupName, context.PartitionId).Inc(); continue; } var properties = new EventProperties(eventData.SystemProperties, eventData.Properties); if (eventData.Body.Array == null) { _logger.Verbose("WARNING: Received empty message with properties {@properties}", properties); continue; } await _handler.HandleAsync(eventData.Body.Array, properties, () => CheckpointAsync(context, eventData)); if (context.CancellationToken.IsCancellationRequested) { // Checkpoint to the last processed event. await CheckpointAsync(context, eventData); context.CancellationToken.ThrowIfCancellationRequested(); } } TotalMessagesCount += messagesCount; kEventProcessorMessages.WithLabels(_processorId, context.EventHubPath, context.ConsumerGroupName, context.PartitionId).Set(TotalMessagesCount); // Checkpoint if needed if (_sw.ElapsedMilliseconds >= _interval) { try { _logger.Debug("Checkpointing EventProcessor {id} for partition {partitionId}...", _processorId, context.PartitionId); await context.CheckpointAsync(); _sw.Restart(); } catch (Exception ex) { _logger.Warning(ex, "Failed checkpointing EventProcessor {id} for partition {partitionId}...", _processorId, context.PartitionId); kEventProcessorDetails.WithLabels(_processorId, context.EventHubPath, context.ConsumerGroupName, context.PartitionId, "checkpoint_failed").Inc(); if (_sw.ElapsedMilliseconds >= 2 * _interval) { // Give up checkpointing after trying a couple more times _sw.Restart(); } } } await Try.Async(_handler.OnBatchCompleteAsync); }
public static Try <B1> SelectMany <A, B, B1>(this Try <A> t, Fn <A, Try <B> > f, Fn <A, B, B1> g) => t.flatMap(f, g);
private Statement Translate(CodeTryCatchFinallyStatement statement){ if (statement == null) return null; Try Try = new Try(); Try.TryBlock = new Block(this.Translate(statement.TryStatements)); Try.Catchers = this.Translate(statement.CatchClauses); if (statement.FinallyStatements != null && statement.FinallyStatements.Count > 0) Try.Finally = new Finally(new Block(this.Translate(statement.FinallyStatements))); return Try; }
public async Task TryExpressionAsync_AppliesMappingFunctionIfNoExceptionsAreThrown() { var result = await Try.ExpressionAsync(async() => await Task.FromResult(4 + 6)); Assert.Equal(10, result.Success); }
public override Statement VisitLock(Lock Lock){ if (Lock == null || Lock.Guard == null) return null; TypeNode lockGuardType = LockGuardType(Lock); Expression temp = new Local(lockGuardType); BlockScope tempScope = Lock.ScopeForTemporaryVariable; if (tempScope.CapturedForClosure){ Identifier id = Identifier.For("lockGuard:"+Lock.GetHashCode()); Field f = new Field(tempScope, null, FieldFlags.CompilerControlled, id, lockGuardType, null); temp = new MemberBinding(new ImplicitThis(), f); } if (Lock.Guard.Type is ITypeParameter && this.useGenerics) Lock.Guard = new BinaryExpression(Lock.Guard, new MemberBinding(null, Lock.Guard.Type), NodeType.Box); AssignmentStatement aStat = new AssignmentStatement(temp, Lock.Guard); aStat.SourceContext = Lock.Guard.SourceContext; ExpressionList arguments = new ExpressionList(1); arguments.Add(temp); MethodCall callEnter = new MethodCall(new MemberBinding(null, Runtime.MonitorEnter), arguments); callEnter.Type = SystemTypes.Void; ExpressionStatement enterMonitor = new ExpressionStatement(callEnter, aStat.SourceContext); MethodCall callExitMonitor = new MethodCall(new MemberBinding(null, Runtime.MonitorExit), arguments); callExitMonitor.Type = SystemTypes.Void; Block exitMonitor = new Block(new StatementList(1)); exitMonitor.Statements.Add(new ExpressionStatement(callExitMonitor, aStat.SourceContext)); Try tryBodyAndExitMonitor = new Try(Lock.Body, null, null, null, new Finally(exitMonitor)); StatementList statements = new StatementList(3); statements.Add(aStat); statements.Add(enterMonitor); statements.Add(tryBodyAndExitMonitor); return this.VisitBlock(new Block(statements)); }
/// <summary> /// Handle retry state of a session /// </summary> /// <param name="id"></param> /// <param name="wrapper"></param> /// <param name="ct"></param> /// <returns></returns> private async Task HandleRetryAsync(ConnectionIdentifier id, SessionWrapper wrapper, CancellationToken ct) { try { if (!wrapper._subscriptions.Any()) { // if the session is idle, just drop it immediately _logger.Information("Idle expired session '{id}' set to {disconnect} state from {state}", id, SessionState.Disconnect, wrapper.State); wrapper.State = SessionState.Disconnect; await HandleDisconnectAsync(id, wrapper).ConfigureAwait(false); return; } else { wrapper.IdleCount = 0; } wrapper.MissedKeepAlives++; _logger.Information("Session '{id}' missed {keepAlives} Keepalive(s) due to {status}, " + "waiting to reconnect...", id, wrapper.MissedKeepAlives, wrapper.ReportedStatus); if (!ct.IsCancellationRequested) { wrapper.Session.Reconnect(); wrapper.ReportedStatus = StatusCodes.Good; wrapper.State = SessionState.Running; wrapper.MissedKeepAlives = 0; // reactivate all subscriptions foreach (var subscription in wrapper._subscriptions.Values) { if (!ct.IsCancellationRequested) { await subscription.ActivateAsync(wrapper.Session).ConfigureAwait(false); } } } return; } catch (Exception e) { wrapper.NumberOfConnectRetries++; if (e is ServiceResultException sre) { switch (sre.StatusCode) { case StatusCodes.BadNotConnected: case StatusCodes.BadNoCommunication: case StatusCodes.BadSessionNotActivated: case StatusCodes.BadServerHalted: case StatusCodes.BadServerNotConnected: case StatusCodes.BadInvalidState: case StatusCodes.BadRequestTimeout: _logger.Warning("Failed to reconnect session '{id}' due to {exception}, " + "will retry later", id, e.Message); if (wrapper.MissedKeepAlives < wrapper.MaxKeepAlives) { // retry later return; } break; default: break; } } _logger.Warning("Failed to reconnect session '{id}' due to {exception}, " + " disposing and trying to create new", id, e.Message); } // cleanup the session if (wrapper.Session.SubscriptionCount > 0) { foreach (var subscription in wrapper.Session.Subscriptions) { Try.Op(() => subscription.DeleteItems()); Try.Op(() => subscription.Delete(true)); } Try.Op(() => wrapper.Session.RemoveSubscriptions(wrapper.Session.Subscriptions)); } Try.Op(wrapper.Session.Close); Try.Op(wrapper.Session.Dispose); wrapper.Session = null; wrapper.MissedKeepAlives = 0; wrapper.ReportedStatus = StatusCodes.Good; wrapper.State = SessionState.Failed; await HandleInitAsync(id, wrapper, ct).ConfigureAwait(false); }
public virtual Statement VisitTry(Try Try1, Try Try2) { if (Try1 == null) return null; if (Try2 == null) { Try1.TryBlock = this.VisitBlock(Try1.TryBlock, null); Try1.Catchers = this.VisitCatchList(Try1.Catchers, null); Try1.Filters = this.VisitFilterList(Try1.Filters, null); Try1.FaultHandlers = this.VisitFaultHandlerList(Try1.FaultHandlers, null); Try1.Finally = (Finally)this.VisitFinally(Try1.Finally, null); } else { Try1.TryBlock = this.VisitBlock(Try1.TryBlock, Try2.TryBlock); Try1.Catchers = this.VisitCatchList(Try1.Catchers, Try2.Catchers); Try1.Filters = this.VisitFilterList(Try1.Filters, Try2.Filters); Try1.FaultHandlers = this.VisitFaultHandlerList(Try1.FaultHandlers, Try2.FaultHandlers); Try1.Finally = (Finally)this.VisitFinally(Try1.Finally, Try2.Finally); } return Try1; }
/// <summary> /// Handles the initialization state of the session /// </summary> /// <param name="id"></param> /// <param name="wrapper"></param> /// <param name="ct"></param> /// <returns></returns> private async Task HandleInitAsync(ConnectionIdentifier id, SessionWrapper wrapper, CancellationToken ct) { try { if (wrapper.Session != null) { _logger.Warning("Session '{id}' still attached to wrapper in {state}", id, wrapper.State); Try.Op(wrapper.Session.Dispose); wrapper.Session = null; } if (!wrapper._subscriptions.Any()) { // The session is idle, stop initialization phase _logger.Information("Idle failed session '{id}' set to {disconnect} state from {state}", wrapper.Id, SessionState.Disconnect, wrapper.State); wrapper.State = SessionState.Disconnect; TriggerKeepAlive(); return; } _logger.Debug("Initializing session '{id}'...", id); var endpointUrlCandidates = id.Connection.Endpoint.Url.YieldReturn(); if (id.Connection.Endpoint.AlternativeUrls != null) { endpointUrlCandidates = endpointUrlCandidates.Concat( id.Connection.Endpoint.AlternativeUrls); } var exceptions = new List <Exception>(); foreach (var endpointUrl in endpointUrlCandidates) { try { if (!ct.IsCancellationRequested) { var session = await CreateSessionAsync(endpointUrl, id, wrapper).ConfigureAwait(false); if (session != null) { _logger.Information("Connected to '{endpointUrl}'", endpointUrl); session.Handle = wrapper; wrapper.Session = session; foreach (var subscription in wrapper._subscriptions.Values) { await subscription.EnableAsync(wrapper.Session).ConfigureAwait(false); } foreach (var subscription in wrapper._subscriptions.Values) { await subscription.ActivateAsync(wrapper.Session).ConfigureAwait(false); } wrapper.State = SessionState.Running; _logger.Debug("Session '{id}' successfully initialized", id); return; } } } catch (Exception ex) { _logger.Debug("Failed to connect to {endpointUrl}: {message} - try again...", endpointUrl, ex.Message); exceptions.Add(ex); } } throw new AggregateException(exceptions); } catch (ServiceResultException sre) { _logger.Warning("Failed to create session '{id}' due to {exception}", id, sre.StatusCode.ToString()); } catch (AggregateException aex) { _logger.Warning("Failed to create session '{id}' due to {exception}", id, aex.Message); } catch (Exception ex) { _logger.Error(ex, "Failed to create session '{id}'", id); } wrapper.NumberOfConnectRetries++; wrapper.State = SessionState.Failed; }
protected internal override void TraverseTry(Try @try) { Dispatch(@try); }
public async Task TestEdgeHubConnection() { var twinMessageConverter = new TwinMessageConverter(); var twinCollectionMessageConverter = new TwinCollectionMessageConverter(); var messageConverterProvider = new MessageConverterProvider( new Dictionary <Type, IMessageConverter>() { { typeof(Client.Message), new DeviceClientMessageConverter() }, { typeof(Twin), twinMessageConverter }, { typeof(TwinCollection), twinCollectionMessageConverter } }); var cloudConnectionProvider = new CloudConnectionProvider(messageConverterProvider, 1, new ClientProvider(), Option.None <UpstreamProtocol>()); var connectionManager = new ConnectionManager(cloudConnectionProvider); string iotHubConnectionString = await SecretsHelper.GetSecretFromConfigKey("iotHubConnStrKey"); Devices.IotHubConnectionStringBuilder iotHubConnectionStringBuilder = Devices.IotHubConnectionStringBuilder.Create(iotHubConnectionString); RegistryManager registryManager = RegistryManager.CreateFromConnectionString(iotHubConnectionString); await registryManager.OpenAsync(); (string edgeDeviceId, string deviceConnStr) = await RegistryManagerHelper.CreateDevice("testHubEdgeDevice1", iotHubConnectionString, registryManager, true, false); try { string iothubHostName = iotHubConnectionStringBuilder.HostName; var identityFactory = new ClientCredentialsFactory(iothubHostName); string edgeHubConnectionString = $"{deviceConnStr};ModuleId={EdgeHubModuleId}"; IClientCredentials edgeHubCredentials = identityFactory.GetWithConnectionString(edgeHubConnectionString); Assert.NotNull(edgeHubCredentials); Assert.NotNull(edgeHubCredentials.Identity); // Set Edge hub desired properties await this.SetDesiredProperties(registryManager, edgeDeviceId); var endpointFactory = new EndpointFactory(connectionManager, new RoutingMessageConverter(), edgeDeviceId); var routeFactory = new EdgeRouteFactory(endpointFactory); var dbStoreProvider = new InMemoryDbStoreProvider(); IStoreProvider storeProvider = new StoreProvider(dbStoreProvider); IEntityStore <string, TwinInfo> twinStore = storeProvider.GetEntityStore <string, TwinInfo>("twins"); var twinManager = new TwinManager(connectionManager, twinCollectionMessageConverter, twinMessageConverter, Option.Some(twinStore)); var routerConfig = new RouterConfig(Enumerable.Empty <Route>()); TimeSpan defaultTimeout = TimeSpan.FromSeconds(60); var endpointExecutorFactory = new SyncEndpointExecutorFactory(new EndpointExecutorConfig(defaultTimeout, new FixedInterval(0, TimeSpan.FromSeconds(1)), defaultTimeout, true)); Router router = await Router.CreateAsync(Guid.NewGuid().ToString(), iothubHostName, routerConfig, endpointExecutorFactory); IInvokeMethodHandler invokeMethodHandler = new InvokeMethodHandler(connectionManager); IEdgeHub edgeHub = new RoutingEdgeHub(router, new RoutingMessageConverter(), connectionManager, twinManager, edgeDeviceId, invokeMethodHandler); var versionInfo = new VersionInfo("v1", "b1", "c1"); // Create Edge Hub connection Try <ICloudProxy> edgeHubCloudProxy = await connectionManager.CreateCloudConnectionAsync(edgeHubCredentials); Assert.True(edgeHubCloudProxy.Success); EdgeHubConnection edgeHubConnection = await EdgeHubConnection.Create( edgeHubCredentials.Identity as IModuleIdentity, edgeHub, twinManager, connectionManager, edgeHubCloudProxy.Value, routeFactory, twinCollectionMessageConverter, twinMessageConverter, versionInfo ); await Task.Delay(TimeSpan.FromMinutes(1)); // Get and Validate EdgeHubConfig Option <EdgeHubConfig> edgeHubConfigOption = await edgeHubConnection.GetConfig(); Assert.True(edgeHubConfigOption.HasValue); EdgeHubConfig edgeHubConfig = edgeHubConfigOption.OrDefault(); Assert.Equal("1.0", edgeHubConfig.SchemaVersion); Assert.NotNull(edgeHubConfig.Routes); Assert.NotNull(edgeHubConfig.StoreAndForwardConfiguration); Assert.Equal(20, edgeHubConfig.StoreAndForwardConfiguration.TimeToLiveSecs); List <(string Name, string Value, Route Route)> routes = edgeHubConfig.Routes.ToList(); Assert.Equal(4, routes.Count); (string Name, string Value, Route Route)route1 = routes[0]; Assert.NotNull(route1); Assert.True(route1.Route.Endpoints.First().GetType() == typeof(CloudEndpoint)); Assert.Equal("route1", route1.Name); Assert.Equal("from /* INTO $upstream", route1.Value); (string Name, string Value, Route Route)route2 = routes[1]; Assert.NotNull(route2); Endpoint endpoint = route2.Route.Endpoints.First(); Assert.True(endpoint.GetType() == typeof(ModuleEndpoint)); Assert.Equal($"{edgeDeviceId}/module2/input1", endpoint.Id); Assert.Equal("route2", route2.Name); Assert.Equal("from /modules/module1 INTO BrokeredEndpoint(\"/modules/module2/inputs/input1\")", route2.Value); (string Name, string Value, Route Route)route3 = routes[2]; Assert.NotNull(route3); endpoint = route3.Route.Endpoints.First(); Assert.True(endpoint.GetType() == typeof(ModuleEndpoint)); Assert.Equal($"{edgeDeviceId}/module3/input1", endpoint.Id); Assert.Equal("route3", route3.Name); Assert.Equal("from /modules/module2 INTO BrokeredEndpoint(\"/modules/module3/inputs/input1\")", route3.Value); (string Name, string Value, Route Route)route4 = routes[3]; Assert.NotNull(route4); endpoint = route4.Route.Endpoints.First(); Assert.True(endpoint.GetType() == typeof(ModuleEndpoint)); Assert.Equal($"{edgeDeviceId}/module4/input1", endpoint.Id); Assert.Equal("route4", route4.Name); Assert.Equal("from /modules/module3 INTO BrokeredEndpoint(\"/modules/module4/inputs/input1\")", route4.Value); // Make sure reported properties were updated appropriately EdgeHubConnection.ReportedProperties reportedProperties = await this.GetReportedProperties(registryManager, edgeDeviceId); Assert.Equal(200, reportedProperties.LastDesiredStatus.Code); Assert.NotNull(reportedProperties.Clients); Assert.Equal(0, reportedProperties.Clients.Count); Assert.Equal("1.0", reportedProperties.SchemaVersion); Assert.Equal(versionInfo, reportedProperties.VersionInfo); // Simulate a module and a downstream device that connects to Edge Hub. string moduleId = "module1"; string sasToken = TokenHelper.CreateSasToken($"{iothubHostName}/devices/{edgeDeviceId}/modules/{moduleId}"); string moduleConnectionstring = $"HostName={iothubHostName};DeviceId={edgeDeviceId};ModuleId={moduleId};SharedAccessSignature={sasToken}"; IClientCredentials moduleClientCredentials = identityFactory.GetWithConnectionString(moduleConnectionstring); var moduleProxy = Mock.Of <IDeviceProxy>(d => d.IsActive); string downstreamDeviceId = "device1"; sasToken = TokenHelper.CreateSasToken($"{iothubHostName}/devices/{downstreamDeviceId}"); string downstreamDeviceConnectionstring = $"HostName={iothubHostName};DeviceId={downstreamDeviceId};SharedAccessSignature={sasToken}"; IClientCredentials downstreamDeviceCredentials = identityFactory.GetWithConnectionString(downstreamDeviceConnectionstring); var downstreamDeviceProxy = Mock.Of <IDeviceProxy>(d => d.IsActive); // Connect the module and downstream device and make sure the reported properties are updated as expected. await connectionManager.AddDeviceConnection(moduleClientCredentials.Identity, moduleProxy); await connectionManager.AddDeviceConnection(downstreamDeviceCredentials.Identity, downstreamDeviceProxy); string moduleIdKey = $"{edgeDeviceId}/{moduleId}"; await Task.Delay(TimeSpan.FromSeconds(10)); reportedProperties = await this.GetReportedProperties(registryManager, edgeDeviceId); Assert.Equal(2, reportedProperties.Clients.Count); Assert.Equal(ConnectionStatus.Connected, reportedProperties.Clients[moduleIdKey].Status); Assert.NotNull(reportedProperties.Clients[moduleIdKey].LastConnectedTimeUtc); Assert.Null(reportedProperties.Clients[moduleIdKey].LastDisconnectTimeUtc); Assert.Equal(ConnectionStatus.Connected, reportedProperties.Clients[downstreamDeviceId].Status); Assert.NotNull(reportedProperties.Clients[downstreamDeviceId].LastConnectedTimeUtc); Assert.Null(reportedProperties.Clients[downstreamDeviceId].LastDisconnectTimeUtc); Assert.Equal(200, reportedProperties.LastDesiredStatus.Code); Assert.Equal("1.0", reportedProperties.SchemaVersion); Assert.Equal(versionInfo, reportedProperties.VersionInfo); // Update desired propertied and make sure callback is called with valid values bool callbackCalled = false; Task ConfigUpdatedCallback(EdgeHubConfig updatedConfig) { Assert.NotNull(updatedConfig); Assert.NotNull(updatedConfig.StoreAndForwardConfiguration); Assert.NotNull(updatedConfig.Routes); routes = updatedConfig.Routes.ToList(); Assert.Equal(4, routes.Count); route1 = routes[0]; Assert.NotNull(route1); Assert.True(route1.Route.Endpoints.First().GetType() == typeof(CloudEndpoint)); Assert.Equal("route1", route1.Name); Assert.Equal("from /* INTO $upstream", route1.Value); route2 = routes[1]; Assert.NotNull(route2); endpoint = route2.Route.Endpoints.First(); Assert.True(endpoint.GetType() == typeof(ModuleEndpoint)); Assert.Equal($"{edgeDeviceId}/module2/input1", endpoint.Id); Assert.Equal("route2", route2.Name); Assert.Equal("from /modules/module1 INTO BrokeredEndpoint(\"/modules/module2/inputs/input1\")", route2.Value); route3 = routes[2]; Assert.NotNull(route3); endpoint = route3.Route.Endpoints.First(); Assert.True(endpoint.GetType() == typeof(ModuleEndpoint)); Assert.Equal($"{edgeDeviceId}/module5/input1", endpoint.Id); Assert.Equal("route4", route3.Name); Assert.Equal("from /modules/module3 INTO BrokeredEndpoint(\"/modules/module5/inputs/input1\")", route3.Value); route4 = routes[3]; Assert.NotNull(route4); endpoint = route4.Route.Endpoints.First(); Assert.True(endpoint.GetType() == typeof(ModuleEndpoint)); Assert.Equal($"{edgeDeviceId}/module6/input1", endpoint.Id); Assert.Equal("route5", route4.Name); Assert.Equal("from /modules/module5 INTO BrokeredEndpoint(\"/modules/module6/inputs/input1\")", route4.Value); callbackCalled = true; return(Task.CompletedTask); } edgeHubConnection.SetConfigUpdatedCallback(ConfigUpdatedCallback); await this.UpdateDesiredProperties(registryManager, edgeDeviceId); await Task.Delay(TimeSpan.FromSeconds(5)); Assert.True(callbackCalled); reportedProperties = await this.GetReportedProperties(registryManager, edgeDeviceId); Assert.Equal(200, reportedProperties.LastDesiredStatus.Code); Assert.NotNull(reportedProperties.Clients); Assert.Equal(2, reportedProperties.Clients.Count); Assert.Equal("1.0", reportedProperties.SchemaVersion); Assert.Equal(versionInfo, reportedProperties.VersionInfo); // Disconnect the downstream device and make sure the reported properties are updated as expected. await connectionManager.RemoveDeviceConnection(moduleIdKey); await connectionManager.RemoveDeviceConnection(downstreamDeviceId); await Task.Delay(TimeSpan.FromSeconds(10)); reportedProperties = await this.GetReportedProperties(registryManager, edgeDeviceId); Assert.Equal(1, reportedProperties.Clients.Count); Assert.True(reportedProperties.Clients.ContainsKey(moduleIdKey)); Assert.False(reportedProperties.Clients.ContainsKey(downstreamDeviceId)); Assert.Equal(ConnectionStatus.Disconnected, reportedProperties.Clients[moduleIdKey].Status); Assert.NotNull(reportedProperties.Clients[moduleIdKey].LastConnectedTimeUtc); Assert.NotNull(reportedProperties.Clients[moduleIdKey].LastDisconnectTimeUtc); Assert.Equal(200, reportedProperties.LastDesiredStatus.Code); Assert.Equal("1.0", reportedProperties.SchemaVersion); Assert.Equal(versionInfo, reportedProperties.VersionInfo); // If the edge hub restarts, clear out the connected devices in the reported properties. await EdgeHubConnection.Create(edgeHubCredentials.Identity as IModuleIdentity, edgeHub, twinManager, connectionManager, edgeHubCloudProxy.Value, routeFactory, twinCollectionMessageConverter, twinMessageConverter, versionInfo); await Task.Delay(TimeSpan.FromMinutes(1)); reportedProperties = await this.GetReportedProperties(registryManager, edgeDeviceId); Assert.Null(reportedProperties.Clients); Assert.Equal("1.0", reportedProperties.SchemaVersion); Assert.Equal(versionInfo, reportedProperties.VersionInfo); } finally { try { await RegistryManagerHelper.RemoveDevice(edgeDeviceId, registryManager); } catch (Exception) { // ignored } } }
public virtual Differences VisitTry(Try try1, Try try2){ Differences differences = new Differences(try1, try2); if (try1 == null || try2 == null){ if (try1 != try2) differences.NumberOfDifferences++; else differences.NumberOfSimilarities++; return differences; } Try changes = (Try)try2.Clone(); Try deletions = (Try)try2.Clone(); Try insertions = (Try)try2.Clone(); CatchList catchChanges, catchDeletions, catchInsertions; Differences diff = this.VisitCatchList(try1.Catchers, try2.Catchers, out catchChanges, out catchDeletions, out catchInsertions); if (diff == null){Debug.Assert(false); return differences;} changes.Catchers = catchChanges; deletions.Catchers = catchDeletions; insertions.Catchers = catchInsertions; differences.NumberOfDifferences += diff.NumberOfDifferences; differences.NumberOfSimilarities += diff.NumberOfSimilarities; FaultHandlerList faultChanges, faultDeletions, faultInsertions; diff = this.VisitFaultHandlerList(try1.FaultHandlers, try2.FaultHandlers, out faultChanges, out faultDeletions, out faultInsertions); if (diff == null){Debug.Assert(false); return differences;} changes.FaultHandlers = faultChanges; deletions.FaultHandlers = faultDeletions; insertions.FaultHandlers = faultInsertions; differences.NumberOfDifferences += diff.NumberOfDifferences; differences.NumberOfSimilarities += diff.NumberOfSimilarities; FilterList filterChanges, filterDeletions, filterInsertions; diff = this.VisitFilterList(try1.Filters, try2.Filters, out filterChanges, out filterDeletions, out filterInsertions); if (diff == null){Debug.Assert(false); return differences;} changes.Filters = filterChanges; deletions.Filters = filterDeletions; insertions.Filters = filterInsertions; differences.NumberOfDifferences += diff.NumberOfDifferences; differences.NumberOfSimilarities += diff.NumberOfSimilarities; diff = this.VisitFinally(try1.Finally, try2.Finally); if (diff == null){Debug.Assert(false); return differences;} changes.Finally = diff.Changes as Finally; deletions.Finally = diff.Deletions as Finally; insertions.Finally = diff.Insertions as Finally; Debug.Assert(diff.Changes == changes.Finally && diff.Deletions == deletions.Finally && diff.Insertions == insertions.Finally); differences.NumberOfDifferences += diff.NumberOfDifferences; differences.NumberOfSimilarities += diff.NumberOfSimilarities; diff = this.VisitBlock(try1.TryBlock, try2.TryBlock); if (diff == null){Debug.Assert(false); return differences;} changes.TryBlock = diff.Changes as Block; deletions.TryBlock = diff.Deletions as Block; insertions.TryBlock = diff.Insertions as Block; Debug.Assert(diff.Changes == changes.TryBlock && diff.Deletions == deletions.TryBlock && diff.Insertions == insertions.TryBlock); differences.NumberOfDifferences += diff.NumberOfDifferences; differences.NumberOfSimilarities += diff.NumberOfSimilarities; if (differences.NumberOfDifferences == 0){ differences.Changes = null; differences.Deletions = null; differences.Insertions = null; }else{ differences.Changes = changes; differences.Deletions = deletions; differences.Insertions = insertions; } return differences; }
/// <summary> /// Apply a Try value to a Try function of arity 2 /// </summary> /// <param name="self">Try function</param> /// <param name="arg">Try argument</param> /// <returns>Returns the result of applying the Try argument to the Try function: /// a Try function of arity 1</returns> public static Try <Func <T2, R> > Apply <T1, T2, R>(this Try <Func <T1, T2, R> > self, Try <T1> arg) => () => { var res = self.Try(); if (res.IsFaulted) { return(new TryResult <Func <T2, R> >(res.Exception)); } var val = arg.Try(); if (val.IsFaulted) { return(new TryResult <Func <T2, R> >(val.Exception)); } return(new TryResult <Func <T2, R> >(par(res.Value, val.Value))); };
private HostConnectResult FollowHostConnectProtocol() { State = HostConnectClientState.Connecting; StateChanged(this, new StateChangedEventArgs(null, State)); Uri masterServerUri = new Uri(ServiceWrapper.settings.MasterServerAddress, UriKind.Absolute); // Ensure the certificate exists before we connect, because it can take a moment to create and we don't want the connection to time out. IdentityVerification.EnsureClientCertificateExists(); tcpClient = new TcpClient(); KeepAliveSender keepAlive = null; try { #region Get Connected tcpClient.NoDelay = true; tcpClient.ReceiveTimeout = 30000; tcpClient.SendTimeout = 30000; tcpClient.Connect(masterServerUri.DnsSafeHost, masterServerUri.Port); stream = tcpClient.GetStream(); if (masterServerUri.Scheme == "https") { try { RemoteCertificateValidationCallback certCallback = null; if (!ServiceWrapper.settings.ValidateServerCertificate) { certCallback = (sender, certificate, chain, sslPolicyErrors) => true; } stream = new SslStream(stream, false, certCallback, null); ((SslStream)stream).AuthenticateAsClient(masterServerUri.DnsSafeHost, null, System.Security.Authentication.SslProtocols.Tls12, ServiceWrapper.settings.ValidateServerCertificate); } catch (ThreadAbortException) { throw; } catch (SocketException) { throw; } catch (Exception ex) { Logger.Debug(ex); return(new HostConnectResult(ProtocolErrors.HttpsNegotiationFailed)); } } { // Create HTTP request. StringBuilder sb = new StringBuilder(); sb.Append("POST ").Append(masterServerUri.PathAndQuery).Append("hostconnect HTTP/1.1\r\n"); sb.Append("Host: ").Append(masterServerUri.Host).Append("\r\n"); sb.Append("Content-Length: 0\r\n"); sb.Append("\r\n"); byte[] buf = ByteUtil.Utf8NoBOM.GetBytes(sb.ToString()); stream.Write(buf, 0, buf.Length); } #endregion #region Authentication Protocol // Auth 0) Receive ClientAuthentication command code. Command command = (Command)ByteUtil.ReadNBytes(stream, 1)[0]; if (command != Command.ClientAuthentication) { return(new HostConnectResult(ProtocolErrors.AuthResponseCommand)); } // Auth 1) Receive authentication challenge. This is an array of 32 random bytes which the Host Service must sign with its private key. byte[] authChallenge = ByteUtil.ReadNBytes(stream, 32); // Auth 2) Build authentication reply. // Auth 2.1) Authentication type HostAuthenticationType authType = HostAuthenticationType.PermanentHost; // Auth 2.2) Encode security key byte[] securityKey = ByteUtil.Utf8NoBOM.GetBytes("NOT REAL"); // TODO: Get the real security key from this exe's embedded settings. if (securityKey.Length > byte.MaxValue) { return(new HostConnectResult(ProtocolErrors.SecurityKeyLength)); } byte[] signature, publicKey; if (authType == HostAuthenticationType.PermanentHost) { // Auth 2.3) Create signature signature = IdentityVerification.SignAuthenticationChallenge(authChallenge); // Auth 2.4) Encode public key publicKey = ByteUtil.Utf8NoBOM.GetBytes(IdentityVerification.GetPublicKeyXML()); } else { signature = new byte[0]; publicKey = new byte[0]; } // Auth 2.5) Encode computer name byte[] computerName = ByteUtil.Utf8NoBOM.GetBytes(Environment.MachineName); // Auth 2.6) Encode host version string byte[] appVersion = ByteUtil.Utf8NoBOM.GetBytes(AppVersion.VersionNumber); // Auth 2.7) Encode OS version string byte[] osVersion = ByteUtil.Utf8NoBOM.GetBytes(OSInfo.GetOSVersionInfo()); // Build single buffer (not strictly necessary, but it helps us ensure we got the length calculated right). int calculatedLength = 1 + 1 + securityKey.Length + 2 + signature.Length + 2 + publicKey.Length + 1 + computerName.Length + 1 + appVersion.Length + 1 + osVersion.Length; if (calculatedLength > ushort.MaxValue) { return(new HostConnectResult(ProtocolErrors.AuthResponseTooLarge)); } using (MemoryDataStream mds = new MemoryDataStream(calculatedLength)) { mds.WriteByte((byte)authType); mds.WriteByte((byte)securityKey.Length); mds.Write(securityKey); mds.WriteUInt16((ushort)signature.Length); mds.Write(signature); mds.WriteUInt16((ushort)publicKey.Length); mds.Write(publicKey); mds.WriteByte((byte)computerName.Length); mds.Write(computerName); mds.WriteByte((byte)appVersion.Length); mds.Write(appVersion); mds.WriteByte((byte)osVersion.Length); mds.Write(osVersion); if (mds.Position != calculatedLength) { return(new HostConnectResult(ProtocolErrors.AuthResponseSizeError)); } mds.Seek(0, SeekOrigin.Begin); // Send authentication reply stream.WriteByte((byte)Command.ClientAuthentication); ByteUtil.WriteUInt16((ushort)calculatedLength, stream); mds.CopyTo(stream); } #endregion // This is the Host Service, which is responsible for sending a KeepAlive packet after 60 seconds of sending inactivity. The Master Server will do the same on a 120 second interval. tcpClient.ReceiveTimeout = 135000; // 120 seconds + 15 seconds for bad network conditions. tcpClient.SendTimeout = 75000; State = HostConnectClientState.Connected; StateChanged(this, new StateChangedEventArgs(null, State)); // Send KeepAlive packets every 60 seconds if no other packets have been sent. keepAlive = new KeepAliveSender("KeepAlive", 60000, SendKeepalive, (ignoredArg) => Disconnect()); CommandLoop(tcpClient, stream); } finally { // Make local copies of these references so they can't become null after the null check. KeepAliveSender k = keepAlive; if (k != null) { Try.Catch_RethrowThreadAbort(keepAlive.Stop); } TcpClient c = tcpClient; if (c != null) { Try.Catch_RethrowThreadAbort(c.Close); } } return(new HostConnectResult()); }
/// <summary> /// Apply Try values to a Try function of arity 2 /// </summary> /// <param name="self">Try function</param> /// <param name="arg1">Try argument</param> /// <param name="arg2">Try argument</param> /// <returns>Returns the result of applying the Try arguments to the Try function</returns> public static Try <R> Apply <T1, T2, R>(this Try <Func <T1, T2, R> > self, Try <T1> arg1, Try <T2> arg2) => () => { var res = self.Try(); if (res.IsFaulted) { return(new TryResult <R>(res.Exception)); } var val1 = arg1.Try(); if (val1.IsFaulted) { return(new TryResult <R>(val1.Exception)); } var val2 = arg2.Try(); if (val2.IsFaulted) { return(new TryResult <R>(val2.Exception)); } return(new TryResult <R>(res.Value(val1.Value, val2.Value))); };
public async Task UpdateDeviceConnectionTest() { int receivedConnectedStatusCount = 0; ConnectionStatusChangesHandler connectionStatusChangesHandler = null; string hostname = "dummy.azure-devices.net"; string deviceId = "device1"; ITokenCredentials GetClientCredentials(TimeSpan tokenExpiryDuration) { string token = TokenHelper.CreateSasToken(hostname, DateTime.UtcNow.AddSeconds(tokenExpiryDuration.TotalSeconds)); var identity = new DeviceIdentity(hostname, deviceId); return(new TokenCredentials(identity, token, string.Empty, false)); } IDeviceProxy GetMockDeviceProxy() { var deviceProxyMock1 = new Mock <IDeviceProxy>(); deviceProxyMock1.SetupGet(dp => dp.IsActive).Returns(true); deviceProxyMock1.Setup(dp => dp.CloseAsync(It.IsAny <Exception>())) .Callback(() => deviceProxyMock1.SetupGet(dp => dp.IsActive).Returns(false)) .Returns(Task.CompletedTask); return(deviceProxyMock1.Object); } IClient GetMockedDeviceClient() { var deviceClient = new Mock <IClient>(); deviceClient.SetupGet(dc => dc.IsActive).Returns(true); deviceClient.Setup(dc => dc.CloseAsync()) .Callback(() => deviceClient.SetupGet(dc => dc.IsActive).Returns(false)) .Returns(Task.FromResult(true)); deviceClient.Setup(dc => dc.SetConnectionStatusChangedHandler(It.IsAny <ConnectionStatusChangesHandler>())) .Callback <ConnectionStatusChangesHandler>(c => connectionStatusChangesHandler = c); deviceClient.Setup(dc => dc.OpenAsync()) .Callback( () => { int currentCount = receivedConnectedStatusCount; Assert.NotNull(connectionStatusChangesHandler); connectionStatusChangesHandler.Invoke(ConnectionStatus.Connected, ConnectionStatusChangeReason.Connection_Ok); Assert.Equal(receivedConnectedStatusCount, currentCount); }) .Returns(Task.CompletedTask); return(deviceClient.Object); } ITokenProvider tokenProvider = null; var deviceClientProvider = new Mock <IClientProvider>(); deviceClientProvider.Setup(dc => dc.Create(It.IsAny <IIdentity>(), It.IsAny <ITokenProvider>(), It.IsAny <ITransportSettings[]>())) .Callback <IIdentity, ITokenProvider, ITransportSettings[]>((s, a, t) => tokenProvider = a) .Returns(() => GetMockedDeviceClient()); var messageConverterProvider = Mock.Of <IMessageConverterProvider>(); var credentialsCache = Mock.Of <ICredentialsCache>(); ICloudConnectionProvider cloudConnectionProvider = new CloudConnectionProvider( messageConverterProvider, 1, deviceClientProvider.Object, Option.None <UpstreamProtocol>(), TokenProvider, DeviceScopeIdentitiesCache, credentialsCache, Mock.Of <IIdentity>(i => i.Id == $"{deviceId}/$edgeHub"), TimeSpan.FromMinutes(60), true, TimeSpan.FromSeconds(20)); cloudConnectionProvider.BindEdgeHub(Mock.Of <IEdgeHub>()); IConnectionManager connectionManager = new ConnectionManager(cloudConnectionProvider, Mock.Of <ICredentialsCache>(), new IdentityProvider(hostname)); ITokenCredentials clientCredentials1 = GetClientCredentials(TimeSpan.FromSeconds(10)); Try <ICloudProxy> cloudProxyTry1 = await connectionManager.CreateCloudConnectionAsync(clientCredentials1); Assert.True(cloudProxyTry1.Success); IDeviceProxy deviceProxy1 = GetMockDeviceProxy(); await connectionManager.AddDeviceConnection(clientCredentials1.Identity, deviceProxy1); await Task.Delay(TimeSpan.FromSeconds(10)); Assert.NotNull(tokenProvider); Task <string> tokenGetter = tokenProvider.GetTokenAsync(Option.None <TimeSpan>()); Assert.False(tokenGetter.IsCompleted); ITokenCredentials clientCredentials2 = GetClientCredentials(TimeSpan.FromMinutes(2)); Try <ICloudProxy> cloudProxyTry2 = await connectionManager.CreateCloudConnectionAsync(clientCredentials2); Assert.True(cloudProxyTry2.Success); IDeviceProxy deviceProxy2 = GetMockDeviceProxy(); await connectionManager.AddDeviceConnection(clientCredentials2.Identity, deviceProxy2); await Task.Delay(TimeSpan.FromSeconds(3)); Assert.False(tokenGetter.IsCompleted); ITokenCredentials clientCredentials3 = GetClientCredentials(TimeSpan.FromMinutes(10)); Try <ICloudProxy> cloudProxyTry3 = await connectionManager.CreateCloudConnectionAsync(clientCredentials3); Assert.True(cloudProxyTry3.Success); IDeviceProxy deviceProxy3 = GetMockDeviceProxy(); await connectionManager.AddDeviceConnection(clientCredentials3.Identity, deviceProxy3); await Task.Delay(TimeSpan.FromSeconds(23)); Assert.True(tokenGetter.IsCompleted); Assert.Equal(tokenGetter.Result, clientCredentials3.Token); }
internal TrySuccContext(Try <T> value, Func <T, R> succHandler) { this.value = value; this.succHandler = succHandler; }
/// <summary> /// Creates the authorization value from the token. /// </summary> /// <param name="model"></param> /// <returns></returns> public static string ToAuthorizationValue(this IdentityTokenModel model) { return(Try.Op(() => Encoding.UTF8.GetBytes( ConnectionString.CreateFromAccessToken(model).ToString()) .ToBase64String())); }
public static Unit Iter <T>(this Try <T> self, Action <T> action) => self.IfSucc(action);
protected internal override void TraverseTry(Try @try) { _writer.WriteLine("try"); Traverse(@try.Body); @try.Clauses.ForEach(Traverse); }
/// <summary> /// Partial application map /// </summary> /// <remarks>TODO: Better documentation of this function</remarks> public static Try <Func <T2, Func <T3, R> > > Map <T1, T2, T3, R>(this Try <T1> self, Func <T1, T2, T3, R> func) => self.Map(curry(func));
protected internal override void TraverseTry(Try @try) { Traverse(@try.Body); @try.Clauses.ForEach(Traverse); Types.Add(@try, null); }
public static Try <T> Where <T>(this Try <T> self, Func <T, bool> pred) => self.Filter(pred);
public override Statement VisitTry(Try Try){ if (Try == null) return null; if (this.currentMethod == null) return null; if (this.currentMethod.ExceptionHandlers == null) this.currentMethod.ExceptionHandlers = new ExceptionHandlerList(); this.continueTargets.Add(Try); this.exitTargets.Add(Try); int savedIteratorEntryPointsCount = this.iteratorEntryPoints == null ? 0 : this.iteratorEntryPoints.Count; this.currentTryStatements.Push(Try); Block savedCurrentExceptionBlock = this.currentExceptionBlock; this.currentExceptionBlock = Try.TryBlock; Block result = this.VisitBlock(Try.TryBlock); if (result == null) return null; if (result.Statements == null) result.Statements = new StatementList(1); if (this.iteratorEntryPoints != null && this.iteratorEntryPoints.Count > savedIteratorEntryPointsCount) return result; Block blockAfterHandlers = new Block(null); result.Statements.Add(new Branch(null, blockAfterHandlers, false, false, true)); Block blockAfterTryBody = new Block(null); result.Statements.Add(blockAfterTryBody); this.AddExceptionHandlers(Try, result, blockAfterTryBody, blockAfterHandlers); result.Statements.Add(blockAfterHandlers); this.continueTargets.Count--; this.exitTargets.Count--; this.currentTryStatements.Pop(); this.currentExceptionBlock = savedCurrentExceptionBlock; return result; }
internal TrySuccUnitContext(Try <T> value, Action <T> succHandler) { this.value = value; this.succHandler = succHandler; }
protected internal override Node TransformTry(Try @try) { return Dispatch(@try); }
public static Lst <Either <Exception, T> > ToList <T>(this Try <T> self) => toList(self.AsEnumerable());
public override Statement VisitTry(Try Try) { if (Try == null) return null; return base.VisitTry((Try)Try.Clone()); }
public static Either <Exception, T>[] ToArray <T>(this Try <T> self) => toArray(self.AsEnumerable());
public virtual void VisitTry(Try Try) { if (Try == null) return; this.VisitBlock(Try.TryBlock); this.VisitCatchList(Try.Catchers); this.VisitFilterList(Try.Filters); this.VisitFaultHandlerList(Try.FaultHandlers); this.VisitFinally(Try.Finally); }
public static TrySuccContext <T, R> Succ <T, R>(this Try <T> self, Func <T, R> succHandler) => new TrySuccContext <T, R>(self, succHandler);
public override Statement VisitTry(Try Try) { if (Try == null) return null; bool savedInsideTryBlock = this.insideTryBlock; this.insideTryBlock = true; // when visiting the try block, use a newly computed set of allowed exceptions. // the set is whatever the current set is augmented with the set of exceptions listed in the // catch clauses TypeNodeList newAllowedExceptions = this.allowedExceptions.Clone(); CatchList cl = Try.Catchers; if (cl != null) { for (int i = 0, n = cl.Count; i < n; i++) { Catch c = cl[i]; if (c == null) continue; // BUGBUG? In both cases, should we just automatically add to the list or first see if // some exception already in the list is a supertype of the one that is currently added? if (c.Type == null) // then this was "catch { }" meaning catch everything, so all checked exceptions will be caught newAllowedExceptions.Add(SystemTypes.ICheckedException); else if (this.GetTypeView(c.Type).IsAssignableTo(SystemTypes.ICheckedException)) newAllowedExceptions.Add(c.Type); } } TypeNodeList saveAllowedExceptions = this.allowedExceptions; this.allowedExceptions = newAllowedExceptions; /* can't call the base visitor because after visiting the try block, the allowedExceptions * need to be restored before visiting the catchers. * So this is a copy of the body of StandardVisitor.VisitTry. If that ever changes, this * will need to be changed too! Statement result = base.VisitTry(Try); */ Try.TryBlock = this.VisitBlock(Try.TryBlock); /* restore the list of allowed exceptions */ this.allowedExceptions = saveAllowedExceptions; Try.Catchers = this.VisitCatchList(Try.Catchers); Try.Filters = this.VisitFilterList(Try.Filters); Try.FaultHandlers = this.VisitFaultHandlerList(Try.FaultHandlers); Try.Finally = (Finally)this.VisitFinally(Try.Finally); this.insideTryBlock = savedInsideTryBlock; CatchList catchers = Try.Catchers; if (catchers != null) { for (int i = 0, n = catchers.Count; i < n; i++) { Catch c = catchers[i]; if (c == null) continue; if (c.Type == null) continue; for (int j = 0; j < i; j++) { Catch c0 = catchers[j]; if (c0 == null || c0.Type == null) continue; if (this.GetTypeView(c.Type).IsAssignableTo(c0.Type)) this.HandleError(c.TypeExpression, Error.UnreachableCatch, this.GetTypeName(c0.Type)); } } } return Try; }
public static TrySuccUnitContext <T> Succ <T>(this Try <T> self, Action <T> succHandler) => new TrySuccUnitContext <T>(self, succHandler);
public virtual Statement VisitTry(Try Try){ if (Try == null) return null; Try.TryBlock = this.VisitBlock(Try.TryBlock); Try.Catchers = this.VisitCatchList(Try.Catchers); Try.Filters = this.VisitFilterList(Try.Filters); Try.FaultHandlers = this.VisitFaultHandlerList(Try.FaultHandlers); Try.Finally = (Finally)this.VisitFinally(Try.Finally); return Try; }
public static int Sum(this Try <int> self) => self.Try().Value;
public virtual Statement VisitTry(Try Try, Try changes, Try deletions, Try insertions){ this.UpdateSourceContext(Try, changes); if (Try == null) return changes; if (changes != null){ if (deletions == null || insertions == null) Debug.Assert(false); else{ } }else if (deletions != null) return null; return Try; }
protected internal virtual Node TransformTry(Try @try) { return @try.AcceptTransformer(this, true); }