Пример #1
0
        public void deleteIoTDevice(string iotHubDeviceId)
        {
            DBHelper._IoTDevice dbhelp            = new DBHelper._IoTDevice();
            IoTDevice           existingIoTDevice = dbhelp.GetByid(iotHubDeviceId);

            dbhelp.Delete(existingIoTDevice);
        }
Пример #2
0
        public List <Detail> GetAllIoTDeviceByCompanyId(int companyId)
        {
            DBHelper._IoTDevice dbhelp_iotDevice = new DBHelper._IoTDevice();
            DBHelper._Factory   dbhelp_factory   = new DBHelper._Factory();
            List <int>          factoryIdList    = dbhelp_factory.GetAllByCompanyId(companyId).Select(s => s.Id).ToList <int>();
            List <IoTDevice>    iotDeviceList    = new List <IoTDevice>();

            foreach (int factoryId in factoryIdList)
            {
                iotDeviceList.AddRange(dbhelp_iotDevice.GetAllByFactory(factoryId));
            }

            return(iotDeviceList.Select(s => new Detail()
            {
                IoTHubDeviceId = s.IoTHubDeviceID,
                IoTHubAlias = s.IoTHubAlias,
                IoTHubProtocol = s.IoTHubProtocol,
                FactoryId = s.FactoryID.ToString(),
                FactoryName = (s.Factory == null ? "" : s.Factory.Name),
                AuthenticationType = s.AuthenticationType,
                DeviceCertificateId = s.DeviceCertificateID.ToString(),
                DeviceCertificateName = (s.DeviceCertificate == null ? "" : s.DeviceCertificate.Name),
                DeviceTypeId = s.DeviceTypeId.ToString(),
                DeviceTypeName = (s.DeviceType == null ? "" : s.DeviceType.Name),
                DeviceVendor = s.DeviceVendor,
                DeviceModel = s.DeviceModel,
                DeviceConfigurationStatus = s.DeviceConfigurationStatus.ToString()
            }).ToList <Detail>());
        }
Пример #3
0
        public int GetIoTDeviceCompanyId(string iotHubDeviceId)
        {
            DBHelper._IoTDevice dbhelp            = new DBHelper._IoTDevice();
            IoTDevice           existingIoTDevice = dbhelp.GetByid(iotHubDeviceId);

            return(existingIoTDevice.Factory.CompanyId);
        }
Пример #4
0
        public void UpdateDBIoTDeviceKey(string deviceKey)
        {
            DBHelper._IoTDevice iotDeviceHelper = new DBHelper._IoTDevice();
            IoTDevice           iotDevice       = iotDeviceHelper.GetByid(this._IoTHubDeviceId);

            iotDevice.IoTHubDeviceKey = deviceKey;
            iotDeviceHelper.Update(iotDevice);
        }
Пример #5
0
        public void ResetIoTDevicePassword(string deviceId, string newPassword)
        {
            DBHelper._IoTDevice dbhelp    = new DBHelper._IoTDevice();
            IoTDevice           iotDevice = dbhelp.GetByid(deviceId);

            iotDevice.IoTHubDevicePW = Crypto.HashPassword(newPassword);
            dbhelp.Update(iotDevice);
        }
Пример #6
0
 public static bool IsIoTDeviceUnderCompany(string iotDeviceId, int companyId)
 {
     DBHelper._IoTDevice dbhelp = new DBHelper._IoTDevice();
     if (companyId == dbhelp.GetCompanyId(iotDeviceId))
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
Пример #7
0
        public bool CheckIoTDevicePassword(string deviceId, string password)
        {
            DBHelper._IoTDevice dbhelp    = new DBHelper._IoTDevice();
            IoTDevice           iotDevice = dbhelp.GetByid(deviceId);

            if (Crypto.VerifyHashedPassword(iotDevice.IoTHubDevicePW, password))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
Пример #8
0
        public void updateIoTDevice(string iotHubDeviceId, Update iotDevice)
        {
            DBHelper._IoTDevice dbhelp            = new DBHelper._IoTDevice();
            IoTDevice           existingIoTDevice = dbhelp.GetByid(iotHubDeviceId);

            existingIoTDevice.IoTHubAlias         = iotDevice.IoTHubAlias;
            existingIoTDevice.IoTHubProtocol      = iotDevice.IoTHubProtocol;
            existingIoTDevice.FactoryID           = iotDevice.FactoryId;
            existingIoTDevice.AuthenticationType  = iotDevice.AuthenticationType;
            existingIoTDevice.DeviceCertificateID = (iotDevice.DeviceCertificateId == 0) ? (int?)null : iotDevice.DeviceCertificateId;
            existingIoTDevice.DeviceTypeId        = iotDevice.DeviceTypeId;
            existingIoTDevice.DeviceVendor        = iotDevice.DeviceVendor;
            existingIoTDevice.DeviceModel         = iotDevice.DeviceModel;

            dbhelp.Update(existingIoTDevice);
        }
Пример #9
0
        public List <Detail_readonly> GetAllIoTDeviceByFactoryIdReadonly(int factoryId)
        {
            DBHelper._IoTDevice dbhelp_iotDevice = new DBHelper._IoTDevice();

            return(dbhelp_iotDevice.GetAllByFactory(factoryId).Select(s => new Detail_readonly()
            {
                IoTHubDeviceId = s.IoTHubDeviceID,
                IoTHubProtocol = s.IoTHubProtocol,
                FactoryId = s.FactoryID.ToString(),
                FactoryName = s.Factory.Name,
                DeviceTypeId = s.DeviceTypeId.ToString(),
                DeviceTypeName = s.DeviceType.Name,
                DeviceVendor = s.DeviceVendor,
                DeviceModel = s.DeviceModel
            }).ToList <Detail_readonly>());
        }
Пример #10
0
        public Detail_readonly getIoTDeviceByIdReadonly(string iotDeviceId)
        {
            DBHelper._IoTDevice dbhelp    = new DBHelper._IoTDevice();
            IoTDevice           iotDevice = dbhelp.GetByid(iotDeviceId);

            return(new Detail_readonly()
            {
                IoTHubDeviceId = iotDevice.IoTHubDeviceID,
                IoTHubProtocol = iotDevice.IoTHubProtocol,
                FactoryId = iotDevice.FactoryID.ToString(),
                FactoryName = iotDevice.Factory.Name,
                DeviceTypeId = iotDevice.DeviceTypeId.ToString(),
                DeviceTypeName = iotDevice.DeviceType.Name,
                DeviceVendor = iotDevice.DeviceVendor,
                DeviceModel = iotDevice.DeviceModel
            });
        }
Пример #11
0
        public void ChangeIoTDevicePassword(string deviceId, PasswordSet passwordSet)
        {
            DBHelper._IoTDevice dbhelp    = new DBHelper._IoTDevice();
            IoTDevice           iotDevice = dbhelp.GetByid(deviceId);

            if (iotDevice == null)
            {
                throw new Exception("404");
            }

            if (Crypto.VerifyHashedPassword(iotDevice.IoTHubDevicePW, passwordSet.OldPassword))
            {
                iotDevice.IoTHubDevicePW = Crypto.HashPassword(passwordSet.NewPassword);
                dbhelp.Update(iotDevice);
            }
            else
            {
                throw new Exception("401");
            }
        }
Пример #12
0
        public List <Detail> GetAllIoTDeviceByFactoryId(int factoryId)
        {
            DBHelper._IoTDevice dbhelp_iotDevice = new DBHelper._IoTDevice();

            return(dbhelp_iotDevice.GetAllByFactory(factoryId).Select(s => new Detail()
            {
                IoTHubDeviceId = s.IoTHubDeviceID,
                IoTHubAlias = s.IoTHubAlias,
                IoTHubProtocol = s.IoTHubProtocol,
                FactoryId = s.FactoryID.ToString(),
                FactoryName = (s.Factory == null ? "" : s.Factory.Name),
                AuthenticationType = s.AuthenticationType,
                DeviceCertificateId = s.DeviceCertificateID.ToString(),
                DeviceCertificateName = (s.DeviceCertificate == null ? "" : s.DeviceCertificate.Name),
                DeviceTypeId = s.DeviceTypeId.ToString(),
                DeviceTypeName = (s.DeviceType == null ? "" : s.DeviceType.Name),
                DeviceVendor = s.DeviceVendor,
                DeviceModel = s.DeviceModel,
                DeviceConfigurationStatus = s.DeviceConfigurationStatus.ToString()
            }).ToList <Detail>());
        }
Пример #13
0
        public Detail getIoTDeviceById(string iotHubDeviceId)
        {
            DBHelper._IoTDevice dbhelp    = new DBHelper._IoTDevice();
            IoTDevice           iotDevice = dbhelp.GetByid(iotHubDeviceId);

            return(new Detail()
            {
                IoTHubDeviceId = iotDevice.IoTHubDeviceID,
                IoTHubAlias = iotDevice.IoTHubAlias,
                IoTHubProtocol = iotDevice.IoTHubProtocol,
                FactoryId = iotDevice.Factory.Id.ToString(),
                FactoryName = (iotDevice.Factory == null ? "" : iotDevice.Factory.Name),
                AuthenticationType = iotDevice.AuthenticationType,
                DeviceCertificateId = iotDevice.DeviceCertificateID.ToString(),
                DeviceCertificateName = (iotDevice.DeviceCertificate == null ? "" : iotDevice.DeviceCertificate.Name),
                DeviceTypeId = iotDevice.DeviceTypeId.ToString(),
                DeviceTypeName = (iotDevice.DeviceType == null ? "" : iotDevice.DeviceType.Name),
                DeviceVendor = iotDevice.DeviceVendor,
                DeviceModel = iotDevice.DeviceModel,
                DeviceConfigurationStatus = iotDevice.DeviceConfigurationStatus.ToString()
            });
        }
Пример #14
0
        public void addIoTDevice(Add iotDevice)
        {
            DBHelper._IoTDevice dbhelp = new DBHelper._IoTDevice();
            var newIoTDevice           = new IoTDevice()
            {
                IoTHubDeviceID      = iotDevice.IoTHubDeviceId,
                IoTHubDevicePW      = Crypto.HashPassword(iotDevice.IoTHubDevicePW),
                IoTHubDeviceKey     = iotDevice.IoTHubDeviceKey,
                IoTHubAlias         = iotDevice.IoTHubAlias,
                IoTHubProtocol      = iotDevice.IoTHubProtocol,
                FactoryID           = iotDevice.FactoryId,
                AuthenticationType  = iotDevice.AuthenticationType,
                DeviceCertificateID = (iotDevice.DeviceCertificateId == 0) ? (int?)null : iotDevice.DeviceCertificateId,
                DeviceTypeId        = iotDevice.DeviceTypeId,
                DeviceVendor        = iotDevice.DeviceVendor,
                DeviceModel         = iotDevice.DeviceModel,
                DeviceTwinsDesired  = "{\"SF_CustomizedConfig\":{},\"SF_SystemConfig\":{}}",
                DeviceTwinsReported = "{\"SF_CustomizedConfig\":{},\"SF_SystemConfig\":{},\"SF_LastUpdatedTimestamp\":0}"
            };

            dbhelp.Add(newIoTDevice);
        }
Пример #15
0
        public List <Detail_readonly> GetAllIoTDeviceByCompanyIdReadonly(int companyId)
        {
            DBHelper._IoTDevice dbhelp_iotdevice = new DBHelper._IoTDevice();
            DBHelper._Factory   dbhelp_factory   = new DBHelper._Factory();
            List <IoTDevice>    iotDeviceList    = new List <IoTDevice>();
            List <int>          factoryIdList    = dbhelp_factory.GetAllByCompanyId(companyId).Select(s => s.Id).ToList <int>();

            foreach (int factoryId in factoryIdList)
            {
                iotDeviceList.AddRange(dbhelp_iotdevice.GetAllByFactory(factoryId));
            }
            return(iotDeviceList.Select(s => new Detail_readonly()
            {
                IoTHubDeviceId = s.IoTHubDeviceID,
                IoTHubProtocol = s.IoTHubProtocol,
                FactoryId = s.FactoryID.ToString(),
                FactoryName = s.Factory.Name,
                DeviceTypeId = s.DeviceTypeId.ToString(),
                DeviceTypeName = s.DeviceType.Name,
                DeviceVendor = s.DeviceVendor,
                DeviceModel = s.DeviceModel
            }).ToList <Detail_readonly>());
        }
Пример #16
0
        public List <Detail> GetAll(string deviceID)
        {
            DBHelper._IoTDevice dbhelp_iotDevice = new DBHelper._IoTDevice();
            DBHelper._IoTDeviceConfiguration           dbhelp_sysConfig        = new DBHelper._IoTDeviceConfiguration();
            DBHelper._IoTDeviceCustomizedConfiguration dbhelp_customizedConfig = new DBHelper._IoTDeviceCustomizedConfiguration();
            List <Detail> returnConfigList = new List <Detail>();

            IoTDevice iotDevice = dbhelp_iotDevice.GetByid(deviceID);
            int       companyId = iotDevice.Factory.CompanyId;
            /***** retrieve existing desired config *****/
            JObject desiredProperty = JObject.Parse(iotDevice.DeviceTwinsDesired);
            Dictionary <string, string> dic_existingSysDesiredConfig = new Dictionary <string, string>();

            if (desiredProperty["SF_SystemConfig"] != null)
            {
                JObject systemConfig = JObject.Parse(desiredProperty["SF_SystemConfig"].ToString());

                foreach (var obj in systemConfig)
                {
                    string value = obj.Value.Value <string>();
                    if (value == "True" || value == "False")
                    {
                        value = value.ToLower();
                    }

                    dic_existingSysDesiredConfig.Add(obj.Key, value);
                }
            }

            Dictionary <string, string> dic_existingCustomizedDesiredConfig = new Dictionary <string, string>();

            if (desiredProperty["SF_CustomizedConfig"] != null)
            {
                JObject customizedConfig = JObject.Parse(desiredProperty["SF_CustomizedConfig"].ToString());
                foreach (var obj in customizedConfig)
                {
                    string value = obj.Value.Value <string>();
                    if (value == "True" || value == "False")
                    {
                        value = value.ToLower();
                    }

                    dic_existingCustomizedDesiredConfig.Add(obj.Key, value);
                }
            }

            /***** retrieve existing reported config *****/
            JObject reportedProperty = JObject.Parse(iotDevice.DeviceTwinsReported);
            Dictionary <string, string> dic_existingSysReportedConfig = new Dictionary <string, string>();

            if (reportedProperty["SF_SystemConfig"] != null)
            {
                JObject systemConfig = JObject.Parse(reportedProperty["SF_SystemConfig"].ToString());
                foreach (var obj in systemConfig)
                {
                    dic_existingSysReportedConfig.Add(obj.Key, obj.Value.Value <string>());
                }
            }

            Dictionary <string, string> dic_existingCustomizedReportedConfig = new Dictionary <string, string>();

            if (reportedProperty["SF_CustomizedConfig"] != null)
            {
                JObject customizedConfig = JObject.Parse(reportedProperty["SF_CustomizedConfig"].ToString());
                foreach (var obj in customizedConfig)
                {
                    dic_existingCustomizedReportedConfig.Add(obj.Key, obj.Value.Value <string>());
                }
            }

            /***** return System Configuration *****/
            foreach (var config in dbhelp_sysConfig.GetAll())
            {
                if (dic_existingSysDesiredConfig.ContainsKey(config.Name))
                {
                    returnConfigList.Add(new Detail()
                    {
                        IsSystem                 = true,
                        Readonly                 = false,
                        ConfigurationName        = config.Name,
                        ConfigurationDataTye     = config.DataType,
                        ConfigurationDescription = config.Description,
                        DeviceValue              = dic_existingSysReportedConfig.ContainsKey(config.Name) ? dic_existingSysReportedConfig[config.Name] : "",
                        SettingValue             = dic_existingSysDesiredConfig[config.Name],
                        EnabledFlag              = true
                    });
                }
                else
                {
                    returnConfigList.Add(new Detail()
                    {
                        IsSystem                 = true,
                        Readonly                 = false,
                        ConfigurationName        = config.Name,
                        ConfigurationDataTye     = config.DataType,
                        ConfigurationDescription = config.Description,
                        DeviceValue              = "",
                        SettingValue             = config.DefaultValue,
                        EnabledFlag              = false
                    });
                }
            }

            /***** return Customized Configuration *****/
            List <string> list_deviceCustomizedConfigName = new List <string>();

            foreach (var config in dbhelp_customizedConfig.GetAllByCompanyId(companyId))
            {
                if (dic_existingCustomizedDesiredConfig.ContainsKey(config.Name))
                {
                    returnConfigList.Add(new Detail()
                    {
                        IsSystem                 = false,
                        Readonly                 = false,
                        ConfigurationName        = config.Name,
                        ConfigurationDataTye     = config.DataType,
                        ConfigurationDescription = config.Description,
                        DeviceValue              = dic_existingCustomizedReportedConfig.ContainsKey(config.Name) ? dic_existingCustomizedReportedConfig[config.Name] : "",
                        SettingValue             = dic_existingCustomizedDesiredConfig[config.Name],
                        EnabledFlag              = true
                    });
                }
                else
                {
                    returnConfigList.Add(new Detail()
                    {
                        IsSystem                 = false,
                        Readonly                 = false,
                        ConfigurationName        = config.Name,
                        ConfigurationDataTye     = config.DataType,
                        ConfigurationDescription = config.Description,
                        DeviceValue              = "",
                        SettingValue             = config.DefaultValue,
                        EnabledFlag              = false
                    });
                }
                list_deviceCustomizedConfigName.Add(config.Name);
            }

            /***** return Customized Configuration (readonly) *****/
            foreach (var config in dic_existingCustomizedReportedConfig)
            {
                if (!list_deviceCustomizedConfigName.Contains(config.Key))
                {
                    returnConfigList.Add(new Detail()
                    {
                        IsSystem                 = false,
                        Readonly                 = true,
                        ConfigurationName        = config.Key,
                        ConfigurationDataTye     = "",
                        ConfigurationDescription = "",
                        DeviceValue              = config.Value,
                        SettingValue             = "",
                        EnabledFlag              = false
                    });
                }
            }

            return(returnConfigList);
        }
Пример #17
0
        public void ThreadProc()
        {
            SFDatabaseEntities         dbEnty  = new SFDatabaseEntities();
            List <ExternalApplication> appList = (from alarm in dbEnty.AlarmNotification
                                                  join app in dbEnty.ExternalApplication on alarm.ExternalApplicationId equals app.Id
                                                  where alarm.AlarmRuleCatalogId == _AlarmRuleCatalogId
                                                  select app).ToList <ExternalApplication>();
            string exceptionString = "";

            foreach (var app in appList)
            {
                string     applicationTargetType = app.TargetType.ToLower();
                WebUtility webUtitlity           = new WebUtility();
                try
                {
                    string  response       = null;
                    JObject outputTemplate = new JObject();
                    switch (applicationTargetType)
                    {
                    case "external":
                        outputTemplate = ParsingOutputTemplate(app.MessageTemplate);
                        switch (app.Method.ToLower())
                        {
                        case "post-x-www":
                            string postData = ConvertJObjectToQueryString(outputTemplate);
                            switch (app.AuthType.ToLower())
                            {
                            case "none":

                                response = webUtitlity.PostContent(app.ServiceURL, postData);
                                break;

                            case "basic auth":
                                response = webUtitlity.PostContent(app.ServiceURL, postData, app.AuthID, app.AuthPW);
                                break;
                            }
                            break;

                        case "post-multi":
                            NameValueCollection formData = new NameValueCollection();
                            foreach (var elem in outputTemplate)
                            {
                                formData.Add(elem.Key, outputTemplate[elem.Key].ToString());
                            }
                            switch (app.AuthType.ToLower())
                            {
                            case "none":
                                response = webUtitlity.PostMultipartContent(app.ServiceURL, formData);
                                break;

                            case "basic auth":
                                break;
                            }
                            break;

                        case "post-json":
                            switch (app.AuthType.ToLower())
                            {
                            case "none":
                                response = webUtitlity.PostJsonContent(app.ServiceURL, JsonConvert.SerializeObject(outputTemplate));
                                break;

                            case "basic auth":
                                response = webUtitlity.PostJsonContent(app.ServiceURL, JsonConvert.SerializeObject(outputTemplate), app.AuthID, app.AuthPW);
                                break;
                            }
                            break;
                        }
                        break;

                    case "dashboard":
                        string defaultUrl = ConfigurationManager.AppSettings["RTMessageFeedInURL"];
                        response = webUtitlity.PostContent(defaultUrl, JsonConvert.SerializeObject(_FullAlarmMessage));
                        if (!response.Contains("OK"))
                        {
                            throw new Exception("RTMessageFeedIn Return: " + response);
                        }
                        break;

                    case "iot device":
                        string iotDeviceId            = app.ServiceURL;
                        DBHelper._IoTDevice dbhelp    = new DBHelper._IoTDevice();
                        IoTDevice           iotDevice = dbhelp.GetByid(iotDeviceId);

                        ServiceClient serviceClient = null;
                        try
                        {
                            serviceClient  = ServiceClient.CreateFromConnectionString(iotDevice.IoTHub.P_IoTHubConnectionString);
                            outputTemplate = ParsingOutputTemplate(app.MessageTemplate);
                            var msg = new Message(Encoding.ASCII.GetBytes(JsonConvert.SerializeObject(outputTemplate)));
                            serviceClient.SendAsync(iotDeviceId, msg);
                        }
                        catch (Exception ex)
                        {
                            Program._sfAppLogger.Error("External App:" + app.ServiceURL + "; Exception:" + ex.Message);
                        }
                        break;
                    }
                    Program._sfAppLogger.Debug("External App:" + app.ServiceURL + "; Result:" + response);
                }
                catch (Exception ex)
                {
                    exceptionString += "Push externalApplication " + app.Name + "(id:" + app.Id + ") failed: " + ex.Message + "\n";
                    continue;
                }

                Console.WriteLine("Push externalApplication success(type: " + app.TargetType + ")");
            }

            if (!string.IsNullOrEmpty(exceptionString))
            {
                Console.WriteLine(exceptionString);
                StringBuilder logMessage = new StringBuilder();
                logMessage.AppendLine("Exception: " + exceptionString);
                logMessage.AppendLine("\tMessageCatalogId:" + _MessageCatalogId);
                logMessage.AppendLine("\tAlarmRuleCatalogId:" + _AlarmRuleCatalogId);
                logMessage.AppendLine("\tMessagePayload:" + JsonConvert.SerializeObject(_Message));

                Program._sfAppLogger.Error(logMessage);
            }
            else
            {
                Console.WriteLine("Push all external application success!");
            }
        }
Пример #18
0
        public async Task <HttpResponseMessage> UploadPhotoFile(string id)
        {
            try
            {
                DeviceUtility deviceHelper = new DeviceUtility();

                // Check if the request contains multipart/form-data.
                if (!Request.Content.IsMimeMultipartContent())
                {
                    return(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
                }

                DeviceModels        deviceModel = new DeviceModels();
                DeviceModels.Detail iotDevice   = await deviceModel.GetIoTDeviceByDeviceId(id);

                FileUtility fileHelper = new FileUtility();
                string      root       = Path.GetTempPath();
                var         provider   = new MultipartFormDataStreamProvider(root);

                // Read the form data.
                string fileAbsoluteUri = "";
                await Request.Content.ReadAsMultipartAsync(provider);

                long logStartTimestamp = 0;

                //FormData
                foreach (var key in provider.FormData.AllKeys)
                {
                    foreach (var val in provider.FormData.GetValues(key))
                    {
                        if (key.ToLower().ToString() == "startts")
                        {
                            logStartTimestamp = long.Parse(val);
                        }
                    }
                }

                //FileData
                foreach (MultipartFileData fileData in provider.FileData)
                {
                    string formColumnName   = fileHelper.LowerAndFilterString(fileData.Headers.ContentDisposition.Name);
                    string fileExtenionName = fileHelper.LowerAndFilterString(fileData.Headers.ContentDisposition.FileName.Split('.')[1]);
                    if (formColumnName.ToLower().Equals("filename"))
                    {
                        DBHelper._IoTDevice dbhelp      = new DBHelper._IoTDevice();
                        IoTDevice           dbIoTDevice = dbhelp.GetByid(id);
                        DateTime            logStartDT  = deviceHelper.GetSpecifyTimeZoneDateTimeByTimeStamp(logStartTimestamp, dbIoTDevice.Factory.TimeZone);

                        string uploadFilePath = logStartDT.ToString("yyyy/MM/dd") + "/" + dbIoTDevice.IoTHubDeviceID + "/" + logStartTimestamp + "." + fileExtenionName;
                        fileAbsoluteUri = fileHelper.SaveFiletoStorage(fileData.LocalFileName, uploadFilePath, "log-device");
                    }
                }

                if (fileAbsoluteUri.Equals(""))
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "File is empty"));
                }

                return(Request.CreateResponse(HttpStatusCode.OK));
            }
            catch (System.Exception ex)
            {
                string logAPI = "[Post] " + Request.RequestUri.ToString();

                switch (ex.Message)
                {
                case "404":
                    return(Request.CreateResponse(HttpStatusCode.NotFound));
                }

                StringBuilder logMessage = LogUtility.BuildExceptionMessage(ex);
                Startup._sfAppLogger.Error(logAPI + logMessage);

                return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex));
            }
        }
        public async void ThreadProc()
        {
            try
            {
                string exceptionString              = "";
                DBHelper._IoTDevice dbhelper        = new DBHelper._IoTDevice();
                DBHelper._IoTHub    dbhelper_iotHub = new DBHelper._IoTHub();
                IoTDevice           iotDevice       = dbhelper.GetByid(_IoTHubDeviceId);
                int deviceConfigurationStatus       = iotDevice.DeviceConfigurationStatus;
                switch (_Action)
                {
                case "update deired":
                    exceptionString += await UpdateDeviceConfigurationToTwins(_PrimaryIothubConnectionString, "primary");

                    //exceptionString += await UpdateDeviceConfigurationToTwins(_SecondaryIothubConnectionString, "secondary");
                    if (_Status != TaskStatus.FAILED)
                    {
                        dbhelper.UpdateDeviceConfigurationStatusAndProperty(_IoTHubDeviceId, IoTDeviceConfigurationStatus.WAITING_DEVICE_ACK);
                    }
                    break;

                case "update db device reported":
                {
                    Thread.Sleep(30000);
                    string iotHubConnectionString = "";

                    //Get IoT Hub Device Twins Reported Value
                    IoTHub iotHub = dbhelper_iotHub.GetByid(_IoTHubAlias);
                    if (_IoTHubIsPrimary)
                    {
                        iotHubConnectionString = iotHub.P_IoTHubConnectionString;
                    }
                    else
                    {
                        iotHubConnectionString = iotHub.S_IoTHubConnectionString;
                    }

                    string reportedObjJsonString = await GetDeviceTwinsReportedValue(iotHubConnectionString, _IoTHubDeviceId);

                    Console.WriteLine(reportedObjJsonString);

                    //update db
                    dbhelper.UpdateDeviceConfigurationStatusAndProperty(_IoTHubDeviceId, IoTDeviceConfigurationStatus.RECEIVE_DEVICE_ACK, null, reportedObjJsonString);

                    return;
                    //recode to operationTask
                }
                break;
                }

                if (exceptionString == "")
                {
                    Program.UpdateTaskBySuccess(_TaskId);
                    Console.WriteLine("[DeviceManagement] Apply device configuration to IoTHub desired property success: IoTHubDeviceId-" + _IoTHubDeviceId);
                }
                else
                {
                    throw new Exception(exceptionString);
                }
            }
            catch (Exception ex)
            {
                StringBuilder logMessage = new StringBuilder();
                logMessage.AppendLine("[DeviceManagement] Apply device configuration to IoTHub desired property faild: IoTHubDeviceId-" + _IoTHubDeviceId);
                logMessage.AppendLine("\tMessage:" + JsonConvert.SerializeObject(this));
                logMessage.AppendLine("\tException:" + ex.Message);
                Program._sfAppLogger.Error(logMessage);
                Program.UpdateTaskByFail(_TaskId, Program.FilterErrorMessage(ex.Message), _Status);
                Console.WriteLine(logMessage);
                _Status = 0;
            }
        }
Пример #20
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);
        }
Пример #21
0
 public void updateIoTDeviceDesired(string iotHubDeviceId, JObject desiredProperty)
 {
     DBHelper._IoTDevice dbhelp = new DBHelper._IoTDevice();
     dbhelp.UpdateDeviceConfigurationStatusAndProperty(iotHubDeviceId, 0, JsonConvert.SerializeObject(desiredProperty));
 }