Beispiel #1
0
 public TaskBootMenu(ComputerEntity computer, ImageProfileEntity imageProfile)
 {
     _computer                = computer;
     _imageProfile            = imageProfile;
     _clusterGroupServices    = new ClusterGroupServices();
     _secondaryServerServices = new SecondaryServerServices();
 }
 public ComputerLoader(string userId, int?computerId, IRepository db)
 {
     _dataBase = db;
     Computer  = LoadComputer(userId, computerId);
     IsExist.CheckComputerAssign(Computer);
     LoadParts();
 }
Beispiel #3
0
        /// <summary>
        /// 构造函数。
        /// </summary>
        /// <param name="computerEntity">表示计算机配置信息的实体对象。</param>
        public ComputerViewContext(ComputerEntity computerEntity)
            : base()
        {
            if (null != computerEntity && computerEntity.ComputerName.Length > 0)
            {
                //TitleName = "计算机配置" + "_" + computerEntity.ComputerName;
                TitleName = StringParser.Parse("${res:FanHai.Hemera.Addins.ComputerConfCtrl.lbl.0001}") + "_" + computerEntity.ComputerName;
            }
            else
            {
                TitleName = StringParser.Parse("${res:FanHai.Hemera.Addins.ComputerConfCtrl.lbl.0001}");
            }

            Panel panel = new Panel();

            //set panel dock style
            panel.Dock = DockStyle.Fill;
            //set panel BorderStyle
            panel.BorderStyle      = BorderStyle.FixedSingle;
            _computerConfCtrl      = new ComputerConfCtrl(computerEntity);
            _computerConfCtrl.Dock = DockStyle.Fill;
            panel.Controls.Add(_computerConfCtrl);
            //set panel to view content
            this.control = panel;
        }
Beispiel #4
0
        public void DeleteBootFiles(ComputerEntity computer)
        {
            if (new ComputerServices().IsComputerActive(computer.Id))
            {
                return; //Files Will Be Processed When task is done
            }
            var pxeMac = StringManipulationServices.MacToPxeMac(computer.Mac);
            var list   = new List <Tuple <string, string> >
            {
                Tuple.Create("bios", ""),
                Tuple.Create("bios", ".ipxe"),
                Tuple.Create("efi32", ""),
                Tuple.Create("efi32", ".ipxe"),
                Tuple.Create("efi64", ""),
                Tuple.Create("efi64", ".ipxe"),
                Tuple.Create("efi64", ".cfg")
            };

            foreach (var tuple in list)
            {
                new FileOpsServices().DeletePath(SettingServices.GetSettingValue(SettingStrings.TftpPath) + "proxy" +
                                                 Path.DirectorySeparatorChar + tuple.Item1 +
                                                 Path.DirectorySeparatorChar + "pxelinux.cfg" +
                                                 Path.DirectorySeparatorChar +
                                                 pxeMac +
                                                 tuple.Item2);
            }

            foreach (var ext in new[] { "", ".ipxe", ".cfg" })
            {
                new FileOpsServices().DeletePath(SettingServices.GetSettingValue(SettingStrings.TftpPath) +
                                                 "pxelinux.cfg" + Path.DirectorySeparatorChar +
                                                 pxeMac + ext);
            }
        }
Beispiel #5
0
 public ApiBoolResponseDTO AddToSmartGroups(ComputerEntity computer)
 {
     Request.Method   = Method.POST;
     Request.Resource = string.Format("api/{0}/AddToSmartGroups/", Resource);
     Request.AddJsonBody(computer);
     return(_apiRequest.Execute <ApiBoolResponseDTO>(Request));
 }
 public ApiBoolResponseDTO AddToSmartGroups(ComputerEntity computer)
 {
     _computerService.AddComputerToSmartGroups(computer);
     return(new ApiBoolResponseDTO {
         Value = true
     });
 }
Beispiel #7
0
        public ComputerConfCtrl(ComputerEntity computerEntity)
        {
            InitializeComponent();
            _computerEntity = computerEntity;

            afterStateChanged += new AfterStateChanged(OnAfterStateChanged);
            if (_computerEntity.ComputerName.Length < 1)
            {
                _udaCommonControl = new UdaCommonControl(EntityType.Computer, "");
                _udaCommonControl.UserDefinedAttrs = _computerEntity.UserDefinedAttrs;
                State = ControlState.New;
            }
            else
            {
                _udaCommonControl = new UdaCommonControl(EntityType.Computer, _computerEntity.CodeKey);
                MapComputerToControl();

                if (_computerEntity.Status == EntityStatus.InActive)
                {
                    State = ControlState.Edit;
                }
                else
                {
                    State = ControlState.ReadOnly;
                }
            }
            _udaCommonControl.Dock = DockStyle.Fill;
            UdaPanel.Controls.Add(_udaCommonControl);
        }
        public void SendTaskErrorEmail(ActiveImagingTaskEntity task, string error)
        {
            //Mail not enabled
            if (SettingServices.GetSettingValue(SettingStrings.SmtpEnabled) == "0")
            {
                return;
            }
            var computer = new ComputerServices().GetComputer(task.ComputerId);

            foreach (
                var user in
                _userServices.SearchUsers("").Where(x => x.NotifyError == 1 && !string.IsNullOrEmpty(x.Email)))
            {
                if (task.UserId == user.Id)
                {
                    if (computer == null)
                    {
                        computer      = new ComputerEntity();
                        computer.Name = "Unknown Computer";
                    }
                    var mail = new MailServices
                    {
                        MailTo  = user.Email,
                        Body    = computer.Name + " Image Task Has Failed. " + error,
                        Subject = "Task Failed"
                    };
                    mail.Send();
                }
            }
        }
Beispiel #9
0
        public string AddComputer(string name, string mac, string clientIdentifier)
        {
            clientIdentifier = clientIdentifier.ToUpper();
            var existingComputer = new ComputerServices().GetComputerFromClientIdentifier(clientIdentifier);

            if (existingComputer != null)
            {
                return
                    (JsonConvert.SerializeObject(new ActionResultDTO
                {
                    Success = false,
                    ErrorMessage = "A Computer With This Client Id Already Exists"
                }));
            }
            var computer = new ComputerEntity
            {
                Name             = name,
                Mac              = mac,
                ClientIdentifier = clientIdentifier,
                SiteId           = -1,
                BuildingId       = -1,
                RoomId           = -1,
                ImageId          = -1,
                ImageProfileId   = -1,
                ClusterGroupId   = -1
            };
            var result = new ComputerServices().AddComputer(computer);

            return(JsonConvert.SerializeObject(result));
        }
Beispiel #10
0
        public ActionResultDTO UpdateComputer(ComputerEntity computer)
        {
            var existingcomputer = GetComputer(computer.Id);

            if (existingcomputer == null)
            {
                return new ActionResultDTO {
                           ErrorMessage = "Computer Not Found", Id = 0
                }
            }
            ;

            computer.Mac = StringManipulationServices.FixMac(computer.Mac);
            var actionResult     = new ActionResultDTO();
            var validationResult = ValidateComputer(computer, "update");

            if (validationResult.Success)
            {
                _uow.ComputerRepository.Update(computer, computer.Id);

                _uow.Save();
                actionResult.Success = true;
                actionResult.Id      = computer.Id;
            }
            else
            {
                actionResult.Success      = false;
                actionResult.ErrorMessage = validationResult.ErrorMessage;
            }

            return(actionResult);
        }
Beispiel #11
0
 public Unicast(int computerId, string direction, int userId, string userIp)
 {
     _direction = direction;
     _computer  = new ComputerServices().GetComputer(computerId);
     _userId    = userId;
     _ipAddress = userIp;
 }
Beispiel #12
0
 public CleanTaskBootFiles(ComputerEntity computer)
 {
     _computer                = computer;
     _bootFile                = StringManipulationServices.MacToPxeMac(_computer.Mac);
     _computerServices        = new ComputerServices();
     _clusterGroupServices    = new ClusterGroupServices();
     _secondaryServerServices = new SecondaryServerServices();
 }
Beispiel #13
0
        public ActionResult EditComputer(ComputerEntity computer)
        {
            _dataBase.UpdateComputerName(computer.Id, computer.Name);

            TempData["Message"] = "You have edited item";

            return(RedirectToAction("Index"));
        }
Beispiel #14
0
 public CreateTaskArguments(ComputerEntity computer, ImageProfileWithImage imageProfile, string direction)
 {
     _computer             = computer;
     _imageProfile         = imageProfile;
     _direction            = direction;
     _activeTaskArguments  = new StringBuilder();
     _imageProfileServices = new ImageProfileServices();
 }
        public static void CheckComputerAssign(ComputerEntity computer)
        {
            _computer = computer;

            CheckComputerAssign();
            if (Computer)
            {
                CheckPartAssign();
            }
        }
Beispiel #16
0
        public ActionResultDTO Put(int id, ComputerEntity tObject)
        {
            Request.Method = Method.PUT;
            Request.AddJsonBody(tObject);
            Request.Resource = string.Format("api/{0}/Put/{1}", Resource, id);
            var response = _apiRequest.Execute <ActionResultDTO>(Request);

            if (response.Id == 0)
            {
                response.Success = false;
            }
            return(response);
        }
        public ActionResultDTO Post(ComputerEntity computer)
        {
            var result = _computerService.AddComputer(computer);

            if (result.Success)
            {
                _auditLog.AuditType  = AuditEntry.Type.Create;
                _auditLog.ObjectId   = result.Id;
                _auditLog.ObjectName = computer.Name;
                _auditLog.Ip         = Request.GetClientIpAddress();
                _auditLog.ObjectJson = JsonConvert.SerializeObject(_computerService.GetComputer(result.Id));
                _auditLogService.AddAuditLog(_auditLog);
            }
            return(result);
        }
        private ComputerEntity GetComInfo(ComputerEntity comInfo)
        {
            Microsoft.VisualBasic.Devices.ComputerInfo info = new Microsoft.VisualBasic.Devices.ComputerInfo();
            comInfo.OSFullName = info.OSFullName;
            //comInfo.OSPlatform = info.OSPlatform;
            comInfo.OSVersion    = info.OSVersion;
            comInfo.ComputerName = Environment.MachineName;
            comInfo.IPAddress    = lblIPAddrress.Text;
            comInfo.MacAddress   = lblMacAddress.Text;
            comInfo.CPUInfo      = GetCpuInfo();
            comInfo.RAmInfo      = GetRamInfo();
            comInfo.DriveInfo    = GetDriveInfo();

            return(comInfo);
        }
Beispiel #19
0
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            Computer = !string.IsNullOrEmpty(Request.QueryString["computerid"])
                ? Call.ComputerApi.Get(Convert.ToInt32(Request.QueryString["computerid"]))
                : null;
            if (Computer == null)
            {
                RequiresAuthorization(AuthorizationStrings.SearchComputer);
            }
            else
            {
                RequiresAuthorizationOrManagedComputer(AuthorizationStrings.ReadComputer, Computer.Id);
            }
        }
Beispiel #20
0
        public void AddComputerToSmartGroups(ComputerEntity computer)
        {
            var groups = new GroupServices().SearchGroups();

            foreach (var group in groups.Where(x => x.Type == "smart"))
            {
                var computers =
                    SearchComputersByName(group.SmartCriteria, int.MaxValue, group.SmartType).Where(x => x.Name == computer.Name);
                var memberships =
                    computers.Select(comp => new GroupMembershipEntity {
                    GroupId = @group.Id, ComputerId = comp.Id
                })
                    .ToList();
                new GroupMembershipServices().AddMembership(memberships);
            }
        }
Beispiel #21
0
        /// <summary>
        /// 获取与当前机器连接的天平秤的串口对象。
        /// </summary>
        /// <returns>串口对象</returns>
        private static SerialPort GetSerialPort()
        {
            //W_PORT_NAME  天平秤端口号
            //W_BAUD_RATE  天平秤串行波特率
            SerialPort     obj           = new SerialPort();
            ComputerEntity entity        = new ComputerEntity();
            DataTable      dtComputerUDA = entity.GetComputerInfo();
            string         portName      = entity.GetComputerUDAAttributeValue(dtComputerUDA, "W_PORT_NAME");
            string         baudRate      = entity.GetComputerUDAAttributeValue(dtComputerUDA, "W_BAUD_RATE");
            int            nBaudRate;

            obj.BaudRate = int.TryParse(baudRate, out nBaudRate) ? nBaudRate : 1200;
            obj.PortName = string.IsNullOrEmpty(portName) ? "COM1" : portName;
            obj.StopBits = System.IO.Ports.StopBits.One;
            obj.Parity   = System.IO.Ports.Parity.None;
            obj.DataBits = 8;
            return(obj);
        }
Beispiel #22
0
        /// <summary>
        /// grid Control Double Click
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridData_DoubleClick(object sender, EventArgs e)
        {
            MapSelectedItemToProperties();

            //返回值的主键为空执行下面操作
            if (null == ComputerKey || ComputerKey.Length < 1)
            {
                return;
            }
            //返回值的计算机名称为空就是没有值执行下面操作
            if (null == ComputerName || ComputerName.Length < 1)
            {
                return;
            }
            ComputerEntity computerEntity = new ComputerEntity(ComputerName);

            computerEntity.CodeKey      = ComputerKey;
            computerEntity.ComputerName = ComputerName;
            computerEntity.ComputerDesc = ComputerDescription;
            _computerEntity             = computerEntity;
            MapComputerToControl();
            State = ControlState.Edit;
            OnAfterStateChanged(State);
            //title=计算机维护_计算机名称
            //string title = StringParser.Parse("${res:FanHai.Hemera.Addins.FMM.ComputerConfCtrl.Title}") + "_" + ComputerName;
            ////string title = StringParser.Parse("${res:FanHai.Hemera.Addins.FMM.WorkOrderManagement.Name}") + "_" + orderSearch.ComputerName;
            //foreach (IViewContent viewContent in WorkbenchSingleton.Workbench.ViewContentCollection)
            //{
            //    if (viewContent.TitleName == title)
            //    {
            //        viewContent.WorkbenchWindow.SelectWindow();
            //        return;
            //    }
            //}
            ////新建视图窗体
            //ComputerViewContext OrderContent = new ComputerViewContext(new ComputerEntity(ComputerName));
            //WorkbenchSingleton.Workbench.ShowView(OrderContent);
            //if (MapSelectedItemToProperties())
            //{
            //    //DialogResult = DialogResult.OK;
            //}
        }
        public ActionResultDTO Put(int id, ComputerEntity computer)
        {
            computer.Id = id;
            var result = _computerService.UpdateComputer(computer);

            if (result.Id == 0)
            {
                throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound, result));
            }
            if (result.Success)
            {
                _auditLog.AuditType  = AuditEntry.Type.Update;
                _auditLog.ObjectId   = result.Id;
                _auditLog.ObjectName = computer.Name;
                _auditLog.Ip         = Request.GetClientIpAddress();
                _auditLog.ObjectJson = JsonConvert.SerializeObject(computer);
                _auditLogService.AddAuditLog(_auditLog);
            }
            return(result);
        }
Beispiel #24
0
        protected void ButtonAddComputer_Click(object sender, EventArgs e)
        {
            RequiresAuthorization(AuthorizationStrings.CreateComputer);
            var computer = new ComputerEntity
            {
                Name           = txtComputerName.Text,
                Mac            = txtComputerMac.Text,
                ImageId        = Convert.ToInt32(ddlComputerImage.SelectedValue),
                ImageProfileId =
                    Convert.ToInt32(ddlComputerImage.SelectedValue) == -1
                        ? -1
                        : Convert.ToInt32(ddlImageProfile.SelectedValue),
                Description         = txtComputerDesc.Text,
                SiteId              = Convert.ToInt32(ddlSite.SelectedValue),
                BuildingId          = Convert.ToInt32(ddlBuilding.SelectedValue),
                RoomId              = Convert.ToInt32(ddlRoom.SelectedValue),
                ClusterGroupId      = Convert.ToInt32(ddlClusterGroup.SelectedValue),
                CustomAttribute1    = txtCustom1.Text,
                CustomAttribute2    = txtCustom2.Text,
                CustomAttribute3    = txtCustom3.Text,
                CustomAttribute4    = txtCustom4.Text,
                CustomAttribute5    = txtCustom5.Text,
                AlternateServerIpId = Convert.ToInt32(altServerIp.SelectedValue)
            };

            var result = Call.ComputerApi.Post(computer);

            if (!result.Success)
            {
                EndUserMessage = result.ErrorMessage;
            }
            else
            {
                Call.ComputerApi.AddToSmartGroups(computer);
                EndUserMessage = "Successfully Created Computer";
                if (!createAnother.Checked)
                {
                    Response.Redirect(string.Format("~/views/computers/edit.aspx?computerid={0}", result.Id));
                }
            }
        }
Beispiel #25
0
        public ActionResultDTO AddComputer(ComputerEntity computer)
        {
            var actionResult = new ActionResultDTO();

            computer.Mac = StringManipulationServices.FixMac(computer.Mac);
            var validationResult = ValidateComputer(computer, "new");

            if (validationResult.Success)
            {
                _uow.ComputerRepository.Insert(computer);
                _uow.Save();
                actionResult.Success = true;
                actionResult.Id      = computer.Id;
            }
            else
            {
                actionResult.Success      = false;
                actionResult.ErrorMessage = validationResult.ErrorMessage;
            }
            return(actionResult);
        }
Beispiel #26
0
        /// <summary>
        /// 获取方阻的配置数据。
        /// </summary>
        /// <returns></returns>
        public static DataFileReadConfig GetResistanceConfig(DateTime startTime)
        {
            //1 R_STARTROW	    方租数据在文件中的起始行
            //2	R_FILEPATH	    方租读取的文件存放路径
            //3	R_DATACOLUMN	方租数据行中列号
            //4 R_SearchPattern 方租文件扩展名
            //5	R_IdentityName	方租数据在行中标识符
            //6 R_Separator     方租数据在行中分隔符
            //7 R_Direction     方租数据的搜索方向
            ComputerEntity entity        = new ComputerEntity();
            DataTable      dtComputerUDA = entity.GetComputerInfo();
            string         startRow      = entity.GetComputerUDAAttributeValue(dtComputerUDA, "R_STARTROW");
            string         filePath      = entity.GetComputerUDAAttributeValue(dtComputerUDA, "R_FILEPATH");
            string         dataColumn    = entity.GetComputerUDAAttributeValue(dtComputerUDA, "R_DATACOLUMN");
            string         identifyName  = entity.GetComputerUDAAttributeValue(dtComputerUDA, "R_IdentityName");
            string         pattern       = entity.GetComputerUDAAttributeValue(dtComputerUDA, "R_SearchPattern");
            string         separator     = entity.GetComputerUDAAttributeValue(dtComputerUDA, "R_Separator");
            string         direction     = entity.GetComputerUDAAttributeValue(dtComputerUDA, "R_Direction");
            string         fileName      = string.Empty;

            pattern = pattern == string.Empty ? "*.*" : pattern;
            if (!string.IsNullOrEmpty(filePath) && System.IO.Directory.Exists(filePath))
            {
                fileName = GetFileNameByLastTime(filePath, pattern, startTime);
            }
            DataFileReadConfig config = new DataFileReadConfig();

            config.Column        = string.IsNullOrEmpty(dataColumn) ? 9 : Convert.ToInt32(dataColumn);
            config.StartRow      = string.IsNullOrEmpty(startRow) ? 0 : Convert.ToInt32(startRow);
            config.FileName      = fileName;
            config.IdentityName  = string.IsNullOrEmpty(identifyName) ? "POINT" : identifyName;
            config.Separator     = string.IsNullOrEmpty(separator) ? ',' : separator.ToCharArray()[0];
            config.SearchPattern = pattern;
            config.Direction     = string.IsNullOrEmpty(direction) ? "F" : direction;
            if (System.IO.File.Exists(fileName))
            {
                config.FileLastWriteTime = System.IO.File.GetLastWriteTime(fileName);
            }
            return(config);
        }
Beispiel #27
0
        /// <summary>
        /// 获取折射率的配置数据。
        /// </summary>
        /// <returns></returns>
        public static DataFileReadConfig GetRefractionConfig()
        {
            //1 A_STARTROW	    折射率数据在文件中的起始行
            //2	A_FILEPATH	    折射率读取的文件存放路径
            //3	A_DATACOLUMN	折射率数据行中列号
            //4 A_SearchPattern 折射率文件扩展名
            //5	A_IdentityName	折射率数据在行中标识符
            //6 A_Separator     折射率数据在行中分隔符
            //7 A_Direction     折射率数据的搜索方向
            ComputerEntity entity        = new ComputerEntity();
            DataTable      dtComputerUDA = entity.GetComputerInfo();
            string         startRow      = entity.GetComputerUDAAttributeValue(dtComputerUDA, "A_STARTROW");
            string         filePath      = entity.GetComputerUDAAttributeValue(dtComputerUDA, "A_FILEPATH");
            string         dataColumn    = entity.GetComputerUDAAttributeValue(dtComputerUDA, "A_DATACOLUMN");
            string         identifyName  = entity.GetComputerUDAAttributeValue(dtComputerUDA, "A_IdentityName");
            string         pattern       = entity.GetComputerUDAAttributeValue(dtComputerUDA, "A_SearchPattern");
            string         separator     = entity.GetComputerUDAAttributeValue(dtComputerUDA, "A_Separator");
            string         direction     = entity.GetComputerUDAAttributeValue(dtComputerUDA, "A_Direction");
            string         fileName      = string.Empty;

            pattern = pattern == string.Empty ? "*.*" : pattern;
            if (!string.IsNullOrEmpty(filePath) && System.IO.Directory.Exists(filePath))
            {
                fileName = GetFileNameByLastTime(filePath, pattern);
            }
            DataFileReadConfig config = new DataFileReadConfig();

            config.Column        = string.IsNullOrEmpty(dataColumn) ? 2 : Convert.ToInt32(dataColumn);
            config.StartRow      = string.IsNullOrEmpty(startRow) ? 0 : Convert.ToInt32(startRow);
            config.FileName      = fileName;
            config.IdentityName  = string.IsNullOrEmpty(identifyName) ? "n:" : identifyName;
            config.Separator     = string.IsNullOrEmpty(separator) ? ' ' : separator.ToCharArray()[0];
            config.SearchPattern = pattern;
            config.Direction     = string.IsNullOrEmpty(direction) ? "F" : direction;
            return(config);
        }
Beispiel #28
0
        public string OnDemandCheckIn(string mac, int objectId, string task, string userId, string computerId)
        {
            var checkIn          = new CheckIn();
            var computerServices = new ComputerServices();

            if (userId != null) //on demand
            {
                //Check permissions
                if (task.Contains("deploy"))
                {
                    if (
                        !new AuthorizationServices(Convert.ToInt32(userId), AuthorizationStrings.ImageDeployTask)
                        .IsAuthorized())
                    {
                        checkIn.Result  = "false";
                        checkIn.Message = "This User Is Not Authorized To Deploy Images";
                        return(JsonConvert.SerializeObject(checkIn));
                    }
                }

                if (task.Contains("upload"))
                {
                    if (
                        !new AuthorizationServices(Convert.ToInt32(userId), AuthorizationStrings.ImageUploadTask)
                        .IsAuthorized())
                    {
                        checkIn.Result  = "false";
                        checkIn.Message = "This User Is Not Authorized To Upload Images";
                        return(JsonConvert.SerializeObject(checkIn));
                    }
                }

                if (task.Contains("multicast"))
                {
                    if (
                        !new AuthorizationServices(Convert.ToInt32(userId), AuthorizationStrings.ImageMulticastTask)
                        .IsAuthorized())
                    {
                        checkIn.Result  = "false";
                        checkIn.Message = "This User Is Not Authorized To Multicast Images";
                        return(JsonConvert.SerializeObject(checkIn));
                    }
                }
            }

            ComputerEntity computer = null;

            if (computerId != "false")
            {
                computer = computerServices.GetComputer(Convert.ToInt32(computerId));
            }

            ImageProfileWithImage imageProfile;

            var arguments = "";

            if (task == "deploy" || task == "upload" || task == "clobber" || task == "ondupload" || task == "onddeploy" ||
                task == "unregupload" || task == "unregdeploy" || task == "modelmatchdeploy")
            {
                imageProfile = new ImageProfileServices().ReadProfile(objectId);
                arguments    = new CreateTaskArguments(computer, imageProfile, task).Execute();
            }
            else //Multicast
            {
                var multicast = new ActiveMulticastSessionServices().GetFromPort(objectId);
                imageProfile = new ImageProfileServices().ReadProfile(multicast.ImageProfileId);
                arguments    = new CreateTaskArguments(computer, imageProfile, task).Execute(objectId.ToString());
            }

            var imageDistributionPoint = new GetImageServer(computer, task).Run();

            if (imageProfile.Image.Protected == 1 && (task == "upload" || task == "ondupload" || task == "unregupload"))
            {
                checkIn.Result  = "false";
                checkIn.Message = "This Image Is Protected";
                return(JsonConvert.SerializeObject(checkIn));
            }

            if (imageProfile.Image.Environment == "")
            {
                imageProfile.Image.Environment = "linux";
            }
            checkIn.ImageEnvironment = imageProfile.Image.Environment;

            if (imageProfile.Image.Environment == "winpe")
            {
                arguments += "dp_id=\"" + imageDistributionPoint + "\"\r\n";
            }
            else
            {
                arguments += " dp_id=\"" + imageDistributionPoint + "\"";
            }

            var activeTask = new ActiveImagingTaskEntity();

            activeTask.Direction = task;
            activeTask.UserId    = Convert.ToInt32(userId);
            activeTask.Type      = task;

            activeTask.DpId   = imageDistributionPoint;
            activeTask.Status = "1";

            if (computer == null)
            {
                //Create Task for an unregistered on demand computer
                var rnd           = new Random(DateTime.Now.Millisecond);
                var newComputerId = rnd.Next(-200000, -100000);

                if (imageProfile.Image.Environment == "winpe")
                {
                    arguments += "computer_id=" + newComputerId + "\r\n";
                }
                else
                {
                    arguments += " computer_id=" + newComputerId;
                }
                activeTask.ComputerId = newComputerId;
                activeTask.Arguments  = mac;
            }
            else
            {
                //Create Task for a registered on demand computer
                activeTask.ComputerId = computer.Id;
                activeTask.Arguments  = arguments;
            }
            new ActiveImagingTaskServices().AddActiveImagingTask(activeTask);

            var auditLog = new AuditLogEntity();

            switch (task)
            {
            case "ondupload":
            case "unregupload":
            case "upload":
                auditLog.AuditType = AuditEntry.Type.OndUpload;
                break;

            default:
                auditLog.AuditType = AuditEntry.Type.OndDeploy;
                break;
            }

            try
            {
                auditLog.ObjectId = activeTask.ComputerId;
                var user = new UserServices().GetUser(activeTask.UserId);
                if (user != null)
                {
                    auditLog.UserName = user.Name;
                }
                auditLog.ObjectName = computer != null ? computer.Name : mac;
                auditLog.Ip         = "";
                auditLog.UserId     = activeTask.UserId;
                auditLog.ObjectType = "Computer";
                auditLog.ObjectJson = JsonConvert.SerializeObject(activeTask);
                new AuditLogServices().AddAuditLog(auditLog);

                auditLog.ObjectId   = imageProfile.ImageId;
                auditLog.ObjectName = imageProfile.Image.Name;
                auditLog.ObjectType = "Image";
                new AuditLogServices().AddAuditLog(auditLog);
            }
            catch
            {
                //Do Nothing
            }


            checkIn.Result        = "true";
            checkIn.TaskArguments = arguments;
            checkIn.TaskId        = activeTask.Id.ToString();
            return(JsonConvert.SerializeObject(checkIn));
        }
Beispiel #29
0
        private ValidationResultDTO ValidateComputer(ComputerEntity computer, string type)
        {
            var validationResult = new ValidationResultDTO {
                Success = false
            };

            if (type == "new" || type == "update")
            {
                if (string.IsNullOrEmpty(computer.Name) || computer.Name.Any(c => c == ' '))
                {
                    validationResult.ErrorMessage = "Computer Name Is Not Valid";
                    return(validationResult);
                }

                if (string.IsNullOrEmpty(computer.Mac) ||
                    !computer.Mac.All(c => char.IsLetterOrDigit(c) || c == ':' || c == '-') && computer.Mac.Length == 12 &&
                    !computer.Mac.All(char.IsLetterOrDigit))
                {
                    validationResult.ErrorMessage = "Computer Mac Is Not Valid";
                    return(validationResult);
                }

                if (type == "new")
                {
                    if (_uow.ComputerRepository.Exists(h => h.Name == computer.Name))
                    {
                        validationResult.ErrorMessage = "A Computer With This Name Already Exists";
                        return(validationResult);
                    }
                    if (_uow.ComputerRepository.Exists(h => h.Mac == computer.Mac))
                    {
                        var existingComputer = GetComputerFromMac(computer.Mac);
                        if (string.IsNullOrEmpty(existingComputer.ClientIdentifier) ||
                            string.IsNullOrEmpty(computer.ClientIdentifier) ||
                            existingComputer.ClientIdentifier == computer.ClientIdentifier)
                        {
                            validationResult.ErrorMessage =
                                "Duplicate MAC Addresses Are Only Allowed If Each Computer Has A Unique Client Identifier";
                            return(validationResult);
                        }
                    }
                }
                else
                {
                    var originalComputer = _uow.ComputerRepository.GetById(computer.Id);
                    if (originalComputer.Name != computer.Name)
                    {
                        if (_uow.ComputerRepository.Exists(h => h.Name == computer.Name))
                        {
                            validationResult.ErrorMessage = "A Computer With This Name Already Exists";
                            return(validationResult);
                        }
                    }
                    else if (originalComputer.Mac != computer.Mac)
                    {
                        if (_uow.ComputerRepository.Exists(h => h.Mac == computer.Mac))
                        {
                            var existingComputer = GetComputerFromMac(computer.Mac);
                            if (string.IsNullOrEmpty(existingComputer.ClientIdentifier) ||
                                string.IsNullOrEmpty(computer.ClientIdentifier) ||
                                existingComputer.ClientIdentifier == computer.ClientIdentifier)
                            {
                                validationResult.ErrorMessage =
                                    "Duplicate MAC Addresses Are Only Allowed If Each Computer Has A Unique Client Identifier";
                                return(validationResult);
                            }
                        }
                    }
                }
            }

            if (type == "delete")
            {
                if (IsComputerActive(computer.Id))
                {
                    validationResult.ErrorMessage = "A Computer Cannot Be Deleted While It Has An Active Task";
                    return(validationResult);
                }
            }

            validationResult.Success = true;
            return(validationResult);
        }
Beispiel #30
0
        /// <summary>
        /// 打印条码。
        /// </summary>
        /// <param name="batch">是否批量打印。</param>
        private void Print(bool batch)
        {
            try
            {
                ComputerEntity computerEntity = new ComputerEntity();
                if (computerEntity.GetComputerPrinterInfo(PropertyService.Get(PROPERTY_FIELDS.COMPUTER_NAME)))
                {
                    if (computerEntity.PrinterType.Length < 1 || computerEntity.BarcodeModule.Length < 1)
                    {
                        MessageService.ShowError("请配置打印机类型或标签模板");
                        return;
                    }
                    else
                    {
                        if (Convert.ToInt32(computerEntity.PrinterType) == (int)PortType.Local)
                        {
                            if (computerEntity.PrinterName.Length == 0)
                            {
                                MessageService.ShowMessage("请配置打印机名称");
                                return;
                            }
                        }
                        else
                        {
                            if (computerEntity.PrinterPort.Length == 0)
                            {
                                MessageService.ShowMessage("请配置打印机端口");
                                return;
                            }
                            if (Convert.ToInt32(computerEntity.PrinterType) == (int)PortType.Network && computerEntity.PrinterIP.Length == 0)
                            {
                                MessageService.ShowError("请配置打印机Ip地址");
                                return;
                            }
                        }
                    }
                    if (rowHandle > -1)
                    {
                        //组织要打印的数据。
                        List <BarCode> barcodeList = new List <BarCode>();
                        if (batch)//如果要批量打印。
                        {
                            foreach (int i in gvLotInfo.GetSelectedRows())
                            {
                                string  lotNumber = gvLotInfo.GetRowCellValue(i, POR_LOT_FIELDS.FIELD_LOT_NUMBER).ToString();
                                BarCode barcode   = new BarCode(lotNumber);
                                barcodeList.Add(barcode);
                            }
                        }
                        else
                        {
                            BarCode barcode = new BarCode(_lotNumber);
                            barcodeList.Add(barcode);
                        }
                        //打印
                        int printNumber = 0;
                        try
                        {
                            printNumber = CodePrint.BarCodePrint(barcodeList, computerEntity.BarcodeModule, computerEntity.PrinterName, computerEntity.PrinterIP, computerEntity.PrinterPort, (PortType)(Convert.ToInt32(computerEntity.PrinterType)));
                        }
                        catch (Exception ex)
                        {
                            MessageService.ShowWarning("打印失败:" + ex.Message);
                            return;
                        }
                        //更新批次状态。
                        LotEntity     entity     = new LotEntity();
                        List <string> lotNumbers = new List <string>();
                        for (int i = 0; i < printNumber; i++)
                        {
                            lotNumbers.Add(barcodeList[i].BatteryCellCode);
                        }
                        if (!entity.UpdatePrintFlag(lotNumbers))
                        {
                            MessageService.ShowError("更新批次号打印机状态失败。");
                            return;
                        }
                        else
                        {
                            if (batch)//如果要批量打印。
                            {
                                foreach (int i in gvLotInfo.GetSelectedRows())
                                {
                                    gvLotInfo.SetRowCellValue(i, POR_LOT_FIELDS.FIELD_IS_PRINT, (Convert.ToInt32(_printFlag) + 1).ToString());
                                }
                            }
                            else
                            {
                                gvLotInfo.SetRowCellValue(rowHandle, POR_LOT_FIELDS.FIELD_IS_PRINT, (Convert.ToInt32(_printFlag) + 1).ToString());
                            }
                        }

                        if (printNumber == barcodeList.Count)//打印成功
                        {
                            MessageService.ShowMessage("${res:FanHai.Hemera.Addins.Sorting.Message.PrintFinished}", "提示");
                        }
                        else
                        {
                            MessageService.ShowMessage("部分条码打印未成功。", "提示");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageService.ShowError(ex.Message);
            }
        }