protected MathOperator(MathToken token, int precedence, ICalculatorProxy proxy, CalculatorProxy.SingleBinaryOperation operation) : base(token.Token, token.Index) { this.Precedence = precedence; this.proxy = proxy; this.operation = operation; }
public static void Main() { // Bond has an abstraction for network protocols called a Transport. Epoxy is a custom protocol that is // lightweight and built into Bond.Comm. If it doesn't meet your needs, you can write your own Transport. var transport = new EpoxyTransportBuilder().Construct(); var connection = transport.ConnectToAsync(new IPEndPoint(IPAddress.Loopback, EpoxyTransport.DefaultPort)).Result; // For each service, Bond will generate a proxy with methods corresponding to the service methods you defined. var proxy = new CalculatorProxy <EpoxyConnection>(connection); var addArgs = new BinaryOpArgs { left = 2, right = 2 }; // The result of a Bond call is a IMessage, which is either a payload or an error. // Display() shows how to handle both cases. var addResult = proxy.AddAsync(addArgs).Result; Display("Add", addArgs, addResult); var divArgs = new BinaryOpArgs { left = 1, right = 0 }; var divResult = proxy.DivideAsync(divArgs).Result; Display("Divide", divArgs, divResult); Console.ReadLine(); }
public async Task MethodCall() { await DefaultSetup(new CalculatorService(), 1); const int first = 91; const int second = 23; int addResult = first + second; int subResult = first - second; var calculatorProxy = new CalculatorProxy <SimpleInMemConnection>(connections[0]); var input = new PairedInput { First = first, Second = second }; var request = new Message <PairedInput>(input); IMessage <Output> addResponse = await calculatorProxy.AddAsync(request, System.Threading.CancellationToken.None); IMessage <Output> subResponse = await calculatorProxy.SubtractAsync(request, System.Threading.CancellationToken.None); Output addOutput = addResponse.Payload.Deserialize(); Output subOutput = subResponse.Payload.Deserialize(); Assert.AreEqual(addResult, addOutput.Result); Assert.AreEqual(subResult, subOutput.Result); }
static void Main(string[] args) { CalculatorProxy calc = new CalculatorProxy(); Console.WriteLine(calc.Add(5, 6)); Console.ReadKey(); }
public async Task MethodCall_ReqRsp_WithStatefulLayers() { var layerProvider = new TestLayerProvider_StatefulAppend("Layer"); var layerStackProvider = new LayerStackProvider <Dummy>(layerProvider); transportBuilder.SetLayerStackProvider(layerStackProvider); await DefaultSetup(new CalculatorService(), 1); layerProvider.Layers.Clear(); var calculatorProxy = new CalculatorProxy <SimpleInMemConnection>(connections[0]); var request = new Message <PairedInput>(new PairedInput { First = 1, Second = 2 }); IMessage <Output> response = await calculatorProxy.AddAsync(request, CancellationToken.None); Assert.IsFalse(response.IsError); Assert.AreEqual(2, layerProvider.Layers.Count); Assert.AreEqual("Layer0SendLayer0Receive", layerProvider.Layers[0].State); Assert.AreEqual("Layer1ReceiveLayer1Send", layerProvider.Layers[1].State); request = new Message <PairedInput>(new PairedInput { First = 1, Second = 2 }); response = await calculatorProxy.AddAsync(request, CancellationToken.None); Assert.IsFalse(response.IsError); Assert.AreEqual(4, layerProvider.Layers.Count); Assert.AreEqual("Layer2SendLayer2Receive", layerProvider.Layers[2].State); Assert.AreEqual("Layer3ReceiveLayer3Send", layerProvider.Layers[3].State); }
public async Task MultipleClientConnectionsEventCalls() { await DefaultSetup(new CalculatorService(), 10); Task[] connectionTasks = new Task[connections.Length]; const int taskCount = 25; for (int connectionIndex = 0; connectionIndex < connections.Length; connectionIndex++) { SimpleInMemConnection conn = connections[connectionIndex]; connectionTasks[connectionIndex] = Task.Run(() => { Task[] tasks = new Task[taskCount]; for (int taskIndex = 0; taskIndex < taskCount; taskIndex++) { tasks[taskIndex] = Task.Run(() => { var calculatorProxy = new CalculatorProxy <SimpleInMemConnection>(conn); calculatorProxy.IncrementCountAsync(); }); } Task.WaitAll(tasks); }); } Task.WaitAll(connectionTasks); int totalWaitTime = 0; const int maxWait = 5000; // Intentionally avoiding exponential back-off due to simple nature of this test const int incrementalWait = 500; while (totalWaitTime < maxWait) { await Task.Delay(incrementalWait); totalWaitTime += incrementalWait; try { Assert.AreEqual(CalculatorService.Count, connections.Length * taskCount); break; } catch (AssertionException) { // The implementation of SimpleInMem can guarantee delivery of events just be virtue of staying with in the process boundary. // SimpleInMem event failing after 5 seconds needs to raise alarm and investigation. if (totalWaitTime > maxWait) { throw; } } } Console.WriteLine($"{nameof(MultipleClientConnectionsEventCalls)} - Count: {CalculatorService.Count}"); }
public void SetUp() { _lexer = new MathLexer(new ExpressionFixer()); _calculator = new Calculator(); _calcProxy = new CalcProxy(new Validator(-100, 100), _calculator); _precedence = new Precedence(); _resolver = new Resolver(_lexer, _calcProxy, _precedence); _parser = new MathParser(_lexer, _resolver); }
public void SubstractIntegracion() { var validator = new LimitsValidator(-100, 100); var calculator = new Calculator(); var proxy = new CalculatorProxy(validator); var result = proxy.BinaryOperation(calculator.Substract, 5, 3); Assert.AreEqual(2, result); }
/// <summary> /// Runs this instance. /// </summary> private void Run() { Console.WriteLine("Run a ServiceHost via programmatic configuration..."); using (ServiceHost serviceHost = new ServiceHost(typeof(Calculator), new Uri("soap.amqp:///"))) { var serviceEndpoint = serviceHost.AddServiceEndpoint( typeof(ICalculator), new RabbitMQBinding( "localhost", 5672, "guest", "guest", "/", 8192, Protocols.AMQP_0_9_1) { OneWayOnly = false }, "Calculator"); ////serviceEndpoint.Behaviors.Add(new RabbitMqEndpointBehavior(null)); Console.WriteLine("Num. behaviors: {0}", serviceEndpoint.Behaviors.Count); serviceHost.Open(); Console.WriteLine("The service is opened, press ENTER to follow next instructions..."); ////Console.ReadLine(); var proxyBinding = new RabbitMQBinding( "localhost", 5672, "guest", "guest", "/", 8192, Protocols.AMQP_0_9_1) { OneWayOnly = false } ; var endpoint = new EndpointAddress("soap.amqp:///Calculator"); using (var proxy = new CalculatorProxy(proxyBinding, endpoint)) { ////proxy.Endpoint.Behaviors.Add(new RabbitMqEndpointBehavior(null)); var res = proxy.Add(4, 5); Console.WriteLine(res); Console.WriteLine("Type name: {0}", proxy.PrintTypeName(new Person())); Console.WriteLine("Type name: {0}", proxy.PrintTypeName(new Student())); } Console.ReadLine(); } }
public void SetUp() { _mathRegex = new MathRegex(); _fixer = new ExpressionFixer(); _lexer = new MathLexer(_fixer); _calculator = new Calculator(); _calcProxy = new CalcProxy(new Validator(-100, 100), _calculator); _resolver = new Resolver(_lexer, new Precedence()); _parser = new MathParser(_lexer, _resolver); }
public void SetUp() { var expressionValidator = new MathRegex(); var expressionFixer = new ExpressionFixer(expressionValidator); this.lexer = new MathLexer(expressionValidator, expressionFixer); var limitsValidator = new LimitsValidator(-100, 100); var proxy = new CalculatorProxy(limitsValidator); var calculator = new Calculator(); var operatorFactory = new OperatorFactory(proxy, calculator); this.parser = new MathParser(this.lexer, operatorFactory); }
public async void EventCall() { await DefaultSetup(new CalculatorService(), 1); var calculatorProxy = new CalculatorProxy <SimpleInMemConnection>(connections[0]); calculatorProxy.ClearAsync(); bool wasSignaled = CalculatorService.ClearCalledEvent.WaitOne(30000); Assert.IsTrue(wasSignaled, "Timed out waiting for event"); }
public async void TestWithServerAndClientConnections() { await DefaultSetup(new CalculatorService(), 1); IEnumerator <Guid> pairIds = listener.GetPairIds().GetEnumerator(); pairIds.MoveNext(); Guid firstPair = pairIds.Current; SimpleInMemConnection serverConnection = listener.GetConnection(firstPair, ConnectionType.Server); SimpleInMemConnection clientConnection = listener.GetConnection(firstPair, ConnectionType.Client); const int first = 91; const int second = 23; int addResult = first + second; int subResult = first - second; var serverProxy = new CalculatorProxy <SimpleInMemConnection>(serverConnection); var clientProxy = new CalculatorProxy <SimpleInMemConnection>(clientConnection); var input = new PairedInput { First = first, Second = second }; var request = new Message <PairedInput>(input); IMessage <Output> addResponse = await clientProxy.AddAsync(request, System.Threading.CancellationToken.None); IMessage <Output> subResponse = await clientProxy.SubtractAsync(request, System.Threading.CancellationToken.None); Assert.IsFalse(addResponse.IsError); Assert.IsFalse(subResponse.IsError); Output addOutput = addResponse.Payload.Deserialize(); Output subOutput = subResponse.Payload.Deserialize(); Assert.AreEqual(addResult, addOutput.Result); Assert.AreEqual(subResult, subOutput.Result); addResponse = await serverProxy.AddAsync(request, System.Threading.CancellationToken.None); subResponse = await serverProxy.SubtractAsync(request, System.Threading.CancellationToken.None); Assert.IsTrue(addResponse.IsError); Assert.IsTrue(subResponse.IsError); Error addError = addResponse.Error.Deserialize(); Error subError = subResponse.Error.Deserialize(); Assert.AreEqual((int)ErrorCode.METHOD_NOT_FOUND, (int)addError.error_code); Assert.AreEqual("Got request for unknown method [unittest.simpleinmem.Calculator.Add].", addError.message); Assert.AreEqual((int)ErrorCode.METHOD_NOT_FOUND, (int)subError.error_code); Assert.AreEqual("Got request for unknown method [unittest.simpleinmem.Calculator.Subtract].", subError.message); }
public void CoordinateValidation() { const int n1 = 10; const int n2 = -20; const int result = 1000; var validatorMock = new Mock<ILimitsValidator>(); var calculatorMock = new Mock<ICalculator>(); calculatorMock.Setup(x => x.Add(n1,n2)).Returns(result); var calcProxy = new CalculatorProxy(validatorMock.Object); calcProxy.BinaryOperation(calculatorMock.Object.Add, n1, n2); validatorMock.Verify(x => x.ValidateArgs(n1, n2)); validatorMock.Verify(x => x.ValidateResult(result)); }
public void CoordinateValidation() { const int n1 = 10; const int n2 = -20; const int result = 1000; var validatorMock = new Mock <ILimitsValidator>(); var calculatorMock = new Mock <ICalculator>(); calculatorMock.Setup(x => x.Add(n1, n2)).Returns(result); var calcProxy = new CalculatorProxy(validatorMock.Object); calcProxy.BinaryOperation(calculatorMock.Object.Add, n1, n2); validatorMock.Verify(x => x.ValidateArgs(n1, n2)); validatorMock.Verify(x => x.ValidateResult(result)); }
public async void TestWithServerAndClientConnections() { await DefaultSetup(new CalculatorService(), 1); IEnumerator<Guid> pairIds = listener.GetPairIds().GetEnumerator(); pairIds.MoveNext(); Guid firstPair = pairIds.Current; SimpleInMemConnection serverConnection = listener.GetConnection(firstPair, ConnectionType.Server); SimpleInMemConnection clientConnection = listener.GetConnection(firstPair, ConnectionType.Client); const int first = 91; const int second = 23; int addResult = first + second; int subResult = first - second; var serverProxy = new CalculatorProxy<SimpleInMemConnection>(serverConnection); var clientProxy = new CalculatorProxy<SimpleInMemConnection>(clientConnection); var input = new PairedInput { First = first, Second = second }; var request = new Message<PairedInput>(input); IMessage<Output> addResponse = await clientProxy.AddAsync(request, System.Threading.CancellationToken.None); IMessage<Output> subResponse = await clientProxy.SubtractAsync(request, System.Threading.CancellationToken.None); Assert.IsFalse(addResponse.IsError); Assert.IsFalse(subResponse.IsError); Output addOutput = addResponse.Payload.Deserialize(); Output subOutput = subResponse.Payload.Deserialize(); Assert.AreEqual(addResult, addOutput.Result); Assert.AreEqual(subResult, subOutput.Result); addResponse = await serverProxy.AddAsync(request, System.Threading.CancellationToken.None); subResponse = await serverProxy.SubtractAsync(request, System.Threading.CancellationToken.None); Assert.IsTrue(addResponse.IsError); Assert.IsTrue(subResponse.IsError); Error addError = addResponse.Error.Deserialize(); Error subError = subResponse.Error.Deserialize(); Assert.AreEqual((int)ErrorCode.MethodNotFound, (int)addError.error_code); Assert.AreEqual("Got request for unknown method [unittest.simpleinmem.Calculator.Add].", addError.message); Assert.AreEqual((int)ErrorCode.MethodNotFound, (int)subError.error_code); Assert.AreEqual("Got request for unknown method [unittest.simpleinmem.Calculator.Subtract].", subError.message); }
public async Task MethodCall_WithServiceError() { await DefaultSetup(new CalculatorService(), 1); const int first = 91; const int second = 23; var calculatorProxy = new CalculatorProxy <SimpleInMemConnection>(connections[0]); var input = new PairedInput { First = first, Second = second }; var request = new Message <PairedInput>(input); IMessage <Output> multiplyResponse = await calculatorProxy.MultiplyAsync(request, System.Threading.CancellationToken.None); Assert.IsTrue(multiplyResponse.IsError); InternalServerError error = multiplyResponse.Error.Deserialize <InternalServerError>(); Assert.AreEqual((int)ErrorCode.INTERNAL_SERVER_ERROR, error.error_code); Assert.That(error.message, Is.StringContaining(Errors.InternalErrorMessage)); }
public async Task MethodCall_WithLayerStack() { var testList = new List <string>(); var layer1 = new TestLayer_Append("foo", testList); var layer2 = new TestLayer_Append("bar", testList); transportBuilder.SetLayerStackProvider(new LayerStackProvider <Dummy>(layer1, layer2)); await DefaultSetup(new CalculatorService(), 1); const int first = 91; const int second = 23; int addResult = first + second; var calculatorProxy = new CalculatorProxy <SimpleInMemConnection>(connections[0]); var input = new PairedInput { First = first, Second = second }; var request = new Message <PairedInput>(input); IMessage <Output> addResponse = await calculatorProxy.AddAsync(request, System.Threading.CancellationToken.None); Output addOutput = addResponse.Payload.Deserialize(); Assert.AreEqual(addResult, addOutput.Result); Assert.AreEqual(8, testList.Count); Assert.AreEqual(layer1.value, testList[0]); Assert.AreEqual(testList[0] + layer2.value, testList[1]); Assert.AreEqual(testList[1] + layer2.value, testList[2]); Assert.AreEqual(testList[2] + layer1.value, testList[3]); Assert.AreEqual(layer1.value, testList[4]); Assert.AreEqual(testList[4] + layer2.value, testList[5]); Assert.AreEqual(testList[5] + layer2.value, testList[6]); Assert.AreEqual(testList[6] + layer1.value, testList[7]); }
public async Task MethodCall() { await DefaultSetup(new CalculatorService(), 1); const int first = 91; const int second = 23; int addResult = first + second; int subResult = first - second; var calculatorProxy = new CalculatorProxy<SimpleInMemConnection>(connections[0]); var input = new PairedInput { First = first, Second = second }; var request = new Message<PairedInput>(input); IMessage<Output> addResponse = await calculatorProxy.AddAsync(request, System.Threading.CancellationToken.None); IMessage<Output> subResponse = await calculatorProxy.SubtractAsync(request, System.Threading.CancellationToken.None); Output addOutput = addResponse.Payload.Deserialize(); Output subOutput = subResponse.Payload.Deserialize(); Assert.AreEqual(addResult, addOutput.Result); Assert.AreEqual(subResult, subOutput.Result); }
public async Task MultipleClientConnectionsMethodCalls() { Stopwatch sw = Stopwatch.StartNew(); await DefaultSetup(new CalculatorService(), 10); Task[] connectionTasks = new Task[connections.Length]; for (int connectionIndex = 0; connectionIndex < connections.Length; connectionIndex++) { SimpleInMemConnection conn = connections[connectionIndex]; connectionTasks[connectionIndex] = Task.Run(() => { int taskCount = 25; Task[] tasks = new Task[taskCount]; for (int taskIndex = 0; taskIndex < taskCount; taskIndex++) { tasks[taskIndex] = Task.Run(async() => { Random rand = new Random(DateTime.UtcNow.Millisecond); int first = rand.Next(1, 100); int second = rand.Next(1, 50); int expectedAddResult = first + second; int expectedSubResult = first - second; var addTraceId = Guid.NewGuid().ToString(); var subTraceId = Guid.NewGuid().ToString(); var calculatorProxy = new CalculatorProxy <SimpleInMemConnection>(conn); var addInput = new PairedInput { First = first, Second = second, TraceId = addTraceId }; var subInput = new PairedInput { First = first, Second = second, TraceId = subTraceId }; Message <PairedInput> addRequest = new Message <PairedInput>(addInput); Message <PairedInput> subRequest = new Message <PairedInput>(subInput); IMessage <Output> addResponse = await calculatorProxy.AddAsync(addRequest, System.Threading.CancellationToken.None); IMessage <Output> subResponse = await calculatorProxy.SubtractAsync(subRequest, System.Threading.CancellationToken.None); Output addOutput = addResponse.Payload.Deserialize(); Output subOutput = subResponse.Payload.Deserialize(); Assert.AreEqual(expectedAddResult, addOutput.Result); Assert.AreEqual(addInput.TraceId, addOutput.TraceId); Assert.AreEqual(expectedSubResult, subOutput.Result); Assert.AreEqual(subInput.TraceId, subOutput.TraceId); }); } Task.WaitAll(tasks); }); } Task.WaitAll(connectionTasks); sw.Stop(); Console.WriteLine($"{nameof(MultipleClientConnectionsMethodCalls)} - test time: {sw.Elapsed.TotalSeconds}"); }
public Resolver( Lexer lexer, CalculatorProxy calcProxy, TokenProcedence precedence) { _lexer = lexer; _calcProxy = calcProxy; _precedence = precedence; }
static void Main() { TraceSource ts = new TraceSource("ClientCalculatorTraceSource"); // Start the calculator activity Guid newGuid = Guid.NewGuid(); Trace.CorrelationManager.ActivityId = newGuid; ts.TraceEvent(TraceEventType.Start, 0, "Calculator Activity"); // Create a proxy with given client endpoint configuration using (CalculatorProxy proxy = new CalculatorProxy()) { // Save the calculator activity id to transfer back and forth from/to it Guid originalGuid = Trace.CorrelationManager.ActivityId; // Create and start the Add activity // Generate a new activity id newGuid = Guid.NewGuid(); // Transfer from the calculator activity to the new (Add) activity // The value for the "from" in the transfer is implicit; it is the activity id // previously set in Trace.CorrelationManager.ActivityId // The value for the "to" is explicitly passed as the newGuid parameter ts.TraceTransfer(0, "Transferring...", newGuid); // Set the new activity id in Trace.CorrelationManager.ActivityId; it is now in scope // for subsequently emitted traces Trace.CorrelationManager.ActivityId = newGuid; // Emit the Start trace for the new activity ts.TraceEvent(TraceEventType.Start, 0, "Add Activity"); // Now make the Add request double value1 = 100.00D; double value2 = 15.99D; ts.TraceEvent(TraceEventType.Information, 0, "Client sends Add request message."); double result = proxy.Add(value1, value2); // Trace that you have received the response ts.TraceEvent(TraceEventType.Information, 0, "Client receives Add response message."); Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result); // Transfer back to the Calculator activity and stop the current activity ts.TraceTransfer(667, "Transferring...", originalGuid); ts.TraceEvent(TraceEventType.Stop, 0, "Add Activity"); // Set the calculator activity back in scope Trace.CorrelationManager.ActivityId = originalGuid; // Call the Subtract service operation newGuid = Guid.NewGuid(); ts.TraceTransfer(0, "Transferring...", newGuid); Trace.CorrelationManager.ActivityId = newGuid; ts.TraceEvent(TraceEventType.Start, 0, "Subtract Activity"); value1 = 100.00D; value2 = 15.99D; ts.TraceEvent(TraceEventType.Information, 0, "Client sends Subtract request message."); result = proxy.Subtract(value1, value2); ts.TraceEvent(TraceEventType.Information, 0, "Client receives Subtract response message."); Console.WriteLine("Subtract({0},{1}) = {2}", value1, value2, result); ts.TraceTransfer(667, "Transferring...", originalGuid); ts.TraceEvent(TraceEventType.Stop, 0, "Subtract Activity"); Trace.CorrelationManager.ActivityId = originalGuid; // Call the Multiply service operation newGuid = Guid.NewGuid(); ts.TraceTransfer(0, "Transferring...", newGuid); Trace.CorrelationManager.ActivityId = newGuid; ts.TraceEvent(TraceEventType.Start, 0, "Multiply Activity"); value1 = 100.00D; value2 = 15.99D; ts.TraceEvent(TraceEventType.Information, 0, "Client sends Multiply request message."); result = proxy.Multiply(value1, value2); ts.TraceEvent(TraceEventType.Information, 0, "Client receives Multiply response message."); Console.WriteLine("Multiply({0},{1}) = {2}", value1, value2, result); ts.TraceTransfer(667, "Transferring...", originalGuid); ts.TraceEvent(TraceEventType.Stop, 0, "Multiply Activity"); Trace.CorrelationManager.ActivityId = originalGuid; // Call the Divide service operation newGuid = Guid.NewGuid(); ts.TraceTransfer(0, "Transferring...", newGuid); Trace.CorrelationManager.ActivityId = newGuid; ts.TraceEvent(TraceEventType.Start, 0, "Divide Activity"); value1 = 100.00D; value2 = 15.99D; ts.TraceEvent(TraceEventType.Information, 0, "Client sends Divide request message."); result = proxy.Divide(value1, value2); ts.TraceEvent(TraceEventType.Information, 0, "Client receives Divide response message."); Console.WriteLine("Divide({0},{1}) = {2}", value1, value2, result); ts.TraceTransfer(667, "Transferring...", originalGuid); ts.TraceEvent(TraceEventType.Stop, 0, "Divide Activity"); Trace.CorrelationManager.ActivityId = originalGuid; } ts.TraceEvent(TraceEventType.Stop, 0, "Calculator Activity"); Console.WriteLine(); Console.WriteLine("Press <ENTER> to terminate client."); Console.ReadLine(); }
public Resolver(Lexer lexer, CalculatorProxy calcProxy, TokenPrecedence precedence) { _lexer = lexer; _calcProxy = calcProxy; _precedence = precedence; }
public void SetUp() { _expressionValidator = new MathRegex(); _fixer = new ExpressionFixer(); _lexer = new MathLexer(_fixer); _calculator = new Calculator(); _validator = new Validator(-20, 20); _calcProxy = new CalcProxy(_validator, _calculator); }
static void Main() { // Get the username and password Console.WriteLine("Username authentication required."); Console.WriteLine("Provide a username."); Console.WriteLine(" Enter username: (test1)"); string username = Console.ReadLine(); Console.WriteLine(" Enter password:"******""; ConsoleKeyInfo info = Console.ReadKey(true); while (info.Key != ConsoleKey.Enter) { if (info.Key != ConsoleKey.Backspace) { if (info.KeyChar != '\0') { password += info.KeyChar; } info = Console.ReadKey(true); } else if (info.Key == ConsoleKey.Backspace) { if (password != "") { password = password.Substring(0, password.Length - 1); } info = Console.ReadKey(true); } } for (int i = 0; i < password.Length; i++) { Console.Write("*"); } Console.WriteLine(); // Create a proxy with Username endpoint configuration CalculatorProxy proxy = new CalculatorProxy("Username"); try { proxy.ClientCredentials.UserName.UserName = username; proxy.ClientCredentials.UserName.Password = password; // Call the Add service operation. double value1 = 100.00D; double value2 = 15.99D; double result = proxy.Add(value1, value2); Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result); // Call the Subtract service operation. value1 = 145.00D; value2 = 76.54D; result = proxy.Subtract(value1, value2); Console.WriteLine("Subtract({0},{1}) = {2}", value1, value2, result); // Call the Multiply service operation. value1 = 9.00D; value2 = 81.25D; result = proxy.Multiply(value1, value2); Console.WriteLine("Multiply({0},{1}) = {2}", value1, value2, result); // Call the Divide service operation. value1 = 22.00D; value2 = 7.00D; result = proxy.Divide(value1, value2); Console.WriteLine("Divide({0},{1}) = {2}", value1, value2, result); proxy.Close(); } catch (TimeoutException e) { Console.WriteLine("Call timed out : {0}", e.Message); proxy.Abort(); } catch (Exception e) { Console.WriteLine("Call failed:"); while (e != null) { Console.WriteLine("\t{0}", e.Message); e = e.InnerException; } proxy.Abort(); } Console.WriteLine(); Console.WriteLine("Press <ENTER> to terminate client."); Console.ReadLine(); }
public void SetUp() { _calculator = new Calculator(); _validator = new Validator(-20, 20); _calcProxy = new CalcProxy(_validator, _calculator); _expressionValidator = new MathRegex(); _fixer = new ExpressionFixer(); _lexer = new MathLexer(_fixer); _precedence = new Precedence(); _resolver = new Resolver(_lexer, _calcProxy, _precedence); _parser = new MathParser(_lexer, _expressionValidator, _resolver); }
public MathOperator(int precedence) : base(precedence) { _calcProxy = new CalcProxy(new Validator(-100, 100), new Calculator()); }
public async Task MultipleClientConnectionsEventCalls() { await DefaultSetup(new CalculatorService(), 10); Task[] connectionTasks = new Task[connections.Length]; const int taskCount = 25; for (int connectionIndex = 0; connectionIndex < connections.Length; connectionIndex++) { SimpleInMemConnection conn = connections[connectionIndex]; connectionTasks[connectionIndex] = Task.Run(() => { Task[] tasks = new Task[taskCount]; for (int taskIndex = 0; taskIndex < taskCount; taskIndex++) { tasks[taskIndex] = Task.Run(() => { var calculatorProxy = new CalculatorProxy<SimpleInMemConnection>(conn); calculatorProxy.IncrementCountAsync(); }); } Task.WaitAll(tasks); }); } Task.WaitAll(connectionTasks); int totalWaitTime = 0; const int maxWait = 5000; // Intentionally avoiding exponential back-off due to simple nature of this test const int incrementalWait = 500; while (totalWaitTime < maxWait) { await Task.Delay(incrementalWait); totalWaitTime += incrementalWait; try { Assert.AreEqual(CalculatorService.Count, connections.Length * taskCount); break; } catch (AssertionException) { // The implementation of SimpleInMem can guarantee delivery of events just be virtue of staying with in the process boundary. // SimpleInMem event failing after 5 seconds needs to raise alarm and investigation. if (totalWaitTime > maxWait) { throw; } } } Console.WriteLine($"{nameof(MultipleClientConnectionsEventCalls)} - Count: {CalculatorService.Count}"); }
public async Task MethodCall_ReqRsp_WithStatefulLayers() { var layerProvider = new TestLayerProvider_StatefulAppend("Layer"); var layerStackProvider = new LayerStackProvider<Dummy>(LoggerTests.BlackHole, layerProvider); transportBuilder.SetLayerStackProvider(layerStackProvider); await DefaultSetup(new CalculatorService(), 1); layerProvider.Layers.Clear(); var calculatorProxy = new CalculatorProxy<SimpleInMemConnection>(connections[0]); var request = new Message<PairedInput>(new PairedInput { First = 1, Second = 2 }); IMessage<Output> response = await calculatorProxy.AddAsync(request, CancellationToken.None); Assert.IsFalse(response.IsError); Assert.AreEqual(2, layerProvider.Layers.Count); Assert.AreEqual("Layer0SendLayer0Receive", layerProvider.Layers[0].State); Assert.AreEqual("Layer1ReceiveLayer1Send", layerProvider.Layers[1].State); request = new Message<PairedInput>(new PairedInput { First = 1, Second = 2 }); response = await calculatorProxy.AddAsync(request, CancellationToken.None); Assert.IsFalse(response.IsError); Assert.AreEqual(4, layerProvider.Layers.Count); Assert.AreEqual("Layer2SendLayer2Receive", layerProvider.Layers[2].State); Assert.AreEqual("Layer3ReceiveLayer3Send", layerProvider.Layers[3].State); }
public async Task MethodCall_WithLayerStack() { var testList = new List<string>(); var layer1 = new TestLayer_Append("foo", testList); var layer2 = new TestLayer_Append("bar", testList); transportBuilder.SetLayerStackProvider(new LayerStackProvider<Dummy>(LoggerTests.BlackHole, layer1, layer2)); await DefaultSetup(new CalculatorService(), 1); const int first = 91; const int second = 23; int addResult = first + second; var calculatorProxy = new CalculatorProxy<SimpleInMemConnection>(connections[0]); var input = new PairedInput { First = first, Second = second }; var request = new Message<PairedInput>(input); IMessage<Output> addResponse = await calculatorProxy.AddAsync(request, System.Threading.CancellationToken.None); Output addOutput = addResponse.Payload.Deserialize(); Assert.AreEqual(addResult, addOutput.Result); Assert.AreEqual(8, testList.Count); Assert.AreEqual(layer1.value, testList[0]); Assert.AreEqual(testList[0] + layer2.value, testList[1]); Assert.AreEqual(testList[1] + layer2.value, testList[2]); Assert.AreEqual(testList[2] + layer1.value, testList[3]); Assert.AreEqual(layer1.value, testList[4]); Assert.AreEqual(testList[4] + layer2.value, testList[5]); Assert.AreEqual(testList[5] + layer2.value, testList[6]); Assert.AreEqual(testList[6] + layer1.value, testList[7]); }
public async Task MethodCall_WithServiceError() { await DefaultSetup(new CalculatorService(), 1); const int first = 91; const int second = 23; var calculatorProxy = new CalculatorProxy<SimpleInMemConnection>(connections[0]); var input = new PairedInput { First = first, Second = second }; var request = new Message<PairedInput>(input); IMessage<Output> multiplyResponse = await calculatorProxy.MultiplyAsync(request, System.Threading.CancellationToken.None); Assert.IsTrue(multiplyResponse.IsError); InternalServerError error = multiplyResponse.Error.Deserialize<InternalServerError>(); Assert.AreEqual((int)ErrorCode.InternalServerError, error.error_code); Assert.That(error.message, Is.StringContaining(Errors.InternalErrorMessage)); }
public async Task MultipleClientConnectionsMethodCalls() { Stopwatch sw = Stopwatch.StartNew(); await DefaultSetup(new CalculatorService(), 10); Task[] connectionTasks = new Task[connections.Length]; for (int connectionIndex = 0; connectionIndex < connections.Length; connectionIndex++) { SimpleInMemConnection conn = connections[connectionIndex]; connectionTasks[connectionIndex] = Task.Run(() => { int taskCount = 25; Task[] tasks = new Task[taskCount]; for (int taskIndex = 0; taskIndex < taskCount; taskIndex++) { tasks[taskIndex] = Task.Run(async () => { Random rand = new Random(DateTime.UtcNow.Millisecond); int first = rand.Next(1, 100); int second = rand.Next(1, 50); int expectedAddResult = first + second; int expectedSubResult = first - second; var addTraceId = Guid.NewGuid().ToString(); var subTraceId = Guid.NewGuid().ToString(); var calculatorProxy = new CalculatorProxy<SimpleInMemConnection>(conn); var addInput = new PairedInput { First = first, Second = second, TraceId = addTraceId }; var subInput = new PairedInput { First = first, Second = second, TraceId = subTraceId }; Message<PairedInput> addRequest = new Message<PairedInput>(addInput); Message<PairedInput> subRequest = new Message<PairedInput>(subInput); IMessage<Output> addResponse = await calculatorProxy.AddAsync(addRequest, System.Threading.CancellationToken.None); IMessage<Output> subResponse = await calculatorProxy.SubtractAsync(subRequest, System.Threading.CancellationToken.None); Output addOutput = addResponse.Payload.Deserialize(); Output subOutput = subResponse.Payload.Deserialize(); Assert.AreEqual(expectedAddResult, addOutput.Result); Assert.AreEqual(addInput.TraceId, addOutput.TraceId); Assert.AreEqual(expectedSubResult, subOutput.Result); Assert.AreEqual(subInput.TraceId, subOutput.TraceId); }); } Task.WaitAll(tasks); }); } Task.WaitAll(connectionTasks); sw.Stop(); Console.WriteLine($"{nameof(MultipleClientConnectionsMethodCalls)} - test time: {sw.Elapsed.TotalSeconds}"); }
public async void EventCall() { await DefaultSetup(new CalculatorService(), 1); var calculatorProxy = new CalculatorProxy<SimpleInMemConnection>(connections[0]); calculatorProxy.ClearAsync(); bool wasSignaled = CalculatorService.ClearCalledEvent.WaitOne(30000); Assert.IsTrue(wasSignaled, "Timed out waiting for event"); }
public MathOperator(int precedence) : base(precedence) { _calcProxy = new CalcProxy( new Validator(-100, 100), new Calculator()); }