Exemplo n.º 1
0
        public async void ThreadProc()
        {
            AzureSQLHelper.OperationTaskModel operationTask = new AzureSQLHelper.OperationTaskModel();
            try
            {
                if (!smsCtx.receiverPhoneNumber.StartsWith("+"))
                {
                    smsCtx.receiverPhoneNumber = "+" + smsCtx.receiverPhoneNumber;
                }

                // Initialize the Twilio client
                TwilioClient.Init(_twilioAccountId, _twilioToken);
                MessageResource.Create(
                    from: new PhoneNumber(smsCtx.senderPhoneNumber),
                    to: new PhoneNumber(smsCtx.receiverPhoneNumber),                                                        // Message content
                    body: smsCtx.smsContent);

                SMSApp._appLogger.Info("[Twilio Thread] send SMS success. Receiver PhoneNumber: " + smsCtx.receiverPhoneNumber);
                operationTask.UpdateTaskBySuccess(_TaskId);
            }
            catch (Exception ex)
            {
                StringBuilder logMessage = new StringBuilder();
                logMessage.AppendLine("[Twilio Thread] Failed. Receiver" + smsCtx.receiverPhoneNumber);
                logMessage.AppendLine("\tMessage:" + JsonConvert.SerializeObject(this));
                logMessage.AppendLine("\tException:" + ex.Message);
                SMSApp._appLogger.Error(logMessage);
                operationTask.UpdateTaskByFail(_TaskId, ex.Message);
            }
        }
Exemplo n.º 2
0
        public async void ThreadProc()
        {
            string partitionKey = "";
            int    collectionTTL = 0, collectionRU = 0;

            AzureSQLHelper.OperationTaskModel operationTask = new AzureSQLHelper.OperationTaskModel();
            try
            {
                DocDBHelper docDBHelper = new DocDBHelper(_ConnectionString);
                switch (_Action)
                {
                case "create cosmosdb collection":
                    partitionKey  = _JsonMessage["Content"]["partitionKey"].ToString();
                    collectionTTL = int.Parse(_JsonMessage["Content"]["collectionTTL"].ToString());
                    collectionRU  = int.Parse(_JsonMessage["Content"]["collectionRU"].ToString());
                    await docDBHelper.CreateDatabaseAndCollection(_DatabaseName, _CollectionId, partitionKey, collectionTTL, collectionRU);

                    break;

                case "purge cosmosdb collection":
                    await docDBHelper.PurgeDatabase(_DatabaseName);

                    break;

                case "update cosmosdb collection":
                    collectionTTL = int.Parse(_JsonMessage["Content"]["collectionTTL"].ToString());
                    collectionRU  = int.Parse(_JsonMessage["Content"]["collectionRU"].ToString());
                    await docDBHelper.UpdateCollection(_DatabaseName, _CollectionId, collectionTTL, collectionRU);

                    break;
                }
                ProvisionApp._appLogger.Info("[Cosmosdb] " + _Action + " success: Databae-" + _DatabaseName + ", CollectionId-" + _CollectionId);
                operationTask.UpdateTaskBySuccess(_TaskId);
            }
            catch (Exception ex)
            {
                StringBuilder logMessage = new StringBuilder();
                logMessage.AppendLine("[Cosmosdb] " + _Action + " Failed: Databae-" + _DatabaseName + ", CollectionId-" + _CollectionId);
                logMessage.AppendLine("\tMessage:" + JsonConvert.SerializeObject(this));
                logMessage.AppendLine("\tException:" + ex.Message);
                ProvisionApp._appLogger.Error(logMessage);
                operationTask.UpdateTaskByFail(_TaskId, ex.Message);
            }
        }
Exemplo n.º 3
0
        public async void ThreadProc()
        {
            AzureSQLHelper.OperationTaskModel operationTask = new AzureSQLHelper.OperationTaskModel();
            try
            {
                IoTHubHelper iotHubHelper = new IoTHubHelper(_ConnectionString);
                await iotHubHelper.UpdateTwinDesiredProperty(_IoTDeviceId, _DeviceConfiguration);

                ProvisionApp._appLogger.Info("[IoT Hub Device] " + _Action + " success: DeviceId-" + _IoTDeviceId);
                operationTask.UpdateTaskBySuccess(_TaskId);
            }
            catch (Exception ex)
            {
                StringBuilder logMessage = new StringBuilder();
                logMessage.AppendLine("[IoT Hub Device] " + _Action + " Failed: DeviceId-" + _IoTDeviceId);
                logMessage.AppendLine("\tMessage:" + JsonConvert.SerializeObject(this));
                logMessage.AppendLine("\tException:" + ex.Message);
                ProvisionApp._appLogger.Error(logMessage);
                operationTask.UpdateTaskByFail(_TaskId, ex.Message);
            }
        }
        public async void ThreadProc()
        {
            AzureSQLHelper.OperationTaskModel operationTask = new AzureSQLHelper.OperationTaskModel();
            try
            {
                IoTHubHelper iotHubHelper = new IoTHubHelper(_ConnectionString);
                switch (_Action)
                {
                case "register iothub register":
                    _AuthenticationType = _JsonMessage["Content"]["authenticationType"].ToString().ToLower();
                    if (_AuthenticationType == "key")
                    {
                        string IoTHubDeviceKey = _JsonMessage["Content"]["iothubDeviceKey"].ToString();
                        await iotHubHelper.RegisterDeviceByKey(_IoTDeviceId, IoTHubDeviceKey);
                    }
                    else
                    {
                        string CertificateThumbprint = _JsonMessage["Content"]["certificateThumbprint"].ToString();
                        await iotHubHelper.RegisterDeviceByCertThumbprint(_IoTDeviceId, CertificateThumbprint);
                    }
                    break;

                case "remove iothub register":
                    await iotHubHelper.RemoveDevice(_IoTDeviceId);

                    break;
                }
                ProvisionApp._appLogger.Info("[IoT Hub Device] " + _Action + " success: DeviceId-" + _IoTDeviceId);
                operationTask.UpdateTaskBySuccess(_TaskId);
            }
            catch (Exception ex)
            {
                StringBuilder logMessage = new StringBuilder();
                logMessage.AppendLine("[IoT Hub Device] " + _Action + " Failed: DeviceId-" + _IoTDeviceId);
                logMessage.AppendLine("\tMessage:" + JsonConvert.SerializeObject(this));
                logMessage.AppendLine("\tException:" + ex.Message);
                ProvisionApp._appLogger.Error(logMessage);
                operationTask.UpdateTaskByFail(_TaskId, ex.Message);
            }
        }
Exemplo n.º 5
0
        public async void ThreadProc()
        {
            AzureSQLHelper.OperationTaskModel operationTask = new AzureSQLHelper.OperationTaskModel();
            try
            {
                var client       = new SendGridClient(_ApiKey);
                var from         = new EmailAddress(emailCtx.senderEmail, emailCtx.senderName);
                var to           = new EmailAddress(emailCtx.receverEmail, emailCtx.receverName);
                var emailContext = MailHelper.CreateSingleEmail(from, to, emailCtx.subject, emailCtx.plainTextContent, emailCtx.htmlContent);
                await client.SendEmailAsync(emailContext);

                EmailApp._appLogger.Info("[SendGrid Thread] send email success. Receive Email: " + emailCtx.receverEmail);
                operationTask.UpdateTaskBySuccess(_TaskId);
            }
            catch (Exception ex)
            {
                StringBuilder logMessage = new StringBuilder();
                logMessage.AppendLine("[Send Grid Thread] Failed. Receiver" + emailCtx.receverEmail);
                logMessage.AppendLine("\tMessage:" + JsonConvert.SerializeObject(this));
                logMessage.AppendLine("\tException:" + ex.Message);
                EmailApp._appLogger.Error(logMessage);
                operationTask.UpdateTaskByFail(_TaskId, ex.Message);
            }
        }
Exemplo n.º 6
0
        void ListenOnServiceBusQueue()
        {
            /* Create Queue client and listen on message  */
            _sbQueueClient = QueueClient.CreateFromConnectionString(_sbConnectionString, _sbProvisionQueue);
            OnMessageOptions options = new OnMessageOptions();

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

            _isRunning = true;

            _sbQueueClient.OnMessage((message) =>
            {
                string task;
                int taskId = 0;
                try
                {
                    // Process message from queue.
                    messageBody = message.GetBody <string>();
                    _appLogger.Info("Provision Task onMessage: " + messageBody);
                    _incomeMessage++;
                    JObject jsonMessage = JObject.Parse(messageBody);

                    if (jsonMessage["taskId"] == null || jsonMessage["task"] == null)
                    {
                        _appLogger.Warn("Incomplete message:" + messageBody);
                        _ignoreMessage++;
                        message.Complete();
                    }
                    else
                    {
                        taskId = int.Parse(jsonMessage["taskId"].ToString());
                        task   = jsonMessage["task"].ToString().ToLower();
                        _appLogger.Info("Received task: " + task);
                        switch (task)
                        {
                        case TaskName.CosmosdbCollection_Create:
                        case TaskName.CosmosdbCollection_Delete:
                        case TaskName.CosmosdbCollection_Update:
                            string CosmosDBConnectionString = jsonMessage["cosmosDBConnectionString"].ToString();
                            if (String.IsNullOrEmpty(CosmosDBConnectionString))
                            {
                                CosmosDBConnectionString = AzureSQLHelper.SystemConfigurationModel.GetCDSConfigValueByKey("CosmosDBConnectionString");
                            }

                            DocumentDBThread docDB   = new DocumentDBThread(CosmosDBConnectionString, jsonMessage, task, taskId);
                            Thread docDBthread       = new Thread(new ThreadStart(docDB.ThreadProc));
                            docDBthread.IsBackground = false;
                            docDBthread.Start();
                            message.Complete();
                            break;

                        case TaskName.IoTDevice_Register:
                        case TaskName.IoTDevice_Delete:
                            {
                                string IoTHubConnectionString = jsonMessage["Content"]["IothubConnectionString"].ToString();
                                if (String.IsNullOrEmpty(IoTHubConnectionString))
                                {
                                    _appLogger.Warn("IoT Hub Connection is NULL.");
                                    message.Complete();
                                }
                                else
                                {
                                    IoTHubDeviceRegisterThread iotDeviceRegister = new IoTHubDeviceRegisterThread(IoTHubConnectionString, jsonMessage, task, taskId);
                                    Thread iotDeviceRegisterThread       = new Thread(new ThreadStart(iotDeviceRegister.ThreadProc));
                                    iotDeviceRegisterThread.IsBackground = false;
                                    iotDeviceRegisterThread.Start();
                                    message.Complete();
                                }
                            }
                            break;

                        case TaskName.IoTHubReceiver_Launch:
                        case TaskName.IoTHubReceiver_Shutdown:
                            message.Complete();             //The following task may take longer, let message complete first
                            IoTHubReceiverThread iotHubReceiver = new IoTHubReceiverThread(messageBody);
                            Thread iotHubReceiverThread         = new Thread(new ThreadStart(iotHubReceiver.ThreadProc));
                            iotHubReceiverThread.IsBackground   = false;
                            iotHubReceiverThread.Start();
                            break;
                        }
                        _processedMessage++;
                    }
                }
                catch (Exception ex)
                {
                    // Indicates a problem, unlock message in subscription.
                    _failMessage++;
                    message.Complete();
                    StringBuilder logMessage = new StringBuilder();
                    logMessage.AppendLine("Provision Task Exception: " + ex.Message);
                    logMessage.AppendLine("Provision Task Message: " + messageBody);
                    _appLogger.Error(logMessage);
                    AzureSQLHelper.OperationTaskModel operationTask = new AzureSQLHelper.OperationTaskModel();
                    operationTask.UpdateTaskByFail(taskId, ex.Message);
                }
            }, options);
        }
Exemplo n.º 7
0
        private void ListenOnServiceBusTopic(CdsInfo cdsInfo)
        {
            CdsBackendSetting azureCS = cdsInfo.cdsBackendSetting;
            /* Create Topic Subscription Client, and bind with Message Property on companyid = xx */
            var       namespaceManager = NamespaceManager.CreateFromConnectionString(azureCS.ServiceBusConnectionString);
            string    subscriptionName = "C_" + cdsInfo.CompanyId + "_IoTHubId_" + cdsInfo.IoTHubId + "_P_" + cdsInfo.PartitionNum;
            SqlFilter messageFilter    = new SqlFilter("Process = 'IoTHubReceiver' AND IoTHubId = '" + cdsInfo.IoTHubId + "'");

            /* If the subscription not exist, create it. */
            if (!namespaceManager.SubscriptionExists(azureCS.ServiceBusProcessCommandTopic, subscriptionName))
            {
                namespaceManager.CreateSubscription(azureCS.ServiceBusProcessCommandTopic, subscriptionName, messageFilter);
            }

            /* Create subscription client and listen on message  */
            _sbSubscriptionClient = SubscriptionClient.CreateFromConnectionString(azureCS.ServiceBusConnectionString, azureCS.ServiceBusProcessCommandTopic, subscriptionName);
            OnMessageOptions options = new OnMessageOptions();

            options.AutoComplete = true;

            IoTHubReceiverModel _IoTHubReceiverMsg = null;

            _sbSubscriptionClient.OnMessage(async(message) =>
            {
                AzureSQLHelper.OperationTaskModel operationTask = new AzureSQLHelper.OperationTaskModel();

                try
                {
                    string messagePayload = message.GetBody <string>();
                    _IoTHubReceiverMsg    = JsonConvert.DeserializeObject <IoTHubReceiverModel>(messagePayload);

                    // Process message from subscription.
                    _consoleLog.Info("onMessage: {0}", messagePayload);
                    _consoleLog.BlobLogInfo("onMessage: {0}", messagePayload);

                    _consoleLog.Info("Received Task:" + _IoTHubReceiverMsg.task);
                    _consoleLog.BlobLogInfo("Received Task:" + _IoTHubReceiverMsg.task);

                    switch (_IoTHubReceiverMsg.task)
                    {
                    //case "start":
                    //    await _IoTHubMessageReceiver.Start();
                    //    break;
                    //case "stop":
                    //    await _IoTHubMessageReceiver.Stop();
                    //    break;
                    case TaskName.IoTHubReceiver_Restart:
                        reloadHeartbeatInterval();
                        _IoTHubMessageReceiver.Stop().Wait();
                        _IoTHubMessageReceiver.Start().Wait();
                        break;
                        //case "shutdown":
                        //    message.Complete();
                        //    await _IoTHubMessageReceiver.Stop();
                        //    operationTask.UpdateTaskBySuccess(_IoTHubReceiverMsg.taskId);
                        //    Environment.Exit(0);
                        //    break;
                    }
                    operationTask.UpdateTaskBySuccess(_IoTHubReceiverMsg.taskId);
                }
                catch (Exception ex)
                {
                    // Indicates a problem, unlock message in subscription.
                    _consoleLog.Error("Exception: {0}", ex.Message);
                    _consoleLog.BlobLogError("Exception: {0}", ex.Message);
                    operationTask.UpdateTaskByFail(_IoTHubReceiverMsg.taskId, ex.Message);
                }
            }, options);
        }
Exemplo n.º 8
0
        void ListenOnServiceBusQueue()
        {
            /* Create Queue client and listen on message  */
            _sbQueueClient = QueueClient.CreateFromConnectionString(_sbConnectionString, _sbSMSQueue);
            OnMessageOptions options = new OnMessageOptions();

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

            _isRunning = true;

            _sbQueueClient.OnMessage((message) =>
            {
                string task;
                int taskId = 0;
                try
                {
                    // Process message from queue.
                    messageBody = message.GetBody <string>();
                    StringBuilder logMessage = new StringBuilder();
                    logMessage.AppendLine("SMS Task onMessage: " + messageBody);
                    _incomeMessage++;
                    JObject jsonMessage = JObject.Parse(messageBody);

                    if (jsonMessage["taskId"] == null || jsonMessage["task"] == null)
                    {
                        _appLogger.Warn("Incomplete message:" + messageBody);
                        _ignoreMessage++;
                    }
                    else
                    {
                        taskId = int.Parse(jsonMessage["taskId"].ToString());
                        task   = jsonMessage["task"].ToString().ToLower();
                        _appLogger.Info("Received task: " + task);
                        if (task == "send sms")
                        {
                            string smsProvider = jsonMessage["smsProvider"].ToString().ToLower();
                            switch (smsProvider)
                            {
                            case "twilio":
                                TwilioThread twillo       = new TwilioThread(_twilioAccountId, _twilioToken, _twilioPhoneNumber, jsonMessage, taskId);
                                Thread twilloThread       = new Thread(new ThreadStart(twillo.ThreadProc));
                                twilloThread.IsBackground = false;
                                twilloThread.Start();
                                break;
                            }
                            _processedMessage++;
                        }
                        else
                        {
                            _ignoreMessage++;
                        }
                    }
                    message.Complete();
                }
                catch (Exception ex)
                {
                    // Indicates a problem, unlock message in subscription.
                    _failMessage++;
                    message.Complete();
                    StringBuilder logMessage = new StringBuilder();
                    logMessage.AppendLine("SMS Task Exception: " + ex.Message);
                    logMessage.AppendLine("SMS Task Message: " + messageBody);
                    _appLogger.Error(logMessage);
                    AzureSQLHelper.OperationTaskModel operationTask = new AzureSQLHelper.OperationTaskModel();
                    operationTask.UpdateTaskByFail(taskId, ex.Message);
                }
            }, options);
        }