Example #1
0
 public async Task RegisterMethod(string methodName, MethodCallback method)
 {
     // setup callback for "writeLine" method
     deviceClient.SetMethodHandlerAsync(methodName, method, null).Wait();
     clientMethods.Add(methodName);
     Console.WriteLine("Waiting for direct method call\n Press enter to exit.");
 }
Example #2
0
        /// <summary>
        /// Registers a new delgate for the named method. If a delegate is already associated with
        /// the named method, it will be replaced with the new delegate.
        /// <param name="methodName"></param>
        /// <param name="methodDelegate"></param>
        /// </summary>
        public void SetMethodDelegate(string methodName, MethodCallback methodDelegate)
        {
            /* codes_SRS_DEVICECLIENT_10_001: [ The SetMethodDelegate shall lazy-initialize the deviceMethods property. ]*/
            if (this.deviceMethods == null)
            {
                this.deviceMethods = new Dictionary <string, MethodCallback>();
            }

            /* codes_SRS_DEVICECLIENT_10_002: [** If the given methodName already has an associated delegate, the existing delegate shall be removed. ]*/
            /* codes_SRS_DEVICECLIENT_10_003: [** The given delegate will only be added if it is not null. ]*/
            if (methodDelegate == null)
            {
                this.deviceMethods.Remove(methodName);
            }
            else
            {
                this.deviceMethods[methodName] = methodDelegate;
            }

            /* codes_SRS_DEVICECLIENT_10_004: [** The deviceMethods property shall be deleted if the last delegate has been removed. ]*/
            if (this.deviceMethods.Count == 0)
            {
                this.deviceMethods = null;
            }
        }
Example #3
0
        public async Task HandleExceptionsTest(Type exception)
        {
            // Arrange
            MethodCallback testMethodCallback = (request, context) => Task.FromResult(new MethodResponse(200));

            var sdkModuleClient = new Mock <ISdkModuleClient>(MockBehavior.Strict);

            sdkModuleClient.Setup(s => s.CloseAsync())
            .Returns(Task.CompletedTask);
            sdkModuleClient.Setup(s => s.SetDefaultMethodHandlerAsync(testMethodCallback))
            .ThrowsAsync((Exception)Activator.CreateInstance(exception, "Dummy exception"));

            TimeSpan idleTimeout        = TimeSpan.FromMinutes(3);
            bool     closeOnIdleTimeout = false;

            // Act
            var moduleClient = new ModuleClient(sdkModuleClient.Object, idleTimeout, closeOnIdleTimeout, Core.UpstreamProtocol.Mqtt);

            Assert.Equal(Core.UpstreamProtocol.Mqtt, moduleClient.UpstreamProtocol);
            Assert.True(moduleClient.IsActive);
            await Assert.ThrowsAsync(exception, () => moduleClient.SetDefaultMethodHandlerAsync(testMethodCallback));

            // Assert
            sdkModuleClient.Verify(s => s.SetDefaultMethodHandlerAsync(testMethodCallback), Times.Once);
            sdkModuleClient.Verify(s => s.CloseAsync(), Times.Once);
        }
Example #4
0
        public async Task SetMethodHandlerAsync(string methodName, MethodCallback methodHandler, object userContext)
        {
            MethodMessageHandlers[methodName] = methodHandler;

            Log.Information($"Method Handler Set for {methodName}");
            await Task.FromResult(0);
        }
Example #5
0
 /// <summary>
 /// Registers a callback that is called every time a GPU method, or methods are called.
 /// </summary>
 /// <param name="offset">Offset of the method</param>
 /// <param name="count">Word count of the methods region</param>
 /// <param name="callback">Calllback to be called</param>
 public void RegisterCallback(MethodOffset offset, int count, MethodCallback callback)
 {
     for (int index = 0; index < count; index++)
     {
         _registers[(int)offset + index].Callback = callback;
     }
 }
Example #6
0
 public MethodMetadata(MethodDelegate methoddelegate, MethodCallback callback, bool validate, params Type[] inputtypes)
 {
     Delegate   = methoddelegate;
     InputTypes = inputtypes;
     Callback   = callback;
     Validate   = validate;
 }
Example #7
0
 public async Task SetMethodHandlerAsync(string methodName,
                                         MethodCallback methodHandler,
                                         object userContext)
 {
     await moduleClient.SetMethodHandlerAsync(methodName,
                                              methodHandler,
                                              userContext);
 }
 /// <summary>
 /// Registers a new delegate for the named method. If a delegate is already associated with
 /// the named method, it will be replaced with the new delegate.
 /// </summary>
 public Task SetMethodHandlerAsync(string methodName, MethodCallback methodHandler)
 {
     if (_iotHubClient == null)
     {
         return(_edgeHubClient.SetMethodHandlerAsync(methodName, methodHandler, _edgeHubClient));
     }
     return(_iotHubClient.SetMethodHandlerAsync(methodName, methodHandler, _iotHubClient));
 }
 /// <summary>
 /// Set a callback on direct method
 /// </summary>
 /// <param name="callbackDirectMethod">MethodCallback object</param>
 /// <returns>Task</returns>
 public void SetDirectMethodCallback(string methodName, MethodCallback callbackDirectMethod)
 {
     _callbackDirectMethods.Add(new DirectMethodConfig()
     {
         MethodName           = methodName,
         CallbackDirectMethod = callbackDirectMethod
     });
 }
 /// <summary>
 /// Registers a new delegate that is called for a method that doesn't have a delegate registered for its name.
 /// If a default delegate is already registered it will replace with the new delegate.
 /// </summary>
 public Task SetMethodDefaultHandlerAsync(MethodCallback methodHandler)
 {
     if (_iotHubClient == null)
     {
         return(_edgeHubClient.SetMethodDefaultHandlerAsync(methodHandler, _edgeHubClient));
     }
     return(_iotHubClient.SetMethodDefaultHandlerAsync(methodHandler, _iotHubClient));
 }
Example #11
0
        public async Task <object> RoundtripMethodCallAsync(string connectionId, string methodName, MethodRequestAndResponse requestAndResponse)
        {
            Console.WriteLine("RoundtripMethodCallAsync received for {0} and methodName {1}", connectionId, methodName);
            Console.WriteLine(JsonConvert.SerializeObject(requestAndResponse));
            var client = objectMap[connectionId];
            var mutex  = new System.Threading.SemaphoreSlim(1);
            await mutex.WaitAsync().ConfigureAwait(false);  // Grab the mutex. The handler will release it later

            MethodCallback callback = async(methodRequest, userContext) =>
            {
                Console.WriteLine("Method invocation received");

                object request  = JsonConvert.DeserializeObject(methodRequest.DataAsJson);
                string received = JsonConvert.SerializeObject(new JRaw(request));
                string expected = ((Newtonsoft.Json.Linq.JToken)requestAndResponse.RequestPayload)["payload"].ToString();
                Console.WriteLine("request expected: " + expected);
                Console.WriteLine("request received: " + received);
                if (expected != received)
                {
                    Console.WriteLine("request did not match expectations");
                    Console.WriteLine("Releasing the method mutex");
                    mutex.Release();
                    return(new MethodResponse(500));
                }
                else
                {
                    int status = 200;
                    if (requestAndResponse.StatusCode != null)
                    {
                        status = (int)requestAndResponse.StatusCode;
                    }

                    byte[] responseBytes = GlueUtils.ObjectToBytes(requestAndResponse.ResponsePayload);

                    Console.WriteLine("Releasing the method mutex");
                    mutex.Release();

                    Console.WriteLine("Returning the result");
                    return(new MethodResponse(responseBytes, status));
                }
            };

            Console.WriteLine("Setting the handler");
            await client.SetMethodHandlerAsync(methodName, callback, null).ConfigureAwait(false);

            Console.WriteLine("Waiting on the method mutex");
            await mutex.WaitAsync().ConfigureAwait(false);

            Console.WriteLine("Method mutex released.  Waiting for a tiny bit.");  // Otherwise, the connection might close before the response is actually sent
            await Task.Delay(100).ConfigureAwait(false);

            Console.WriteLine("Nulling the handler");
            await client.SetMethodHandlerAsync(methodName, null, null).ConfigureAwait(false);

            Console.WriteLine("RoundtripMethodCallAsync is complete");
            return(new object());
        }
 /// <inheritdoc />
 public Task SetMethodDefaultHandlerAsync(
     MethodCallback methodHandler, object userContext)
 {
     if (!IsClosed)
     {
         _methods.AddOrUpdate("$default", (methodHandler, userContext));
     }
     return(Task.CompletedTask);
 }
Example #13
0
        public void SetMethodHandler(string methodName, MethodCallback callback)
        {
            _deviceClient.SetMethodHandler(methodName, callback, null);

            if (!_savedMethodHandlers.ContainsKey(methodName))
            {
                _savedMethodHandlers.Add(methodName, callback);
            }
        }
 /// <inheritdoc />
 public Task SetMethodHandlerAsync(string methodName,
                                   MethodCallback methodHandler, object userContext)
 {
     if (!IsClosed)
     {
         _methods.AddOrUpdate(methodName, (methodHandler, userContext));
     }
     return(Task.CompletedTask);
 }
        public async Task SetMethodHandlerAsync(string methodName, MethodCallback callback)
        {
            await _deviceClient.SetMethodHandlerAsync(methodName, callback, null);

            if (!_savedMethodHandlers.ContainsKey(methodName))
            {
                _savedMethodHandlers.Add(methodName, callback);
            }
        }
Example #16
0
        private async Task DoubleCaseRegisterHandler(string name, MethodCallback callback)
        {
            string lowerName = name.ToLower();

            _logger.Information("Registering method handler {HandlerName} and {HandlerLowerName}", name, lowerName);

            await _deviceClient.SetMethodHandlerAsync(name, callback, null);

            await _deviceClient.SetMethodHandlerAsync(lowerName, callback, null);
        }
Example #17
0
        public void GetHashData()
        {
            var snapshot = Blockchain.Singleton.GetSnapshot().Clone();
            var engine   = ApplicationEngine.Create(TriggerType.Application, null, snapshot);

            Assert.ThrowsException <ArgumentException>(() => new MethodCallback(engine, UInt160.Zero, "_test"));

            var contract = new ContractState()
            {
                Manifest = new ContractManifest()
                {
                    Permissions = new ContractPermission[0],
                    Groups      = new ContractGroup[0],
                    Trusts      = WildcardContainer <UInt160> .Create(),
                    Abi         = new ContractAbi()
                    {
                        Methods = new ContractMethodDescriptor[]
                        {
                            new ContractMethodDescriptor()
                            {
                                Name = "test", Parameters = new ContractParameterDefinition[0]
                            }
                        },
                        Events = new ContractEventDescriptor[0],
                    },
                },
                Script = new byte[] { 1, 2, 3 },
                Hash   = new byte[] { 1, 2, 3 }.ToScriptHash()
            };

            engine.LoadScript(contract.Script);
            engine.Snapshot.AddContract(contract.Hash, contract);

            Assert.ThrowsException <InvalidOperationException>(() => new MethodCallback(engine, contract.Hash, "test"));

            contract.Manifest.Permissions = new ContractPermission[] {
                new ContractPermission()
                {
                    Contract = ContractPermissionDescriptor.Create(contract.Hash),
                    Methods  = WildcardContainer <string> .Create("test")
                }
            };
            var data = new MethodCallback(engine, contract.Hash, "test");

            Assert.AreEqual(0, engine.CurrentContext.EvaluationStack.Count);
            var array = new VM.Types.Array();

            data.LoadContext(engine, array);

            Assert.AreEqual(3, engine.CurrentContext.EvaluationStack.Count);
            Assert.AreEqual("9bc4860bb936abf262d7a51f74b4304833fee3b2", engine.Pop <VM.Types.ByteString>().GetSpan().ToHexString());
            Assert.AreEqual("test", engine.Pop <VM.Types.ByteString>().GetString());
            Assert.IsTrue(engine.Pop() == array);
        }
 public async Task SetMethodHandlerAsync(string methodName, MethodCallback methodHandler, object userContext)
 {
     if (client == null)
     {
         await mockClient.SetMethodHandlerAsync(methodName, methodHandler, userContext);
     }
     else
     {
         await client.SetMethodHandlerAsync(methodName, methodHandler, userContext);
     }
 }
Example #19
0
 public async Task SetPnPCommandHandlerAsync(string commandName, MethodCallback callback, object ctx)
 {
     this.logger.LogTrace("Set Command Handler for " + commandName);
     if (isRootComponent)
     {
         await this.client.SetMethodHandlerAsync(commandName, callback, ctx);
     }
     else
     {
         await this.client.SetMethodHandlerAsync($"{this.componentName}*{commandName}", callback, ctx);
     }
 }
Example #20
0
        public async Task EnsureHubConnectionAsync(MethodCallback callback, CancellationToken cancellationToken)
        {
            IsConnInProgress = false;
            Log.Information(
                "Establishing initial connection to IoT Hub {hub} for device {device}",
                _deviceConfig.HubHostname,
                _deviceConfig.DeviceId);

            _cancellationToken    = cancellationToken;
            _directMethodCallback = callback ?? throw new ArgumentNullException(nameof(callback));

            await ConnectToHubAsync(cancellationToken);
        }
        private void SetMethodHandler(string methodName, MethodCallback methodHandler, object userContext)
        {
            var task = _deviceClient.SetMethodHandlerAsync(methodName, methodHandler, userContext);

            //The Windows App version of the Control Relay (not the background task build that runs on the Raspberry Pi)
            //waiting on the SetMethodHandlerAsync runs indefinitely. Even a cancellation token is unable to make the method
            //complete. It seems that although it doesn't complete, it *does* sucessfilly set the method handler. As the
            //WINDOWS_UWP_APP build is only used for testing, removing the wait is a workaround that seems OK for now. The
            //issue needs replicating in a smaller app and reporting to Microsoft.
#if !WINDOWS_UWP_APP
            task.Wait();
#endif
        }
Example #22
0
        public async Task SetMethodHandlerAsync(string methodName, MethodCallback callback)
        {
            try
            {
                this.inactivityTimer.Reset();
                await this.inner.SetMethodHandlerAsync(methodName, callback);
            }
            catch (Exception e)
            {
                await this.HandleException(e);

                throw;
            }
        }
Example #23
0
        public void SetupReceiveMethodHandler(string methodName = null, MethodCallback callback = null)
        {
            this.receivedMethodRequests = new List <MethodRequest>();
            MethodCallback methodCallback = callback ?? this.DefaultMethodCallback;

            if (string.IsNullOrWhiteSpace(methodName))
            {
                this.moduleClient.SetMethodDefaultHandlerAsync(methodCallback, null);
            }
            else
            {
                this.moduleClient.SetMethodHandlerAsync(methodName, methodCallback, null);
            }
        }
Example #24
0
        public async Task SetDefaultMethodHandlerAsync(MethodCallback callback)
        {
            try
            {
                this.inactivityTimer.Reset();
                await this.inner.SetDefaultMethodHandlerAsync(callback);
            }
            catch (Exception e)
            {
                await this.HandleException(e);

                throw;
            }
        }
Example #25
0
        public async Task CloseOnInactivityGetsResetTest()
        {
            // Arrange
            MethodCallback testMethodCallback = (request, context) => Task.FromResult(new MethodResponse(200));

            var sdkModuleClient = new Mock <ISdkModuleClient>(MockBehavior.Strict);

            sdkModuleClient.Setup(s => s.CloseAsync())
            .Returns(Task.CompletedTask);
            sdkModuleClient.Setup(s => s.SetDefaultMethodHandlerAsync(testMethodCallback))
            .Returns(Task.CompletedTask);

            TimeSpan idleTimeout        = TimeSpan.FromSeconds(3);
            bool     closeOnIdleTimeout = true;

            // Act
            var moduleClient = new ModuleClient(sdkModuleClient.Object, idleTimeout, closeOnIdleTimeout, Core.UpstreamProtocol.Amqp);

            Assert.True(moduleClient.IsActive);
            Assert.Equal(Core.UpstreamProtocol.Amqp, moduleClient.UpstreamProtocol);

            // Assert
            await Task.Delay(TimeSpan.FromSeconds(2));

            await moduleClient.SetDefaultMethodHandlerAsync(testMethodCallback);

            Assert.True(moduleClient.IsActive);

            await Task.Delay(TimeSpan.FromSeconds(2));

            await moduleClient.SetDefaultMethodHandlerAsync(testMethodCallback);

            Assert.True(moduleClient.IsActive);

            await Task.Delay(TimeSpan.FromSeconds(2));

            await moduleClient.SetDefaultMethodHandlerAsync(testMethodCallback);

            Assert.True(moduleClient.IsActive);

            Assert.True(moduleClient.IsActive);
            await Task.Delay(TimeSpan.FromSeconds(5));

            Assert.False(moduleClient.IsActive);
            sdkModuleClient.Verify(s => s.CloseAsync(), Times.Once);
        }
        // Tests_SRS_DEVICECLIENT_10_004: [ The deviceMethods property shall be deleted if the last delegate has been removed. ]
        // Tests_SRS_DEVICECLIENT_10_006: [ The SetMethodHandler shall DisableMethodsAsync when the last delegate has been removed. ]
        public async Task DeviceClient_SetMethodHandler_UnsetLastMethodHandler_With_SetMethodHandler()
        {
            string       connectionString = "HostName=acme.azure-devices.net;SharedAccessKeyName=AllAccessKey;DeviceId=dumpy;SharedAccessKey=CQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8=";
            DeviceClient deviceClient     = DeviceClient.CreateFromConnectionString(connectionString);

            var innerHandler = Substitute.For <IDelegatingHandler>();

            deviceClient.InnerHandler = innerHandler;

            bool           methodCallbackCalled    = false;
            string         actualMethodName        = string.Empty;
            string         actualMethodBody        = string.Empty;
            object         actualMethodUserContext = null;
            MethodCallback methodCallback          = (methodRequest, userContext) =>
            {
                actualMethodName        = methodRequest.Name;
                actualMethodBody        = methodRequest.DataAsJson;
                actualMethodUserContext = userContext;
                methodCallbackCalled    = true;
                return(Task.FromResult(new MethodResponse(new byte[0], 200)));
            };

            string methodName        = "TestMethodName";
            string methodUserContext = "UserContext";
            string methodBody        = "{\"grade\":\"good\"}";

            deviceClient.SetMethodHandler(methodName, methodCallback, methodUserContext);
            await deviceClient.OnMethodCalled(new MethodRequestInternal(methodName, "fakeRequestId", new MemoryStream(Encoding.UTF8.GetBytes(methodBody))));

            await innerHandler.Received().EnableMethodsAsync(Arg.Any <CancellationToken>());

            Assert.IsTrue(methodCallbackCalled);
            Assert.AreEqual(methodName, actualMethodName);
            Assert.AreEqual(methodBody, actualMethodBody);
            Assert.AreEqual(methodUserContext, actualMethodUserContext);

            methodCallbackCalled = false;
            await deviceClient.SetMethodHandlerAsync(methodName, null, null);

            await deviceClient.OnMethodCalled(new MethodRequestInternal(methodName, "fakeRequestId", new MemoryStream(Encoding.UTF8.GetBytes(methodBody))));

            await innerHandler.Received().DisableMethodsAsync(Arg.Any <CancellationToken>());

            Assert.IsFalse(methodCallbackCalled);
        }
        public async Task RegisterDirectMethodAsync(DirectMethodSetting directMethod)
        {
            if (_directMethodDictionary == null)
            {
                _directMethodDictionary = new Dictionary <string, MethodCallback>();
            }

            var methodName = directMethod.DirectMethodName;

            if (!string.IsNullOrEmpty(methodName) && !_directMethodDictionary.ContainsKey(methodName))
            {
                MethodCallback callbackMethod = async delegate(MethodRequest methodRequest, object userContext)
                {
                    var logOutputMessage = string.Format(_translationsService.GetString("MethodExecuting"),
                                                         methodName,
                                                         Environment.NewLine);
                    _consoleLoggerService.Log(value: logOutputMessage,
                                              logType: ConsoleLogTypes.DirectMethodCommunication);

                    await Task.Delay(TimeSpan.FromSeconds(directMethod.Delay));

                    logOutputMessage = string.Format(_translationsService.GetString("MethodExecuted"),
                                                     methodName,
                                                     Environment.NewLine);
                    _consoleLoggerService.Log(value: logOutputMessage,
                                              logType: ConsoleLogTypes.DirectMethodCommunication);

                    return(new MethodResponse(200));
                };

                await _deviceClient.SetMethodHandlerAsync(methodName : methodName, callbackMethod, null);

                _directMethodDictionary.Add(methodName, callbackMethod);

                var logMessage = string.Format(_translationsService.GetString("MethodRegistered"),
                                               methodName,
                                               Environment.NewLine);
                _consoleLoggerService.Log(value: logMessage,
                                          logType: ConsoleLogTypes.DirectMethodCommunication);
            }
        }
        public void NonceRequestEnsureNonEmpty()
        {
            Func <Task> asyncMethod = async() =>
            {
                var connectionString = await GetTestDeviceConnectionString();

                var deviceClient = DeviceClient.CreateFromConnectionString(connectionString, Microsoft.Azure.Devices.Client.TransportType.Mqtt);

                var            nonceReady             = new AutoResetEvent(/*init=*/ false);
                string         actualNonce            = string.Empty;
                MethodCallback GetReportMethodHandler = (MethodRequest methodRequest, object userContext) =>
                {
                    var data = JsonConvert.DeserializeObject <DeviceHealthAttestationDataContract.GetReportMethodParam>(methodRequest.DataAsJson);
                    actualNonce = data.Nonce;
                    TestContext.WriteLine($"Got Nonce:{actualNonce}");
                    nonceReady.Set();

                    var response = new { response = "succeeded", reason = "" };
                    return(Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(response)), 0)));
                };
                await deviceClient.SetMethodHandlerAsync(DeviceHealthAttestationDataContract.GetReportMethodName, GetReportMethodHandler, null);

                var properties = new Dictionary <string, string>();
                properties.Add("MessageType", DeviceHealthAttestationDataContract.NonceRequestTag);
                await deviceClient.SendMessageAsync("", properties);

                Assert.IsTrue(nonceReady.WaitOne(5000));

                var nonceFromTable = await NonceCloudTable.Instance.GetNonceForDeviceAsync(TestDeviceId);

                await NonceCloudTable.Instance.DeleteNonceForDeviceAsync(TestDeviceId);

                Assert.AreEqual(nonceFromTable, actualNonce);
            };

            asyncMethod().Wait();
        }
Example #29
0
 public async Task RegisterDirectMethodAsync(MethodCallback methodHandler)
 {
     await deviceClient.SetMethodHandlerAsync(methodHandler.Method.Name, methodHandler, null);
 }
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
        public async Task SetMethodHandlerAsync(string methodName, MethodCallback methodHandler, object userContext)
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
        {
            MethodSubscription = methodName;
            MethodCallback     = methodHandler;
        }
Example #31
0
 /// <summary>
 /// Creates a new LayeCallback using the given method.
 /// </summary>
 /// <param name="callback"></param>
 public LayeCallback(MethodCallback method)
     : base(TYPE)
 {
     callback = method;
 }
Example #32
0
 /// <summary>
 /// Creates a new LayeCallback using the given function.
 /// </summary>
 /// <param name="callback"></param>
 public LayeCallback(FunctionCallback function)
     : base(TYPE)
 {
     callback = (state, ths, args) => function(state, args);
 }