public Entity.BaseResponse <Guid> Manage([FromForm] Entity.DeviceModel request)
 {
     Entity.BaseResponse <Guid> response = new Entity.BaseResponse <Guid>(true);
     try
     {
         var status = _service.Manage(request);
         response.IsSuccess = status.Success;
         response.Message   = status.Message;
         response.Data      = status.Data;
     }
     catch (Exception ex)
     {
         base.LogException(ex);
         return(new Entity.BaseResponse <Guid>(false, ex.Message));
     }
     return(response);
 }
예제 #2
0
        public Entity.ActionStatus Manage(Entity.DeviceModel request)
        {
            Entity.ActionStatus actionStatus = new Entity.ActionStatus(true);
            try
            {
                var dbDevice = Mapper.Configuration.Mapper.Map <Entity.Device, Model.Device>(request);
                if (request.Guid == null || request.Guid == Guid.Empty)
                {
                    ////provision kit with kitcode and unique id
                    var kitDeviceList = _deviceRepository.ProvisionKit(new ProvisionKitRequest {
                        DeviceGuid = new Guid(), KitCode = request.KitCode, UniqueId = request.UniqueId
                    });
                    if (kitDeviceList != null && kitDeviceList.Data != null && kitDeviceList.Data.Any())
                    {
                        string templateGuid = _lookupService.GetIotTemplateGuidByName(kitDeviceList.Data.FirstOrDefault().TemplateName);
                        if (!string.IsNullOrEmpty(templateGuid))
                        {
                            request.TemplateGuid = new Guid(templateGuid);
                            request.CompanyGuid  = SolutionConfiguration.CompanyId;

                            var addDeviceResult = _iotConnectClient.Device.Add(Mapper.Configuration.Mapper.Map <IOT.AddDeviceModel>(request)).Result;
                            //
                            if (addDeviceResult != null && addDeviceResult.status && addDeviceResult.data != null)
                            {
                                request.Guid = Guid.Parse(addDeviceResult.data.newid.ToUpper());
                                IOT.DataResponse <IOT.AcquireDeviceResult> acquireResult = _iotConnectClient.Device.AcquireDevice(request.UniqueId, new IOT.AcquireDeviceModel()).Result;
                                if (request.ImageFile != null)
                                {
                                    // upload image
                                    dbDevice.Image = SaveDeviceImage(request.Guid.Value, request.ImageFile);
                                }
                                dbDevice.Guid          = request.Guid.Value;
                                dbDevice.IsProvisioned = acquireResult.status;
                                dbDevice.IsActive      = true;
                                dbDevice.CompanyGuid   = SolutionConfiguration.CompanyId;
                                dbDevice.CreatedDate   = DateTime.Now;
                                dbDevice.CreatedBy     = SolutionConfiguration.CurrentUserId;
                                actionStatus           = _deviceRepository.Manage(dbDevice);
                                actionStatus.Data      = (Guid)(actionStatus.Data);
                                if (!actionStatus.Success)
                                {
                                    _logger.ErrorLog(new Exception($"Device is not added in solution database, Error: {actionStatus.Message}"), this.GetType().Name, MethodBase.GetCurrentMethod().Name);
                                    var deleteEntityResult = _iotConnectClient.Device.Delete(request.Guid.Value.ToString()).Result;
                                    if (deleteEntityResult != null && deleteEntityResult.status)
                                    {
                                        _logger.ErrorLog(new Exception($"Device is not deleted from iotconnect"), this.GetType().Name, MethodBase.GetCurrentMethod().Name);

                                        actionStatus.Success = false;
                                        actionStatus.Message = new UtilityHelper().IOTResultMessage(deleteEntityResult.errorMessages);
                                    }
                                }
                                else
                                {
                                    //Update companyid in hardware kit
                                    var hardwareKit = _hardwareKitRepository.GetByUniqueId(t => t.KitCode == request.KitCode && t.UniqueId == request.UniqueId);
                                    if (hardwareKit != null)
                                    {
                                        hardwareKit.CompanyGuid = SolutionConfiguration.CompanyId;
                                        _hardwareKitRepository.Update(hardwareKit);
                                    }
                                }
                            }
                            else
                            {
                                actionStatus.Data    = Guid.Empty;
                                actionStatus.Success = false;
                                actionStatus.Message = new UtilityHelper().IOTResultMessage(addDeviceResult.errorMessages);
                            }
                        }
                        else
                        {
                            actionStatus.Success = false;
                            actionStatus.Data    = false;
                            actionStatus.Message = "Unable To Locate Kit Type.";
                        }
                    }
                    else
                    {
                        _logger.ErrorLog(new Exception($"Device KitCode or UniqueId is not valid"), this.GetType().Name, MethodBase.GetCurrentMethod().Name);
                        actionStatus.Data    = Guid.Empty;
                        actionStatus.Success = false;
                        actionStatus.Message = "Device KitCode or UniqueId is not valid!";
                    }
                }
                else
                {
                    var olddbDevice = _deviceRepository.FindBy(x => x.Guid.Equals(request.Guid)).FirstOrDefault();
                    if (olddbDevice == null)
                    {
                        throw new NotFoundCustomException($"{CommonException.Name.NoRecordsFound} : Device");
                    }
                    var updateEntityResult = _iotConnectClient.Device.Update(request.Guid.ToString(), Mapper.Configuration.Mapper.Map <IOT.UpdateDeviceModel>(request)).Result;
                    if (updateEntityResult != null && updateEntityResult.status)
                    {
                        if (request.ImageFile != null)
                        {
                            if (File.Exists(SolutionConfiguration.UploadBasePath + dbDevice.Image) && request.ImageFile.Length > 0)
                            {
                                //if already exists image then delete  old image from server
                                File.Delete(SolutionConfiguration.UploadBasePath + dbDevice.Image);
                            }
                            if (request.ImageFile.Length > 0)
                            {
                                // upload new image
                                dbDevice.Image = SaveDeviceImage(dbDevice.Guid, request.ImageFile);
                            }
                        }
                        else
                        {
                            dbDevice.Image = olddbDevice.Image;
                        }
                        dbDevice.CreatedDate  = olddbDevice.CreatedDate;
                        dbDevice.CreatedBy    = olddbDevice.CreatedBy;
                        dbDevice.UpdatedDate  = DateTime.Now;
                        dbDevice.UpdatedBy    = SolutionConfiguration.CurrentUserId;
                        dbDevice.CompanyGuid  = SolutionConfiguration.CompanyId;
                        dbDevice.TemplateGuid = olddbDevice.TemplateGuid;
                        actionStatus          = _deviceRepository.Manage(dbDevice);
                        actionStatus.Data     = (Guid)(actionStatus.Data);
                        if (!actionStatus.Success)
                        {
                            _logger.ErrorLog(new Exception($"Device is not updated in solution database, Error: {actionStatus.Message}"), this.GetType().Name, MethodBase.GetCurrentMethod().Name);
                            actionStatus.Success = false;
                            actionStatus.Message = "Something Went Wrong!";
                        }
                    }
                    else
                    {
                        _logger.ErrorLog(new Exception($"Device is not updated in iotconnect, Error: {updateEntityResult.message}"), this.GetType().Name, MethodBase.GetCurrentMethod().Name);
                        actionStatus.Success = false;
                        actionStatus.Message = new UtilityHelper().IOTResultMessage(updateEntityResult.errorMessages);
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.ErrorLog(ex, this.GetType().Name, MethodBase.GetCurrentMethod().Name);
                return(new Entity.ActionStatus
                {
                    Success = false,
                    Message = ex.Message
                });
            }
            return(actionStatus);
        }
        public Entity.ActionStatus Manage(Entity.DeviceModel request)
        {
            Entity.ActionStatus actionStatus = new Entity.ActionStatus(true);
            try
            {
                var dbDevice = Mapper.Configuration.Mapper.Map <Entity.DeviceModel, Model.DeviceModel>(request);
                if (request.Guid == null || request.Guid == Guid.Empty)
                {
                    request.CompanyGuid = SolutionConfiguration.CompanyId;

                    var addDeviceResult = _iotConnectClient.Device.Add(Mapper.Configuration.Mapper.Map <IOT.AddDeviceModel>(request)).Result;

                    if (addDeviceResult != null && addDeviceResult.status && addDeviceResult.data != null)
                    {
                        request.Guid = Guid.Parse(addDeviceResult.data.newid.ToUpper());
                        IOT.DataResponse <IOT.AcquireDeviceResult> acquireResult = _iotConnectClient.Device.AcquireDevice(request.UniqueId, new IOT.AcquireDeviceModel()).Result;
                        //if (request.ImageFile != null)
                        //{
                        //    // upload image
                        //    dbDevice.Image = SaveDeviceImage(request.Guid.Value, request.ImageFile);
                        //}
                        dbDevice.Guid          = request.Guid.Value;
                        dbDevice.IsProvisioned = true;
                        dbDevice.IsActive      = true;
                        dbDevice.CompanyGuid   = SolutionConfiguration.CompanyId;
                        dbDevice.CreatedDate   = DateTime.Now;
                        dbDevice.CreatedBy     = SolutionConfiguration.CurrentUserId;
                        dbDevice.TemplateGuid  = request.TemplateGuid;

                        /*
                         * <attrbs><attrb><attrGuid>12A5CD86-F6C6-455F-B27A-EFE587ED410D</attrGuid><attrName>devTemp</attrName><dispName>Temprature1</dispName></attrb>
                         *                                                      <attrb><attrGuid>12A5CD86-F6C6-455F-B26A-EFE587ED410D</attrGuid><attrName>devCurrent</attrName><dispName>Current1</dispName></attrb>
                         *                                                      <attrb><attrGuid>12A5CD86-F6C6-455F-B25A-EFE587ED410D</attrGuid><attrName>devVibration</attrName><dispName>Vibration1</dispName></attrb>
                         *                                      </attrbs>
                         */

                        var attributes = new List <attrb>();
                        var xmlData    = string.Empty;
                        //request.ArrayAttrbs = JsonConvert.DeserializeObject<List<attrb>>(request.attrbs);
                        using (var stringwriter = new System.IO.StringWriter())
                        {
                            var serializer = new XmlSerializer(request.attrbs.GetType());
                            serializer.Serialize(stringwriter, request.attrbs);
                            xmlData = stringwriter.ToString().Replace("ArrayOfAttrb", "attrbs");
                        }
                        dbDevice.attrData = xmlData;
                        actionStatus      = _deviceRepository.Manage(dbDevice);
                        actionStatus.Data = actionStatus.Data != null ? (Guid)(actionStatus.Data) : Guid.Empty;
                        if (!actionStatus.Success)
                        {
                            _logger.Error($"Device is not added in solution database, Error: {actionStatus.Message}");
                            var deleteEntityResult = _iotConnectClient.Device.Delete(request.Guid.Value.ToString()).Result;
                            if (deleteEntityResult != null && deleteEntityResult.status)
                            {
                                _logger.Error($"Device is not deleted from iotconnect");

                                actionStatus.Success = false;
                                actionStatus.Message = actionStatus.Message;
                            }
                        }
                        else
                        {
                            //upload multiple images
                            if (request.ImageFiles != null && request.ImageFiles.Count > 0)
                            {
                                UploadFiles(request.ImageFiles, dbDevice.Guid.ToString(), "I");
                            }
                            //upload media files
                            if (request.MediaFiles != null && request.MediaFiles.Count > 0)
                            {
                                UploadFiles(request.MediaFiles, dbDevice.Guid.ToString(), "M");
                            }
                        }
                    }
                    else
                    {
                        actionStatus.Data    = Guid.Empty;
                        actionStatus.Success = false;
                        actionStatus.Message = new UtilityHelper().IOTResultMessage(addDeviceResult.errorMessages);
                    }
                }
                else
                {
                    var olddbDevice = _deviceRepository.FindBy(x => x.Guid.Equals(request.Guid)).FirstOrDefault();
                    if (olddbDevice == null)
                    {
                        throw new NotFoundCustomException($"{CommonException.Name.NoRecordsFound} : Device");
                    }
                    request.UniqueId     = olddbDevice.UniqueId;
                    request.TemplateGuid = olddbDevice.TemplateGuid;
                    request.EntityGuid   = olddbDevice.EntityGuid;
                    var updateEntityResult = _iotConnectClient.Device.Update(request.Guid.ToString(), Mapper.Configuration.Mapper.Map <IOT.UpdateDeviceModel>(request)).Result;
                    if (updateEntityResult != null && updateEntityResult.status)
                    {
                        //if (request.ImageFile != null)
                        //{
                        //    if (File.Exists(SolutionConfiguration.UploadBasePath + dbDevice.Image) && request.ImageFile.Length > 0)
                        //    {
                        //        //if already exists image then delete  old image from server
                        //        File.Delete(SolutionConfiguration.UploadBasePath + dbDevice.Image);
                        //    }
                        //    if (request.ImageFile.Length > 0)
                        //    {
                        //        // upload new image
                        //        dbDevice.Image = SaveDeviceImage(dbDevice.Guid, request.ImageFile);
                        //    }
                        //}
                        //else
                        //{
                        //    dbDevice.Image = olddbDevice.Image;
                        //}

                        dbDevice.CreatedDate     = olddbDevice.CreatedDate;
                        dbDevice.CreatedBy       = olddbDevice.CreatedBy;
                        dbDevice.UpdatedDate     = DateTime.Now;
                        dbDevice.UpdatedBy       = SolutionConfiguration.CurrentUserId;
                        dbDevice.CompanyGuid     = SolutionConfiguration.CompanyId;
                        dbDevice.TemplateGuid    = olddbDevice.TemplateGuid;
                        dbDevice.TypeGuid        = olddbDevice.TypeGuid;
                        dbDevice.SensorGuid      = olddbDevice.SensorGuid;
                        dbDevice.SensorCondition = olddbDevice.SensorCondition;
                        dbDevice.SensorValue     = olddbDevice.SensorValue;
                        dbDevice.Specification   = request.Specification;
                        var attributes = new List <attrb>();
                        var xmlData    = string.Empty;
                        //request.ArrayAttrbs = JsonConvert.DeserializeObject<List<attrb>>(request.attrbs);
                        using (var stringwriter = new System.IO.StringWriter())
                        {
                            var serializer = new XmlSerializer(request.attrbs.GetType());
                            serializer.Serialize(stringwriter, request.attrbs);
                            xmlData = stringwriter.ToString().Replace("ArrayOfAttrb", "attrbs");
                        }
                        dbDevice.attrData = xmlData;
                        actionStatus      = _deviceRepository.Manage(dbDevice);
                        actionStatus.Data = (Guid)(actionStatus.Data);
                        if (!actionStatus.Success)
                        {
                            _logger.Error($"Device is not updated in solution database, Error: {actionStatus.Message}");
                            actionStatus.Success = false;
                            actionStatus.Message = "Something Went Wrong!";
                            actionStatus.Data    = Guid.Empty;
                        }
                        else
                        {
                            //upload multiple images
                            if (request.ImageFiles != null && request.ImageFiles.Count > 0)
                            {
                                UploadFiles(request.ImageFiles, dbDevice.Guid.ToString(), "I");
                            }
                            //upload media files
                            if (request.MediaFiles != null && request.MediaFiles.Count > 0)
                            {
                                UploadFiles(request.MediaFiles, dbDevice.Guid.ToString(), "M");
                            }
                        }
                    }
                    else
                    {
                        _logger.Error($"Device is not updated in iotconnect, Error: {updateEntityResult.message}");
                        actionStatus.Success = false;
                        actionStatus.Message = new UtilityHelper().IOTResultMessage(updateEntityResult.errorMessages);
                        actionStatus.Data    = Guid.Empty;
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.Error(Constants.ACTION_EXCEPTION, "DeviceService.Manage " + ex);
                return(new Entity.ActionStatus
                {
                    Success = false,
                    Message = ex.Message
                });
            }
            return(actionStatus);
        }