Exemplo n.º 1
0
        public IoTHubDeviceHelper(IoTHubDeviceMessageModel message, string action)
        {
            _Message         = message;
            _TaskId          = Int32.Parse(message.taskId);
            _IoTHubDeviceId  = message.iothubDeviceId;
            _IoTHubDeviceKey = message.iothubDeviceKey;
            _OldPrimaryIoTHubConnectionString = message.oldPrimaryIothubConnectionString;
            //_OldSecondaryIoTHubConnectionString = message.oldSecondaryIothubConnectionString;
            _PrimaryIoTHubConnectionString = message.primaryIothubConnectionString;
            //_SecondaryIoTHubConnectionString = message.secondaryIothubConnectionString;
            _AuthenticationType    = message.authenticationType;
            _CertificateThumbprint = message.certificateThumbprint;

            if (action.StartsWith("create"))
            {
                _Action = "create";
            }
            else if (action.StartsWith("update"))
            {
                _Action = "update";
            }
            else
            {
                _Action = "remove";
            }
        }
Exemplo n.º 2
0
        static void ListenOnServiceBusQueue()
        {
            /* Create Queue client and listen on message  */
            _sbQueueClient = QueueClient.CreateFromConnectionString(_sbConnectionString, _sbInfraOpsQueue);
            OnMessageOptions options = new OnMessageOptions();

            options.MaxConcurrentCalls = 1;
            options.AutoComplete       = false;
            string messageBody = "";

            _isRunning = true;

            _sbQueueClient.OnMessage((message) =>
            {
                string task, command;
                int taskId = 0;
                try
                {
                    // Process message from queue.
                    messageBody = message.GetBody <string>();
                    StringBuilder logMessage = new StringBuilder();
                    logMessage.AppendLine("OpsInfra onMessage: " + messageBody);

                    JObject jsonMessage = JObject.Parse(messageBody);

                    if (jsonMessage["taskId"] != null)
                    {
                        taskId = int.Parse(jsonMessage["taskId"].ToString());
                    }

                    if (jsonMessage["command"] != null)
                    {
                        command = jsonMessage["command"].ToString();
                        Console.WriteLine("command:" + command);
                        switch (command.ToLower())
                        {
                        case "shutdown":
                            _sfAppLogger.Info("Received Command: Shutdown");
                            message.Complete();
                            UpdateTaskBySuccess(taskId);
                            Environment.Exit(0);
                            break;
                        }
                        message.Complete();
                    }
                    else if (jsonMessage["task"] != null)
                    {
                        task = jsonMessage["task"].ToString();
                        Console.WriteLine("task:" + task);

                        _sfAppLogger.Info("Received task: " + task);
                        switch (task.ToLower())
                        {
                        case "create documentdb collection":
                        case "purge documentdb collection":
                            DocumentDBMessageModel docDBMsg = new DocumentDBMessageModel()
                            {
                                ConnectionString = jsonMessage["documentdbConnectionString"].ToString(),
                                DatabaseName     = jsonMessage["databaseName"].ToString(),
                                CollectionId     = jsonMessage["collectionId"].ToString(),
                                TaskId           = jsonMessage["taskId"].ToString()
                            };

                            if (String.IsNullOrEmpty(docDBMsg.ConnectionString))
                            {
                                docDBMsg.ConnectionString = ConfigurationManager.AppSettings["sfDocDBConnectionString"];
                            }

                            DocumentDBHelper docDB   = new DocumentDBHelper(docDBMsg, task.ToLower());
                            Thread docDBthread       = new Thread(new ThreadStart(docDB.ThreadProc));
                            docDBthread.IsBackground = false;
                            docDBthread.Start();
                            message.Complete();
                            break;

                        case "create iothub register":
                        case "update iothub register":
                        case "remove iothub register":
                            IoTHubDeviceMessageModel deviceMessage = new IoTHubDeviceMessageModel()
                            {
                                taskId = jsonMessage["taskId"].ToString(),
                                oldPrimaryIothubConnectionString = jsonMessage["oldPrimaryIothubConnectionString"].ToString(),
                                //oldSecondaryIothubConnectionString = jsonMessage["oldSecondaryIothubConnectionString"].ToString(),
                                primaryIothubConnectionString = jsonMessage["primaryIothubConnectionString"].ToString(),
                                //secondaryIothubConnectionString = jsonMessage["secondaryIothubConnectionString"].ToString(),
                                iothubDeviceId        = jsonMessage["iothubDeviceId"].ToString(),
                                iothubDeviceKey       = jsonMessage["iothubDeviceKey"].ToString(),
                                authenticationType    = jsonMessage["authenticationType"].ToString(),
                                certificateThumbprint = jsonMessage["certificateThumbprint"].ToString()
                            };

                            IoTHubDeviceHelper iotHubDeviceHelper = new IoTHubDeviceHelper(deviceMessage, task.ToLower());
                            Thread createDeviceThread             = new Thread(new ThreadStart(iotHubDeviceHelper.ThreadProc));
                            createDeviceThread.IsBackground       = false;
                            createDeviceThread.Start();
                            message.Complete();
                            break;

                        case "create iothub alias":
                        case "remove iothub alias":
                            IoTHubEventProcessorHelper iotHubEP  = new IoTHubEventProcessorHelper(jsonMessage["entityId"].ToString(), int.Parse(jsonMessage["taskId"].ToString()), task.ToLower());
                            Thread manageIoTHubAliasThread       = new Thread(new ThreadStart(iotHubEP.ThreadProc));
                            manageIoTHubAliasThread.IsBackground = false;
                            manageIoTHubAliasThread.Start();
                            message.Complete();
                            break;

                        case "update device desired property":
                            {
                                DBHelper._IoTDevice dbhelper     = new DBHelper._IoTDevice();
                                IoTDevice iotDevice              = dbhelper.GetByid(jsonMessage["iothubDeviceId"].ToString());
                                int deviceConfigurationStatus    = iotDevice.DeviceConfigurationStatus;
                                JObject existingDesiredObj       = JObject.Parse(iotDevice.DeviceTwinsDesired);
                                JObject newDesiredObj            = JObject.Parse(jsonMessage["deviceConfiguration"].ToString());
                                int existingLastUpdatedTimestamp = Convert.ToInt32(existingDesiredObj["SF_LastUpdatedTimestamp"]);
                                int newLastUpdatedTimestamp      = Convert.ToInt32(newDesiredObj["SF_LastUpdatedTimestamp"]);

                                if (newLastUpdatedTimestamp >= existingLastUpdatedTimestamp)
                                {
                                    IoTHubDeviceManagementMessageModel deviceManagementMessage = new IoTHubDeviceManagementMessageModel()
                                    {
                                        taskId = jsonMessage["taskId"] == null ? "0" : jsonMessage["taskId"].ToString(),
                                        primaryIothubConnectionString = jsonMessage["primaryIothubConnectionString"] == null ? "" : jsonMessage["primaryIothubConnectionString"].ToString(),
                                        //secondaryIothubConnectionString = jsonMessage["secondaryIothubConnectionString"] == null ? "" : jsonMessage["secondaryIothubConnectionString"].ToString(),
                                        iothubDeviceId      = jsonMessage["iothubDeviceId"].ToString(),
                                        deviceConfiguration = JObject.Parse(jsonMessage["deviceConfiguration"].ToString())
                                    };
                                    IoTHubDeviceManagementHelper iotHubDMHelper = new IoTHubDeviceManagementHelper(deviceManagementMessage, task.ToLower());
                                    Thread deviceManagementThread       = new Thread(new ThreadStart(iotHubDMHelper.ThreadProc));
                                    deviceManagementThread.IsBackground = false;
                                    deviceManagementThread.Start();
                                    message.Complete();
                                }
                                else
                                {
                                    throw new Exception("It's old version of device configuration");
                                }
                            }
                            break;

                        case "update device reported property to db":
                            {
                                DBHelper._IoTDevice dbhelper     = new DBHelper._IoTDevice();
                                IoTDevice iotDevice              = dbhelper.GetByid(jsonMessage["iothubDeviceId"].ToString());
                                int deviceConfigurationStatus    = iotDevice.DeviceConfigurationStatus;
                                JObject existingReportedObj      = JObject.Parse(iotDevice.DeviceTwinsReported);
                                JObject newReportedObj           = JObject.Parse(jsonMessage["deviceConfiguration"].ToString());
                                int existingLastUpdatedTimestamp = Convert.ToInt32(existingReportedObj["SF_LastUpdatedTimestamp"]);
                                int newLastUpdatedTimestamp      = Convert.ToInt32(newReportedObj["SF_LastUpdatedTimestamp"]);

                                if (newLastUpdatedTimestamp >= existingLastUpdatedTimestamp)
                                {
                                    switch (deviceConfigurationStatus)
                                    {
                                    case IoTDeviceConfigurationStatus.SUBMIT:
                                        message.Abandon();
                                        break;

                                    case IoTDeviceConfigurationStatus.WAITING_DEVICE_ACK:
                                    case IoTDeviceConfigurationStatus.RECEIVE_DEVICE_ACK:
                                        IoTHubDeviceManagementMessageModel deviceManagementMessage = new IoTHubDeviceManagementMessageModel()
                                        {
                                            taskId              = "0",
                                            iothubDeviceId      = jsonMessage["iothubDeviceId"].ToString(),
                                            deviceConfiguration = newReportedObj,
                                            iothubAlias         = jsonMessage["iothubAlias"].ToString(),
                                            iothubIsPrimary     = Convert.ToBoolean(jsonMessage["iothubIsPrimary"].ToString()),
                                            taskContent         = JsonConvert.SerializeObject(jsonMessage)
                                        };
                                        IoTHubDeviceManagementHelper iotHubDMHelper = new IoTHubDeviceManagementHelper(deviceManagementMessage, task.ToLower());
                                        Thread deviceManagementThread       = new Thread(new ThreadStart(iotHubDMHelper.ThreadProc));
                                        deviceManagementThread.IsBackground = false;
                                        deviceManagementThread.Start();
                                        message.Complete();
                                        break;
                                    }
                                }
                                else
                                {
                                    throw new Exception("It's old version of device configuration");
                                }
                            }
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    // Indicates a problem, unlock message in subscription.
                    Console.WriteLine(ex.Message);
                    StringBuilder logMessage = new StringBuilder();
                    logMessage.AppendLine("OpsInfra Exception: " + ex.Message);
                    logMessage.AppendLine("OpsInfra Message: " + messageBody);
                    _sfAppLogger.Error(logMessage);
                    Console.WriteLine();
                    message.Complete();

                    UpdateTaskByFail(taskId, ex.Message);
                }
            }, options);
        }