예제 #1
0
        public IHttpActionResult GetRolesByEmployeeId(int id)
        {
            RedisKey cacheKey   = "employee_" + id + "_Role";
            string   cacheValue = RedisCacheHelper.GetValueByKey(cacheKey);

            if (cacheValue == null)
            {
                using (var ctx = new SFDatabaseEntities())
                {
                    var roles = ctx.EmployeeInRole
                                .Where(s => s.EmployeeID == id && s.DeletedFlag == false)
                                .Select(s => new EmployeeRoleModels.Detail()
                    {
                        UserRoleId   = s.UserRoleID,
                        UserRoleName = s.UserRole.Name
                    }).ToList <EmployeeRoleModels.Detail>();

                    RedisCacheHelper.SetKeyValue(cacheKey, new JavaScriptSerializer().Serialize(roles));
                    return(Ok(roles));
                }
            }
            else
            {
                return(Ok(new JavaScriptSerializer().Deserialize <List <Object> >(cacheValue)));
            }
        }
예제 #2
0
        public IHttpActionResult DeleteSuperAdminById(int id)
        {
            string logAPI = "[Post] " + Request.RequestUri.ToString();

            using (var ctx = new SFDatabaseEntities())
            {
                var superAdmin = ctx.SuperAdmin
                                 .Where(s => s.Id == id)
                                 .FirstOrDefault();
                if (superAdmin != null)
                {
                    superAdmin.DeletedFlag = true;
                    try
                    {
                        ctx.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        StringBuilder logMessage = LogUtility.BuildExceptionMessage(ex);
                        Startup._sfAppLogger.Error(logAPI + logMessage);
                        return(InternalServerError());
                    }
                }
                else
                {
                    return(NotFound());
                }
            }
            return(Ok("Success"));
        }
예제 #3
0
        public IHttpActionResult Delete(int factoryId)
        {
            using (var ctx = new SFDatabaseEntities())
            {
                var factory = ctx.Factory
                              .Where(s => s.Id == factoryId)
                              .FirstOrDefault();
                if (factory != null)
                {
                    factory.DeletedFlag = true;
                    try
                    {
                        ctx.SaveChanges();
                    }
                    catch
                    {
                        return(InternalServerError());
                    }
                }
                else
                {
                    return(NotFound());
                }
            }

            return(Ok("Success"));
        }
예제 #4
0
        public DocDB_AlarmMessageModels(int companyId)
        {
            SFDatabaseEntities dbEnty = new SFDatabaseEntities();

            _ConnectionString = (from c in dbEnty.Company
                                 where c.Id == companyId
                                 select c.DocDBConnectionString).Single <string>();
            if (string.IsNullOrEmpty(_ConnectionString))
            {
                _ConnectionString = ConfigurationManager.AppSettings["sfDocDBConnectionString"];
            }

            _DBName         = "db" + companyId;
            _CollecitonName = companyId.ToString();
            _CollectionLink = UriFactory.CreateDocumentCollectionUri(_DBName, _CollecitonName);

            try
            {
                //init DocumentClient
                _ConnectionString = _ConnectionString.Replace("AccountEndpoint=", "");
                _ConnectionString = _ConnectionString.Replace(";", "");
                _ConnectionString = _ConnectionString.Replace("AccountKey=", ";");
                string endpointUri = _ConnectionString.Split(';')[0];
                string primaryKey  = _ConnectionString.Split(';')[1];
                _Client = new DocumentClient(new Uri(endpointUri), primaryKey);
            }
            catch (Exception ex)
            {
                throw new Exception("Initial DocumentClient failed: " + ex.Message);
            }
        }
예제 #5
0
        public int getCompanyId(string equipmentId)
        {
            SFDatabaseEntities dbEntity = new SFDatabaseEntities();
            int companyId = (from c in dbEntity.Equipment
                             where c.EquipmentId == equipmentId
                             select c.Factory.CompanyId).Single <int>();

            return(companyId);
        }
예제 #6
0
        public object GetAllPermissionById(int id)
        {
            SFDatabaseEntities dbEntity = new SFDatabaseEntities();
            var L2Enty = from er in dbEntity.EmployeeInRole.AsNoTracking()
                         join urp in dbEntity.UserRolePermission on er.UserRoleID equals urp.UserRoleID
                         where er.EmployeeID == id && er.DeletedFlag == false && urp.DeletedFlag == false
                         orderby urp.PermissionCatalog.PermissionId ascending
                         select urp.PermissionCatalog;

            List <PermissionCatalog> permissionList = L2Enty.Distinct().ToList <PermissionCatalog>();

            return(permissionList.Select(s => new  {
                PermissionId = s.PermissionId,
                PermissionName = s.Name
            }));
        }
예제 #7
0
 public IHttpActionResult GetAllEquipmentClassByCompanyId(int companyId)
 {
     using (var ctx = new SFDatabaseEntities())
     {
         var equipClasses = ctx.EquipmentClass
                            .Where(s => s.CompanyId == companyId && s.DeletedFlag == false)
                            .Select(s => new EquipmentClassModels.Detail()
         {
             Id          = s.Id,
             CompanyId   = s.CompanyId,
             CompanyName = s.Company.Name,
             Name        = s.Name,
             Description = s.Description
         }).ToList <EquipmentClassModels.Detail>();
         return(Ok(equipClasses));
     }
 }
예제 #8
0
파일: Device.cs 프로젝트: KevinKao809/CDS10
        public async Task <Detail> GetIoTDeviceByDeviceId(string deviceId)
        {
            DeviceUtility      deviceHelper = new DeviceUtility();
            SFDatabaseEntities dbEnty       = new SFDatabaseEntities();
            var device = dbEnty.IoTDevice.Find(deviceId);

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

            Detail returnDeviceInfo = new Detail()
            {
                DeviceId                 = device.IoTHubDeviceID,
                IoTHubProtocol           = device.IoTHubProtocol,
                IoTHubAuthenticationType = device.AuthenticationType
            };

            //Confirm connectionstring
            if (await deviceHelper.CheckIoTHubConnectionString(device.IoTHub.P_IoTHubConnectionString, device.IoTHubDeviceID))
            {
                returnDeviceInfo.IoTHubName    = device.IoTHub.P_IoTHubConnectionString.Split(';')[0].Split('=')[1];
                returnDeviceInfo.ContainerName = device.IoTHub.P_UploadContainer;
            }
            else if (await deviceHelper.CheckIoTHubConnectionString(device.IoTHub.S_IoTHubConnectionString, device.IoTHubDeviceID))
            {
                returnDeviceInfo.IoTHubName    = device.IoTHub.S_IoTHubConnectionString.Split(';')[0].Split('=')[1];
                returnDeviceInfo.ContainerName = device.IoTHub.S_UploadContainer;
            }
            else
            {
                throw new Exception("None vaild IoT Hub");
            }

            if (returnDeviceInfo.IoTHubAuthenticationType == "Key")
            {
                returnDeviceInfo.DeviceKey = device.IoTHubDeviceKey;
            }
            else if (returnDeviceInfo.IoTHubAuthenticationType == "Certificate")
            {
                returnDeviceInfo.CertificateFileName = device.DeviceCertificate.FileName;
                returnDeviceInfo.CertificatePassword = device.DeviceCertificate.PFXPassword;
            }

            return(returnDeviceInfo);
        }
예제 #9
0
        public IHttpActionResult GetAllSuperAdmins()
        {
            using (var ctx = new SFDatabaseEntities())
            {
                var superAdmins = ctx.SuperAdmin
                                  .Select(s => new SuperAdminModels.Detail
                {
                    Id          = s.Id,
                    FirstName   = s.FirstName,
                    LastName    = s.LastName,
                    Email       = s.Email,
                    CreatedAt   = s.CreatedAt,
                    DeletedFlag = s.DeletedFlag
                }).ToList <SuperAdminModels.Detail>();

                return(Ok(superAdmins));
            }
        }
예제 #10
0
        public List <Detail_EquipmentClass> getAllEquipmentClassDashboardByCompnayId(int companyId)
        {
            List <Detail_EquipmentClass> resultList = new List <Detail_EquipmentClass>();
            SFDatabaseEntities           dbEntity   = new SFDatabaseEntities();
            var allFactoryIds = from c in dbEntity.Factory.AsNoTracking()
                                where c.CompanyId == companyId && c.DeletedFlag == false
                                select c.Id;

            var allEquipmentClassesGroup = from c in dbEntity.Equipment.AsNoTracking()
                                           where allFactoryIds.Contains(c.FactoryId) && c.DeletedFlag == false
                                           join ec in dbEntity.EquipmentClass on c.EquipmentClassId equals ec.Id
                                           select ec;

            var allEquipmentClasses = allEquipmentClassesGroup.GroupBy(equipmentClass => equipmentClass.Id)
                                      .Select(s => s.FirstOrDefault())
                                      .Select(s => new Detail_EquipmentClass()
            {
                EquipmentClassId   = s.Id,
                EquipmentClassName = s.Name,
                Description        = s.Description,
                IsReady            = false
            });

            var allExistEquipmentClassDashboards = from c in dbEntity.Dashboard.AsNoTracking()
                                                   where c.CompanyID == companyId && c.DashboardType == "EquipmentClass"
                                                   select c;
            var existingEquipmentClassId = from c in allExistEquipmentClassDashboards
                                           select c.EquipmentClassID;

            foreach (var equipmentClass in allEquipmentClasses)
            {
                if (existingEquipmentClassId.Contains(equipmentClass.EquipmentClassId))
                {
                    equipmentClass.IsReady = true;
                    var tmp = from c in allExistEquipmentClassDashboards
                              where c.EquipmentClassID == equipmentClass.EquipmentClassId
                              select c.Id;
                    equipmentClass.DashboardId = tmp.FirstOrDefault();
                }
                resultList.Add(equipmentClass);
            }

            return(resultList);
        }
예제 #11
0
        public IHttpActionResult AddFactoryFormData([FromBody] FactoryModels.Edit factory)
        {
            JavaScriptSerializer js = new JavaScriptSerializer();
            string logForm          = "Form : " + js.Serialize(factory);
            string logAPI           = "[Post] " + Request.RequestUri.ToString();

            if (!ModelState.IsValid || factory == null)
            {
                Startup._sfAppLogger.Warn(logAPI + " || Input Parameter not expected || " + logForm);
                return(BadRequest("Invalid data"));
            }

            var newFactory = new Factory()
            {
                Name        = factory.Name,
                Description = factory.Description,
                CompanyId   = factory.CompanyId,
                Latitude    = (float)factory.Latitude,
                Longitude   = (float)factory.Longitude,
                CultureInfo = factory.CultureInfoId,
                TimeZone    = factory.TimeZone,
                CreatedAt   = DateTime.Parse(DateTime.Now.ToString()),
                DeletedFlag = false
            };

            using (var ctx = new SFDatabaseEntities())
            {
                ctx.Factory.Add(newFactory);
                try
                {
                    ctx.SaveChanges();
                }
                catch (Exception ex)
                {
                    StringBuilder logMessage = LogUtility.BuildExceptionMessage(ex);
                    logMessage.AppendLine(logForm);
                    Startup._sfAppLogger.Error(logAPI + logMessage);

                    return(InternalServerError(ex));
                }
            }
            return(Json(new { id = newFactory.Id }));
        }
예제 #12
0
        public IHttpActionResult EditSuperAdminById(int id, [FromBody] SuperAdminModels.Edit superAdmin)
        {
            string logForm = "Form : " + Startup._jsSerializer.Serialize(superAdmin);
            string logAPI  = "[Post] " + Request.RequestUri.ToString();

            if (!ModelState.IsValid)
            {
                return(BadRequest("Invalid data"));
            }


            using (var ctx = new SFDatabaseEntities())
            {
                var existingSuperAdmin = ctx.SuperAdmin
                                         .Where(s => s.Id == id)
                                         .FirstOrDefault();
                if (existingSuperAdmin != null)
                {
                    existingSuperAdmin.FirstName   = superAdmin.FirstName;
                    existingSuperAdmin.LastName    = superAdmin.LastName;
                    existingSuperAdmin.Email       = superAdmin.Email;
                    existingSuperAdmin.UpdatedAt   = DateTime.Parse(DateTime.Now.ToString());
                    existingSuperAdmin.DeletedFlag = superAdmin.DeletedFlag;
                    try
                    {
                        ctx.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        StringBuilder logMessage = LogUtility.BuildExceptionMessage(ex);
                        logMessage.AppendLine(logForm);
                        Startup._sfAppLogger.Error(logAPI + logMessage);
                        return(InternalServerError());
                    }
                }
                else
                {
                    return(NotFound());
                }

                return(Ok("Success"));
            }
        }
예제 #13
0
        public IHttpActionResult ChangePassword(int id, [FromBody] ChangePasswordModels newPasswords)
        {
            string logForm = "Form : " + Startup._jsSerializer.Serialize(newPasswords);
            string logAPI  = "[Post] " + Request.RequestUri.ToString();

            if (!ModelState.IsValid)
            {
                return(BadRequest("Invalid data"));
            }

            using (var ctx = new SFDatabaseEntities())
            {
                var existingSuperAdmin = ctx.SuperAdmin
                                         .Where(s => s.Id == id)
                                         .FirstOrDefault();

                if (existingSuperAdmin == null)
                {
                    return(NotFound());
                }

                if (Crypto.VerifyHashedPassword(existingSuperAdmin.Password, newPasswords.OldPassword))
                {
                    existingSuperAdmin.Password = Crypto.HashPassword(newPasswords.NewPassword);
                    try
                    {
                        ctx.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        StringBuilder logMessage = LogUtility.BuildExceptionMessage(ex);
                        logMessage.AppendLine(logForm);
                        Startup._sfAppLogger.Error(logAPI + logMessage);
                        return(InternalServerError());
                    }
                }
                else
                {
                    return(Unauthorized());
                }
            }
            return(Ok("Success"));
        }
예제 #14
0
        public IHttpActionResult AddRolesByEmployeeId(int id, [FromBody] EmployeeRoleModels.Edit roles)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            using (var ctx = new SFDatabaseEntities())
            {
                foreach (var roleId in roles.UserRoleId)
                {
                    EmployeeInRole newEmployeeRole = new EmployeeInRole()
                    {
                        EmployeeID  = id,
                        UserRoleID  = roleId,
                        CreatedAt   = DateTime.Parse(DateTime.Now.ToString()),
                        DeletedFlag = false
                    };
                    ctx.EmployeeInRole.Add(newEmployeeRole);
                }

                StringBuilder logMessage = new StringBuilder();
                try
                {
                    ctx.SaveChanges();
                    RedisCacheHelper.DeleteEmployeeCache(id);

                    logMessage.AppendLine("(AddRolesByEmployeeId) Delete EmployCache: " + id);
                    Startup._sfAppLogger.Debug(logMessage);
                    return(Ok());
                }
                catch (Exception ex)
                {
                    logMessage.AppendLine("(AddRolesByEmployeeId) Excepton on Delete EmployCache: " + id + "; Exception:" + ex.Message);
                    Startup._sfAppLogger.Error(logMessage);
                    return(InternalServerError());
                }
            }
        }
예제 #15
0
        public IHttpActionResult AddSuperAdmin([FromBody] SuperAdminModels.Edit superAdmin)
        {
            string logForm = "Form : " + Startup._jsSerializer.Serialize(superAdmin);
            string logAPI  = "[Post] " + Request.RequestUri.ToString();

            if (!ModelState.IsValid)
            {
                Startup._sfAppLogger.Warn(logAPI + " || Input Parameter not expected || " + logForm);
                return(BadRequest("Invalid data"));
            }

            using (var ctx = new SFDatabaseEntities())
            {
                SuperAdmin newSuperAdmin = new SuperAdmin()
                {
                    FirstName   = superAdmin.FirstName,
                    LastName    = superAdmin.LastName,
                    Email       = superAdmin.Email,
                    Password    = Crypto.HashPassword(superAdmin.Password),
                    CreatedAt   = DateTime.Parse(DateTime.Now.ToString()),
                    DeletedFlag = superAdmin.DeletedFlag
                };

                ctx.SuperAdmin.Add(newSuperAdmin);
                try
                {
                    ctx.SaveChanges();
                    return(Ok());
                }
                catch (Exception ex)
                {
                    StringBuilder logMessage = LogUtility.BuildExceptionMessage(ex);
                    logMessage.AppendLine(logForm);
                    Startup._sfAppLogger.Error(logAPI + logMessage);
                    return(InternalServerError());
                }
            }
        }
예제 #16
0
        public IHttpActionResult GetSuperAdminById(int id)
        {
            using (var ctx = new SFDatabaseEntities())
            {
                var superAdmin = ctx.SuperAdmin
                                 .Where(s => s.Id == id)
                                 .Select(s => new SuperAdminModels.Detail()
                {
                    Id          = s.Id,
                    FirstName   = s.FirstName,
                    LastName    = s.LastName,
                    Email       = s.Email,
                    CreatedAt   = s.CreatedAt,
                    DeletedFlag = s.DeletedFlag
                }).FirstOrDefault <SuperAdminModels.Detail>();

                if (superAdmin == null)
                {
                    return(NotFound());
                }
                return(Ok(superAdmin));
            }
        }
예제 #17
0
        public IHttpActionResult EditFactoryFormData(int factoryId, [FromBody] FactoryModels.Edit factory)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Invalid data"));
            }
            using (var ctx = new SFDatabaseEntities())
            {
                var existingFactory = ctx.Factory
                                      .Where(s => s.Id == factoryId && s.DeletedFlag == false)
                                      .FirstOrDefault();
                if (existingFactory != null)
                {
                    existingFactory.Name        = factory.Name;
                    existingFactory.Description = factory.Description;
                    existingFactory.TimeZone    = factory.TimeZone;
                    existingFactory.Latitude    = factory.Latitude;
                    existingFactory.Longitude   = factory.Longitude;
                    existingFactory.CultureInfo = factory.CultureInfoId;
                    existingFactory.UpdatedAt   = DateTime.Parse(DateTime.Now.ToString());

                    try
                    {
                        ctx.SaveChanges();
                    }
                    catch
                    {
                        return(InternalServerError());
                    }
                }
                else
                {
                    return(NotFound());
                }
            }
            return(Ok("Success"));
        }
예제 #18
0
        private Dictionary <int, List <AlarmRuleCatalogEngine> > findAllMessageAlarmRules(string iotHubAlias)
        {
            Dictionary <int, List <AlarmRuleCatalogEngine> > messageIdAlarmRules = new Dictionary <int, List <AlarmRuleCatalogEngine> >();

            SFDatabaseEntities dbEntity = new SFDatabaseEntities();
            var L2Enty = from c in dbEntity.IoTDevice
                         join msgCatalog in dbEntity.IoTDeviceMessageCatalog on c.IoTHubDeviceID equals msgCatalog.IoTHubDeviceID
                         where c.IoTHubAlias == iotHubAlias && msgCatalog.MessageCatalog.DeletedFlag == false
                         select msgCatalog.MessageCatalog;
            List <MessageCatalog> mcList = L2Enty.Distinct().ToList <MessageCatalog>();

            foreach (MessageCatalog mc in mcList)
            {
                List <AlarmRuleCatalogEngine> arcEngineList = new List <AlarmRuleCatalogEngine>();
                foreach (AlarmRuleCatalog arc in mc.AlarmRuleCatalog)
                {
                    if (arc.DeletedFlag == false && arc.ActiveFlag == true)
                    {
                        ConsoleLog.WriteMessageAlarmLogToConsole("AlarmRuleCatalogId={0}", arc.Id);

                        AlarmRuleCatalogEngine are = new AlarmRuleCatalogEngine();
                        are.AlarmRuleCatalogId = arc.Id;
                        are.AlarmRuleCatalog   = arc;
                        are.RuleEngineItems    = createRuleEngineItem(arc.Id);
                        are.LastTriggerTime    = new DateTime(2017, 1, 1);
                        are.Triggered          = false;

                        arcEngineList.Add(are);
                    }
                }

                messageIdAlarmRules.Add(mc.Id, arcEngineList);
            }

            return(messageIdAlarmRules);
        }
예제 #19
0
        public IHttpActionResult GetAll()
        {
            RedisKey cacheKey   = "cultureCodesJson";
            string   cacheValue = RedisCacheHelper.GetValueByKey(cacheKey);

            if (cacheValue == null)
            {
                using (var ctx = new SFDatabaseEntities())
                {
                    var cultureCodes = ctx.RefCultureInfo
                                       .Select(s => new RefCultureInfoModels()
                    {
                        CultureCode = s.CultureCode,
                        Name        = s.Name
                    }).ToList <RefCultureInfoModels>();
                    RedisCacheHelper.SetKeyValue(cacheKey, new JavaScriptSerializer().Serialize(cultureCodes));
                    return(Ok(cultureCodes));
                }
            }
            else
            {
                return(Ok(new JavaScriptSerializer().Deserialize <List <RefCultureInfoModels> >(cacheValue)));
            }
        }
예제 #20
0
        public List <Detail> searchInPastSevenDaysOperations(SearchCondition condition, int companyId = 0)
        {
            int    hours;
            string taskStatus;

            if (condition == null)
            {
                hours      = -168;
                taskStatus = null;
            }
            else
            {
                hours      = (condition.hours == 0 || condition.hours > 168) ? -168 : -(condition.hours);
                taskStatus = condition.taskStatus;
            }

            DBHelper._OperationTask dbhelp                     = new DBHelper._OperationTask();
            DBHelper._Company       dbhelp_company             = new DBHelper._Company();
            List <OperationTask>    operationTaskList          = new List <OperationTask>();
            List <Detail>           returnOperationtTaskDetail = new List <Detail>();

            if (companyId > 0)
            {
                operationTaskList = dbhelp.Search(taskStatus, hours, companyId);
                Company company = dbhelp_company.GetByid(companyId);

                foreach (OperationTask operationTask in operationTaskList)
                {
                    try
                    {
                        returnOperationtTaskDetail.Add(new Detail()
                        {
                            Id           = operationTask.Id,
                            Name         = operationTask.Name,
                            TaskStatus   = operationTask.TaskStatus,
                            CompanyId    = operationTask.CompanyId,
                            CompanyName  = company == null ? "" : company.Name,
                            CompletedAt  = operationTask.CompletedAt,
                            RetryCounter = (operationTask.RetryCounter == null) ? "" : operationTask.RetryCounter.ToString(),
                            Entity       = operationTask.Entity,
                            EntityId     = operationTask.EntityId,
                            TaskContent  = (operationTask.TaskContent == null) ? null : JObject.Parse(operationTask.TaskContent),
                            TaskLog      = operationTask.TaskLog
                        });
                    }
                    catch { }
                }
            }
            else
            {
                operationTaskList = dbhelp.Search(taskStatus, hours);

                List <int>         companyIdList = operationTaskList.Select(s => s.CompanyId).Distinct().ToList <int>();
                SFDatabaseEntities dbEntity      = new SFDatabaseEntities();
                var L2Enty = from c in dbEntity.Company
                             where companyIdList.Contains(c.Id)
                             select new { Id = c.Id, Name = c.Name };
                Dictionary <int, string> companyTable = new Dictionary <int, string>();
                foreach (var company in L2Enty)
                {
                    companyTable.Add(company.Id, company.Name);
                }

                foreach (OperationTask operationTask in operationTaskList)
                {
                    try
                    {
                        returnOperationtTaskDetail.Add(new Detail()
                        {
                            Id           = operationTask.Id,
                            Name         = operationTask.Name,
                            TaskStatus   = operationTask.TaskStatus,
                            CompanyId    = operationTask.CompanyId,
                            CompanyName  = companyTable.ContainsKey(operationTask.CompanyId) ? companyTable[operationTask.CompanyId] : "",
                            CompletedAt  = operationTask.CompletedAt,
                            RetryCounter = (operationTask.RetryCounter == null) ? "" : operationTask.RetryCounter.ToString(),
                            Entity       = operationTask.Entity,
                            EntityId     = operationTask.EntityId,
                            TaskContent  = (operationTask.TaskContent == null) ? null : JObject.Parse(operationTask.TaskContent),
                            TaskLog      = operationTask.TaskLog
                        });
                    }
                    catch { }
                }
            }

            return(returnOperationtTaskDetail);
        }
예제 #21
0
        //帳密驗證
        private UserClaims loginAuthentication(string id, string password, string role)
        {
            UserClaims userClaims = new UserClaims();

            userClaims.IsAuthenticated = false;
            userClaims.CompanyId       = 0;

            switch (role)
            {
            case "superadmin":
                using (var ctx = new SFDatabaseEntities())
                {
                    var superAdmin = ctx.SuperAdmin
                                     .Where(s => s.Email == id && s.DeletedFlag == false)
                                     .Select(s => new { s.Password }).FirstOrDefault();

                    try
                    {
                        if (Crypto.VerifyHashedPassword(superAdmin.Password, password))
                        {
                            userClaims.IsAuthenticated = true;
                        }
                    }
                    catch
                    {
                    }
                }
                break;

            case "admin":
                using (var ctx = new SFDatabaseEntities())
                {
                    var employee = ctx.Employee
                                   .Where(s => s.Email == id && s.DeletedFlag == false && s.Company.DeletedFlag == false)
                                   .Select(s => new { s.Password }).FirstOrDefault();

                    try
                    {
                        if (Crypto.VerifyHashedPassword(employee.Password, password))
                        {
                            userClaims.IsAuthenticated = true;
                        }
                    }
                    catch
                    {
                    }
                }
                break;

            case "device":
                AccountModels accountModels = new AccountModels();
                userClaims.IsAuthenticated = accountModels.CheckIoTDevicePassword(id, password);
                break;

            case "external":
                using (var ctx = new SFDatabaseEntities())
                {
                    var company = ctx.Company
                                  .Where(s => s.ExtAppAuthenticationKey == password && s.DeletedFlag == false)
                                  .Select(s => new { s.Id }).FirstOrDefault();
                    if (company != null)
                    {
                        userClaims.IsAuthenticated = true;
                        userClaims.CompanyId       = company.Id;
                    }
                }
                break;
            }
            return(userClaims);
        }
예제 #22
0
        //Add return token info
        private AuthenticationProperties addTokenOtherInfo(string id, string role)
        {
            var tokenOtherInfo = new AuthenticationProperties(new Dictionary <string, string> {
            });

            switch (role)
            {
            case "admin":
                using (var ctx = new SFDatabaseEntities())
                {
                    var employee = ctx.Employee
                                   .Where(s => s.Email == id && s.DeletedFlag == false)
                                   .Select(s => new EmployeeModels.Detail
                    {
                        Id             = s.Id,
                        CompanyId      = s.CompanyId,
                        EmployeeNumber = s.EmployeeNumber,
                        FirstName      = s.FirstName,
                        LastName       = s.LastName,
                        Email          = s.Email,
                        PhotoURL       = s.PhotoURL,
                        AdminFlag      = s.AdminFlag,
                        Lang           = s.Lang
                    }).FirstOrDefault();

                    if (employee != null)
                    {
                        var employeeTokenInfo = new AuthenticationProperties(new Dictionary <string, string>
                        {
                            { "Id", employee.Id.ToString() },
                            { "CompanyId", employee.CompanyId.ToString() },
                            { "EmployeeNumber", (employee.EmployeeNumber != null) ? employee.EmployeeNumber : "" },
                            { "FirstName", (employee.FirstName != null) ? employee.FirstName.ToString() : "" },
                            { "LastName", (employee.LastName != null) ? employee.LastName.ToString() : "" },
                            { "Email", employee.Email },
                            { "PhotoURL", (employee.PhotoURL != null) ? employee.PhotoURL.ToString() : "" },
                            { "Lang", (employee.Lang != null) ? employee.Lang.ToString() : "" },
                            { "AdminFlag", employee.AdminFlag.ToString() }
                        });
                        return(employeeTokenInfo);
                    }
                }
                break;

            case "superadmin":
                using (var ctx = new SFDatabaseEntities())
                {
                    var superAdmin = ctx.SuperAdmin
                                     .Where(s => s.Email == id && s.DeletedFlag == false)
                                     .Select(s => new SuperAdminModels.Detail {
                        Id        = s.Id,
                        FirstName = s.FirstName,
                        LastName  = s.LastName,
                        Email     = s.Email
                    }).FirstOrDefault();

                    if (superAdmin != null)
                    {
                        var superAdminTokenInfo = new AuthenticationProperties(new Dictionary <string, string>
                        {
                            { "Id", superAdmin.Id.ToString() },
                            { "FirstName", (superAdmin.FirstName != null) ? superAdmin.FirstName.ToString() : "" },
                            { "LastName", (superAdmin.LastName != null) ? superAdmin.LastName.ToString() : "" },
                            { "Email", superAdmin.Email }
                        });
                        return(superAdminTokenInfo);
                    }
                }
                break;
            }
            return(null);
        }
예제 #23
0
        public IHttpActionResult EditRolesByEmployeeId(int id, [FromBody] EmployeeRoleModels.Edit roles)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            using (var ctx = new SFDatabaseEntities())
            {
                var existingRoles = ctx.EmployeeInRole
                                    .Where(s => s.EmployeeID == id)
                                    .Select(s => s).ToList();

                //調整現有的Role
                List <int> existingRolesId = new List <int>();
                if (existingRoles != null)
                {
                    foreach (var er in existingRoles)
                    {
                        if (roles == null || (!roles.UserRoleId.Contains(er.UserRoleID) && !er.DeletedFlag))
                        {
                            er.DeletedFlag = true;
                            er.UpdatedAt   = DateTime.Parse(DateTime.Now.ToString());
                        }
                        else if (roles.UserRoleId.Contains(er.UserRoleID) && er.DeletedFlag)
                        {
                            er.DeletedFlag = false;
                            er.UpdatedAt   = DateTime.Parse(DateTime.Now.ToString());
                        }

                        existingRolesId.Add(er.UserRoleID);
                    }
                }
                //新增沒有的Role
                if (roles != null)
                {
                    foreach (var userRoleId in roles.UserRoleId)
                    {
                        if (existingRoles == null || (userRoleId > 0 && !existingRolesId.Contains(userRoleId)))
                        {
                            var newEmployeeRole = new EmployeeInRole()
                            {
                                EmployeeID = id,
                                UserRoleID = userRoleId,
                                CreatedAt  = DateTime.Parse(DateTime.Now.ToString())
                            };
                            ctx.EmployeeInRole.Add(newEmployeeRole);
                        }
                    }
                }

                StringBuilder logMessage = new StringBuilder();
                try
                {
                    ctx.SaveChanges();
                    RedisCacheHelper.DeleteEmployeeCache(id);

                    logMessage.AppendLine("(EditRolesByEmployeeId )Delete EmployCache: " + id);
                    Startup._sfAppLogger.Debug(logMessage);
                    return(Ok());
                }
                catch (Exception ex)
                {
                    logMessage.AppendLine("(EditRolesByEmployeeId) Excepton on Delete EmployCache: " + id + "; Exception:" + ex.Message);
                    Startup._sfAppLogger.Error(logMessage);
                    return(InternalServerError());
                }
            }
        }
예제 #24
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!");
            }
        }
예제 #25
0
        public async Task <HttpResponseMessage> UploadFactoryPhotoFile(int factoryId)
        {
            // Check if the request contains multipart/form-data.
            if (!Request.Content.IsMimeMultipartContent())
            {
                return(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
            }

            using (var ctx = new SFDatabaseEntities())
            {
                var existingFactory = ctx.Factory
                                      .Where(s => s.Id == factoryId && s.DeletedFlag == false)
                                      .FirstOrDefault();

                if (existingFactory == null)
                {
                    return(Request.CreateResponse(HttpStatusCode.NotFound));
                }

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

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

                    char[] trimChar = { '\"' };

                    //FileData
                    foreach (MultipartFileData fileData in provider.FileData)
                    {
                        string formColumnName   = fileData.Headers.ContentDisposition.Name.ToLower().Trim(trimChar);
                        string fileExtenionName = fileData.Headers.ContentDisposition.FileName.Split('.')[1].ToLower().Trim(trimChar);
                        if (formColumnName.Equals("image"))
                        {
                            if (fileExtenionName.Equals("png") || fileExtenionName.Equals("jpg"))
                            {
                                string          uploadFilePath  = "company-" + existingFactory.CompanyId + "/factory/" + factoryId + "-default." + fileExtenionName;
                                SharedFunctions sharedFunctions = new SharedFunctions();
                                fileAbsoluteUri = sharedFunctions.SaveFiletoStorage(fileData.LocalFileName, uploadFilePath, "images");
                            }
                            else
                            {
                                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Wrong extension name"));
                            }
                        }
                    }

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

                    //Edit factory logo path
                    existingFactory.PhotoURL = fileAbsoluteUri;
                    ctx.SaveChanges();

                    var returnObj = new
                    {
                        imageURL = fileAbsoluteUri
                    };
                    return(Request.CreateResponse(HttpStatusCode.OK, returnObj));
                }
                catch (System.Exception e)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e));
                }
            }
        }