private async void SendCommandAsync(string commandName, string data, int delay) { // this.rootPage.NotifyUser($"Command Started: {commandName}", NotifyType.StatusMessage); while (!this.commandToken.IsCancellationRequested) { int duration = 100; try { Tuple <string, string, int> cmd; if (this.commandQueue.TryDequeue(out cmd)) { Func <Task> appFunction = () => this.svcHelper.SendCommandAsync(App.AppData.ConnectedAucovei.Id, cmd.Item1, new KeyValuePair <string, string>("data", cmd.Item2)); await AzureRetryHelper.OperationWithBasicRetryAsync(appFunction); duration = cmd.Item3; } } catch (Exception ex) { Debug.Write(ex); } finally { await Task.Delay(TimeSpan.FromMilliseconds(duration)); } } }
public async void OperationWithBasicRetryAsyncRetryTest_IotHubException() { count = 0; await AzureRetryHelper.OperationWithBasicRetryAsync(async() => await this.Function(new IotHubException("MSG", true))); Assert.Equal(count, 2); }
public async Task SendCommand(string deviceId, bool isSimuated, dynamic command) { ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(_iotHubConnectionString); byte[] commandAsBytes = null; if (isSimuated) { commandAsBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(command)); } else { JObject cmdObject = new JObject(); cmdObject.Add("Name", command.Name); cmdObject.Add("Parameters", command.Parameters); string cmdstr = cmdObject.ToString().Replace("\r\n", string.Empty).Replace(" ", string.Empty); commandAsBytes = Encoding.UTF8.GetBytes(cmdstr); } var notificationMessage = new Message(commandAsBytes); notificationMessage.Ack = DeliveryAcknowledgement.Full; notificationMessage.MessageId = command.MessageId; await AzureRetryHelper.OperationWithBasicRetryAsync(async() => await serviceClient.SendAsync(deviceId, notificationMessage)); await serviceClient.CloseAsync(); }
public async Task SignalRejectedCommand(DeserializableCommand command) { if (command == null) { throw new ArgumentNullException("command"); } Debug.Assert( !string.IsNullOrEmpty(command.LockToken), "command.LockToken is a null reference or empty string."); await AzureRetryHelper.OperationWithBasicRetryAsync( async() => { try { await _deviceClient.RejectAsync(command.LockToken); } catch (Exception ex) { _logger.LogError( "{0}{0}*** Exception: Reject Command ***{0}{0}Command Name: {1}{0}Command: {2}{0}Exception: {3}{0}{0}", Console.Out.NewLine, command.CommandName, command.CommandHistory, ex); } }); }
public async void OperationWithBasicRetryAsyncTest_HttpRequestException() { count = 0; await AzureRetryHelper.OperationWithBasicRetryAsync(async() => await this.Function(new HttpRequestException())); Assert.Equal(count, 2); }
/// <summary> /// Adds the provided device to the IoT hub with the provided security keys /// </summary> /// <param name="device"></param> /// <param name="securityKeys"></param> /// <returns></returns> public async Task <DeviceModel> AddDeviceAsync(DeviceModel device, SecurityKeys securityKeys) { var iotHubDevice = new Device(device.DeviceProperties.DeviceID) { Authentication = new AuthenticationMechanism { SymmetricKey = new SymmetricKey { PrimaryKey = securityKeys.PrimaryKey, SecondaryKey = securityKeys.SecondaryKey } } }; await AzureRetryHelper.OperationWithBasicRetryAsync(async() => await this._deviceManager.AddDeviceAsync(iotHubDevice)); if (device.Twin?.Tags.Count > 0 || device.Twin?.Properties.Desired.Count > 0) { device.Twin.ETag = "*"; await this._deviceManager.UpdateTwinAsync(device.DeviceProperties.DeviceID, device.Twin); } return(device); }
public async Task SendCommand(string deviceId, CommandHistory command) { if (command.DeliveryType == DeliveryType.Message) { var commandAsBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(command)); var notificationMessage = new Message(commandAsBytes); notificationMessage.Ack = DeliveryAcknowledgement.Full; notificationMessage.MessageId = command.MessageId; await AzureRetryHelper.OperationWithBasicRetryAsync(async() => await this._deviceManager.SendAsync(deviceId, notificationMessage)); await this._deviceManager.CloseAsyncDevice(); } else { var method = new CloudToDeviceMethod(command.Name); method.SetPayloadJson(JsonConvert.SerializeObject(command.Parameters)); var result = await AzureRetryHelper.OperationWithBasicRetryAsync(async() => await this._deviceManager.InvokeDeviceMethodAsync(deviceId, method)); command.Result = result.Status.ToString(); command.ReturnValue = result.GetPayloadAsJson(); command.UpdatedTime = DateTime.UtcNow; } }
/// <summary> /// Sends an event to IoT Hub using the provided eventId GUID /// </summary> /// <param name="device"></param> /// <param name="eventId"></param> /// <param name="eventData"></param> /// <returns></returns> public async Task SendEventAsync(Guid eventId, dynamic eventData) { byte[] bytes; string objectType = this.GetObjectType(eventData); var objectTypePrefix = _configurationProvider.GetConfigurationSettingValue("ObjectTypePrefix"); if (!string.IsNullOrWhiteSpace(objectType) && !string.IsNullOrEmpty(objectTypePrefix)) { eventData.ObjectType = objectTypePrefix + objectType; } // sample code to trace the raw JSON that is being sent //string rawJson = JsonConvert.SerializeObject(eventData); //Trace.TraceInformation(rawJson); bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(eventData)); var message = new Client.Message(bytes); message.Properties["EventId"] = eventId.ToString(); await AzureRetryHelper.OperationWithBasicRetryAsync(async() => { try { await _deviceClient.SendEventAsync(message); } catch (Exception ex) { _logger.LogError($"SendEventAsync failed, device: {_device.DeviceID}, exception: {ex.Message}"); } }); }
public async void OperationWithBasicRetryAsyncRetryTest_Exception() { count = 0; await Assert.ThrowsAsync <Exception>( async() => await AzureRetryHelper.OperationWithBasicRetryAsync(async() => await this.Function(new Exception()))); }
// send a message through the device client through the iot hub private async Task SendMessageAsync(string messageJson, DeviceClient deviceClient) { await AzureRetryHelper.OperationWithBasicRetryAsync(async() => { var message = new Message(Encoding.UTF8.GetBytes(messageJson)); await deviceClient.SendEventAsync(message); AddLineToTextbox(SentMessagesTextbox, messageJson); }); }
public async Task UpdateDeviceEnabledStatusAsync(string deviceId, bool isEnabled) { Azure.Devices.Device iotHubDevice = await AzureRetryHelper.OperationWithBasicRetryAsync <Azure.Devices.Device>(async() => await _deviceManager.GetDeviceAsync(deviceId)); iotHubDevice.Status = isEnabled ? DeviceStatus.Enabled : DeviceStatus.Disabled; await AzureRetryHelper.OperationWithBasicRetryAsync(async() => await _deviceManager.UpdateDeviceAsync(iotHubDevice)); }
public async Task <Device> UpdateDeviceEnabledStatusAsync(string deviceId, bool isEnabled) { var iotHubDevice = await AzureRetryHelper.OperationWithBasicRetryAsync(async() => await this._deviceManager.GetDeviceAsync(deviceId)); iotHubDevice.Status = isEnabled ? DeviceStatus.Enabled : DeviceStatus.Disabled; return(await AzureRetryHelper.OperationWithBasicRetryAsync(async() => await this._deviceManager.UpdateDeviceAsync(iotHubDevice))); }
public async void OperationWithBasicRetryAsyncRetryTest_WebException() { count = 0; var response = new Mock <HttpWebResponse>(); var ex = new WebException("message", new Exception(), WebExceptionStatus.Timeout, response.Object); await AzureRetryHelper.OperationWithBasicRetryAsync(async() => await this.Function(ex)); Assert.Equal(count, 2); }
private async Task SendMessageAsync(string messageJson, string schema) { await AzureRetryHelper.OperationWithBasicRetryAsync(async() => { var message = new Message(Encoding.UTF8.GetBytes(messageJson)); message.Properties.Add("$$CreationTimeUtc", DateTime.UtcNow.ToString()); message.Properties.Add("$$MessageSchema", schema); message.Properties.Add("$$ContentType", "JSON"); await Client.SendEventAsync(message); Console.WriteLine($"{Id}.{nameof(SendMessageAsync)}: {messageJson}"); }); }
public async Task SendCommand(string deviceId, CommandHistory command) { var commandAsBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(command)); var notificationMessage = new Message(commandAsBytes); notificationMessage.Ack = DeliveryAcknowledgement.Full; notificationMessage.MessageId = command.MessageId; await AzureRetryHelper.OperationWithBasicRetryAsync(async() => await this._deviceManager.SendAsync(deviceId, notificationMessage)); await this._deviceManager.CloseAsyncDevice(); }
/// <summary> /// Attempts to remove the device from the IoT Hub and eats any exceptions that are thrown during the /// delete process. /// </summary> /// <param name="deviceId">ID of the device to remove</param> /// <returns>true if the remove was successful and false if the remove was not successful</returns> public async Task <bool> TryRemoveDeviceAsync(string deviceId) { try { await AzureRetryHelper.OperationWithBasicRetryAsync(async() => await this._deviceManager.RemoveDeviceAsync(deviceId)); } catch (Exception) { // swallow any exceptions that happen during this remove return(false); } return(true); }
/// <summary> /// Sends a fire and forget command to the device /// </summary> /// <param name="deviceId"></param> /// <param name="command"></param> /// <returns></returns> public async Task SendCommand(string deviceId, dynamic command) { ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(_iotHubConnectionString); byte[] commandAsBytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(command)); var notificationMessage = new Message(commandAsBytes); notificationMessage.Ack = DeliveryAcknowledgement.Full; notificationMessage.MessageId = command.MessageId; await AzureRetryHelper.OperationWithBasicRetryAsync(async() => await serviceClient.SendAsync(deviceId, notificationMessage)); await serviceClient.CloseAsync(); }
private async Task <string> PerformRestCallAsync(string endpoint, string httpVerb, DocDbResourceType resourceType, string resourceId, string body) { using (WebClient webClient = new WebClient()) { webClient.Encoding = System.Text.Encoding.UTF8; webClient.Headers.Add(CONTENT_TYPE_HEADER_KEY, APPLICATION_JSON); webClient.Headers.Add(ACCEPT_HEADER_KEY, APPLICATION_JSON); webClient.Headers.Add(VERSION_HEADER_KEY, X_MS_VERSION); // https://msdn.microsoft.com/en-us/library/azure/dn783368.aspx // The date of the request, as specified in RFC 1123. The date format is expressed in // Coordinated Universal Time (UTC), for example. Fri, 08 Apr 2015 03:52:31 GMT. string formattedTimeString = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture).ToLowerInvariant(); webClient.Headers.Add(DATE_HEADER_KEY, formattedTimeString); webClient.Headers.Add(AUTHORIZATION_HEADER_KEY, GetAuthorizationToken(httpVerb, DocDbResourceTypeHelper.GetResourceTypeString(resourceType), resourceId, formattedTimeString)); return(await AzureRetryHelper.OperationWithBasicRetryAsync <string>(async() => await webClient.UploadStringTaskAsync(endpoint, httpVerb, body))); } }
/// <summary> /// Retrieves the next message from the IoT Hub /// </summary> /// <param name="device">The device to retieve the IoT Hub message for</param> /// <returns>Returns a DeserializableCommand that wraps the byte array of the message from IoT Hub</returns> public async Task <DeserializableCommand> ReceiveAsync() { Client.Message message = await AzureRetryHelper.OperationWithBasicRetryAsync( async() => { Exception exp; Client.Message msg; exp = null; msg = null; try { msg = await _deviceClient.ReceiveAsync(); } catch (Exception exception) { exp = exception; } if (exp != null) { _logger.LogError( "{0}{0}*** Exception: ReceiveAsync ***{0}{0}{1}{0}{0}", Console.Out.NewLine, exp); if (msg != null) { await _deviceClient.AbandonAsync(msg); } } return(msg); }); if (message != null) { return(new DeserializableCommand(message)); } return(null); }
/// <summary> /// Adds the provided device to the IoT hub with the provided security keys /// </summary> /// <param name="device"></param> /// <param name="securityKeys"></param> /// <returns></returns> public async Task <DeviceModel> AddDeviceAsync(DeviceModel device, SecurityKeys securityKeys) { var iotHubDevice = new Device(device.DeviceProperties.DeviceID); var authentication = new AuthenticationMechanism { SymmetricKey = new SymmetricKey { PrimaryKey = securityKeys.PrimaryKey, SecondaryKey = securityKeys.SecondaryKey } }; iotHubDevice.Authentication = authentication; await AzureRetryHelper.OperationWithBasicRetryAsync(async() => await this._deviceManager.AddDeviceAsync(iotHubDevice)); return(device); }
/// <summary> /// Adds the provided device to the IoT hub with the provided security keys /// </summary> /// <param name="device"></param> /// <param name="securityKeys"></param> /// <returns></returns> public async Task <dynamic> AddDeviceAsync(dynamic device, SecurityKeys securityKeys) { Azure.Devices.Device iotHubDevice = new Azure.Devices.Device(DeviceSchemaHelper.GetDeviceID(device)); var authentication = new AuthenticationMechanism { SymmetricKey = new SymmetricKey { PrimaryKey = securityKeys.PrimaryKey, SecondaryKey = securityKeys.SecondaryKey } }; iotHubDevice.Authentication = authentication; await AzureRetryHelper.OperationWithBasicRetryAsync <Azure.Devices.Device>(async() => await _deviceManager.AddDeviceAsync(iotHubDevice)); return(device); }
/// <summary> /// Attempts to add the device as a new device and swallows all exceptions /// </summary> /// <param name="oldIotHubDevice">The IoT Hub Device to add back into the IoT Hub</param> /// <returns>true if the device was added successfully, false if there was a problem adding the device</returns> public async Task <bool> TryAddDeviceAsync(Device oldIotHubDevice) { try { // the device needs to be added as a new device as the one that was saved // has an eTag value that cannot be provided when registering a new device var newIotHubDevice = new Device(oldIotHubDevice.Id) { Authentication = oldIotHubDevice.Authentication, Status = oldIotHubDevice.Status }; await AzureRetryHelper.OperationWithBasicRetryAsync(async() => await this._deviceManager.AddDeviceAsync(newIotHubDevice)); } catch (Exception) { return(false); } return(true); }
/// <summary> /// Sends an event to IoT Hub using the provided eventId GUID /// </summary> /// <param name="eventId"></param> /// <param name="eventData"></param> /// <returns></returns> public async Task SendEventAsync(Guid eventId, dynamic eventData) { string objectType = this.GetObjectType(eventData); var objectTypePrefix = _configurationProvider.GetConfigurationSettingValue("ObjectTypePrefix"); if (!string.IsNullOrWhiteSpace(objectType) && !string.IsNullOrEmpty(objectTypePrefix)) { eventData.ObjectType = objectTypePrefix + objectType; } // sample code to trace the raw JSON that is being sent string rawJson = JsonConvert.SerializeObject(eventData); Trace.TraceInformation("Sending message: " + rawJson); byte[] bytes = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(eventData)); var message = new Client.Message(bytes); message.Properties["EventId"] = eventId.ToString(); await AzureRetryHelper.OperationWithBasicRetryAsync(async() => { try { await _deviceClient.SendEventAsync(message); } catch (Exception ex) { _logger.LogError( "{0}{0}*** Exception: SendEventAsync ***{0}{0}EventId: {1}{0}Event Data: {2}{0}Exception: {3}{0}{0}", Console.Out.NewLine, eventId, eventData, ex); } }); }
public async Task <DeserializableCommand> ReceiveAsync() { Client.Message message = await AzureRetryHelper.OperationWithBasicRetryAsync( async() => { try { return(await _deviceClient.ReceiveAsync()); } catch (Exception ex) { _logger.LogError($"ReceiveAsync failed, device: {_device.DeviceID}, exception: {ex.Message}"); return(null); } }); if (message != null) { return(new DeserializableCommand(message)); } return(null); }
public async Task SignalRejectedCommand(DeserializableCommand command) { if (command == null) { throw new ArgumentNullException("command"); } Debug.Assert( !string.IsNullOrEmpty(command.LockToken), "command.LockToken is a null reference or empty string."); await AzureRetryHelper.OperationWithBasicRetryAsync( async() => { try { await _deviceClient.RejectAsync(command.LockToken); } catch (Exception ex) { _logger.LogError($"Reject Command failed, device: {_device.DeviceID}, exception: {ex.Message}"); } }); }
public async Task RemoveDeviceAsync(string deviceId) { await AzureRetryHelper.OperationWithBasicRetryAsync(async() => await this._deviceManager.RemoveDeviceAsync(deviceId)); }
public async Task <Device> GetIotHubDeviceAsync(string deviceId) { return(await AzureRetryHelper.OperationWithBasicRetryAsync(async() => await this._deviceManager.GetDeviceAsync(deviceId))); }
private async Task <DocDbRestQueryResult> QueryDocDbInternal(string endpoint, string queryString, Dictionary <string, Object> queryParams, DocDbResourceType resourceType, string resourceId, int pageSize = -1, string continuationToken = null) { if (string.IsNullOrWhiteSpace(endpoint)) { throw new ArgumentException("endpoint is null or whitespace"); } if (string.IsNullOrWhiteSpace(queryString)) { throw new ArgumentException("queryString is null or whitespace"); } using (WebClient client = new WebClient()) { client.Encoding = System.Text.Encoding.UTF8; client.Headers.Add(CONTENT_TYPE_HEADER_KEY, APPLICATION_QUERY_JSON); client.Headers.Add(ACCEPT_HEADER_KEY, APPLICATION_JSON); client.Headers.Add(VERSION_HEADER_KEY, X_MS_VERSION); // https://msdn.microsoft.com/en-us/library/azure/dn783368.aspx // The date of the request, as specified in RFC 1123. The date format is expressed in // Coordinated Universal Time (UTC), for example. Fri, 08 Apr 2015 03:52:31 GMT. string formattedTimeString = DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture).ToLowerInvariant(); client.Headers.Add(DATE_HEADER_KEY, formattedTimeString); client.Headers.Add(AUTHORIZATION_HEADER_KEY, GetAuthorizationToken(POST_VERB, DocDbResourceTypeHelper.GetResourceTypeString(resourceType), resourceId, formattedTimeString)); client.Headers.Add(IS_QUERY_HEADER_KEY, "true"); if (pageSize >= 0) { client.Headers.Add(MAX_ITEMS_HEADER_KEY, pageSize.ToString()); } if (continuationToken != null && continuationToken.Length > 0) { client.Headers.Add(CONTINUATION_HEADER_KEY, continuationToken); } var body = new JObject(); body.Add("query", queryString); if (queryParams != null && queryParams.Count > 0) { var paramsArray = new JArray(); foreach (string key in queryParams.Keys) { var param = new JObject(); param.Add("name", key); param.Add("value", JToken.FromObject(queryParams[key])); paramsArray.Add(param); } body.Add("parameters", paramsArray); } var result = new DocDbRestQueryResult(); string response = await AzureRetryHelper.OperationWithBasicRetryAsync <string>(async() => await client.UploadStringTaskAsync(endpoint, POST_VERB, body.ToString())); JObject responseJobj = JObject.Parse(response); JToken jsonResultSet = responseJobj.GetValue(DocDbResourceTypeHelper.GetResultSetKey(resourceType)); if (jsonResultSet != null) { result.ResultSet = (JArray)jsonResultSet; } WebHeaderCollection responseHeaders = client.ResponseHeaders; string count = responseHeaders[ITEM_COUNT_RESPONSE_HEADER_KEY]; if (!string.IsNullOrEmpty(count)) { result.TotalResults = int.Parse(count); } result.ContinuationToken = responseHeaders[CONTINUATION_HEADER_KEY]; return(result); } }