Пример #1
0
 private void FinishedAction(InvocationResult result)
 {
     if (InvokeRequired)
         Invoke(new InvocationCompleteAction(FinishedAction), result);
     else
         webBrowser.DocumentText = summaryResultsCollector.Document.ToString();
 }
        /// <summary>
        ///     Serializes and sends the response for the AppServiceRequest
        /// </summary>
        private static async Task SendResponse(AppServiceRequest request, InvocationResult result)
        {
            if (result.Result == null)
            {
                return;
            }

            object response = null;

            var asyncAction = result.Result as IAsyncAction;

            if (asyncAction != null)
            {
                await asyncAction;
            }
            else
            {
                var awaitAsyncOperationMethod = typeof(AppServiceChannelHelper).GetRuntimeMethods()
                                                .Single(method => method.Name == nameof(AwaitAsyncOperation));

                var awaitMethod = awaitAsyncOperationMethod.MakeGenericMethod(result.ResultType.GenericTypeArguments[0]);
                response = awaitMethod.Invoke(null, new[] { result.Result });
            }

            //Send a new ValueSet with the key as a random string and the value as the serialized result
            await request.SendResponseAsync(new ValueSet
            {
                { Guid.NewGuid().ToString(), JsonConvert.SerializeObject(response) }
            });
        }
Пример #3
0
 public void OnExecuted(InvocationResult result)
 {
     if (result.ReturnValue is T value)
     {
         _action(value);
     }
 }
Пример #4
0
            private void SetResult(InvocationResult result)
            {
                switch (result.Kind)
                {
                case InvocationResultKind.Empty:
                    break;

                case InvocationResultKind.Normal:
                {
                    var paragraph = new Paragraph();
                    paragraph.Inlines.Add(result.Message);
                    this.Blocks.Add(paragraph);
                    break;
                }

                case InvocationResultKind.Error:
                {
                    var paragraph = new Paragraph();
                    paragraph.Inlines.Add(result.Message);
                    paragraph.Foreground = this._owner.ErrorForeground;
                    this.Blocks.Add(paragraph);
                    this.Blocks.Add(new Paragraph());
                    break;
                }
                }
            }
        protected internal override async Task <InvocationResult> Invoke()
        {
            DateTimeOffset before;

            if (MinAge != null)
            {
                before = DateTimeOffset.UtcNow - MinAge.Value;
            }
            else
            {
                before = Before ?? DateTimeOffset.UtcNow;
            }

            // Get purgable invocations
            Log.FindingPurgableInvocations(before);
            var purgable = (await Context.Queue.GetPurgable(before)).ToList();

            Log.FoundPurgableInvocations(purgable.Count, before);

            // Purge 'em
            Log.PurgingInvocations(purgable.Count);
            await Context.Queue.Purge(purgable.Select(i => i.Id));

            Log.PurgedInvocations(purgable.Count);

            return(InvocationResult.Completed());
        }
        public void DisposeTest()
        {
            OcDispatcher         dispatcher = new OcDispatcher();
            ManualResetEventSlim mre        = new ManualResetEventSlim(false);
            bool invoked1 = false;
            bool invoked2 = false;
            bool freezed  = false;
            InvocationResult <bool> invocationResult  = null;
            InvocationResult <bool> invocationResult1 = null;

            dispatcher.InvokeAsync(() =>
            {
                dispatcher.InvokeAsync(() =>
                {
                    freezed = true;
                    mre.Wait();
                });


                invocationResult = dispatcher.Invoke(() => invoked1 = true);
            });

            Thread thread = new Thread(
                () =>
            {
                while (!freezed)
                {
                }

                invocationResult1 = dispatcher.Invoke(() => invoked2 = true);
            });

            thread.Start();

            ManualResetEventSlim mreDisposed = new ManualResetEventSlim(false);

            dispatcher.PropertyChanged += (sender, args) =>
            {
                if (args.PropertyName == nameof(OcDispatcher.Status) &&
                    dispatcher.Status == OcDispatcherStatus.Disposed)
                {
                    mreDisposed.Set();
                }
            };

            while (dispatcher.GetQueueCount() != 2)
            {
            }

            dispatcher.Dispose();
            mre.Set();
            thread.Join();
            mreDisposed.Wait();

            Assert.IsFalse(invoked1);
            Assert.IsFalse(invoked2);
            Assert.AreEqual(invocationResult.Invocation.Status, InvocationStatus.Canceled);
            Assert.AreEqual(invocationResult1.Invocation.Status, InvocationStatus.Canceled);
        }
Пример #7
0
 public InvocationEntry(Type targetType, MethodInfo methodInfo, object[] arguments, InvocationResult invocationResult, DateTimeOffset timestamp)
 {
     Arguments        = arguments;
     InvocationResult = invocationResult;
     Method           = methodInfo.Name;
     TargetType       = targetType;
     Timestamp        = timestamp;
 }
 public InvocationFinishedEventDescriptor(
     InvocationDescriptor methodCallDescriptor,
     InvocationResult result,
     long durationMs)
 {
     MethodCallDescriptor = methodCallDescriptor;
     Result     = result;
     DurationMs = durationMs;
 }
        public void TestFuncAsync()
        {
            OcDispatcher dispatcher   = new OcDispatcher(2);
            object       returnObject = new object();
            InvocationResult <object> invocationResult = dispatcher.InvokeAsync(() => returnObject);

            dispatcher.Pass();
            Assert.AreEqual(invocationResult.Value, invocationResult.Value);
            Assert.AreEqual(invocationResult.ToString(), "(ObservableComputations.InvocationResult<Object> (Value = '(System.Object)'))");
            dispatcher.Dispose();
        }
Пример #10
0
        public async Task <T> InvokeClientMethodAsync <T>(string socketId, string methodName, object[] arguments)
        {
            // create the method invocation descriptor.
            InvocationDescriptor invocationDescriptor = new InvocationDescriptor {
                MethodName = methodName, Arguments = arguments
            };

            // generate a unique identifier for this invocation.
            invocationDescriptor.Identifier = Guid.NewGuid();

            // add ourselves to the waiting list for return values.
            TaskCompletionSource <InvocationResult> task = new TaskCompletionSource <InvocationResult>();

            // after a timeout of 60 seconds we will cancel the task and remove it from the waiting list.
            new CancellationTokenSource(1000 * 60).Token.Register(() => { _waitingRemoteInvocations.Remove(invocationDescriptor.Identifier); task.TrySetCanceled(); });
            _waitingRemoteInvocations.Add(invocationDescriptor.Identifier, task);

            // send the method invocation to the client.
            var message = new Message()
            {
                MessageType = MessageType.MethodInvocation, Data = JsonConvert.SerializeObject(invocationDescriptor, _jsonSerializerSettings)
            };

            await SendMessageAsync(socketId, message).ConfigureAwait(false);

            // wait for the return value elsewhere in the program.
            InvocationResult result = await task.Task;

            // ... we just got an answer.

            // if we have completed successfully:
            if (task.Task.IsCompleted)
            {
                // there was a remote exception so we throw it here.
                if (result.Exception != null)
                {
                    throw new Exception(result.Exception.Message);
                }

                // return the value.

                // support null.
                if (result.Result == null)
                {
                    return(default(T));
                }
                // cast anything to T and hope it works.
                return((T)result.Result);
            }

            // if we reach here we got cancelled or alike so throw a timeout exception.
            throw new TimeoutException(); // todo: insert fancy message here.
        }
 private void OnActionFinished(InvocationDescriptor callDescriptor, InvocationResult callResult, long startMs)
 {
     if (callDescriptor == null)
     {
         return;
     }
     _appLifecycleManager.OnInvocationFinished(
         new InvocationFinishedEventDescriptor(
             callDescriptor,
             callResult,
             _stopwatch.ElapsedMilliseconds - startMs));
 }
Пример #12
0
 public void AddResult(InvocationResult result)
 {
     tableElement.Add
         (
         new XElement
             (
             "tr",
             new XElement("td", result.AlgorithmName),
             new XElement("td", result.MinMillisecondsPerInvocation.ToString("0.00000000"))
             )
         );
 }
Пример #13
0
        protected override object Invoke(MethodInfo targetMethod, object[] args)
        {
            var name = targetMethod.Name;

            ExecuteBeforeExecutionRules(forTargetMethod: targetMethod, withArgs: args);

            var result = ExecuteStubExecutionRules(forTargetMethod: targetMethod, withArgs: args);

            if (_afterExecutionRules.Count() == 0)
            {
                return(result);
            }

            var invocationResult = default(InvocationResult);

            if (result is Task task)
            {
                invocationResult = WaitForResultOf(task, targetMethod);
            }
            else
            {
                // We now callout with the original value: it is better the recipient serialize / deserialize this by casting to the expected type first.
                if (targetMethod.ReturnType == typeof(void))
                {
                    invocationResult = new InvocationResult();
                }
                else
                {
                    invocationResult = new InvocationResult()
                    {
                        HasReturnValue = true,
                        ReturnValue    = result
                    };
                }
            }

            var afterExecutionRules = _afterExecutionRules.Where(f => f.MethodName == targetMethod.Name);

            afterExecutionRules.ToList().ForEach(ar =>
            {
                try
                {
                    ar.Callback(new AfterExecutionResult(ar, invocationResult.HasReturnValue, invocationResult.ReturnValue, args, targetMethod.GetParameters()));
                }
                catch (Exception)
                {
                    // Design decision: if anything goes wrong in the callback, we do not want to change the result of invoking the method. Therefore, sink the exception.
                }
            });

            return(result);
        }
Пример #14
0
        /// <summary>
        /// Serializes and sends the response for the AppServiceRequest
        /// </summary>
        private static async Task SendResponse(AppServiceRequest request, InvocationResult result)
        {
            if (result.Result == null)
            {
                return;
            }

            //Send a new ValueSet with the key as a random string and the value as the serialized result
            await request.SendResponseAsync(new ValueSet
            {
                { Guid.NewGuid().ToString(), JsonConvert.Serialize(result.Result) }
            });
        }
Пример #15
0
        public void InitTest()
        {
            var obj = new InvocationResult <object>();

            Assert.IsNull(obj.Result);
            Assert.IsFalse(obj.Successful);

            obj.Successful = true;
            Assert.IsTrue(obj.Successful);

            obj.Result = 1;
            Assert.AreEqual(1, obj.Result);
        }
        public void TestFuncAsyncState()
        {
            OcDispatcher dispatcher   = new OcDispatcher(2);
            TestValue    returnObject = new TestValue();
            InvocationResult <TestValue> invocationResult = dispatcher.InvokeAsync(s => returnObject, new object());
            bool propertyChanged = false;

            invocationResult.PropertyChanged += (sender, args) => propertyChanged = true;
            dispatcher.Pass();
            Assert.AreEqual(invocationResult.Value, returnObject);
            Assert.IsTrue(propertyChanged);
            Assert.AreEqual(invocationResult.ToString(), "(ObservableComputations.InvocationResult<TestValue> (Value = 'Mesasage'))");
            Assert.AreEqual(invocationResult.Invocation.Status, InvocationStatus.Executed);
            dispatcher.Dispose();
        }
Пример #17
0
        public AssemblyResult Analyse()
        {
            try
            {
                using (var ass = Mono.Cecil.AssemblyDefinition.ReadAssembly(_assembly))
                {
                    var assembly = new AssemblyResult(ass.FullName, _assembly);

                    foreach (var module in ass.Modules.OrderBy(m => m.FileName))
                    {
                        foreach (var classType in module.GetTypes().OrderBy(z => z.FullName).Where(z => !z.IsInterface))
                        {
                            var typeResult = new ClassTypeResult(classType.FullName, classType.Module.FileName);
                            foreach (var method in classType.Methods.Where(e => !e.IsAbstract).OrderBy(e => e.FullName))
                            {
                                int seq = 0;
                                if (method.HasBody)
                                {
                                    string parameters   = String.Join(",", method.Parameters);
                                    var    methodResult = new MethodResult(method.Name, parameters);

                                    foreach (var instruction in method.Body.Instructions
                                             .Where(u => ((u.OpCode == OpCodes.Call)) ||
                                                    (u.OpCode == OpCodes.Callvirt) ||
                                                    (u.OpCode == OpCodes.Calli) ||
                                                    (u.OpCode == OpCodes.Newobj)
                                                    ))
                                    {
                                        var splits = instruction.Operand.ToString().Split(" ");
                                        var invoke = new InvocationResult(splits[1], splits[0], seq++);
                                        methodResult.Invocations.Add(invoke);
                                    }
                                    typeResult.Methods.Add(methodResult);
                                }
                            }
                            assembly.Types.Add(typeResult);
                        }
                    }
                    return(assembly);
                }
            }
            catch (Exception ex)
            {
                var err = new AssemblyResult("NotAvailable", _assembly);
                err.HandleException(ex);
                return(err);
            }
        }
Пример #18
0
        public static Generated.InvocationResult ToProto(this InvocationResult info)
        {
            switch (info)
            {
            case InvocationResult.Succeeded:
                return(Generated.InvocationResult.Succeeded);

            case InvocationResult.Canceled:
                return(Generated.InvocationResult.Canceled);

            case InvocationResult.Failed:
                return(Generated.InvocationResult.Failed);

            default:
                throw new ArgumentOutOfRangeException(nameof(info), info, null);
            }
        }
Пример #19
0
        /// <summary>
        /// Send a method invoke request to the server and waits for a reply.
        /// </summary>
        /// <param name="invocationDescriptor">Example usage: set the MethodName to SendMessage and set the arguments to the connectionID with a text message</param>
        /// <returns>An awaitable task with the return value on success.</returns>
        public async Task <T> SendAsync <T>(InvocationDescriptor invocationDescriptor)
        {
            // generate a unique identifier for this invocation.
            invocationDescriptor.Identifier = Guid.NewGuid();

            // add ourselves to the waiting list for return values.
            TaskCompletionSource <InvocationResult> task = new TaskCompletionSource <InvocationResult>();

            // after a timeout of 60 seconds we will cancel the task and remove it from the waiting list.
            new CancellationTokenSource(1000 * 60).Token.Register(() => { _waitingRemoteInvocations.Remove(invocationDescriptor.Identifier); task.TrySetCanceled(); });
            _waitingRemoteInvocations.Add(invocationDescriptor.Identifier, task);

            // send the method invocation to the server.
            var bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new Message {
                MessageType = MessageType.MethodInvocation, Data = JsonConvert.SerializeObject(invocationDescriptor, _jsonSerializerSettings)
            }, _jsonSerializerSettings));
            await _clientWebSocket.SendAsync(new ArraySegment <byte>(bytes), WebSocketMessageType.Text, true, CancellationToken.None);

            // wait for the return value elsewhere in the program.
            InvocationResult result = await task.Task;

            // ... we just got an answer.

            // if we have completed successfully:
            if (task.Task.IsCompleted)
            {
                // there was a remote exception so we throw it here.
                if (result.Exception != null)
                {
                    throw new Exception(result.Exception.Message);
                }

                // return the value.

                // support null.
                if (result.Result == null)
                {
                    return(default(T));
                }
                // cast anything to T and hope it works.
                return((T)result.Result);
            }

            // if we reach here we got cancelled or alike so throw a timeout exception.
            throw new TimeoutException(); // todo: insert fancy message here.
        }
Пример #20
0
            public async Task AcknowledgesMessageOnCompletionOfInvocation()
            {
                // Arrange
                var cts        = new CancellationTokenSource();
                var runner     = new TestableJobRunner(TimeSpan.FromSeconds(5));
                var invocation = TestHelpers.CreateInvocation(Guid.NewGuid(), "test", "test", new Dictionary <string, string>());

                runner.MockDispatcher
                .Setup(d => d.Dispatch(It.IsAny <InvocationContext>()))
                .Completes(InvocationResult.Completed())
                .Verifiable();

                // Act
                await runner.Dispatch(invocation, cts.Token);

                // Assert
                runner.MockQueue.Verify(q => q.Complete(invocation, ExecutionResult.Completed, null, null));
            }
        public void AddResult(InvocationResult result)
        {
            if (ListView.InvokeRequired)
                ListView.Invoke(new AddResultDelegate(AddResult), result);
            else
                ListView.Items.Add
                    (
                    new ListViewItem(
                        new []
                            {
                                result.AlgorithmName,
                                result.MinMillisecondsPerInvocation.ToString("0.00000000")
                            }
                        )
                    );

            Application.DoEvents();
        }
Пример #22
0
            public async Task DispatchesTheJobUsingTheDispatcher()
            {
                // Arrange
                var cts        = new CancellationTokenSource();
                var runner     = new TestableJobRunner(TimeSpan.FromSeconds(5));
                var invocation = TestHelpers.CreateInvocation(Guid.NewGuid(), "test", "test", new Dictionary <string, string>());

                runner.MockDispatcher
                .Setup(d => d.Dispatch(It.IsAny <InvocationContext>()))
                .Completes(InvocationResult.Completed())
                .Verifiable();

                // Act
                await runner.Dispatch(invocation, cts.Token);

                // Assert
                runner.MockDispatcher.VerifyAll();
            }
        public ActionResult Post([FromBody] InvocationRequest value)
        {
            foreach (var data in value.Data.Keys)
            {
                _logger.LogInformation($"data:{data} value:{value.Data[data]}");
            }

            foreach (var metadadata in value.Metadata.Keys)
            {
                _logger.LogInformation($"data:{metadadata} value:{value.Metadata[metadadata]}");
            }
            InvocationResult invocationResult = new InvocationResult()
            {
                ReturnValue = "HelloWorld from c# worker"
            };

            return(new JsonResult(invocationResult));
        }
Пример #24
0
        private void Run(string[] args, IEnumerable <Type> classes, Type expectException = null)
        {
            $"Running {string.Join(" ", args)}".H2();
            var errsb               = new StringBuilder();
            var invocation          = new Invocation(stdout: null, stderr: new StringWriter(errsb), ignoreCase: true);
            InvocationResult result = null;

            try
            {
                if (expectException == null)
                {
                    // no try/catch for easier debugging by default
                    result = invocation.Invoke(args, classes);
                    return;
                }

                try
                {
                    result = invocation.Invoke(args, classes);
                }
                catch (Exception e)
                {
                    if (expectException != null && expectException.IsAssignableFrom(e.GetType()))
                    {
                        $"Exception {expectException.GetTypeName()}".H2();
                        _sb.AppendLine();
                        return;
                    }

                    throw;
                }
            }
            finally
            {
                if (errsb.Length != 0)
                {
                    _sb.AppendLine("stderr:");
                    _sb.AppendLine("```");
                    _sb.Append(errsb.ToString());
                    _sb.AppendLine("```");
                    _sb.AppendLine();
                }
            }
        }
Пример #25
0
        public async Task SendClientErrorAsync(string socketId, long id, string methodName, RemoteException error)
        {
            // create the method invocation descriptor.
            InvocationResult invocationResult = new InvocationResult {
                Id = id, MethodName = methodName, Exception = error
            };
            WebSocketConnection socket = WebSocketConnectionManager.GetSocketById(socketId);

            if (socket == null)
            {
                return;
            }

            var message = new Message()
            {
                MessageType = MessageType.MethodInvocation,
                Data        = JsonConvert.SerializeObject(invocationResult)
            };

            await SendMessageAsync(socketId, message).ConfigureAwait(false);
        }
Пример #26
0
            public async Task UpdatesTheStatusOfTheRequestToExecuting()
            {
                // Arrange
                var cts        = new CancellationTokenSource();
                var runner     = new TestableJobRunner(TimeSpan.FromSeconds(5));
                var invocation = TestHelpers.CreateInvocation(Guid.NewGuid(), "test", "test", new Dictionary <string, string>());

                var dispatchTCS = runner
                                  .MockDispatcher
                                  .Setup(d => d.Dispatch(It.IsAny <InvocationContext>()))
                                  .WaitsForSignal();

                // Act
                var task = runner.Dispatch(invocation, cts.Token);

                // Assert
                runner.MockQueue.Verify(q => q.UpdateStatus(invocation, InvocationStatus.Executing, ExecutionResult.Incomplete));

                dispatchTCS.SetResult(InvocationResult.Completed());

                await task;
            }
Пример #27
0
        public virtual async Task OnPeerResponseAsync(WebSocketConnection socket, InvocationResult invocationResult)
        {
            var socketId = WebSocketConnectionManager.GetId(socket);

            try
            {
                if (_waitingRemoteInvocations.ContainsKey(socketId) && invocationResult.Id > 0)
                {
                    if (_waitingRemoteInvocations[socketId].ContainsKey(invocationResult.Id))
                    {
                        _waitingRemoteInvocations[socketId][invocationResult.Id].SetResult(invocationResult);
                        // remove the completion source from the waiting list.
                    }
                    _waitingRemoteInvocations[socketId].Remove(invocationResult.Id);
                }
            }
            catch (Exception e)
            {
                var str = e.Message;
            }
            await Task.CompletedTask;
        }
Пример #28
0
            public async Task SuspendsInvocationIfJobRemainsIncompleteWithAContinuation()
            {
                // Arrange
                var cts        = new CancellationTokenSource();
                var runner     = new TestableJobRunner(TimeSpan.FromSeconds(5));
                var invocation = TestHelpers.CreateInvocation(Guid.NewGuid(), "test", "test", new Dictionary <string, string>());

                var continuationPayload = new Dictionary <string, string>()
                {
                    { "foo", "bar" }
                };

                runner.MockDispatcher
                .Setup(d => d.Dispatch(It.IsAny <InvocationContext>()))
                .Completes(InvocationResult.Suspended(new JobContinuation(TimeSpan.FromDays(365), continuationPayload)))
                .Verifiable();

                // Act
                await runner.Dispatch(invocation, cts.Token);

                // Assert
                runner.MockQueue.Verify(q => q.Suspend(invocation, continuationPayload, TimeSpan.FromDays(365), null));
            }
Пример #29
0
        private async Task StartClient(Uri uri, CancellationToken token, ReconnectionType type)
        {
            // also check if connection was lost, that's probably why we get called multiple times.
            if (_clientWebSocket == null || _clientWebSocket.State != WebSocketState.Open)
            {
                // create a new web-socket so the next connect call works.
                _clientWebSocket?.Dispose();
                //var options = new ClientWebSocketOptions();
                _clientWebSocket = new ClientWebSocket();
                _clientWebSocket.Options.KeepAliveInterval = new TimeSpan(0, 0, 15, 0);

                if (!string.IsNullOrEmpty(_token))
                {
                    _clientWebSocket.Options.SetRequestHeader("Authorization", "Bearer " + _token);
                }
            }
            // don't do anything, we are already connected.
            else
            {
                return;
            }
            try
            {
                //await _clientWebSocket.ConnectAsync(uri, CancellationToken.None).ConfigureAwait(false);
                await _clientWebSocket.ConnectAsync(uri, token).ConfigureAwait(false);

                OnConnect?.Invoke(this, EventArgs.Empty);
                IsRunning = true;
                await Receive(_clientWebSocket, token, async (receivedMessage) =>
                {
                    JObject jObject = null;
                    InvocationDescriptor invocationDescriptor = null;
                    try
                    {
                        jObject = Newtonsoft.Json.JsonConvert.DeserializeObject <JObject>(receivedMessage);
                        //invocationDescriptor = JsonConvert.DeserializeObject<InvocationDescriptor>(serializedMessage);
                        invocationDescriptor = jObject.ToObject <InvocationDescriptor>();
                        //if (invocationDescriptor == null) return;
                    }
                    catch (Exception ex)
                    {
                        // ignore invalid data sent to the server.
                    }
                    if (jObject == null)
                    {
                        try
                        {
                            var obj = MethodInvocationStrategy.OnTextReceivedAsync("", receivedMessage);
                        }
                        catch (Exception ex)
                        {
                        }
                        return;
                    }
                    if (invocationDescriptor != null && invocationDescriptor.Params != null)
                    {
                        if (invocationDescriptor.Id == 0)
                        {
                            // invoke the method only.
                            try
                            {
                                await MethodInvocationStrategy.OnInvokeMethodReceivedAsync("", invocationDescriptor);
                            }
                            catch (Exception)
                            {
                                // we consume all exceptions.
                                return;
                            }
                        }
                        else
                        {
                            // invoke the method and get the result.
                            InvocationResult invokeResult;
                            try
                            {
                                // create an invocation result with the results.
                                invokeResult = new InvocationResult()
                                {
                                    Id        = invocationDescriptor.Id,
                                    Result    = await MethodInvocationStrategy.OnInvokeMethodReceivedAsync("", invocationDescriptor),
                                    Exception = null
                                };
                            }
                            // send the exception as the invocation result if there was one.
                            catch (Exception ex)
                            {
                                invokeResult = new InvocationResult()
                                {
                                    Id        = invocationDescriptor.Id,
                                    Result    = null,
                                    Exception = new RemoteException(ex)
                                };
                            }

                            // send a message to the server containing the result.
                            var message = new Message()
                            {
                                MessageType = MessageType.MethodReturnValue,
                                Data        = JsonConvert.SerializeObject(invokeResult)
                            };
                            //var bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message, _jsonSerializerSettings));
                            //var bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message.Data, _jsonSerializerSettings));
                            //await _clientWebSocket.SendAsync(new ArraySegment<byte>(bytes), WebSocketMessageType.Text, true, CancellationToken.None).ConfigureAwait(false);
                            await Send(message.Data);
                        }
                    }
                    else
                    {
                        try
                        {
                            var invocationResult = jObject.ToObject <InvocationResult>();
                            if ((invocationResult != null) && (invocationResult.Exception != null || invocationResult.Result != null))
                            {
                                // find the completion source in the waiting list.
                                if (_waitingRemoteInvocations.ContainsKey(invocationResult.Id))
                                {
                                    // set the result of the completion source so the invoke method continues executing.
                                    _waitingRemoteInvocations[invocationResult.Id].SetResult(invocationResult);
                                    // remove the completion source from the waiting list.
                                    _waitingRemoteInvocations.Remove(invocationResult.Id);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            var str = e.Message;
                        }
                    }
                });

                ActivateLastChance();
            }
            catch (Exception e)
            {
                Console.WriteLine($"{DateTime.Now} _clientWebSocket.ConnectAsync Exception: {e.Message}");
                IsRunning = false;
                await Task.Delay(ErrorReconnectTimeoutMs, _cancelation.Token).ConfigureAwait(false);
                await Reconnect(ReconnectionType.Error).ConfigureAwait(false);
            }
        }
Пример #30
0
        public async Task StartConnectionAsync(string uri)
        {
            // also check if connection was lost, that's probably why we get called multiple times.
            if (_clientWebSocket == null || _clientWebSocket.State != WebSocketState.Open)
            {
                // create a new web-socket so the next connect call works.
                _clientWebSocket?.Dispose();
                _clientWebSocket = new ClientWebSocket();
            }
            // don't do anything, we are already connected.
            else
            {
                return;
            }

            await _clientWebSocket.ConnectAsync(new Uri(uri), CancellationToken.None).ConfigureAwait(false);

            await Receive(_clientWebSocket, async (receivedMessage) =>
            {
                if (receivedMessage.MessageType == MessageType.ConnectionEvent)
                {
                    this.ConnectionId = receivedMessage.Data;
                }
                else if (receivedMessage.MessageType == MessageType.MethodInvocation)
                {
                    // retrieve the method invocation request.
                    InvocationDescriptor invocationDescriptor = null;
                    try
                    {
                        invocationDescriptor = JsonConvert.DeserializeObject <InvocationDescriptor>(receivedMessage.Data, _jsonSerializerSettings);
                        if (invocationDescriptor == null)
                        {
                            return;
                        }
                    }
                    catch { return; } // ignore invalid data sent to the client.

                    // if the unique identifier hasn't been set then the server doesn't want a return value.
                    if (invocationDescriptor.Identifier == Guid.Empty)
                    {
                        // invoke the method only.
                        try
                        {
                            await MethodInvocationStrategy.OnInvokeMethodReceivedAsync(_clientWebSocket, invocationDescriptor);
                        }
                        catch (Exception)
                        {
                            // we consume all exceptions.
                        }
                    }
                    else
                    {
                        // invoke the method and get the result.
                        InvocationResult invokeResult;
                        try
                        {
                            // create an invocation result with the results.
                            invokeResult = new InvocationResult()
                            {
                                Identifier = invocationDescriptor.Identifier,
                                Result     = await MethodInvocationStrategy.OnInvokeMethodReceivedAsync(_clientWebSocket, invocationDescriptor),
                                Exception  = null
                            };
                        }
                        // send the exception as the invocation result if there was one.
                        catch (Exception ex)
                        {
                            invokeResult = new InvocationResult()
                            {
                                Identifier = invocationDescriptor.Identifier,
                                Result     = null,
                                Exception  = new RemoteException(ex)
                            };
                        }

                        // send a message to the server containing the result.
                        var message = new Message()
                        {
                            MessageType = MessageType.MethodReturnValue,
                            Data        = JsonConvert.SerializeObject(invokeResult, _jsonSerializerSettings)
                        };
                        var bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message, _jsonSerializerSettings));
                        await _clientWebSocket.SendAsync(new ArraySegment <byte>(bytes), WebSocketMessageType.Text, true, CancellationToken.None).ConfigureAwait(false);
                    }
                }
                else if (receivedMessage.MessageType == MessageType.MethodReturnValue)
                {
                    var invocationResult = JsonConvert.DeserializeObject <InvocationResult>(receivedMessage.Data, _jsonSerializerSettings);
                    // find the completion source in the waiting list.
                    if (_waitingRemoteInvocations.ContainsKey(invocationResult.Identifier))
                    {
                        // set the result of the completion source so the invoke method continues executing.
                        _waitingRemoteInvocations[invocationResult.Identifier].SetResult(invocationResult);
                        // remove the completion source from the waiting list.
                        _waitingRemoteInvocations.Remove(invocationResult.Identifier);
                    }
                }
            });
        }
 public void Succeeded(InvocationResult result) { Succeeded(InvocationContext.GetCurrentInvocationId(), DateTimeOffset.UtcNow.ToString("O")); }
 public void Suspended(InvocationResult result) { Suspended(InvocationContext.GetCurrentInvocationId(), DateTimeOffset.UtcNow.ToString("O"), result.Continuation != null ? result.Continuation.WaitPeriod.ToString() : "<UNKNOWN>"); }
 public void UnknownStatus(InvocationResult result) { UnknownStatus(InvocationContext.GetCurrentInvocationId(), DateTimeOffset.UtcNow.ToString("O"), result.Result.ToString()); }
 public void Faulted(InvocationResult result) { Faulted(InvocationContext.GetCurrentInvocationId(), DateTimeOffset.UtcNow.ToString("O"), result.Exception != null ? result.Exception.ToString() : ""); }
Пример #35
0
 internal void SetResult(InvocationResult p_result)
 {
     this.Result = p_result;
     this.Status = Constants.InvocationStatus.Invoked;
 }
Пример #36
0
 public virtual async Task PostRpcResponse(WebSocketConnection socket, InvocationResult invocationResult)
 {
     await Task.CompletedTask;
 }
Пример #37
0
        public virtual async Task OnReceivedTextAsync(WebSocketConnection socket, string serializedMessage)
        {
            var     timer   = new Stopwatch();
            JObject jObject = null;
            InvocationDescriptor invocationDescriptor = null;
            InvocationResult     invocationResult     = null;

            timer.Start();
            try
            {
                jObject = JsonConvert.DeserializeObject <JObject>(serializedMessage);
            }
            catch (Exception e)
            {
                // ignore invalid data sent to the server.
                //socket.WebSocket.CloseOutputAsync();
                return;
            }
            try
            {
                invocationResult = jObject.ToObject <InvocationResult>();
                if ((invocationResult != null) && (invocationResult.Exception != null || invocationResult.Result != null))
                {
                    await PreRpcResponse(socket, invocationResult).ConfigureAwait(false);
                    await OnPeerResponseAsync(socket, invocationResult);
                    await PostRpcResponse(socket, invocationResult).ConfigureAwait(false);

                    return;
                }
            }
            catch (Exception e)
            {
                // Ignore if is not jsonrpc result
            }
            try
            {
                invocationDescriptor = jObject.ToObject <InvocationDescriptor>();
            }
            catch (Exception e)
            {
                // Not jsonrpc request
                //return;
            }
            // method invocation request.
            if (invocationDescriptor != null)
            {
                await PreRpcRequest(socket, invocationDescriptor).ConfigureAwait(false);

                // retrieve the method invocation request.
                // if the unique identifier hasn't been set then the client doesn't want a return value.
                if (invocationDescriptor.Id == 0)
                {
                    // invoke the method only.
                    try
                    {
                        var result = await MethodInvocationStrategy.OnInvokeMethodReceivedAsync(socket, invocationDescriptor);

                        timer.Stop();
                        await PostRpcRequest(socket, invocationDescriptor, timer.ElapsedMilliseconds).ConfigureAwait(false);
                    }
                    catch (Exception e)
                    {
                        // we consume all exceptions.
                    }
                    timer.Start();
                }
                else
                {
                    try
                    {
                        var invokeResult = await MethodInvocationStrategy.OnInvokeMethodReceivedAsync(socket, invocationDescriptor);

                        if (invokeResult != null)
                        {
                            string json = JsonConvert.SerializeObject(invokeResult);
                            // send a message to the client containing the result.
                            var message = new Message()
                            {
                                MessageType = MessageType.MethodReturnValue,
                                Data        = json
                                              //Data = JsonConvert.SerializeObject(invokeResult, _jsonSerializerSettings)
                            };
                            await SendMessageAsync(socket, message).ConfigureAwait(false);

                            timer.Stop();
                            await PostRpcRequest(socket, invocationDescriptor, timer.ElapsedMilliseconds);
                        }
                    }
                    catch (Exception e)
                    {
                        throw;
                    }
                }
            }
            else
            {
                await OnUnknownAsync(socket, jObject);
            }
        }