Ejemplo n.º 1
0
        public Response <object> ChangePassword(UserChangePasswordModel _)
        {
            var user       = _repository.GetUserByUsername(_contextAccessor.HttpContext.User.Identity.Name);
            var userBefore = CloneObject.Clone(user);

            //if (user.IdUserAuthorizationType != (int)UserAuthorizationTypeIds.SystemAccount)
            //{
            //    _saveLog.LogInformation("User with Active Directory cannot change password from this system!");
            //    return new Response<object>(PublicResultStatusCodes.NotAllowedOperation);
            //}

            var checkPassword = HashHelper.Verify(user.SaltedPassword, user.Password, _.OldPassword);

            if (checkPassword)
            {
                var hashHelper = new HashHelper(_.NewPassword);
                user.Password                 = hashHelper.Hash;
                user.SaltedPassword           = hashHelper.Salt;
                user.LatestPasswordChangeDate = DateTime.Now;

                var serials = ConvertToBinaryHelper <User> .SerializeAndConvert(userBefore, user);

                _generalUpdateService.UpdateAddLogDataChange(user, serials.Item1, serials.Item2);

                return(new Response <object>(PublicResultStatusCodes.Done));
            }
            _saveLog.LogInformation("Password do not match with data in Database!");
            return(new Response <object>(PublicResultStatusCodes.WrongOldPassword));
        }
Ejemplo n.º 2
0
        public Response <object> ChangePasswordForFirstTime(UserChangePasswordForFirstTimeModel _)
        {
            var user       = _repository.GetUserByUsername(_contextAccessor.HttpContext.User.Identity.Name);
            var userBefore = CloneObject.Clone(user);

            //if (user.IdUserAuthorizationType != (int)UserAuthorizationTypeIds.SystemAccount)
            //{
            //    _saveLog.LogInformation("User with Active Directory cannot change password from this system!");
            //    return new Response<object>(PublicResultStatusCodes.NotAllowedOperation);
            //}

            var checkPassword = PasswordHelper.ValidatePassword(_.NewPassword);

            if (checkPassword)
            {
                var hashHelper = new HashHelper(_.NewPassword);
                user.Password                 = hashHelper.Hash;
                user.SaltedPassword           = hashHelper.Salt;
                user.LatestPasswordChangeDate = DateTime.Now;
                user.ChangePasswordNeeded     = false;

                var serials = ConvertToBinaryHelper <User> .SerializeAndConvert(userBefore, user);

                _generalUpdateService.UpdateAddLogDataChange(user, serials.Item1, serials.Item2);

                return(new Response <object>(PublicResultStatusCodes.Done));
            }
            _saveLog.LogInformation("Password must have at least six characters, one upperCase and one number!");
            return(new Response <object>(PublicResultStatusCodes.ModelIsNotValid));
        }
Ejemplo n.º 3
0
        public Response <object> ChangePasswordFromProfile(string password)
        {
            var userId = int.Parse(NetworkHelper._contextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value);
            var user   = _repository.GetUserById(userId);

            var userBefore = CloneObject.Clone(user);

            //if (user.IdUserAuthorizationType != (int)UserAuthorizationTypeIds.SystemAccount)
            //{
            //    _saveLog.LogInformation("User with Active Directory cannot change password from this system!");
            //    return new Response<object>(PublicResultStatusCodes.NotAllowedOperation);
            //}

            var hashHelper = new HashHelper(password);

            user.Password                 = hashHelper.Hash;
            user.SaltedPassword           = hashHelper.Salt;
            user.LatestPasswordChangeDate = DateTime.Now;

            var serials = ConvertToBinaryHelper <User> .SerializeAndConvert(userBefore, user);

            _generalUpdateService.UpdateAddLogDataChange(user, serials.Item1, serials.Item2);

            return(new Response <object>(PublicResultStatusCodes.Done));
        }
Ejemplo n.º 4
0
        public Response <object> ChangePasswordFromResetPasswordLink(ResetPasswordModel _)
        {
            var user       = _repository.GetUserById(_.Id);
            var userBefore = CloneObject.Clone(user);

            //EntryUpdateUserHelper.FillUpdateData(ref user);

            if (user != null)
            {
                var hash = HashHelper.GetSha256FromString(user.Account + " " + user.ID + "$aa$" + user.EntryDate);
                if (!hash.Equals(_.Hash))
                {
                    return(new Response <object>(PublicResultStatusCodes.ModelIsNotValid));
                }

                var hashHelper = new HashHelper(_.Password);
                user.Password                 = hashHelper.Hash;
                user.SaltedPassword           = hashHelper.Salt;
                user.LatestPasswordChangeDate = DateTime.Now;
                user.ResetPasswordToken       = Guid.NewGuid();

                var serials = ConvertToBinaryHelper <User> .SerializeAndConvert(userBefore, user);

                _generalUpdateService.UpdateAddLogDataChange(user, serials.Item1, serials.Item2);

                return(new Response <object>(PublicResultStatusCodes.Done));
            }

            return(new Response <object>(PublicResultStatusCodes.ModelIsNotValid));
        }
Ejemplo n.º 5
0
        internal async Task <EST_DataExportModel> Process_DisplosedAssetList(EST_DataExportModel model, ServiceProgressReportBsm serviceProgressReport)
        {
            if (model == null)
            {
                return(model);
            }
            var returnList = new List <SCAuditBsm>();

            model.DisplosedAssetList.ToList().ForEach(asset =>
            {
                HardwareTemplate_Full newHardwareAsset;

                var bamTemplate = _hardwareAssetService.GetHardwareAsset_Full(asset.SerialNumber).FirstOrDefault();

                if (bamTemplate != null)
                {
                    newHardwareAsset = CloneObject.Clone(bamTemplate);
                }
                else
                {
                    newHardwareAsset = CreateNewItem(asset);
                }

                newHardwareAsset.OwnedBy = null;
                newHardwareAsset.Target_HardwareAssetHasCostCenter = null;
                newHardwareAsset = _hardwareAssetService.SetHardwareAssetStatus(newHardwareAsset, EST_HWAssetStatus.Disposed);
                newHardwareAsset.Target_HardwareAssetHasLocation = null;
                newHardwareAsset.DisposalDate      = DateTime.Now;
                newHardwareAsset.DisposalReference = "Esteem";

                _hardwareAssetService.UpdateTemplate(newHardwareAsset, bamTemplate);

                // Check Update was successful
                var updatedbamTemplate = _hardwareAssetService.GetHardwareAsset_Full(asset.SerialNumber).FirstOrDefault();
                if (updatedbamTemplate?.Target_HardwareAssetHasLocation?.DisplayName != "Esteem")
                {
                    _reportings.Add(new BAM_ReportingBsm()
                    {
                        ServiceProgressReportId        = serviceProgressReport.Id,
                        SerialNumber                   = asset.SerialNumber,
                        AssetStatus                    = EST_HWAssetStatus.Disposed,
                        SCAudit_Item                   = asset,
                        BAM_HardwareTemplate_Exception = updatedbamTemplate,
                        ExceptionMessage               = "Failed to Update"
                    });
                    returnList.Add(asset);
                }
                _billables.Add(new BAM_ReportingBsm()
                {
                    ServiceProgressReportId        = serviceProgressReport.Id,
                    SerialNumber                   = asset.SerialNumber,
                    AssetStatus                    = EST_HWAssetStatus.Disposed,
                    SCAudit_Item                   = asset,
                    BAM_HardwareTemplate_Exception = updatedbamTemplate,
                });
            });
            model.DisplosedAssetList = returnList;
            return(model);
        }
Ejemplo n.º 6
0
        public HardwareTemplate_Full SetHardwareAssetStatus(HardwareTemplate_Full template, EST_HWAssetStatus hWAssetStatus)
        {
            if (template == null)
            {
                throw new Exception("Template must not be null");
            }

            // Clone the object so we can check the changes
            var newHardwareAsset = CloneObject.Clone(template);

            newHardwareAsset.HardwareAssetStatus = _assetStatusService.HardwareAssetStatusList.FirstOrDefault(x => x.Name == hWAssetStatus.ToDescriptionString());
            return(newHardwareAsset);
        }
Ejemplo n.º 7
0
        public HardwareTemplate_Full SetCostCode(HardwareTemplate_Full template, string costCode)
        {
            if (template == null)
            {
                throw new Exception("Template must not be null");
            }

            // Clone the object so we can check the changes
            var newHardwareAsset = CloneObject.Clone(template);

            newHardwareAsset.Target_HardwareAssetHasCostCenter = _costCenterService.CostCenterList.FirstOrDefault(x => x.DisplayName == costCode);
            return(newHardwareAsset);
        }
Ejemplo n.º 8
0
        public HardwareTemplate SetAssetTag(HardwareTemplate template, string assetTag)
        {
            if (template == null)
            {
                throw new Exception("Template must not be null");
            }

            // Clone the object so we can check the changes
            var newHardwareAsset = CloneObject.Clone(template);

            newHardwareAsset.AssetTag = assetTag;
            return(newHardwareAsset);
        }
Ejemplo n.º 9
0
        public HardwareTemplate SetHardwareAssetStatus(HardwareTemplate template, EST_HWAssetStatus hWAssetStatus)
        {
            if (template == null)
            {
                throw new Exception("Template must not be null");
            }

            // Clone the object so we can check the changes
            var newHardwareAsset = CloneObject.Clone(template);

            newHardwareAsset.HardwareAssetStatus = _assetStatusService.GetAssetStatusTemplate(hWAssetStatus);
            return(newHardwareAsset);
        }
Ejemplo n.º 10
0
        internal async Task <EST_DataExportModel> Process_LocationChangeList(EST_DataExportModel model, ServiceProgressReportBsm serviceProgressReport)
        {
            if (model == null)
            {
                return(model);
            }
            var returnList = new List <SCAuditBsm>();

            model.LocationChangeList.ToList().ForEach(asset => {
                HardwareTemplate_Full newHardwareAsset;

                var bamTemplate = _hardwareAssetService.GetHardwareAsset_Full(asset.SerialNumber).FirstOrDefault();

                // If the Location is already set to Esteem then do nothing
                if (bamTemplate != null && bamTemplate.Target_HardwareAssetHasLocation?.DisplayName == "Esteem")
                {
                    return;
                }

                if (bamTemplate != null)
                {
                    newHardwareAsset = CloneObject.Clone(bamTemplate);
                }
                else
                {
                    newHardwareAsset = CreateNewItem(asset);
                }

                newHardwareAsset = _hardwareAssetService.SetLocation(newHardwareAsset, asset.Audit_Dest_Site_Num);
                _hardwareAssetService.UpdateTemplate(newHardwareAsset, bamTemplate);

                // Check Update was successful
                var updatedbamTemplate = _hardwareAssetService.GetHardwareAsset_Full(asset.SerialNumber).FirstOrDefault();
                if (updatedbamTemplate?.Target_HardwareAssetHasLocation?.DisplayName != "Esteem")
                {
                    _reportings.Add(new BAM_ReportingBsm()
                    {
                        ServiceProgressReportId        = serviceProgressReport.Id,
                        SerialNumber                   = asset.SerialNumber,
                        AssetStatus                    = EST_HWAssetStatus.LocationChanged,
                        SCAudit_Item                   = asset,
                        BAM_HardwareTemplate_Exception = newHardwareAsset,
                        ExceptionMessage               = "Failed to Update"
                    });
                    returnList.Add(asset);
                }
            });
            model.LocationChangeList = returnList;
            return(model);
        }
Ejemplo n.º 11
0
        internal async Task <EST_DataExportModel> Process_AssetTagChangeList(EST_DataExportModel model, ServiceProgressReportBsm serviceProgressReport)
        {
            if (model == null)
            {
                return(model);
            }
            var returnList = new List <SCAuditBsm>();

            model.AssetTagChangeList.ToList().ForEach(asset => {
                HardwareTemplate newHardwareAsset;

                var bamTemplate = _hardwareAssetService.GetHardwareAsset_Full(asset.SerialNumber).FirstOrDefault();

                // If the Asset isn't null and the Tag is already correct then just return
                if (bamTemplate != null && bamTemplate.AssetTag == asset.Audit_Part_Num)
                {
                    return;
                }
                else if (bamTemplate != null)
                {
                    newHardwareAsset = CloneObject.Clone(bamTemplate);
                }
                else
                {
                    newHardwareAsset = CreateNewItem(asset);
                }

                newHardwareAsset = _hardwareAssetService.SetAssetTag(newHardwareAsset, asset.Audit_Part_Num);
                _hardwareAssetService.UpdateTemplate(newHardwareAsset, bamTemplate);

                // Check Update was successful
                var updatedbamTemplate = _hardwareAssetService.GetHardwareAsset_Full(asset.SerialNumber).FirstOrDefault();
                if (updatedbamTemplate?.AssetTag != asset.Audit_Part_Num)
                {
                    _reportings.Add(new BAM_ReportingBsm()
                    {
                        ServiceProgressReportId        = serviceProgressReport.Id,
                        SerialNumber                   = asset.SerialNumber,
                        AssetStatus                    = EST_HWAssetStatus.AssetTagChanged,
                        SCAudit_Item                   = asset,
                        BAM_HardwareTemplate_Exception = updatedbamTemplate,
                        ExceptionMessage               = "Failed to Update"
                    });
                    returnList.Add(asset);
                }
            });
            model.AssetTagChangeList = returnList;
            return(model);
        }
Ejemplo n.º 12
0
        public HardwareTemplate_Full SetUser(HardwareTemplate_Full template, BAM_User user)
        {
            if (template == null)
            {
                throw new Exception("Template must not be null");
            }

            // Clone the object so we can check the changes
            var newHardwareAsset = CloneObject.Clone(template);

            newHardwareAsset.OwnedBy = new OwnedBy
            {
                BaseId = user.Id
            };
            return(newHardwareAsset);
        }
Ejemplo n.º 13
0
        public HardwareTemplate_Full SetHardwareAssetPrimaryUser(HardwareTemplate_Full template, string userName)
        {
            if (template == null)
            {
                throw new Exception("Template must not be null");
            }

            // Clone the object so we can check the changes
            var newHardwareAsset = CloneObject.Clone(template);

            newHardwareAsset.OwnedBy = new OwnedBy
            {
                BaseId = _userService.UserList.FirstOrDefault(x => x.Name == userName).Id
            };
            return(newHardwareAsset);
        }
        public async Task B03_Update_Basic()
        {
            var serialNumber = "CNU0183F33";

            Guid.TryParse("acdcedb7-100c-8c91-d664-4629a218bd94", out var objectStatusId);

            var updateAssetStatus    = EST_HWAssetStatus.Retired;
            var originalModifiedDate = new DateTime();
            var updatedModifiedDate  = new DateTime();

            var hardwareAssetService = new BAM_HardwareAssetServices();
            var result = hardwareAssetService.GetHardwareAsset(serialNumber);

            var originalhardwareAsset = result.First();

            originalModifiedDate = (DateTime)originalhardwareAsset.LastModified;

            var newHardwareAsset = CloneObject.Clone(originalhardwareAsset);

            // hardwareAssetService.SetHardwareAssetStatus(originalhardwareAsset, updateAssetStatus);
            newHardwareAsset.AssetTag = "Hugh Test";
            //newHardwareAsset.BaseId = null;
            //newHardwareAsset.TimeAdded =
            newHardwareAsset.ObjectStatus = new ObjectStatus()
            {
                Id = objectStatusId.ToString()
            };

            //newHardwareAsset.LastModified = DateTime.Now;
            List <HardwareTemplate> hardwareAssetList = new List <HardwareTemplate>();

            hardwareAssetList = hardwareAssetService.UpdateTemplate(newHardwareAsset, originalhardwareAsset);
            Assert.IsNotNull(hardwareAssetList, "Return list is null");
            Assert.IsTrue(hardwareAssetList.Count > 1, "Return list doesn't include 2 records");

            var updatedHardwareAsset = hardwareAssetService.GetHardwareAsset(serialNumber).FirstOrDefault();

            Assert.IsNotNull(updatedHardwareAsset, "Updated Asset is null");
            Assert.IsTrue(updatedHardwareAsset.SerialNumber == serialNumber, "SerialNumbers don't match");

            updatedModifiedDate = (DateTime)updatedHardwareAsset.LastModified;

            Assert.IsTrue(updatedModifiedDate != originalModifiedDate, "Original and Updated LastModified Date are the same");
            Assert.IsTrue(updatedModifiedDate > originalModifiedDate, "Updated LastModified Date is not greater that the Original");
        }
Ejemplo n.º 15
0
        public HardwareTemplate_Full SetLocation(HardwareTemplate_Full template, string siteLocation)
        {
            if (template == null)
            {
                throw new Exception("Template must not be null");
            }

            // Clone the object so we can check the changes
            var newHardwareAsset = CloneObject.Clone(template);

            //if (siteLocation == "Esteem" || siteLocation == "LTX")
            //{
            newHardwareAsset.Target_HardwareAssetHasLocation = new TargetHardwareAssetHasLocation
            {
                BaseId = "ae7423eb-0952-d69c-4d7d-77f1699bfe92",
            };
            //}
            return(newHardwareAsset);
        }
Ejemplo n.º 16
0
        public Response <UserModel> Update(int id, EditUserModel _)
        {
            var entryUser = _repository.GetUserByUsername(_contextAccessor.HttpContext.User?.Identity?.Name);

            var user = _repository.GetUserById(id);

            if (user == null)
            {
                _saveLog.LogInformation("Failed to Update User because user with Id=\"" + id + "\" does not exist");
                return(new Response <UserModel>(PublicResultStatusCodes.ModelIsNotValid));
            }

            var beforeUser = CloneObject.Clone(user);

            if (!string.IsNullOrWhiteSpace(_.Password))
            {
                var hashHelper = new HashHelper(_.Password);
                user.Password                 = hashHelper.Hash;
                user.SaltedPassword           = hashHelper.Salt;
                user.LatestPasswordChangeDate = DateTime.Now;
            }

            user.Account                 = _.Account;
            user.First                   = _.First;
            user.Last                    = _.Last;
            user.IsActive                = _.IsActive;
            user.ExpireDate              = _.ExprieDate;
            user.IDRole                  = _.IdRole;
            user.EmailAddress            = _.EmailAddress;
            user.IDUserAuthorizationType = _.IdUserAuthorizationType;
            //user.WithUserAuthorization = _.WithUserAuthorization;
            // user.SerialNumber = _.SerialNumber;
            //user.IdEmployee = _.IdEmployee;
            EntryUpdateUserHelper.FillUpdateData(ref user);


            var serials = ConvertToBinaryHelper <User> .SerializeAndConvert(beforeUser, user);

            _generalUpdateService.UpdateAddLogDataChange(user, serials.Item1, serials.Item2);

            return(new Response <UserModel>(PublicResultStatusCodes.Done));
        }
Ejemplo n.º 17
0
        public Response <object> ChangePassword(AdminChangePasswordModel _)
        {
            var user       = _repository.GetUserById(_.IdUser);
            var userBefore = CloneObject.Clone(user);

            //if (user.IdUserAuthorizationType != (int)UserAuthorizationTypeIds.SystemAccount)
            //{
            //    _saveLog.LogInformation("User with Active Directory cannot change password from this system!");
            //    return new Response<object>(PublicResultStatusCodes.NotAllowedOperation);
            //}
            var hashHelper = new HashHelper(_.NewPassword);

            user.Password                 = hashHelper.Hash;
            user.SaltedPassword           = hashHelper.Salt;
            user.LatestPasswordChangeDate = DateTime.Now;

            var serials = ConvertToBinaryHelper <User> .SerializeAndConvert(userBefore, user);

            _generalUpdateService.UpdateAddLogDataChange(user, serials.Item1, serials.Item2);

            return(new Response <object>(PublicResultStatusCodes.Done));
        }
Ejemplo n.º 18
0
 public object Clone()
 {
     return(CloneObject.Clone(this));
 }
Ejemplo n.º 19
0
        internal async Task <EST_DataExportModel> Process_DeployedToBAMUserList(EST_DataExportModel model, ServiceProgressReportBsm serviceProgressReport)
        {
            if (model == null)
            {
                return(model);
            }
            var returnList = new List <SCAuditDeployBsm>();

            model.DeployedToBAMUserList.ToList().ForEach(asset => {
                HardwareTemplate_Full newHardwareAsset;
                if (string.IsNullOrEmpty(asset.RequestUser))
                {
                    returnList.Add(asset); return;
                }
                var bamTemplate = _hardwareAssetService.GetHardwareAsset_Full(asset.SerialNumber).FirstOrDefault();

                var user = _hardwareAssetService.GetUser(asset.RequestUser);
                if (user == null || !user.Name.Contains(asset.RequestUser))
                {
                    _reportings.Add(new BAM_ReportingBsm()
                    {
                        ServiceProgressReportId        = serviceProgressReport.Id,
                        SerialNumber                   = asset.SerialNumber,
                        AssetStatus                    = EST_HWAssetStatus.Deployed,
                        SCAuditDeploy_Item             = asset,
                        BAM_HardwareTemplate_Exception = bamTemplate,
                        ExceptionMessage               = "No User Found in BAM"
                    });
                    returnList.Add(asset);
                    return;
                }

                // The asset is not null and User is correct, HardwareStatus is Deployed and location is null then return
                if (bamTemplate != null &&
                    bamTemplate?.OwnedBy != null &&
                    (bool)bamTemplate?.OwnedBy?.DisplayName?.Contains(user?.Name) &&
                    bamTemplate?.HardwareAssetStatus?.Name == EST_HWAssetStatus.Deployed.ToBAMString() &&
                    bamTemplate?.AssetTag == asset.AssetTag &&
                    bamTemplate?.Name == asset.AssetTag &&
                    bamTemplate?.DisplayName == asset.AssetTag &&
                    bamTemplate?.Target_HardwareAssetHasLocation == null)
                {
                    return;
                }
                else if (bamTemplate != null)
                {
                    newHardwareAsset = CloneObject.Clone(bamTemplate);
                }
                else
                {
                    newHardwareAsset = CreateNewItem(asset);
                }

                newHardwareAsset.Target_HardwareAssetHasLocation = null;
                newHardwareAsset = _hardwareAssetService.SetHardwareAssetStatus(newHardwareAsset, EST_HWAssetStatus.Deployed);
                newHardwareAsset = _hardwareAssetService.SetUser(newHardwareAsset, user);

                newHardwareAsset = _hardwareAssetService.SetCostCode(newHardwareAsset, asset.CostCode);


                newHardwareAsset.AssetTag    = asset.AssetTag;
                newHardwareAsset.Name        = asset.AssetTag;
                newHardwareAsset.DisplayName = asset.AssetTag;

                _hardwareAssetService.UpdateTemplate(newHardwareAsset, bamTemplate);

                // Check Update was successful
                var updatedbamTemplate = _hardwareAssetService.GetHardwareAsset_Full(asset.SerialNumber).FirstOrDefault();
                if (!(bool)updatedbamTemplate?.OwnedBy?.DisplayName?.Contains(asset.RequestUser))
                {
                    _reportings.Add(new BAM_ReportingBsm()
                    {
                        ServiceProgressReportId        = serviceProgressReport.Id,
                        SerialNumber                   = asset.SerialNumber,
                        AssetStatus                    = EST_HWAssetStatus.Deployed,
                        SCAuditDeploy_Item             = asset,
                        BAM_HardwareTemplate_Exception = updatedbamTemplate,
                        ExceptionMessage               = "Failed to Update"
                    });
                    returnList.Add(asset);
                }
                _billables.Add(new BAM_ReportingBsm()
                {
                    ServiceProgressReportId        = serviceProgressReport.Id,
                    SerialNumber                   = asset.SerialNumber,
                    AssetStatus                    = EST_HWAssetStatus.Deployed,
                    SCAuditDeploy_Item             = asset,
                    BAM_HardwareTemplate_Exception = updatedbamTemplate,
                });
            });
            model.DeployedToBAMUserList = returnList;
            return(model);
        }
Ejemplo n.º 20
0
        internal async Task <EST_DataExportModel> Process_SwappedAssetList(EST_DataExportModel model, ServiceProgressReportBsm serviceProgressReport)
        {
            if (model == null)
            {
                return(model);
            }
            var returnList = new List <SCAuditDeployBsm>();

            model.SwappedAssetList.ToList().ForEach(asset =>
            {
                #region Deploy Process
                HardwareTemplate_Full newHardwareAsset;

                var bamTemplate = _hardwareAssetService.GetHardwareAsset_Full(asset.SerialNumber).FirstOrDefault();

                if (bamTemplate != null)
                {
                    newHardwareAsset = CloneObject.Clone(bamTemplate);
                }
                else
                {
                    newHardwareAsset = CreateNewItem(asset);
                }

                #region Deploy
                newHardwareAsset.Target_HardwareAssetHasLocation = null;
                newHardwareAsset         = _hardwareAssetService.SetHardwareAssetStatus(newHardwareAsset, EST_HWAssetStatus.Deployed);
                newHardwareAsset.OwnedBy = newHardwareAsset.OwnedBy;
                newHardwareAsset.Target_HardwareAssetHasCostCenter = newHardwareAsset.Target_HardwareAssetHasCostCenter;

                newHardwareAsset.AssetTag    = asset.AssetTag;
                newHardwareAsset.Name        = asset.AssetTag;
                newHardwareAsset.DisplayName = asset.AssetTag;

                _hardwareAssetService.UpdateTemplate(newHardwareAsset, bamTemplate);
                #endregion Deploy

                // Check Deployed Update was successful
                var updatedDeployedTemplate = _hardwareAssetService.GetHardwareAsset_Full(asset.SerialNumber).FirstOrDefault();
                if (updatedDeployedTemplate?.Target_HardwareAssetHasLocation?.DisplayName == "Esteem")
                {
                    _reportings.Add(new BAM_ReportingBsm()
                    {
                        ServiceProgressReportId        = serviceProgressReport.Id,
                        SerialNumber                   = updatedDeployedTemplate.SerialNumber,
                        AssetStatus                    = EST_HWAssetStatus.Deployed,
                        SCAuditDeploy_Item             = asset,
                        BAM_HardwareTemplate_Exception = updatedDeployedTemplate,
                        ExceptionMessage               = "Failed to Update"
                    });
                    returnList.Add(asset);
                }
                _billables.Add(new BAM_ReportingBsm()
                {
                    ServiceProgressReportId        = serviceProgressReport.Id,
                    SerialNumber                   = updatedDeployedTemplate.SerialNumber,
                    AssetStatus                    = EST_HWAssetStatus.Deployed,
                    SCAuditDeploy_Item             = asset,
                    BAM_HardwareTemplate_Exception = updatedDeployedTemplate,
                });

                #endregion Deploy Process

                #region Return Process

                HardwareTemplate_Full newReturnedHardwareAsset;

                var returnedBamTemplate = _hardwareAssetService.GetHardwareAsset_Full(asset.SerialNumberReturned).FirstOrDefault();

                if (returnedBamTemplate != null)
                {
                    newReturnedHardwareAsset = CloneObject.Clone(returnedBamTemplate);
                }
                else
                {
                    newReturnedHardwareAsset = CreateNewItem(asset);
                }

                #region Returned
                newReturnedHardwareAsset.OwnedBy = null;
                newReturnedHardwareAsset.Target_HardwareAssetHasCostCenter = null;
                newReturnedHardwareAsset = _hardwareAssetService.SetHardwareAssetStatus(newReturnedHardwareAsset, EST_HWAssetStatus.Returned);
                newReturnedHardwareAsset = _hardwareAssetService.SetLocation(newReturnedHardwareAsset, "Esteem");

                _hardwareAssetService.UpdateTemplate(newReturnedHardwareAsset, returnedBamTemplate);
                #endregion Returned

                // Check Returned Update was successful
                var updatedReturnedTemplate = _hardwareAssetService.GetHardwareAsset_Full(asset.SerialNumberReturned).FirstOrDefault();
                if (updatedReturnedTemplate?.Target_HardwareAssetHasLocation?.DisplayName != "Esteem")
                {
                    _reportings.Add(new BAM_ReportingBsm()
                    {
                        ServiceProgressReportId        = serviceProgressReport.Id,
                        SerialNumber                   = updatedReturnedTemplate.SerialNumber,
                        AssetStatus                    = EST_HWAssetStatus.Returned,
                        SCAuditDeploy_Item             = asset,
                        BAM_HardwareTemplate_Exception = updatedDeployedTemplate,
                        ExceptionMessage               = "Failed to Update"
                    });
                    returnList.Add(asset);
                }
                _billables.Add(new BAM_ReportingBsm()
                {
                    ServiceProgressReportId        = serviceProgressReport.Id,
                    SerialNumber                   = updatedReturnedTemplate.SerialNumber,
                    AssetStatus                    = EST_HWAssetStatus.Returned,
                    SCAuditDeploy_Item             = asset,
                    BAM_HardwareTemplate_Exception = updatedReturnedTemplate,
                });

                #endregion Return Process
            });
            model.SwappedAssetList = returnList;
            return(model);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// 将考勤记录导入数据库.
        /// </summary>
        /// <param name="xlsFilePath"></param>
        /// <param name="randomStr"></param>
        /// <param name="pb"></param>
        /// <returns></returns>
        public static MSG  ImportAttendanceRecordToDB(string xlsFilePath, string randomStr, BackgroundWorker bgWork)
        {
            string excelName = Usual_Excel_Helper.getExcelName(xlsFilePath);

            bgWork.ReportProgress(0, string.Format(@"lblPrompt.Text = {0},准备读取:", excelName));
            int pbLength = 0;

            bgWork.ReportProgress(pbLength, "pb.Maximum");
            int pbValue = 0;

            bgWork.ReportProgress(pbValue, "pb.Value");
            MSG msg = new MSG();

            //用于确定本月最后一天.
            Stack <int> sDate = new Stack <int>();
            //Queue<AttendanceR> qAttendanceR = new Queue<AttendanceR>();
            Queue <AttendanceRecordDetail> qARDetail = new Queue <AttendanceRecordDetail>();

            AttendanceRecordDetail._random_str = randomStr;
            //按指纹日期
            string fingerPrintDate = String.Empty;

            //行最大值.
            int rowsMaxCount            = 0;
            int colsMaxCount            = 0;
            Usual_Excel_Helper uEHelper = null;

            MyExcel myExcel = new MyExcel(xlsFilePath);

            //打开该文档。
            myExcel.openWithoutAlerts();
            //只获取第一个表格。
            Worksheet ws = myExcel.getFirstWorkSheetAfterOpen();

            bgWork.ReportProgress(0, string.Format(@"lblPrompt.Text = {0},正在读取:", excelName));
            AttendanceRecordDetail._file_path = xlsFilePath;
            //行;列最大值 赋值.
            rowsMaxCount = ws.UsedRange.Rows.Count;
            colsMaxCount = ws.UsedRange.Columns.Count;


            AttendanceRecordDetail._sheet_name = ws.Name;
            //判断首行是否为 考勤记录表;以此判断此表是否为考勤记录表.
            string A1Str = ((Range)ws.Cells[1, 1]).Text.ToString().Trim().Replace("\n", "").Replace("\r", "").Replace(" ", "");

            if (String.IsNullOrEmpty(A1Str))
            {
                msg.Msg  = "工作表的A1单元格不能为空!";
                msg.Flag = false;
                myExcel.close();
                return(msg);
            }
            //如果A1Str的内容不包含"考勤记录表"5个字。
            if (!A1Str.Contains("考勤记录表"))
            {
                msg.Msg  = "A1内容未包含'考勤记录表'";
                msg.Flag = false;
                myExcel.close();
                return(msg);
            }
            #region 判断名称中是否区分了考勤记录。
            string Seq_Attendance_Record = string.Empty;
            int    indexOfFullStop       = xlsFilePath.LastIndexOf(".");
            Seq_Attendance_Record = xlsFilePath.Substring(indexOfFullStop - 1, 1);
            if (!CheckPattern.CheckNumber(Seq_Attendance_Record))
            {
                msg.Msg  = "考勤记录表名称请以数字结尾!";
                msg.Flag = false;
                myExcel.close();
                return(msg);
            }
            #endregion

            AttendanceRecordDetail._prefix_Job_Number = excelName.Substring(excelName.Length - 1, 1).ToCharArray()[0];
            string C3Str = ((Range)ws.Cells[3, 3]).Text.ToString().Trim();
            //  \0: 表空字符.
            if (String.IsNullOrEmpty(C3Str))
            {
                msg.Msg  = "异常: 考勤时间为空!";
                msg.Flag = false;
                myExcel.close();
                return(msg);
            }
            //
            string[] ArrayC3 = C3Str.Split('~');
            if (ArrayC3.Length == 0)
            {
                msg.Msg  = "异常: 考勤时间格式变更!";
                msg.Flag = false;
                myExcel.close();
                return(msg);
            }
            AttendanceRecordDetail._start_date = ArrayC3[0].ToString().Trim().Replace('/', '-');
            AttendanceRecordDetail._end_date   = ArrayC3[1].ToString().Trim().Replace('/', '-');
            //制表时间:  L3 3行12列.
            string L3Str = ((Range)ws.Cells[3, 12]).Text.ToString().Trim().Replace('/', '-');
            if (String.IsNullOrEmpty(L3Str))
            {
                msg.Msg  = "异常: 制表时间为空!";
                msg.Flag = false;
                myExcel.close();
                return(msg);
            }
            //制表时间.
            AttendanceRecordDetail._tabulation_time = L3Str;
            //检查第4行是否为;考勤时间:
            string A4Str = ((Range)ws.Cells[4, 1]).Text.ToString().Trim();
            if (!"1".Equals(A4Str, StringComparison.CurrentCultureIgnoreCase))
            {
                msg.Msg  = "异常: 第四行已变更!";
                msg.Flag = false;
                myExcel.close();
                return(msg);
            }
            uEHelper = new Usual_Excel_Helper(ws);
            //此刻不能删除,只是获取行号。
            Queue <Range> rangeToDelQueue = new Queue <Range>();
            //判断是否有空行。
            for (int i = 5; i <= rowsMaxCount; i++)
            {
                if (uEHelper.isBlankRow(i))
                {
                    //只要上一列不是
                    //删除掉此行。
                    //判断上一行中的A列是否为工号。
                    string temp = uEHelper.getSpecificCellValue("A" + (i - 1).ToString());
                    if ("工号:".Equals(temp))
                    {
                        //本行为空,上一行为工号行,则也统计。
                        continue;
                    }
                    //本行,为空,上一行非工号行。则删除本行。
                    Range rangeToDel = (Microsoft.Office.Interop.Excel.Range)uEHelper.WS.Rows[i, System.Type.Missing];
                    //不为工号
                    rangeToDelQueue.Enqueue(rangeToDel);
                }
                ;
            }
            Range rangeToDelete;
            //开始删除空行。
            while (rangeToDelQueue.Count > 0)
            {
                rangeToDelete = rangeToDelQueue.Dequeue();
                rangeToDelete.Delete(XlDeleteShiftDirection.xlShiftUp);
            }
            ;
            rowsMaxCount = ws.UsedRange.Rows.Count;
            //进度条长度增加。
            pbLength += colsMaxCount;
            pbLength += (colsMaxCount * (rowsMaxCount - 5 + 1));
            bgWork.ReportProgress(pbLength, "pb.Maximum");
            //入队列值0
            sDate.Push(0);
            //显示进度条。
            //考勤表中第4行,某月的最大考勤天数。
            //lblPrompt.Text = excelName + ",正在读取:";

            int actualMaxDay = 0;
            //开始循环
            for (int i = 1; i <= colsMaxCount; i++)
            {
                A4Str = ((Range)ws.Cells[4, i]).Text.ToString();
                //碰到第4行某列为空,退出循环。
                if (String.IsNullOrEmpty(A4Str))
                {
                    break;
                }
                int aDate = 0;
                //对A4Str进行分析.
                if (!Int32.TryParse(A4Str, out aDate))
                {
                    msg.Msg  = String.Format(@"异常: 考勤日期行第{0}列出现非数字内容!", aDate);
                    msg.Flag = false;
                    myExcel.close();
                    return(msg);
                }
                //判断新增的日期是否大于上一个.
                if (aDate <= sDate.Peek())
                {
                    //跳出循环.
                    break;
                }
                actualMaxDay++;
                sDate.Push(aDate);
                //pb.Value++;
                bgWork.ReportProgress(pbValue++, "pb.Value");
            }
            //取其中的最小值。
            colsMaxCount = Math.Min(sDate.Count - 1, actualMaxDay);
            //考勤日期
            fingerPrintDate = AttendanceRecordDetail._start_date.Substring(0, 7).Replace('/', '-');
            string tempStr = string.Empty;
            //开始循环
            for (int colIndex = 1; colIndex <= colsMaxCount; colIndex++)
            {
                //从第5行开始.
                //奇数;偶数行共用一个对象.
                AttendanceRecordDetail ARDetail = null;
                //设定用于填充的对象
                AttendanceRecordDetail._prefix_Job_Number = Seq_Attendance_Record.ToCharArray()[0];
                for (int rowIndex = 5; rowIndex <= rowsMaxCount; rowIndex++)
                {
                    //如果行数为奇数则为工号行.
                    if (rowIndex % 2 == 1)
                    {
                        //工号行.
                        //取工号
                        ARDetail            = new AttendanceRecordDetail();
                        ARDetail.Job_number = ((Range)ws.Cells[rowIndex, 3]).Text.ToString().Trim();
                        //自行拼凑AR.
                        ARDetail.combine_Job_Number();
                        //取姓名:  K5
                        ARDetail.Name = ((Range)ws.Cells[rowIndex, Usual_Excel_Helper.getColIndexByStr("K")]).Text.ToString().Trim();
                        //取部门: U5
                        ARDetail.Dept = ((Range)ws.Cells[rowIndex, Usual_Excel_Helper.getColIndexByStr("U")]).Text.ToString().Trim();
                        //部门为空,则填充为NULL;
                        ARDetail.Dept = !String.IsNullOrEmpty(ARDetail.Dept) ? ARDetail.Dept : "NULL";
                        //取日期.填充0;
                        ARDetail.Fingerprint_date = fingerPrintDate + "-" + colIndex.ToString().PadLeft(2, '0');
                    }
                    else
                    {
                        //偶数行取考勤结果.
                        //上班时间. 如B10;
                        tempStr = ((Range)ws.Cells[rowIndex, colIndex]).Text.ToString().Trim();
                        string        tempFirstTime = String.Empty;
                        string        tempLastTime  = String.Empty;
                        List <string> strTimeList   = null;
                        msg = getFPTimeReturnMSG(tempStr, out strTimeList);
                        if (!msg.Flag)
                        {
                            msg.Msg = string.Format(@"导入失败,提交数据尚未开始:第{0}行{1}列,{1}!", rowIndex, colIndex, msg.Msg);
                            myExcel.close();
                            return(msg);
                        }
                        ;
                        //无打卡记录,不提交
                        if (strTimeList.Count == 0)
                        {
                            qARDetail.Enqueue(ARDetail);
                        }
                        //有打卡记录
                        for (int i = 0; i < strTimeList.Count; i++)
                        {
                            AttendanceRecordDetail ARDetailTemp = (AttendanceRecordDetail)CloneObject.Clone(ARDetail);
                            ARDetailTemp.Finger_print_time = ARDetailTemp.Fingerprint_date + " " + strTimeList[i].ToString();
                            qARDetail.Enqueue(ARDetailTemp);
                        }
                    }
                    //pb.Value++;
                    bgWork.ReportProgress(pbValue++, "pb.Value");
                }
            }
            //释放对象
            myExcel.close();
            System.Threading.Thread.Sleep(2000);
            GC.Collect();
            GC.WaitForPendingFinalizers();
            //lblResult.Text = "";
            bgWork.ReportProgress(0, "lblResult.Text = ''");
            //lblPrompt.Text = "提交数据: ";
            bgWork.ReportProgress(0, string.Format(@"lblPrompt.Text = {0}, 提交数据:", excelName));
            //
            bgWork.ReportProgress(qARDetail.Count, "pb.Maximum");
            //*******/
            pbValue = 0;
            bgWork.ReportProgress(pbValue, "pb.Value");
            #region
            //OracleDaoHelper.noLogging("Attendance_Record");
            OracleDaoHelper.noLogging("Attendance_Record_Detail");
            OracleConnection  conn = OracleConnHelper.getConn();
            OracleTransaction tran = conn.BeginTransaction();
            //保存对象
            while (qARDetail.Count > 0)
            {
                try
                {
                    AttendanceRecordDetail aRDetail = qARDetail.Dequeue();

                    affectedCount += aRDetail.saveBySpecificConn(conn);
                    //pb.Value++;
                    bgWork.ReportProgress(pbValue++, "pb.Value");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString(), "提示:", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    msg.Msg  = DirectoryHelper.getFileName(xlsFilePath) + ":导入失败; " + ex.ToString();
                    msg.Flag = false;
                    tran.Rollback();
                    conn.Close();
                    conn.Dispose();
                    return(msg);

                    throw;
                }
            }
            tran.Commit();
            conn.Close();
            conn.Dispose();
            #endregion
            //OracleDaoHelper.logging("Attendance_Record");
            OracleDaoHelper.logging("Attendance_Record_Detail");
            msg.Flag = true;
            msg.Msg  = String.Format(@"导入完成;总计{0}条.", affectedCount.ToString());
            return(msg);
        }