Ejemplo n.º 1
0
        public computerdto(ComputerDTO dt)
        {
            this.Address           = dt.Address;
            this.ADName            = dt.ADName;
            this.AssetNumber       = dt.AssetNumber;
            this.CNName            = dt.CNName;
            this.company           = dt.company;
            this.ComputerOnwer     = dt.ComputerOnwer;
            this.Description       = dt.Description;
            this.DistinguishedName = dt.DistinguishedName;
            this.dNSHostName       = dt.dNSHostName;
            this.FPC                    = dt.FPC;
            this.LastLoggedUser         = dt.LastLoggedUser;
            this.LDAPPath               = dt.LDAPPath;
            this.managedBy              = dt.managedBy;
            this.Name                   = dt.Name;
            this.operatingSystem        = dt.operatingSystem;
            this.operatingSystemVersion = dt.operatingSystemVersion;
            this.OUName                 = OuString.OuStringFormat(dt.OUName);


            this.site      = dt.site;
            this.Telephone = dt.Telephone;
            this.TypeName  = dt.TypeName;
        }
        public async Task <IHttpActionResult> Put(ComputerDTO computerDTO, int id)
        {
            if (ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            if (computerDTO.Id != id)
            {
                return(BadRequest(ModelState));
            }

            var flag = await computerService.GetById(id);

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

            try
            {
                var computer = mapper.Map <Computer>(computerDTO);
                computer = await computerService.Insert(computer);

                return(Ok(computer));
            }
            catch (Exception e)
            {
                return(InternalServerError(e));
            }
        }
Ejemplo n.º 3
0
        public JsonResult SearchModify()
        {
            //Log日志要记录的用户名
            string             domain         = Request.Form["domain"].Trim().ToString();
            string             searchcriteria = Request.Form["searchcriteria"].Trim().ToString();
            string             searchkeyword  = Request.Form["searchkeyword"].Trim().ToString();
            Computers          ad_computer    = HttpContext.Application["ad_computer"] as Computers;
            List <ComputerDTO> col;

            if (searchkeyword.Trim() != "")
            {
                col = ad_computer.SearchAllComputersDTO(searchkeyword, domain, Int32.Parse(searchcriteria));
            }
            else
            {
                col = ad_computer.SearchAllComputersDTO(searchkeyword, domain, 0);
            }

            string con = "<table id = \"example\" class=\"display\" cellspacing=\"0\" width=\"100%\"><thead><tr><th>ID</th><th>Name</th><th>OUName</th><th>OperatingSystem</th></tr></thead><tbody>";

            for (int i = 0; i < col.Count; i++)
            {
                ComputerDTO cd = col.ElementAt(i);
                con += "<tr" + " " + "onclick=\"computer_detail(this)\"><td>" + i + "</td><td>" + cd.Name + "</td><td>" + cd.OUName + "</td><td>" + cd.operatingSystem + "</td></tr>";//数据行,字段对应数据库查询字段
            }
            con += " </tbody></table>";

            return(Json(new JsonData(con)));
        }
Ejemplo n.º 4
0
        public JsonResult Delete()
        {
            string Operator = "";

            if (Session["username"].ToString() != null)
            {
                Operator = Session["username"].ToString();
            }                                                                       //Log日志要记录的用户名
            string             computername = Request.Form["computername"].Trim().ToString();
            string             domain       = Request.Form["domain"].Trim().ToString();
            Computers          ad_computer  = HttpContext.Application["ad_computer"] as Computers;
            List <ComputerDTO> col          = ad_computer.SearchAllComputersDTO(computername, domain, (int)SearchPattern.Equals);
            ComputerDTO        cd           = col.ElementAt(0);
            string             m;

            if (ad_computer.DeleteComputerDTO(cd))
            {
                m = "Delete success";
                LogHelper.WriteLog(typeof(ComputerManagementController), Operator, "Delete%a%Computer%named%" + computername, true);
            }
            else
            {
                m = "Delete failed";
                LogHelper.WriteLog(typeof(ComputerManagementController), Operator, "Delete%a%Computer%named%" + computername, false);
            }
            return(Json(new JsonData(m)));
        }
        public ComputerDTO SetComponentToNull(ComputerDTO computer, Component component)
        {
            switch (component)
            {
            case Component.CPU:
                computer.CpuId = null;
                break;

            case Component.MEMORY:
                computer.MemoryId = null;
                break;

            case Component.VGA:
                computer.VgaId = null;
                break;

            case Component.MOTHERBOARD:
                computer.MotherboardId = null;
                break;

            case Component.MONITOR:
                computer.MonitorId = null;
                break;

            default:
                break;
            }
            return(computer);
        }
Ejemplo n.º 6
0
        public int Upsert(ComputerDTO cmp)
        {
            try
            {
                var model = Converter.Convert <ComputerEntity, ComputerDTO>(cmp);

                var item = dbaccess.Computer.Where(x => x.Name == model.Name && x.FirmId == model.FirmId).FirstOrDefault <ComputerEntity>();
                if (item == null)
                {
                    model.InsertDate = DateTime.Now;
                    dbaccess.Computer.Add(model);
                }
                else
                {
                    item.Ip              = model.Ip;
                    item.IsComputer      = model.IsComputer;
                    item.IsRootMachine   = model.IsRootMachine;
                    item.Name            = model.Name;
                    item.PyshicalAddress = model.PyshicalAddress;
                    item.IsVisible       = model.IsVisible;
                }

                dbaccess.SaveChanges();
                return(dbaccess.Computer.Where(x => x.Name == model.Name && x.FirmId == model.FirmId).FirstOrDefault().Id);
            }
            catch (System.Data.Entity.Validation.DbEntityValidationException ex)
            {
                string validationerror = "";
                foreach (var eve in ex.EntityValidationErrors)
                {
                    validationerror = "Entity of type \"" + eve.Entry.Entity.GetType().Name + "\" in state \"" + eve.Entry.State + "\" has the following validation errors:";
                    foreach (var ve in eve.ValidationErrors)
                    {
                        validationerror += "- Property: \"" + ve.PropertyName + "\", Error: \"" + ve.ErrorMessage + "\"";
                    }
                }

                throw new Exception(validationerror);
            }
            catch (System.Data.Entity.Infrastructure.DbUpdateException ex)
            {
                if (ex.InnerException != null)
                {
                    if (ex.InnerException.InnerException != null)
                    {
                        throw new Exception(ex.InnerException.InnerException.Message);
                    }
                    else
                    {
                        throw new Exception(ex.InnerException.Message);
                    }
                }
                else
                {
                    throw new Exception(ex.Message);
                }
            }
        }
Ejemplo n.º 7
0
        public JsonResult Update_Computer()
        {
            string Operator = "";

            if (Session["username"].ToString() != null)
            {
                Operator = Session["username"].ToString();
            }                                                                       //Log日志要记录的用户名
            string    name         = Request.Form["name"].ToString();
            string    computername = Request.Form["computername"].Trim().ToString();
            string    site         = Request.Form["site"].Trim().ToString();
            string    oupath       = Request.Form["oupath"].ToString();
            string    description  = Request.Form["Description"].Trim().ToString();
            string    domain       = Request.Form["domain"].Trim().ToString();
            string    manageby     = Request.Form["manageby"].ToString();
            Computers ad_computer  = HttpContext.Application["ad_computer"] as Computers;

            List <ComputerDTO> col = ad_computer.SearchAllComputersDTO(name, domain, (int)SearchPattern.Equals);

            ComputerDTO cd = col.ElementAt(0);

            cd.site        = site;
            cd.Name        = computername;
            cd.managedBy   = manageby;
            cd.Description = description;
            string m;

            if (oupath != "")
            {
                if (ad_computer.UpdateComputerDTO(cd) && ad_computer.MoveComputerIntoNewOU(cd, oupath))
                {
                    m = "Successful modification!";
                    LogHelper.WriteLog(typeof(ComputerManagementController), Operator, "Modify%the%information%of%" + computername.Replace(" ", ""), true);
                    return(Json(new JsonData(m, true)));
                }
                else
                {
                    m = "Modify failed!";
                    LogHelper.WriteLog(typeof(ComputerManagementController), Operator, "Modify%the%information%of%" + computername.Replace(" ", ""), false);
                    return(Json(new JsonData(m, false)));
                }
            }
            else
            {
                if (ad_computer.UpdateComputerDTO(cd))
                {
                    m = "Successful modification!";
                    LogHelper.WriteLog(typeof(ComputerManagementController), Operator, "Modify%the%information%of%" + computername.Replace(" ", ""), true);
                    return(Json(new JsonData(m, true)));
                }
                else
                {
                    m = "Modify failed!";
                    LogHelper.WriteLog(typeof(ComputerManagementController), Operator, "Modify%the%information%of%" + computername.Replace(" ", ""), false);
                    return(Json(new JsonData(m, false)));
                }
            }
        }
 public void RemoveComponentFromSession(Component component)
 {
     if (session.Get("computer") != null)
     {
         var         data     = session.GetString("computer");
         ComputerDTO computer = JsonConvert.DeserializeObject <ComputerDTO>(data);
         computer = SetComponentToNull(computer, component);
         var newData = JsonConvert.SerializeObject(computer);
         session.SetString("computer", newData);
     }
 }
Ejemplo n.º 9
0
        public JsonResult Details()
        {
            //Log日志要记录的用户名
            string             computername = Request.Form["computername"].Trim().ToString();
            string             domainname   = Request.Form["domainname"].Trim().ToString();
            Computers          ad_computer  = HttpContext.Application["ad_computer"] as Computers;
            List <ComputerDTO> col          = ad_computer.SearchAllComputersDTO(computername, domainname, (int)SearchPattern.Equals);
            ComputerDTO        cd           = col.ElementAt(0);
            computerdto        cdt          = new computerdto(cd);

            return(Json(cdt, JsonRequestBehavior.AllowGet));
        }
Ejemplo n.º 10
0
        public void Update(ComputerDTO comp)
        {
            var model = Converter.Convert <ComputerEntity, ComputerDTO>(comp);
            var item  = dbaccess.Computer.Where(x => x.Id == model.Id).FirstOrDefault <ComputerEntity>();

            item.Ip              = model.Ip;
            item.IsComputer      = model.IsComputer;
            item.IsRootMachine   = model.IsRootMachine;
            item.Name            = model.Name;
            item.PyshicalAddress = model.PyshicalAddress;
            item.IsVisible       = model.IsVisible;
            dbaccess.SaveChanges();
        }
Ejemplo n.º 11
0
        public static ComputerDTO ExecuteLocal()
        {
            var localcomp = new ComputerDTO
            {
                Ip   = GetLocalIp(),
                Name = GetLocalMachineName(),
                Type = "Local",
                //PyshicalAddress="",
                IsRootMachine = false,
                IsComputer    = true,
                InsertDate    = DateTime.Now
            };

            return(localcomp);
        }
Ejemplo n.º 12
0
        public ActionResult Create()
        {
            string Operator = "";

            if (Session["username"].ToString() != null)
            {
                Operator = Session["username"].ToString();
            }                                                                       //Log日志要记录的用户名
            string message = "";

            string domain       = Request.Form["domain"].Trim().ToString();
            string computername = Request.Form["computername"].Trim().ToString();
            string ou           = Request.Form["ou"].Trim().ToString();
            string description  = Request.Form["description"].Trim().ToString();

            Computers   ad_computer = HttpContext.Application["ad_computer"] as Computers;
            ComputerDTO cdt         = new ComputerDTO();

            cdt.Description = description;
            cdt.Name        = computername;
            cdt.dNSHostName = computername + "@" + domain;
            int errLevel = 0;

            if (ad_computer.CreateComputerDTO(cdt, ou, ref errLevel))
            {
                message = "The name <span style =\"color:green\">" + computername + "</span> is created for the success of the computer";
                LogHelper.WriteLog(typeof(ComputerManagementController), Operator, "Create%Computer%named%" + computername, true);
                XmlDocument doc = new XmlDocument();
                doc.Load(Server.MapPath("~/ComputerDetail.xml"));
                XmlNode    rootnode = doc.SelectSingleNode("ADComputerDetail");
                XmlElement xe1      = doc.CreateElement("computer");
                xe1.SetAttribute("Name", computername);
                XmlElement xesub1 = doc.CreateElement("CreateBy");
                xesub1.InnerText = Operator;
                xe1.AppendChild(xesub1);
                XmlElement xesub2 = doc.CreateElement("CreateTime");
                xesub2.InnerText = DateTime.Today.ToString("yyyyMMdd");
                xe1.AppendChild(xesub2);
                rootnode.AppendChild(xe1);
                doc.Save(Server.MapPath("~/ComputerDetail.xml"));
            }
            else
            {
                message = "Failed to create a computer, may be the name<span style =\"color:green\">" + computername + "</span> already exists";
                LogHelper.WriteLog(typeof(ComputerManagementController), Operator, "Create%Computer%named%" + computername, false);
            }
            return(Json(new JsonData(message)));
        }
Ejemplo n.º 13
0
        // Add computer components to the cart.

        public IActionResult OnPostComputerToCart()
        {
            var         computerData = session.GetString("computer");
            ComputerDTO computer     = JsonConvert.DeserializeObject <ComputerDTO>(computerData);

            Product cpu         = context.Product.FirstOrDefault(m => m.ID == computer.CpuId);
            Product vga         = context.Product.FirstOrDefault(m => m.ID == computer.VgaId);
            Product memory      = context.Product.FirstOrDefault(m => m.ID == computer.MemoryId);
            Product monitor     = context.Product.FirstOrDefault(m => m.ID == computer.MonitorId);
            Product motherboard = context.Product.FirstOrDefault(m => m.ID == computer.MotherboardId);

            ProductOrderDTO cpuDto         = new ProductOrderDTO(cpu, 1);
            ProductOrderDTO vgaDto         = new ProductOrderDTO(vga, 1);
            ProductOrderDTO memoryDto      = new ProductOrderDTO(memory, 1);
            ProductOrderDTO monitorDto     = new ProductOrderDTO(monitor, 1);
            ProductOrderDTO motherboardDto = new ProductOrderDTO(motherboard, 1);

            ShoppingCartDTO cartDto  = null;
            var             cartData = session.GetString("cart");

            if (cartData != null)
            {
                cartDto = JsonConvert.DeserializeObject <ShoppingCartDTO>(cartData);
            }
            else
            {
                cartDto = new ShoppingCartDTO();
            }

            cartDto.Add(cpuDto);
            cartDto.Add(vgaDto);
            cartDto.Add(memoryDto);
            cartDto.Add(monitorDto);
            cartDto.Add(motherboardDto);

            // Save cart.
            var newCart = JsonConvert.SerializeObject(cartDto);

            session.SetString("cart", newCart);

            // Delete computer.
            session.Remove("computer");

            return(RedirectToAction("OnGetAsync"));
        }
Ejemplo n.º 14
0
 public void AddComponentToSession(int id, Component component)
 {
     if (session.Get("computer") == null)
     {
         ComputerDTO computer = new ComputerDTO();
         computer = SetComponent(computer, component, id);
         var data = JsonConvert.SerializeObject(computer);
         session.SetString("computer", data);
     }
     else
     {
         var         data     = session.GetString("computer");
         ComputerDTO computer = JsonConvert.DeserializeObject <ComputerDTO>(data);
         computer = SetComponent(computer, component, id);
         var newData = JsonConvert.SerializeObject(computer);
         session.SetString("computer", newData);
     }
 }
        public async Task <IHttpActionResult> Post(ComputerDTO computerDTO)
        {
            if (ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            try
            {
                var computer = mapper.Map <Computer>(computerDTO);
                computer = await computerService.Insert(computer);

                return(Ok(computer));
            } catch (Exception e)
            {
                return(InternalServerError(e));
            }
        }
Ejemplo n.º 16
0
        public OperationDetails CreateComputer(ProductDTO product, ComputerDTO item, string oldComputer)
        {
            Product productInDB = Database.Products.Find(p => p.Name == oldComputer).FirstOrDefault();

            if (productInDB != null)
            {
                return(UpdateComputer(product, item, oldComputer));
            }

            if (item == null || product == null)
            {
                return(new OperationDetails(false, "ОбЪект ссылается на null", this.ToString()));
            }
            Computer computer = _mappers.ToComputer.Map <ComputerDTO, Computer>(item);

            computer.Name = product.Name;
            if (item.MotherBoard != null)
            {
                ComputerComponent motherBoard = Database.ComputerComponents.Find(c => c.Name == item.MotherBoard.Name).FirstOrDefault();
                if (motherBoard == null)
                {
                    return(new OperationDetails(false, "Не удалось найти материнскую плату", this.ToString()));
                }
                computer.MotherBoard = motherBoard;
            }
            if (item.PowerSupply != null)
            {
                ComputerComponent powerSypply = Database.ComputerComponents.Find(c => c.Name == item.PowerSupply.Name).FirstOrDefault();
                if (powerSypply == null)
                {
                    return(new OperationDetails(false, "Не удалось найти блок питания", this.ToString()));
                }
                computer.PowerSupply = powerSypply;
            }
            if (item.Processor != null)
            {
                ComputerComponent processor = Database.ComputerComponents.Find(c => c.Name == item.Processor.Name).FirstOrDefault();
                if (processor == null)
                {
                    return(new OperationDetails(false, "Не удалось найти процессор", this.ToString()));
                }
                computer.Processor = processor;
            }
            if (item.SystemBlock != null)
            {
                ComputerComponent systemBlock = Database.ComputerComponents.Find(c => c.Name == item.SystemBlock.Name).FirstOrDefault();
                if (systemBlock == null)
                {
                    return(new OperationDetails(false, "Не удалось найти системный блок", this.ToString()));
                }
                computer.SystemBlock = systemBlock;
            }
            List <ComputerComponent> RAMs = new List <ComputerComponent>();

            foreach (var r in item.RAM)
            {
                ComputerComponent ram = Database.ComputerComponents.Find(c => c.Name == r.Name && c.Type == ComponentType.RAM).FirstOrDefault();
                if (ram == null)
                {
                    return(new OperationDetails(false, "Не удалось найти оперативную память", this.ToString()));
                }
                RAMs.Add(ram);
            }
            computer.RAM = RAMs;
            List <ComputerComponent> ROMs = new List <ComputerComponent>();

            foreach (var r in item.ROM)
            {
                ComputerComponent rom = Database.ComputerComponents.Find(c => c.Name == r.Name && c.Type == ComponentType.ROM).FirstOrDefault();
                if (rom == null)
                {
                    return(new OperationDetails(false, "Не удалось найти постоянную память", this.ToString()));
                }
                ROMs.Add(rom);
            }
            computer.ROM = ROMs;
            List <ComputerComponent> videoCards = new List <ComputerComponent>();

            foreach (var v in item.VideoCard)
            {
                ComputerComponent videoCard = Database.ComputerComponents.Find(c => c.Name == v.Name && c.Type == ComponentType.VideoCard).FirstOrDefault();
                if (videoCard == null)
                {
                    return(new OperationDetails(false, "Не удалось найти видеокарту", this.ToString()));
                }
                videoCards.Add(videoCard);
            }
            computer.VideoCard = videoCards;
            Database.Computers.Add(computer);
            Database.Save();

            Product localProduct = _mappers.ToProduct.Map <ProductDTO, Product>(product);

            if (localProduct == null)
            {
                return(new OperationDetails(false, "Не удалось преобразовать объект", this.ToString()));
            }
            localProduct       = CreateProduct(localProduct);
            localProduct.Table = Goods.Computer;
            Computer computerInDB = Database.Computers.Find(x => x.Name == localProduct.Name).FirstOrDefault();

            if (computerInDB == null)
            {
                return(new OperationDetails(false, "Не удалось найти объект", this.ToString()));
            }
            localProduct.FromTableId = computerInDB.Id;
            Database.Products.Add(localProduct);
            Database.Save();
            return(new OperationDetails(true, "Компьютер был успешно добавлен", this.ToString()));
        }
Ejemplo n.º 17
0
        public async Task <IActionResult> OnGetAsync()
        {
            await init();

            // Get ids from session
            if (session.Get("computer") != null)
            {
                var data = session.GetString("computer");
                if (data != null && data != "")
                {
                    ComputerDTO computer = JsonConvert.DeserializeObject <ComputerDTO>(data);

                    // If all parts are selected, then the user can order the computer.
                    IsAllSelected = computer.CpuId != null && computer.VgaId != null && computer.MemoryId != null &&
                                    computer.MonitorId != null && computer.MotherboardId != null;

                    // Set selected parts.

                    Product selectedCpu = context.Product.FirstOrDefault(m => m.ID == computer.CpuId);
                    SelectedCpuName = selectedCpu?.Name ?? "";

                    Product selectedVga = context.Product.FirstOrDefault(m => m.ID == computer.VgaId);
                    SelectedVgaName = selectedVga?.Name ?? "";

                    Product selectedMemory = context.Product.FirstOrDefault(m => m.ID == computer.MemoryId);
                    SelectedMemoryName = selectedMemory?.Name ?? "";

                    Product selectedMonitor = context.Product.FirstOrDefault(m => m.ID == computer.MonitorId);
                    SelectedMonitorName = selectedMonitor?.Name ?? "";

                    Product selectedMotherboard = context.Product.FirstOrDefault(m => m.ID == computer.MotherboardId);
                    SelectedMotherboardName = selectedMotherboard?.Name ?? "";

                    // CPU - Motherboard
                    if (computer.CpuId != null)
                    {
                        var query =
                            from compatible in context.Compatible
                            join product in context.Product on compatible.ProductId equals product.ID
                            where compatible.CompatibleProductId == computer.CpuId && product.CategoryID == CategoryId.MOTHERBOARD_ID
                            select product;

                        Motherboards = query.ToList();
                    }

                    // Motherboard - CPU, VGA, Memory
                    if (computer.MotherboardId != null)
                    {
                        // Sort lists.
                        var cpuQuery =
                            from compatible in context.Compatible
                            join product in context.Product on compatible.ProductId equals product.ID
                            where compatible.CompatibleProductId == computer.MotherboardId && product.CategoryID == CategoryId.CPU_ID
                            select product;

                        Cpus = cpuQuery.ToList();

                        var vgaQuery =
                            from compatible in context.Compatible
                            join product in context.Product on compatible.ProductId equals product.ID
                            where compatible.CompatibleProductId == computer.MotherboardId && product.CategoryID == CategoryId.VGA_ID
                            select product;

                        Vgas = vgaQuery.ToList();

                        var memoryQuery =
                            from compatible in context.Compatible
                            join product in context.Product on compatible.ProductId equals product.ID
                            where compatible.CompatibleProductId == computer.MotherboardId && product.CategoryID == CategoryId.MEMORY_ID
                            select product;

                        Memories = memoryQuery.ToList();
                    }

                    // VGA - Motherboard, Monitor
                    if (computer.VgaId != null)
                    {
                        var motherboardQuery =
                            from compatible in context.Compatible
                            join product in context.Product on compatible.ProductId equals product.ID
                            where compatible.CompatibleProductId == computer.VgaId && product.CategoryID == CategoryId.MOTHERBOARD_ID
                            select product;

                        Motherboards = motherboardQuery.ToList();

                        var monitorQuery =
                            from compatible in context.Compatible
                            join product in context.Product on compatible.ProductId equals product.ID
                            where compatible.CompatibleProductId == computer.VgaId && product.CategoryID == CategoryId.MONITOR_ID
                            select product;

                        Monitors = monitorQuery.ToList();
                    }

                    // Memory - Motherboard
                    if (computer.MemoryId != null)
                    {
                        var motherboardQuery =
                            from compatible in context.Compatible
                            join product in context.Product on compatible.ProductId equals product.ID
                            where compatible.CompatibleProductId == computer.MemoryId && product.CategoryID == CategoryId.MOTHERBOARD_ID
                            select product;

                        Motherboards = motherboardQuery.ToList();
                    }

                    // Monitor - VGA
                    if (computer.MonitorId != null)
                    {
                        var vgaQuery =
                            from compatible in context.Compatible
                            join product in context.Product on compatible.ProductId equals product.ID
                            where compatible.CompatibleProductId == computer.MonitorId && product.CategoryID == CategoryId.VGA_ID
                            select product;

                        Vgas = vgaQuery.ToList();
                    }
                }
            }



            return(Page());
        }
 public void ComputerUpdate(ComputerDTO comp)
 {
     computerService.Update(comp);
 }
 public int ComputerUpsert(ComputerDTO comp)
 {
     return(computerService.Upsert(comp));
 }
Ejemplo n.º 20
0
 public ActionResult CreateComputer(CreateComputerVM item)
 {
     if (ModelState.IsValid)
     {
         ProductDTO product = new ProductDTO()
         {
             Name = item.Name, Description = item.Description, Price = item.Price, Sale = item.Sale
         };
         ComputerDTO computer = new ComputerDTO();
         if (item.Images != null)
         {
             foreach (var i in item.Images)
             {
                 ImageDTO image = new ImageDTO();
                 image.Text = item.Alt;
                 using (var reader = new BinaryReader(i.InputStream))
                     image.Photo = reader.ReadBytes(i.ContentLength);
                 product.Images = new List <ImageDTO>();
                 product.Images.Add(image);
             }
         }
         else
         {
             product.Images = new List <ImageDTO>();
             foreach (var i in item.ImagesInDatebase)
             {
                 product.Images.Add(_mappers.ToImageDTO.Map <ImageDM, ImageDTO>(i));
             }
         }
         computer.MotherBoard = new ComputerComponentDTO()
         {
             Name = item.SelectedMotherBoard
         };
         computer.PowerSupply = new ComputerComponentDTO()
         {
             Name = item.SelectedPowerSupply
         };
         computer.Processor = new ComputerComponentDTO()
         {
             Name = item.SelectedProcessor
         };
         computer.SystemBlock = new ComputerComponentDTO()
         {
             Name = item.SelectedSystemBlock
         };
         computer.RAM = new List <ComputerComponentDTO>();
         foreach (var i in item.SelectedRAM)
         {
             computer.RAM.Add(new ComputerComponentDTO()
             {
                 Name = i
             });
         }
         computer.ROM = new List <ComputerComponentDTO>();
         foreach (var i in item.SelectedROM)
         {
             computer.ROM.Add(new ComputerComponentDTO()
             {
                 Name = i
             });
         }
         computer.VideoCard = new List <ComputerComponentDTO>();
         foreach (var i in item.SelectedVideoCard)
         {
             computer.VideoCard.Add(new ComputerComponentDTO()
             {
                 Name = i
             });
         }
         computer.Properties = _mappers.ToPropertyDTO.Map <ICollection <PropertyDM>, ICollection <PropertyDTO> >(item.Properties);
         OperationDetails result = _adminService.CreateComputer(product, computer, product.Name);
         ViewBag.Result = result.Message;
         ViewBag.Status = result.Succedeed;
         List <ComputerComponentDM> compMotherBoard = _mappers.ToComputerComponentDM.Map <ICollection <ComputerComponentDTO>, List <ComputerComponentDM> >(_adminService.GetComputerComponentsByType(ComponentType.MotherBoard));
         var compMotherBoardItems = compMotherBoard.Select(x => new SelectListItem()
         {
             Text = x.Name, Value = x.Name
         }).ToList();
         List <ComputerComponentDM> compPowerSupply = _mappers.ToComputerComponentDM.Map <ICollection <ComputerComponentDTO>, List <ComputerComponentDM> >(_adminService.GetComputerComponentsByType(ComponentType.PowerSupply));
         var compPowerSupplyItems = compPowerSupply.Select(x => new SelectListItem()
         {
             Text = x.Name, Value = x.Name
         }).ToList();
         List <ComputerComponentDM> compProcessor = _mappers.ToComputerComponentDM.Map <ICollection <ComputerComponentDTO>, List <ComputerComponentDM> >(_adminService.GetComputerComponentsByType(ComponentType.Processor));
         var compProcessorItems = compProcessor.Select(x => new SelectListItem()
         {
             Text = x.Name, Value = x.Name
         }).ToList();
         List <ComputerComponentDM> compRAM = _mappers.ToComputerComponentDM.Map <ICollection <ComputerComponentDTO>, List <ComputerComponentDM> >(_adminService.GetComputerComponentsByType(ComponentType.RAM));
         var compRAMItems = compRAM.Select(x => new SelectListItem()
         {
             Text = x.Name, Value = x.Name
         }).ToList();
         List <ComputerComponentDM> compROM = _mappers.ToComputerComponentDM.Map <ICollection <ComputerComponentDTO>, List <ComputerComponentDM> >(_adminService.GetComputerComponentsByType(ComponentType.ROM));
         var compROMItems = compROM.Select(x => new SelectListItem()
         {
             Text = x.Name, Value = x.Name
         }).ToList();
         List <ComputerComponentDM> compSystemBlock = _mappers.ToComputerComponentDM.Map <ICollection <ComputerComponentDTO>, List <ComputerComponentDM> >(_adminService.GetComputerComponentsByType(ComponentType.SystemBlock));
         var compSystemBlockItems = compSystemBlock.Select(x => new SelectListItem()
         {
             Text = x.Name, Value = x.Name
         }).ToList();
         List <ComputerComponentDM> compVideoCard = _mappers.ToComputerComponentDM.Map <ICollection <ComputerComponentDTO>, List <ComputerComponentDM> >(_adminService.GetComputerComponentsByType(ComponentType.VideoCard));
         var compVideoCardItems = compVideoCard.Select(x => new SelectListItem()
         {
             Text = x.Name, Value = x.Name
         }).ToList();
         item.MotherBoards  = compMotherBoardItems;
         item.PowerSupplies = compPowerSupplyItems;
         item.Processors    = compProcessorItems;
         item.RAMs          = compRAMItems;
         item.ROMs          = compROMItems;
         item.SystemBlocks  = compSystemBlockItems;
         item.VideoCards    = compVideoCardItems;
         return(View(item));
     }
     return(View());
 }
Ejemplo n.º 21
0
        public OperationDetails UpdateComputer(ProductDTO product, ComputerDTO item, string oldComputerName)
        {
            if (product == null || item == null)
            {
                return(new OperationDetails(false, "ОбЪект ссылается на null", this.ToString()));
            }
            Product localProduct = UpdateProduct(product);

            Database.Products.Update(localProduct);

            Computer oldComputer = Database.Computers.Find(x => x.Name == oldComputerName).FirstOrDefault();

            if (oldComputer == null)
            {
                return(new OperationDetails(false, "Не удалось найти объект", this.ToString()));
            }
            if (item.MotherBoard != null && item.MotherBoard.Type == ComponentType.MotherBoard)
            {
                ComputerComponent motherBoard = Database.ComputerComponents.Find(c => c.Name == item.MotherBoard.Name).FirstOrDefault();
                if (motherBoard == null)
                {
                    return(new OperationDetails(false, "Не удалось найти материнскую плату", this.ToString()));
                }
                oldComputer.MotherBoard = motherBoard;
            }
            if (item.PowerSupply != null && item.MotherBoard.Type == ComponentType.PowerSupply)
            {
                ComputerComponent powerSypply = Database.ComputerComponents.Find(c => c.Name == item.PowerSupply.Name).FirstOrDefault();
                if (powerSypply == null)
                {
                    return(new OperationDetails(false, "Не удалось найти блок питания", this.ToString()));
                }
                oldComputer.PowerSupply = powerSypply;
            }
            if (item.Processor != null && item.MotherBoard.Type == ComponentType.Processor)
            {
                ComputerComponent processor = Database.ComputerComponents.Find(c => c.Name == item.Processor.Name).FirstOrDefault();
                if (processor == null)
                {
                    return(new OperationDetails(false, "Не удалось найти процессор", this.ToString()));
                }
                oldComputer.Processor = processor;
            }
            if (item.SystemBlock != null && item.MotherBoard.Type == ComponentType.SystemBlock)
            {
                ComputerComponent systemBlock = Database.ComputerComponents.Find(c => c.Name == item.SystemBlock.Name).FirstOrDefault();
                if (systemBlock == null)
                {
                    return(new OperationDetails(false, "Не удалось найти системный блок", this.ToString()));
                }
                oldComputer.SystemBlock = systemBlock;
            }
            List <ComputerComponent> RAMs = new List <ComputerComponent>();

            foreach (var r in item.RAM)
            {
                ComputerComponent ram = Database.ComputerComponents.Find(c => c.Name == r.Name && c.Type == ComponentType.RAM).FirstOrDefault();
                if (ram == null)
                {
                    return(new OperationDetails(false, "Не удалось найти оперативную память", this.ToString()));
                }
                RAMs.Add(ram);
            }
            oldComputer.RAM = RAMs;
            List <ComputerComponent> ROMs = new List <ComputerComponent>();

            foreach (var r in item.ROM)
            {
                ComputerComponent rom = Database.ComputerComponents.Find(c => c.Name == r.Name && c.Type == ComponentType.ROM).FirstOrDefault();
                if (rom == null)
                {
                    return(new OperationDetails(false, "Не удалось найти постоянную память", this.ToString()));
                }
                ROMs.Add(rom);
            }
            oldComputer.ROM = ROMs;
            List <ComputerComponent> videoCards = new List <ComputerComponent>();

            foreach (var v in item.VideoCard)
            {
                ComputerComponent videoCard = Database.ComputerComponents.Find(c => c.Name == v.Name && c.Type == ComponentType.VideoCard).FirstOrDefault();
                if (videoCard == null)
                {
                    return(new OperationDetails(false, "Не удалось найти видеокарту", this.ToString()));
                }
                videoCards.Add(videoCard);
            }
            oldComputer.VideoCard = videoCards;

            oldComputer.Properties = _mappers.ToProperty.Map <IEnumerable <PropertyDTO>, ICollection <Property> >(item.Properties);
            Database.Computers.Update(oldComputer);
            Database.Save();
            return(new OperationDetails(true, "Компьютер успешно изменён", this.ToString()));
        }