Example #1
0
        private async void sendMessageToDeviceButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (checkBox1.Checked)
                {
                    if(String.IsNullOrEmpty(textBoxMessage.Text))
                    {
                        cloudToDeviceMessage = DateTime.Now.ToLocalTime().ToString();
                    }
                    else
                    {
                        cloudToDeviceMessage = DateTime.Now.ToLocalTime() + " - " + textBoxMessage.Text;
                    }
                }
                else
                {
                    cloudToDeviceMessage = textBoxMessage.Text;
                }

                ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(activeIoTHubConnectionString);

                var serviceMessage = new Microsoft.Azure.Devices.Message(Encoding.ASCII.GetBytes(cloudToDeviceMessage));
                serviceMessage.Ack = DeliveryAcknowledgement.Full;
                serviceMessage.MessageId = Guid.NewGuid().ToString();
                await serviceClient.SendAsync(deviceIDsComboBoxForCloudToDeviceMessage.SelectedItem.ToString(), serviceMessage);

                messagesTextBox.Text += String.Format("Sent to Device ID: [{0}], Message:\"{1}\", message Id: {2}\n", deviceIDsComboBoxForCloudToDeviceMessage.SelectedItem.ToString(), cloudToDeviceMessage, serviceMessage.MessageId);

                await serviceClient.CloseAsync();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Example #2
0
        static async Task MainAsync(CancellationToken token)
        {
            EventHubClient   eventHubClient   = null;
            EventHubReceiver eventHubReceiver = null;

            eventHubClient = EventHubClient.CreateFromConnectionString(Properties.Settings.Default.IoTHubConnectionString, "messages/events");
            int    eventHubPartitionsCount = eventHubClient.GetRuntimeInformation().PartitionCount;
            string partition = EventHubPartitionKeyResolver.ResolveToPartition(Properties.Settings.Default.IoTDeviceId, eventHubPartitionsCount);

            eventHubReceiver = eventHubClient.GetConsumerGroup(Properties.Settings.Default.ConsumerGroupName).CreateReceiver(partition, DateTime.Now);

            while (true)
            {
                try
                {
                    EventData eventData = eventHubReceiver.Receive(TimeSpan.FromSeconds(1));

                    if (eventData != null)
                    {
                        string data = Encoding.UTF8.GetString(eventData.GetBytes());
                        string connectionDeviceId = eventData.SystemProperties["iothub-connection-device-id"].ToString();

                        if (string.CompareOrdinal(Properties.Settings.Default.IoTDeviceId, connectionDeviceId) == 0)
                        {
                            // Get RSSI reading from message
                            int rssi = 0;

                            if (rssi < RANGE)
                            {
                                if ((DateTime.Now - previousEvent).TotalSeconds >= RANGEINTERVAL)
                                {
                                    previousEvent = DateTime.Now;
                                    string cloudToDeviceMessage = "{\"message\":\"flash\"}";

                                    ServiceClient serviceClient  = ServiceClient.CreateFromConnectionString(Properties.Settings.Default.IoTHubConnectionString);
                                    var           serviceMessage = new Microsoft.Azure.Devices.Message(Encoding.ASCII.GetBytes(cloudToDeviceMessage));
                                    serviceMessage.Ack       = DeliveryAcknowledgement.Full;
                                    serviceMessage.MessageId = Guid.NewGuid().ToString();
                                    await serviceClient.SendAsync(Properties.Settings.Default.IoTDeviceId, serviceMessage);

                                    System.Threading.Thread.Sleep(1000);
                                    await serviceClient.CloseAsync();

                                    Console.WriteLine("Sent flash message");

                                    // Send Twilio message
                                    string AccountSid = Properties.Settings.Default.TwilioAccountSid;
                                    string AuthToken  = Properties.Settings.Default.TwilioAuthToken;
                                    var    twilio     = new TwilioRestClient(AccountSid, AuthToken);

                                    var message = twilio.SendMessage(Properties.Settings.Default.TwilioNumber, Properties.Settings.Default.NurseNumber, "Patient arrived in area");
                                    Console.WriteLine("SMS message sent. Sid: " + message.Sid);
                                }
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("An error occured. Error was " + ex.Message);
                }
            }
        }
Example #3
0
        public override async Task SendAsync(EventMessage message)
        {
            AuditRecord record = null;

            byte[] payload = null;

            try
            {
                payload = GetPayload(message);
                if (payload == null)
                {
                    await logger?.LogWarningAsync(
                        $"Subscription '{metadata.SubscriptionUriString}' message not written to iot hub sink because message is null.");

                    return;
                }

                if (serviceClient != null)
                {
                    if (!string.IsNullOrEmpty(methodName))
                    {
                        if (message.ContentType == "application/json")
                        {
                            CloudToDeviceMethod method = new CloudToDeviceMethod(methodName);
                            method.SetPayloadJson(Encoding.UTF8.GetString(payload));
                            await serviceClient.InvokeDeviceMethodAsync(deviceId, method);

                            record = new MessageAuditRecord(message.MessageId,
                                                            $"iothub://{uri.Authority}", "IoTHub", "IoTHub", payload.Length,
                                                            MessageDirectionType.Out, true, DateTime.UtcNow);
                        }
                        else
                        {
                            await logger?.LogWarningAsync(
                                $"Subscription '{metadata.SubscriptionUriString}' cannot send IoTHub direct method sink because content-type is not JSON.");

                            record = new MessageAuditRecord(message.MessageId,
                                                            string.Format("iothub://{0}", uri.Authority), "IoTHub", "IoTHub", payload.Length,
                                                            MessageDirectionType.Out, false, DateTime.UtcNow,
                                                            string.Format(
                                                                "Cannot send IoTHub device {0} direct message because content-type is not JSON.",
                                                                deviceId));
                        }
                    }
                    else
                    {
                        Message serviceMessage = new Message(payload)
                        {
                            ContentType = message.ContentType,
                            MessageId   = message.MessageId
                        };

                        if (!string.IsNullOrEmpty(propertyName))
                        {
                            serviceMessage.Properties.Add(propertyName, propertyValue);
                        }

                        await serviceClient.SendAsync(deviceId, serviceMessage);

                        record = new MessageAuditRecord(message.MessageId, string.Format("iothub://{0}", uri.Authority),
                                                        "IoTHub", "IoTHub", payload.Length, MessageDirectionType.Out, true, DateTime.UtcNow);
                    }
                }
                else if (deviceClient != null)
                {
                    Microsoft.Azure.Devices.Client.Message msg = new Microsoft.Azure.Devices.Client.Message(payload)
                    {
                        ContentType = message.ContentType,
                        MessageId   = message.MessageId
                    };

                    if (!string.IsNullOrEmpty(propertyName))
                    {
                        msg.Properties.Add(propertyName, propertyValue);
                    }

                    await deviceClient.SendEventAsync(msg);

                    record = new MessageAuditRecord(message.MessageId, $"iothub://{uri.Authority}",
                                                    "IoTHub", "IoTHub", payload.Length, MessageDirectionType.Out, true, DateTime.UtcNow);
                }
                else
                {
                    await logger?.LogWarningAsync(
                        $"Subscription '{metadata.SubscriptionUriString}' IoTHub sink has neither service or device client.");

                    record = new MessageAuditRecord(message.MessageId, $"iothub://{uri.Authority}",
                                                    "IoTHub", "IoTHub", payload.Length, MessageDirectionType.Out, false, DateTime.UtcNow,
                                                    "IoTHub subscription has neither service or device client");
                }
            }
            catch (Exception ex)
            {
                await logger?.LogErrorAsync(ex,
                                            $"Subscription '{metadata.SubscriptionUriString}' message not written to IoTHub sink.");

                record = new MessageAuditRecord(message.MessageId, $"iothub://{uri.Authority}",
                                                "IoTHub", "IoTHub", payload.Length, MessageDirectionType.Out, false, DateTime.UtcNow, ex.Message);
            }
            finally
            {
                if (record != null && message.Audit)
                {
                    await auditor?.WriteAuditRecordAsync(record);
                }
            }
        }
        public ActionResult Purchase(string id)
        {
            var stock = db.Stocks.Include("Product").FirstOrDefault(x => x.StockID.ToString() == id);

            if (stock == null)
            {
                throw new Exception("Errore!! Lo Stock selezionato non esiste");
            }

            var username = User.Identity.GetUserName();

            var machineReservation = new MachineReservation
            {
                ConsumerID           = username,
                IsDeleted            = false,
                IsLocked             = false,
                MachineID            = stock.MachineID,
                MachineReservationID = Guid.NewGuid(),
                RequestDate          = DateTime.Now,
                Status = MachineReservationStatus.Reserved
            };

            var transactionDetail = new TransactionDetail
            {
                ProductID           = stock.ProductID,
                Quantity            = 1,
                TotalAmount         = stock.Product.Price,
                TransactionDetailID = Guid.NewGuid(),
                UnitPrice           = stock.Product.Price
            };

            var user = db.Users.FirstOrDefault(x => x.UserName == username);

            var shippingDetail = new ShippingDetail {
                Address    = "Via Cantalupo, 4",
                City       = "Cesenatico",
                Email      = user.Email,
                FirstName  = user.FirstName,
                LastName   = user.LastName,
                Mobile     = user.PhoneNumber,
                PostalCode = "47042",
                Province   = "FC",
                ShippingID = Guid.NewGuid()
            };

            var transaction = new Transaction
            {
                CashChannel        = CashChannelType.Unknown,
                ConsumerID         = username,
                MachineID          = stock.MachineID,
                MachineReservation = machineReservation,
                Status             = TransactionStatus.InProgress,
                TotalAmount        = stock.Product.Price,
                TransactionDate    = DateTime.Now,
                Type              = TransactionType.Totem,
                TransactionID     = Guid.NewGuid(),
                TransactionDetail = transactionDetail,
                ShippingDetail    = shippingDetail
            };

            db.Transactions.Add(transaction);

            db.SaveChanges();

            MessagesRepository _messageRepository = new MessagesRepository();

            _messageRepository.SetToReaded();

            // Invoke the direct method on the device, passing the payload
            serviceClient = ServiceClient.CreateFromConnectionString(connectionString);

            // Invoke the direct method asynchronously and get the response from the simulated device.
            var getRfidMessage = new Microsoft.Azure.Devices.Message(Encoding.ASCII.GetBytes("{ \"Method\": \"Purchase\", \"transactionid\": \"" + transaction.TransactionID + "\", \"total\": \"" + stock.Product.Price + "\", \"selection\": \"" + stock.MachineKeyBoardNumber + "\" }"));

            serviceClient.SendAsync("raspberry", getRfidMessage);

            return(View(stock));
        }
Example #5
0
 private async static Task SendCloudToDeviceMessageAsync(string podaci)
 {
     var commandMessage = new Microsoft.Azure.Devices.Message(Encoding.ASCII.GetBytes(podaci));
     await serviceClient.SendAsync("RPiUWPKodMustafe", commandMessage);
 }
        private async void sendMessageToDeviceButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (checkBox1.Checked)
                {
                    if (string.IsNullOrEmpty(textBoxMessage.Text))
                    {
                        cloudToDeviceMessage = DateTime.Now.ToLocalTime().ToString();
                    }
                    else
                    {
                        if (isInJsonFormat(textBoxMessage.Text)) //any JSON format string should start with "{" || "[" and end with "}" || "]"
                        {
                            JValue date = new JValue(DateTime.Now.ToLocalTime());
                            JToken t    = JToken.Parse(textBoxMessage.Text);
                            if (t.Type.Equals(JTokenType.Object)) //JSON string is of type Object
                            {
                                JObject o = (JObject)t;
                                o.Add("timestamp", date);
                                cloudToDeviceMessage = o.ToString();
                            }
                            else if (t.Type.Equals(JTokenType.Array)) //JSON string is of type Array
                            {
                                JObject o = new JObject();
                                o.Add("message", (JArray)t);
                                o.Add("timestamp", date);
                                cloudToDeviceMessage = o.ToString();
                            }
                        }
                        else
                        {
                            cloudToDeviceMessage = DateTime.Now.ToLocalTime() + " - " + textBoxMessage.Text;
                        }
                    }
                }
                else
                {
                    isInJsonFormat(textBoxMessage.Text); //any JSON format string should start with "{" || "[" and end with "}" || "]"
                    cloudToDeviceMessage = textBoxMessage.Text;
                }

                ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(activeIoTHubConnectionString);

                var serviceMessage = new Microsoft.Azure.Devices.Message(Encoding.ASCII.GetBytes(cloudToDeviceMessage));
                serviceMessage.Ack       = DeliveryAcknowledgement.Full;
                serviceMessage.MessageId = Guid.NewGuid().ToString();

                for (var i = 0; i < messagePropertiesGrid.Rows.Count - 1; i++)
                {
                    var row = messagePropertiesGrid.Rows[i];
                    if (row.Cells[0].Value == null && row.Cells[1].Value == null)
                    {
                        continue;
                    }

                    if (row.Cells[0].Value == null || row.Cells[1].Value == null)
                    {
                        throw new InvalidOperationException("Properties have null key or value.");
                    }

                    serviceMessage.Properties.Add(row.Cells[0].Value?.ToString() ?? string.Empty, row.Cells[1].Value?.ToString() ?? string.Empty);
                }


                if (messageSysPropMessageId.Cells[1].Value != null)
                {
                    serviceMessage.MessageId = (string)messageSysPropMessageId.Cells[1].Value;
                }

                if (messageSysPropCorrelationId.Cells[1].Value != null)
                {
                    serviceMessage.CorrelationId = (string)messageSysPropCorrelationId.Cells[1].Value;
                }

                if (messageSysPropContentType.Cells[1].Value != null)
                {
                    serviceMessage.ContentType = (string)messageSysPropContentType.Cells[1].Value;
                }

                if (messageSysPropContentEncoding.Cells[1].Value != null)
                {
                    serviceMessage.ContentEncoding = (string)messageSysPropContentEncoding.Cells[1].Value;
                }

                await serviceClient.SendAsync(deviceIDsComboBoxForCloudToDeviceMessage.SelectedItem.ToString(), serviceMessage);

                messagesTextBox.Text += $"Sent to Device ID: [{deviceIDsComboBoxForCloudToDeviceMessage.SelectedItem.ToString()}], Message:\"{cloudToDeviceMessage}\", message Id: {serviceMessage.MessageId}\n";
                messagesTextBox.Focus();

                await serviceClient.CloseAsync();
            }
            catch (Exception ex)
            {
                using (new CenterDialog(this))
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
 private async static Task SendCloudToDeviceMessageAsync()
 {
     var commandMessage = new
                          Microsoft.Azure.Devices.Message(Encoding.ASCII.GetBytes("Cloud to device message."));
     await serviceClient.SendAsync("myDevice", commandMessage);
 }
Example #8
0
        public override async Task SendAsync(EventMessage message)
        {
            AuditRecord record = null;

            byte[] payload = null;

            try
            {
                payload = GetPayload(message);
                if (payload == null)
                {
                    Trace.TraceWarning("Subscription {0} could not write to iot hub sink because payload was either null or unknown protocol type.");
                    return;
                }

                if (serviceClient != null)                 //send message to device
                {
                    if (!String.IsNullOrEmpty(methodName)) //direct method to device
                    {
                        if (message.ContentType == "application/json")
                        {
                            CloudToDeviceMethod method = new CloudToDeviceMethod(methodName);
                            method.SetPayloadJson(Encoding.UTF8.GetString(payload));
                            await serviceClient.InvokeDeviceMethodAsync(deviceId, method);

                            record = new MessageAuditRecord(message.MessageId, String.Format("iothub://{0}", uri.Authority), "IoTHub", "IoTHub", payload.Length, MessageDirectionType.Out, true, DateTime.UtcNow);
                        }
                        else
                        {
                            Trace.TraceWarning("Cannot send IoTHub device {0} direct message because content-type is not JSON.", deviceId);
                            record = new MessageAuditRecord(message.MessageId, String.Format("iothub://{0}", uri.Authority), "IoTHub", "IoTHub", payload.Length, MessageDirectionType.Out, false, DateTime.UtcNow, String.Format("Cannot send IoTHub device {0} direct message because content-type is not JSON.", deviceId));
                        }
                    }
                    else //command to device
                    {
                        Microsoft.Azure.Devices.Message serviceMessage = new Microsoft.Azure.Devices.Message(payload);
                        serviceMessage.ContentType = message.ContentType;
                        serviceMessage.MessageId   = message.MessageId;

                        if (!String.IsNullOrEmpty(propertyName))
                        {
                            serviceMessage.Properties.Add(propertyName, propertyValue);
                        }

                        await serviceClient.SendAsync(deviceId, serviceMessage);

                        record = new MessageAuditRecord(message.MessageId, String.Format("iothub://{0}", uri.Authority), "IoTHub", "IoTHub", payload.Length, MessageDirectionType.Out, true, DateTime.UtcNow);
                    }
                }
                else if (deviceClient != null) //this subscription is a device and will send to IoTHub
                {
                    Microsoft.Azure.Devices.Client.Message msg = new Microsoft.Azure.Devices.Client.Message(payload);
                    msg.ContentType = message.ContentType;
                    msg.MessageId   = message.MessageId;
                    if (!String.IsNullOrEmpty(propertyName))
                    {
                        msg.Properties.Add(propertyName, propertyValue);
                    }
                    await deviceClient.SendEventAsync(msg);

                    record = new MessageAuditRecord(message.MessageId, String.Format("iothub://{0}", uri.Authority), "IoTHub", "IoTHub", payload.Length, MessageDirectionType.Out, true, DateTime.UtcNow);
                }
                else
                {
                    Trace.TraceWarning("IoTHub subscription has neither Service or Device client");
                    record = new MessageAuditRecord(message.MessageId, String.Format("iothub://{0}", uri.Authority), "IoTHub", "IoTHub", payload.Length, MessageDirectionType.Out, false, DateTime.UtcNow, "IoTHub subscription has neither service or device client");
                }
            }
            catch (Exception ex)
            {
                record = new MessageAuditRecord(message.MessageId, String.Format("iothub://{0}", uri.Authority), "IoTHub", "IoTHub", payload.Length, MessageDirectionType.Out, false, DateTime.UtcNow, ex.Message);
            }
            finally
            {
                if (record != null && message.Audit)
                {
                    await auditor?.WriteAuditRecordAsync(record);
                }
            }
        }
Example #9
0
        //--------------------------------------------------------------------
        // Purpose:
        //     Receive the Messages
        //
        // Notes:
        //     This is also the task that handles sending the tweet now message
        //--------------------------------------------------------------------
        private static async Task ReceiveMessagesFromDeviceAsync(string partition)
        {
            var eventHubReceiver = mEventHubClient1.GetDefaultConsumerGroup().CreateReceiver(partition, DateTime.UtcNow);

            while (true == mRunThread)
            {
                // If there tweet now flag is set, send the message down to tweet
                if (true == mTweetNow)
                {
                    var commandMessage = new Microsoft.Azure.Devices.Message(Encoding.ASCII.GetBytes("TweetStatus"));
                    commandMessage.Properties.Add(new KeyValuePair <string, string>("TweetNow", "True"));
                    await mServiceClient.SendAsync(mConfig.mDeviceString, commandMessage);

                    mTweetNow = false;
                }

                // Get Messages
                Thread.Sleep(10);
                EventData eventData = await eventHubReceiver.ReceiveAsync();

                if (eventData == null)
                {
                    continue;
                }

                string data = Encoding.UTF8.GetString(eventData.GetBytes());
                Console.WriteLine("Message received. Partition: {0} Data: '{1}'", partition, data);

                // Parse all of the properties
                for (int i = 0; i < eventData.Properties.Count; i++)
                {
                    KeyValuePair <string, object> theEvent = eventData.Properties.ElementAt(i);

                    if ("FreezerDoor" == theEvent.Key)
                    {
                        mFreezerDoor = (string)theEvent.Value;
                    }
                    if ("FreezerTemp" == theEvent.Key)
                    {
                        mFreezerTemp = (string)theEvent.Value;
                    }
                    if ("FridgeDoor" == theEvent.Key)
                    {
                        mFridgeDoor = (string)theEvent.Value;
                    }
                    if ("FridgeTemp" == theEvent.Key)
                    {
                        mFridgeTemp = (string)theEvent.Value;
                    }
                    if ("LastTweet" == theEvent.Key)
                    {
                        mLastTweet = (string)theEvent.Value;
                    }
                    if ("LastTweet" == theEvent.Key)
                    {
                        mLastTweet = (string)theEvent.Value;
                    }
                    if ("DoorTime" == theEvent.Key)
                    {
                        mDoorTime = (string)theEvent.Value;
                    }
                    if ("LockoutTime" == theEvent.Key)
                    {
                        mLockoutTime = (string)theEvent.Value;
                    }
                    if ("BoredTime" == theEvent.Key)
                    {
                        mBoredTime = (string)theEvent.Value;
                    }
                    Console.WriteLine("  Prop {0} {1}", theEvent.Key, (string)theEvent.Value);
                }
            }
        }
Example #10
0
 private async Task SendInstruction()
 {
     string matrixdata     = (Loc - 1).ToString() + "|" + Global.R + "|" + Global.G + "|" + Global.B;
     var    commandMessage = new Microsoft.Azure.Devices.Message(Encoding.ASCII.GetBytes(matrixdata));
     await serviceClient.SendAsync(Global.DeviceId, commandMessage);
 }
Example #11
0
        private async void sendMessageToDeviceButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (checkBox1.Checked)
                {
                    if (string.IsNullOrEmpty(textBoxMessage.Text))
                    {
                        cloudToDeviceMessage = DateTime.Now.ToLocalTime().ToString();
                    }
                    else
                    {
                        cloudToDeviceMessage = DateTime.Now.ToLocalTime() + " - " + textBoxMessage.Text;
                    }
                }
                else
                {
                    cloudToDeviceMessage = textBoxMessage.Text;
                }

                ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(activeIoTHubConnectionString);

                var serviceMessage = new Microsoft.Azure.Devices.Message(Encoding.ASCII.GetBytes(cloudToDeviceMessage));
                serviceMessage.Ack = DeliveryAcknowledgement.Full;
                serviceMessage.MessageId = Guid.NewGuid().ToString();

                for (var i = 0; i < messagePropertiesGrid.Rows.Count - 1; i++)
                {
                    var row = messagePropertiesGrid.Rows[i];
                    if (row.Cells[0].Value == null && row.Cells[1].Value == null)
                    {
                        continue;
                    }

                    if (row.Cells[0].Value == null || row.Cells[1].Value == null)
                    {
                        throw new InvalidOperationException("Properties have null key or value.");
                    }

                    serviceMessage.Properties.Add(row.Cells[0].Value?.ToString() ?? string.Empty, row.Cells[1].Value?.ToString() ?? string.Empty);
                }

                await serviceClient.SendAsync(deviceIDsComboBoxForCloudToDeviceMessage.SelectedItem.ToString(), serviceMessage);

                messagesTextBox.Text += $"Sent to Device ID: [{deviceIDsComboBoxForCloudToDeviceMessage.SelectedItem.ToString()}], Message:\"{cloudToDeviceMessage}\", message Id: {serviceMessage.MessageId}\n";

                await serviceClient.CloseAsync();

            }
            catch (Exception ex)
            {
                using (new CenterDialog(this))
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Example #12
0
        private async Task SendMsgToDevice(string message)
        {
            try
            {

                ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(activeIoTHubConnectionString);

                var serviceMessage = new Microsoft.Azure.Devices.Message(Encoding.ASCII.GetBytes(message));
                serviceMessage.Ack = DeliveryAcknowledgement.Full;
                serviceMessage.MessageId = Guid.NewGuid().ToString();
                await serviceClient.SendAsync(deviceIDsComboBoxForCloudToDeviceMessage.SelectedItem.ToString(), serviceMessage);

                messagesTextBox.Text += $"Sent to Device ID: [{deviceIDsComboBoxForCloudToDeviceMessage.SelectedItem.ToString()}], Message:\"{message}\", message Id: {serviceMessage.MessageId}\n";

                await serviceClient.CloseAsync();

            }
            catch (Exception ex)
            {
                using (new CenterDialog(this))
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        /// <summary>
        /// Copies the properties from the amqp message to the Message instance.
        /// </summary>
        public static void UpdateMessageHeaderAndProperties(AmqpMessage amqpMessage, Message data)
        {
            Fx.AssertAndThrow(amqpMessage.DeliveryTag != null, "AmqpMessage should always contain delivery tag.");
            data.DeliveryTag = amqpMessage.DeliveryTag;

            SectionFlag sections = amqpMessage.Sections;
            if ((sections & SectionFlag.Properties) != 0)
            {
                // Extract only the Properties that we support
                data.MessageId = amqpMessage.Properties.MessageId != null ? amqpMessage.Properties.MessageId.ToString() : null;
                data.To = amqpMessage.Properties.To != null ? amqpMessage.Properties.To.ToString() : null;

                if (amqpMessage.Properties.AbsoluteExpiryTime.HasValue)
                {
                    data.ExpiryTimeUtc = amqpMessage.Properties.AbsoluteExpiryTime.Value;
                }

                data.CorrelationId = amqpMessage.Properties.CorrelationId != null ? amqpMessage.Properties.CorrelationId.ToString() : null;
                data.UserId = amqpMessage.Properties.UserId.Array != null ? Encoding.UTF8.GetString(amqpMessage.Properties.UserId.Array) : null;

                if (!string.IsNullOrWhiteSpace(amqpMessage.Properties.ContentType.Value))
                {
                    data.ContentType = amqpMessage.Properties.ContentType.Value;
                }

                if (!string.IsNullOrWhiteSpace(amqpMessage.Properties.ContentEncoding.Value))
                {
                    data.ContentEncoding = amqpMessage.Properties.ContentEncoding.Value;
                }
            }

            if ((sections & SectionFlag.MessageAnnotations) != 0)
            {
                string lockToken;
                if (amqpMessage.MessageAnnotations.Map.TryGetValue(LockTokenName, out lockToken))
                {
                    data.LockToken = lockToken;
                }

                ulong sequenceNumber;
                if (amqpMessage.MessageAnnotations.Map.TryGetValue(SequenceNumberName, out sequenceNumber))
                {
                    data.SequenceNumber = sequenceNumber;
                }

                DateTime enqueuedTime;
                if (amqpMessage.MessageAnnotations.Map.TryGetValue(MessageSystemPropertyNames.EnqueuedTime, out enqueuedTime))
                {
                    data.EnqueuedTimeUtc = enqueuedTime;
                }

                byte deliveryCount;
                if (amqpMessage.MessageAnnotations.Map.TryGetValue(MessageSystemPropertyNames.DeliveryCount, out deliveryCount))
                {
                    data.DeliveryCount = deliveryCount;
                }
            }

            if ((sections & SectionFlag.ApplicationProperties) != 0)
            {
                foreach (KeyValuePair<MapKey, object> pair in amqpMessage.ApplicationProperties.Map)
                {
                    object netObject = null;
                    if (TryGetNetObjectFromAmqpObject(pair.Value, MappingType.ApplicationProperty, out netObject))
                    {
                        var stringObject = netObject as string;

                        if (stringObject != null)
                        {
                            switch (pair.Key.ToString())
                            {
                                case MessageSystemPropertyNames.Operation:
                                    data.SystemProperties[pair.Key.ToString()] = stringObject;
                                    break;

                                case MessageSystemPropertyNames.MessageSchema:
                                    data.MessageSchema = stringObject;
                                    break;

                                case MessageSystemPropertyNames.CreationTimeUtc:
                                    data.CreationTimeUtc = DateTime.Parse(stringObject);
                                    break;

                                default:
                                    data.Properties[pair.Key.ToString()] = stringObject;
                                    break;
                            }
                        }
                        else
                        {
                            // TODO: RDBug 4093369 Handling of non-string property values in Amqp messages
                            // Drop non-string properties and log an error
                            Fx.Exception.TraceHandled(new InvalidDataException("IotHub does not accept non-string Amqp properties"), "MessageConverter.UpdateMessageHeaderAndProperties");
                        }
                    }
                }
            }
        }
        /// <summary>
        /// Copies the Message instance's properties to the AmqpMessage instance.
        /// </summary>
        public static void UpdateAmqpMessageHeadersAndProperties(AmqpMessage amqpMessage, Message data, bool copyUserProperties = true)
        {
            amqpMessage.Properties.MessageId = data.MessageId;

            if (data.To != null)
            {
                amqpMessage.Properties.To = data.To;
            }

            if (!data.ExpiryTimeUtc.Equals(default(DateTime)))
            {
                amqpMessage.Properties.AbsoluteExpiryTime = data.ExpiryTimeUtc;
            }

            if (data.CorrelationId != null)
            {
                amqpMessage.Properties.CorrelationId = data.CorrelationId;
            }

            if (data.UserId != null)
            {
                amqpMessage.Properties.UserId = new ArraySegment<byte>(Encoding.UTF8.GetBytes(data.UserId));
            }

            if (amqpMessage.ApplicationProperties == null)
            {
                amqpMessage.ApplicationProperties = new ApplicationProperties();
            }

            object propertyValue;
            if (data.SystemProperties.TryGetValue(MessageSystemPropertyNames.Ack, out propertyValue))
            {
                amqpMessage.ApplicationProperties.Map["iothub-ack"] = (string)propertyValue;
            }

            if (data.SystemProperties.TryGetValue(MessageSystemPropertyNames.MessageSchema, out propertyValue))
            {
                amqpMessage.ApplicationProperties.Map[MessageSystemPropertyNames.MessageSchema] = (string)propertyValue;
            }

            if (data.SystemProperties.TryGetValue(MessageSystemPropertyNames.CreationTimeUtc, out propertyValue))
            {
                amqpMessage.ApplicationProperties.Map[MessageSystemPropertyNames.CreationTimeUtc] = ((DateTime)propertyValue).ToString("o");   // Convert to string that complies with ISO 8601
            }

            if (data.SystemProperties.TryGetValue(MessageSystemPropertyNames.ContentType, out propertyValue))
            {
                amqpMessage.Properties.ContentType = (string)propertyValue;
            }

            if (data.SystemProperties.TryGetValue(MessageSystemPropertyNames.ContentEncoding, out propertyValue))
            {
                amqpMessage.Properties.ContentEncoding = (string)propertyValue;
            }

            if (copyUserProperties && data.Properties.Count > 0)
            {
                foreach (var pair in data.Properties)
                {
                    object amqpObject;
                    if (TryGetAmqpObjectFromNetObject(pair.Value, MappingType.ApplicationProperty, out amqpObject))
                    {
                        amqpMessage.ApplicationProperties.Map[pair.Key] = amqpObject;
                    }
                }
            }
        }
Example #15
0
 public async Task SendC2DMessage(string deviceId, byte[] msg)
 {
     var message = new Microsoft.Azure.Devices.Message(msg);
     await serviceClient.SendAsync(deviceId, message);
 }
Example #16
0
        private static async Task C2DLoop(ServiceClient serviceClient, DeviceClient deviceClient, string deviceId, CancellationToken token)
        {
            while (!token.IsCancellationRequested)
            {
                var index    = C2DOperationCounts[deviceId];
                var identity = $"[Device={deviceId}, Index={index}, Direction=C2D]";
                ConsoleLogger.LogDebug($"{identity}: Enter C2D loop...");

                var operationName  = "SendC2DMessage";
                var messagePayload = $"C2D message: {identity}";
                var message        = new C2DMessage(Encoding.UTF8.GetBytes(messagePayload));
                try
                {
                    await serviceClient.SendAsync(deviceId, message);

                    ConsoleLogger.LogDebug($"{identity}: Sent C2D message successfully.");

                    operationName = "ReceiveC2DMessage";
                    var received = await deviceClient.ReceiveAsync(OperationTimeOut);

                    while (received != null)
                    {
                        var content = Encoding.UTF8.GetString(received.GetBytes());
                        ConsoleLogger.LogDebug($"{identity}: Received C2D message successfully.");
                        try
                        {
                            await deviceClient.CompleteAsync(received);
                        }
                        catch (Exception e)
                        {
                            // swallow CompleteAsync failure
                            ConsoleLogger.LogInfo($"{identity}: Complete C2D message failed: {e}.");
                        }

                        if (content == messagePayload)
                        {
                            // quit loop when message is received
                            break;
                        }
                    }

                    if (message == null)
                    {
                        ConsoleLogger.LogInfo($"{identity}: Receive C2D message failed: not received.");
                    }
                    else
                    {
                        ConsoleLogger.LogDebug($"{identity}: Receive C2D message successfully.");
                    }

                    operationName = "InvokeDeviceMethod";
                    var methodPayload = new TwinCollection();
                    methodPayload["Operation"] = $"Operation: {identity}";
                    methodPayload["Args"]      = $"Args: {identity}";
                    var methodRequest = new CloudToDeviceMethod(MethodName);
                    methodRequest.SetPayloadJson(methodPayload.ToJson());
                    var methodResponse = await serviceClient.InvokeDeviceMethodAsync(deviceId, methodRequest);

                    var status = methodResponse.Status;
                    ConsoleLogger.LogDebug($"{identity}: Invoke method response: status={status}, payload={methodResponse.GetPayloadAsJson()}.");
                    if (status != 200)
                    {
                        ConsoleLogger.LogInfo($"{identity}: Invoke method failed: status={status}, payload={methodResponse.GetPayloadAsJson()}.");
                    }
                }
                catch (Exception ex)
                {
                    ConsoleLogger.LogInfo($"{identity}: Operation {operationName} failed: {ex}");
                }
                finally
                {
                    if ((index + 1) % 100 == 0)
                    {
                        ConsoleLogger.LogInfo($"{identity}: finished {index + 1} C2D loop.");
                    }

                    C2DOperationCounts[deviceId] = index + 1;
                    ConsoleLogger.LogDebug($"{identity}: Exit C2D loop.");
                    await Task.Delay(TestFrequency);
                }
            }
        }
Example #17
0
 private async static Task SendCloudToDeviceMessageAsync(string commandString)
 {
     var commandMessage = new Microsoft.Azure.Devices.Message(Encoding.ASCII.GetBytes(commandString));
     await serviceClient.SendAsync("TheIntouchables", commandMessage);
 }
        public void Send(DeviceRegistry item)
        {
            var c2dmsg = new Microsoft.Azure.Devices.Message(System.Text.Encoding.UTF8.GetBytes(item.C2DMessage));

            serviceClient.SendAsync(item.DeviceId, c2dmsg).Wait();
        }
Example #19
0
 public static async Task SendMessageToDeviceAsync(MAD.ServiceClient serviceClient, string targetDeviceId, string message)
 {
     var payload = new MAD.Message(Encoding.UTF8.GetBytes(message));
     await serviceClient.SendAsync(targetDeviceId, payload);
 }
Example #20
0
 // Azure Function -> Console App    [Sender]
 public static async Task SendMessageToDeviceAsync(MAD.ServiceClient serviceClient, string targetDeviceId, string message)
 {
     // Skicka meddelande "message" till Device "targetDeviceId" mha SendAsync
     var payload = new MAD.Message(Encoding.UTF8.GetBytes(message));
     await serviceClient.SendAsync(targetDeviceId, payload);
 }