public void Get_test()
        {
            // arrange
            var maker = "Intel";
            var processorSpeed = 500;
            var ramSize = 2000;
            processors[0] = new Dictionary<string, object>
            {
                { "Maker", maker},
                { "Speed", processorSpeed},
                { "RamId", 0 }
            };
            rams[0] = new Dictionary<string, object>
            {
                { "Size", ramSize }
            };
            var aggregatorProvider = aggregatorProviderMock.Object;
            var processorModel = new ProcessorModel(0, processorCollectionMock.Object);
            var ramModel = new RAMModel(0, ramCollectionMock.Object);
            var computer = new Computer(aggregatorProvider, processorModel);
            var ram = new RAM(aggregatorProvider, ramModel);
            aggregatorProvider.Save(computer, ram);

            // act and assert
            computer.RAM.Size.Should().Be(ramSize);
            computer.ProcessorSpeed.Should().Be(processorSpeed);
            computer.Maker.Should().Be(maker);
        }
Example #2
0
 ///<summary>Inserts one Computer into the database.  Returns the new priKey.</summary>
 internal static long Insert(Computer computer)
 {
     if(DataConnection.DBtype==DatabaseType.Oracle) {
         computer.ComputerNum=DbHelper.GetNextOracleKey("computer","ComputerNum");
         int loopcount=0;
         while(loopcount<100){
             try {
                 return Insert(computer,true);
             }
             catch(Oracle.DataAccess.Client.OracleException ex){
                 if(ex.Number==1 && ex.Message.ToLower().Contains("unique constraint") && ex.Message.ToLower().Contains("violated")){
                     computer.ComputerNum++;
                     loopcount++;
                 }
                 else{
                     throw ex;
                 }
             }
         }
         throw new ApplicationException("Insert failed.  Could not generate primary key.");
     }
     else {
         return Insert(computer,false);
     }
 }
Example #3
0
    public ComputeEngine(FractalSettings settings)
    {
        int height = settings.Height;		// note that we need to use these locals to avoid creating tens of thousands of BigFloat objects in the loop
        int width = settings.Width;
        m_samples = new float[width, height];
        for (int v = 0; v < height; ++v)
            for (int h = 0; h < width; ++h)
                m_samples[h, v] = float.NaN;

        //		Console.WriteLine("dx: {0:F}", settings.Extent.Width/width);

        const int NumThreads = 4;
        m_computers = new Computer[NumThreads];

        int startRow = 0;
        int numRows = height/NumThreads;
        for (int i = 0; i < NumThreads; ++i)
        {
            if (i + 1 == NumThreads)
                numRows = height - startRow;

            m_computers[i] = new Computer(settings, startRow, numRows, m_samples);
            startRow += numRows;
        }
    }
Example #4
0
        static void Main()
        {
            Components mcardVLC = new MotherBoard("VLC", (decimal)185.98);
            Components vcardRadeon = new GraphicsCard("Radeon", (decimal)102.34, "the best grafic card forever");
            Components vcardGeForce = new GraphicsCard("GeForce", (decimal)154.45, "is not worth");

            Components procIntel = new Processor("Intel", (decimal)346.563, "can be better");
            Components procAMD = new Processor("AMD", (decimal)405.239, "always the best");
            Components procMac = new Processor("IOS", 2000m, "It is okaaaay");

            Computer mac = new Computer("Mac", new List<Components>() { mcardVLC, vcardRadeon, vcardGeForce });
            Computer windows = new Computer("Windows");
            windows.Components.Add(procIntel);
            windows.Components.Add(procAMD);
            windows.Components.Add(procMac);
            //Console.WriteLine(windows);

            Computer linux = new Computer("Linux", new List<Components>() { mcardVLC, vcardGeForce, vcardRadeon, procAMD, procIntel, procMac });

            List<Computer> computers = new List<Computer>() { mac, windows, linux };

            computers.OrderBy(p => p.TotalPrice).ToList().ForEach(p => Console.WriteLine(p.ToString()));


            //or

            //computers.OrderBy(a => a.TotalPrice);

            //foreach (var computer in computers)
            //{
            //    Console.WriteLine(computer);
            //}
        }
 public override void AddInteractions(InteractionObjectPair iop, Sim actor, Computer target, List<InteractionObjectPair> results)
 {
     foreach (AfterschoolActivityData data in AfterschoolActivityBooter.Activities.Values)
     {
         results.Add(new InteractionObjectPair(new Definition(data.mActivity.CurrentActivityType), iop.Target));
     }
 }
Example #6
0
    public JSONGPUData(Computer computer, bool names)
    {
        // Create lists
        Temp = new List<JSONNameValue>();
        Fans = new List<JSONNameValue>();
        Load = new List<JSONNameValue>();
        Clock = new List<JSONNameValue>();

        IEnumerable<IHardware> gpus = computer.Hardware.Where(h => h.HardwareType == HardwareType.GpuNvidia || h.HardwareType == HardwareType.GpuAti);

        foreach (IHardware h in gpus) {
            foreach (ISensor s in h.Sensors) {
                String name;
                if (names) name = s.Name;
                else name = "";

                switch (s.SensorType) {
                    case SensorType.Temperature: Temp.Add(new JSONNameValueFloat(name, (float)s.Value)); break;
                    case SensorType.Fan: Fans.Add(new JSONNameValueInt(name, (int)s.Value)); break;
                    case SensorType.Load: Load.Add(new JSONNameValueInt(name, (int)s.Value)); break;
                    case SensorType.Clock: Clock.Add(new JSONNameValueInt(name, (int)s.Value)); break;
                }
            }
        }
    }
Example #7
0
    static void Main()
    {
        var computerOne = new Computer("Pentagon 4", new List<Component>()
        {
            new Component("processor", 4532.4321),
            new Component("graphics card", 459, "Intel HD Graphics 4400" ),
            new Component("screen", 200, "13.3 (33.78 cm) – 3200 x 1800 (QHD+), IPS sensor display")
        });
        var computerTwo = new Computer("Pentagon 2 test", new List<Component>());
        try
        {
            var computerThree = new Computer("Pentagon 3 experiments", new List<Component>()
            {

            //    new Component("", 341.432),
              //  new Component("Processor", - 2142.435, "perfect condition" ),
                new Component(null, 2512, "good condition"),
                new Component("graphics", 241, "")
            });

            Console.WriteLine(computerThree);
        }
         catch(ArgumentException e)
        {
            Console.WriteLine(e.Message);
        }
        Console.WriteLine(computerOne);
        Console.WriteLine(computerTwo);
    }
Example #8
0
        static void Main(string[] args)
        {
            Components ram1 = new Components("2GB RAM", 20);
            Components ram2 = new Components("6GB RAM", 60);

            Components hdd1 = new Components("1TB HHD", 350);
            Components hdd2 = new Components("250GB HDD", 131);
            Components hdd3 = new Components("2TB SSD", 640);

            Components gpu1 = new Components("No Info", 0);
            Components gpu2 = new Components("ATI Radeon HD 5500", 65);
            Components gpu3 = new Components("NVidia GTX Titan", 650);

            Components cpu1 = new Components("Intel Core i3 2.4 GHz", 65);
            Components cpu2 = new Components("Intel Core i7 4.0 GHz", 315);
            Components cpu3 = new Components("Intel Core i5 3.2 GHz", 135);

            Components motherboard = new Components("Motherboard :AMD",200);
            Components motherboard2 = new Components("Motherboard Intel", 500);

            Computer PC1 = new Computer("PC1", new List<Components>() { ram2, hdd1, gpu1, cpu1,motherboard2 });
            Computer PC2 = new Computer("PC2", new List<Components>() { ram1, hdd2, gpu2, cpu2,motherboard });
            Computer PC3 = new Computer("PC4", new List<Components>() { ram1, hdd3, gpu3, cpu3,motherboard });
            Computer PC4 = new Computer("UnknownTrash");

            List<Computer> myList = new List<Computer>() { PC1, PC2, PC3, PC4 };
            myList = myList.OrderBy(pr => pr.Price).ToList();
            foreach (var pc in myList)
            {
                Console.WriteLine(pc.ToString());
            }
        }
    public decimal ComputerPrice(Computer computer)
    {
        var components = computer.Components;
        decimal totalSum = components.Sum(component => component.Price);

        return totalSum;
    }
Example #10
0
    static void Main(string[] args)
    {
        Component motherBoard1 = new Component("AsusP8H67/H67/1155", "Game Station", (decimal)155.00);
        Component graphicCard1 = new Component("ATI Radeon HD7850", (decimal)229.00);
        Component ram1 = new Component("2x4GB DDR3 1600Mhz", (decimal)129.00);
        Computer pc1 = new Computer("Asus Game Machine", new List<Component> { motherBoard1, graphicCard1, ram1 });
        Console.WriteLine(pc1);
        Console.WriteLine();
        Console.WriteLine("----------------------------------------------------------------");
        Component motherBoard2 = new Component("ASUS P8H61-M LX2/SI/LGA1155", "Home Station", (decimal)98.00);
        Component graphicCard2 = new Component("ATI Radeon HD 7750", (decimal)138.00);
        Component ram2 = new Component("4 GB DDR3 1333 MHz", (decimal)65.00);
        Computer pc2 = new Computer("Home Machine", new List<Component> { motherBoard2, graphicCard2, ram2 });
        Console.WriteLine(pc2);
        Console.WriteLine();
        Console.WriteLine("----------------------------------------------------------------");
        Component motherBoard3 = new Component("ASROCK Z87 PRO4 BULK", "Game Station", (decimal)217.00);
        Component graphicCard3 = new Component("SAPPHIRE R9 270 2G GDDR5 OC", (decimal)358.00);
        Component ram3 = new Component("2x4GB DDR3 1600 MHz", (decimal)148.00);
        Computer pc3 = new Computer("Game Machine New", new List<Component> { motherBoard3, graphicCard3, ram3 });
        Console.WriteLine(pc3);
        Console.WriteLine();
        Console.WriteLine("----------------------------------------------------------------");
        Console.WriteLine("----------------------------------------------------------------");
        List<Computer> computers = new List<Computer>() { pc1, pc2, pc3 };
        computers.OrderByDescending(computer => computer.Price).ToList().ForEach(computer => Console.WriteLine(computer.ToString()));

    }
Example #11
0
File: Main.cs Project: sopindm/bjeb
        private static void handleConnection(Connection connection)
        {
            Computer computer = new Computer();

            Timer timer = new Timer();

            try
            {
                while(true)
                {
                    Protocol.handle(connection, computer);

                    timer.update();

                    Console.WriteLine(timer.rate.ToString("F2") + " responses in seconds.");
                }
            }
            catch(ConnectionException)
            {
            }
            catch(System.IO.IOException)
            {
            }
            finally
            {
                connection.close();
            }
        }
Example #12
0
 static void ReadXMLToData(XmlDocument doc)
 {
     Computer computer = new Computer();
     XmlAttributeCollection attributes = doc.FirstChild.FirstChild.Attributes;
     computer.Case = new Case(attributes);
     Console.WriteLine(computer.Case.Brand + ", " + computer.Case.Size + ", " + computer.Case.Color);
 }
Example #13
0
    public JSONCPUData(Computer computer, bool names)
    {
        // Find CPU
        IHardware cpu = computer.Hardware.First(h => h.HardwareType == HardwareType.CPU);

        // Create lists
        Load = new List<JSONNameValueInt>();
        Temp = new List<JSONNameValueInt>();
        Clock = new List<JSONNameValueInt>();
        Power = new List<JSONNameValueFloat>();

        // Add data to lists
        if (cpu != null) {
            foreach (ISensor sensor in cpu.Sensors) {
                String name;
                if (names) name = sensor.Name;
                else name = "";

                switch (sensor.SensorType) {
                    case SensorType.Load: Load.Add(new JSONNameValueInt(name, (int)sensor.Value)); break;
                    case SensorType.Temperature: Temp.Add(new JSONNameValueInt(name, (int)sensor.Value)); break;
                    case SensorType.Clock: Clock.Add(new JSONNameValueInt(name, (int)sensor.Value)); break;
                    case SensorType.Power: Power.Add(new JSONNameValueFloat(name, (float)sensor.Value, 2)); break;
                }
            }
        }
    }
        public void MemberwiseCloneTest()
        {
            var gpu = new GraphicsCard
            {
                AmountOfRam = 4,
                GpuFrequency = 1.1m
            };

            var computer = new Computer
            {
                AmountOfCores = 4,
                AmountOfRam = 32,
                CpuFrequency = 3.4m,
                DriveType = "ssd",
                Gpu = gpu
            };

            var computer2 = (Computer)computer.Clone();

            Assert.AreNotSame(computer2, computer);
            Assert.AreNotSame(computer2.AmountOfCores, computer.AmountOfCores);
            Assert.AreNotSame(computer2.AmountOfRam, computer.AmountOfRam);
            Assert.AreNotSame(computer2.CpuFrequency, computer.CpuFrequency);
            Assert.AreSame(computer2.DriveType, computer.DriveType);

            Assert.AreEqual(computer2.Gpu.AmountOfRam, computer.Gpu.AmountOfRam);
            Assert.AreEqual(computer2.Gpu.GpuFrequency, computer.Gpu.GpuFrequency);

            computer.Gpu.AmountOfRam = 8;

            Assert.AreNotEqual(computer2.Gpu.AmountOfRam, computer.Gpu.AmountOfRam);
        }
Example #15
0
    static void Main()
    {
        var HDD = new Component("SSD Intel 530 Ser.", 149.04, "120GB SATA");
        var graphicsCard = new Component("Palit GTX750Ti KalmX", 321.00, "2GB");
        var motherboard = new Component("ASROCK 970 PERFORMANCE", 201.59);
        var processor = new Component("Intel i5-4460", 386.21, "3.2GHz 6MBs.1150");

        var myComponents = new List<Component>();
        myComponents.Add(processor);
        myComponents.Add(HDD);
        myComponents.Add(motherboard);
        myComponents.Add(graphicsCard);

        var hardDiscDrive = new Component("SSD KINGSTON", 190.51, "240GB V300 SATA3");
        var videoCard = new Component("Palit Nvidia", 197.10, " GT740 2GB DDR5");
        var CPU = new Component("AMD A8", 205.44, "X4 7650K BOX s.FM2+");
        var monitor = new Component("23\'\' Samsung", 321.00, " C23A750X Wireles");

        var yourComponents = new List<Component>() { hardDiscDrive, videoCard, CPU, monitor};

        var computer = new Computer("MyComputer", myComponents);
        var secondComputer = new Computer("YourComputer",yourComponents);

        var computers = new List<Computer>() { computer, secondComputer };

        computers.OrderBy(c => c.Price).ToList().ForEach(c => Console.WriteLine(c.ToString()));
    }
Example #16
0
    public JSONSystemData(Computer computer, bool names)
    {
        // Create lists
        Voltages = new List<JSONNameValue>();
        Temp = new List<JSONNameValue>();
        Fans = new List<JSONNameValue>();

        // Find the superIO chip.
        IHardware motherboard = computer.Hardware.FirstOrDefault(h => h.HardwareType == HardwareType.Mainboard && h.SubHardware.Length > 0);
        IHardware superIO;

        if (motherboard != null) {
            superIO = motherboard.SubHardware[0];

            foreach (ISensor s in superIO.Sensors) {
                String name;
                if (names) name = s.Name;
                else name = "";

                switch (s.SensorType) {
                    case SensorType.Voltage: Voltages.Add(new JSONNameValueFloat(name, (float)s.Value, 3)); break;
                    case SensorType.Fan: Fans.Add(new JSONNameValueInt(name, (int)s.Value)); break;
                    case SensorType.Temperature: Temp.Add(new JSONNameValueFloat(name, (float)s.Value, 1)); break;
                }
            }
        }
    }
    static void Main(string[] args)
    {
        Component intelGraphicsCard = new Component("Intel HD Graphics 4400", "Mnogo moshtna", 499.0m);
        Component asrockMotherboard = new Component("Asrock 123412", 199.0m);
        Component intelProcessor = new Component("Intel i5 43-123512", 600.0m);

        Computer MyComp = new Computer("Lenovo", new List<Component> { intelGraphicsCard, asrockMotherboard, intelProcessor });


        Component nvidiaGraphicsCar = new Component("NVIDIA GeForce GTX 880M", " (4GB GDDR5)", (decimal)1000);
        Component inteli7Processor = new Component("Intel Core i7-4700HQ", "(4-ядрен, 2.40 - 3.40 GHz, 6MB кеш)", (decimal)300);
        Component asusMotherboard = new Component("Asus Motherboard", (decimal)200);

        Computer otherComp = new Computer("Asus", new List<Component> { nvidiaGraphicsCar, inteli7Processor, asusMotherboard });

        Component nGraphic = new Component("NVIDIA GeForce GTX 100000", " (64GB GDDR8)", (decimal)80000);
        Component i8Processor = new Component("Intel i8 NNNN", (decimal)1000);
        Component AMotherboard = new Component("Motherboard", (decimal)900);

        Computer mostExpensive = new Computer("HP", new List<Component> { nGraphic, i8Processor, AMotherboard});

        List<Computer> computers = new List<Computer>() { mostExpensive, otherComp, MyComp,};

        computers.OrderByDescending(computer => computer.Price).ToList().ForEach(computer => Console.WriteLine(computer.ToString()));
    }
    static void Main()
    {
        // Play a sound with the Audio class:
        Audio myAudio = new Audio();
        Console.WriteLine("Playing sound...");
        myAudio.Play(@"c:\WINDOWS\Media\chimes.wav");

        // Display time information with the Clock class:
        Clock myClock = new Clock();
        Console.Write("Current day of the week: ");
        Console.WriteLine(myClock.LocalTime.DayOfWeek);
        Console.Write("Current date and time: ");
        Console.WriteLine(myClock.LocalTime);

        // Display machine information with the Computer class:
        Computer myComputer = new Computer();
        Console.WriteLine("Computer name: " + myComputer.Name);

        if (myComputer.Network.IsAvailable)
        {
            Console.WriteLine("Computer is connected to network.");
        }
        else
        {
            Console.WriteLine("Computer is not connected to network.");
        }
    }
    private decimal Calculate(Computer computer)
    {
        var components = computer.Components;
        decimal price = components.Sum(component => component.Price);

        return price;
    }
Example #20
0
    private static void Main()
    {
        List<Computer> computers = new List<Computer>();

        Computer PC1 = new Computer(
                name: "ASUS",
                motherboard: new Component("Asus AK-47", 334m, "mini form factor"),
                processor: new Component("i7 2345", 234m, "64 cores"),
                ram: new Component("32GB", 200m, "DDR5"));

        Computer PC2 = new Computer(
            name: "GigaBUUUG",
            motherboard: new Component("Gigabyte AZ32", 144m, "mini form factor"),
            processor: new Component("i5 2345", 134m, "32 cores"),
            ram: new Component("16GB", 100m, "DDR5"));

        Computer PC3 = new Computer(
            name: "Handmade",
            motherboard: new Component("Marmalad duno", 112m),
            processor: new Component("i3 2200", 104m),
            ram: new Component("8GB", 80m));

        computers.Add(PC1);
        computers.Add(PC2);
        computers.Add(PC3);

        computers = computers.OrderBy(o => o.totalPrice).ToList();

        foreach (var computer in computers)
        {
            Console.WriteLine(computer);
            Console.WriteLine();
        }
    }
Example #21
0
    static void Main()
    {
        Component graphicsCard = new Component("nVidia", 350m);
        Component hdd = new Component("WesternDigital", 130m, "1TB 3.5 HDD (7200 оборота/минута)");
        Component ram = new Component("AsRock", 210m, "8GB (2x 4096MB) - DDR3, 1600Mhz");
        Component motherboard = new Component("AsRock", 520m);
        Component processor = new Component("Intel", 600m, "Core i5-4460 (4-ядрен, 3.20 - 3.40 GHz, 6MB кеш)");
        Component powerSupply = new Component("Superpowerrr", 250m, "5000W");
        Component biggerHdd = new Component("WesternDigital", 189m, "2TB 3.5 HDD");

        Computer lenovo = new Computer("Lenovo", graphicsCard, hdd, ram, motherboard, processor, powerSupply);
        Computer dell = new Computer("Dell", graphicsCard, biggerHdd, ram, motherboard, processor, powerSupply);
        Computer acer = new Computer("Acer", graphicsCard, ram, processor, motherboard);

        List<Computer> computers = new List<Computer>();
        computers.Add(lenovo);
        computers.Add(dell);
        computers.Add(acer);

        computers = computers.OrderBy(computer => computer.Price).ToList();

        foreach (var computer in computers)
        {
            computer.printInfo();
            Console.WriteLine();
        }

    }
    static void Main()
    {
        List<Computer> catalog = new List<Computer>();
        List<Component> components1 = new List<Component>();
        components1.Add(new Component("HDD", 500.00m));
        components1.Add(new Component("CPU", 250.12m));
        Computer hp = new Computer("HP", components1);

        List<Component> components2 = new List<Component>();
        components2.Add(new Component("CPU", 400.01m));
        components2.Add(new Component("RAM", 102.00m));
        components2.Add(new Component("Graphics card", 100));
        Computer sony = new Computer("Sony", components2);


        catalog.Add(hp);
        catalog.Add(sony);

        var sortCatalog = catalog.OrderBy(computer => computer.Price);

        foreach (var computer in sortCatalog)
        {
            Console.WriteLine(computer);
        }
    }
Example #23
0
        private static void Export(Computer data, string format, string outfile, string[] categories)
        {
            string outstr = "";
            switch (format)
            {
                case "txt":
                    outstr = ExportTxt(data, categories);
                    break;

                case "csv":
                    //outstr = data.ToCsv();
                    break;
            }
            if (outfile != null)
            {
                System.IO.StreamWriter file = new System.IO.StreamWriter(outfile);
                file.WriteLine(outstr.Replace("\n", "\r\n"));

                file.Close();
            }
            else
            {
                Console.WriteLine(outstr);
                // print to screen
            }
        }
Example #24
0
    static void Main()
    {
        var cpu = new Component("Generic CPU", "100 lv.");
        var videocard = new Component("Generic Video Card", "200 lv.", "overpriced");
        var motherboard = new Component("Generic Motherboard", "300 lv.");
        var hdd = new Component("Generic HDD", "5 lv.", "Opisanieeee");
        var videocard2 = new Component("NVIDIA", "999 lv.", "Oshte opisanieeeee");

        var computer = new Computer("Kumputar", "6 lv.", cpu, videocard, motherboard);
        var computer2 = new Computer("Po-qk kumputar", "3 lv.", cpu, videocard, motherboard, hdd);
        var computer3 = new Computer("Nai-qkq kumputar", "4 lv.", cpu, videocard2, motherboard, hdd);

        computer2.Display();
        Console.WriteLine();

        var computerList = new List<Computer>()
        {
            computer,
            computer2,
            computer3
        };

        var sortedComputerList = computerList.OrderBy(x => x.Price); //original price, not total price
        foreach (var pc in sortedComputerList)
        {
            pc.Display();
            Console.WriteLine("-----------------");
        }
    }
Example #25
0
 /// <summary>
 /// Called while the ProcessWaiter is locked: attempt to bind the computer to a process;
 /// this fails if it has already been bound to another process. The ProcessWaiter may
 /// be entered into multiple scheduling queues, and the first time it reaches the head
 /// of a queue it will be claimed successfully; it will be dropped after reaching the
 /// heads of other queues
 /// </summary>
 public Computer Claim()
 {
     System.Diagnostics.Debug.Assert(computer != null);
     Computer ret = computer;
     computer = null;
     return ret;
 }
Example #26
0
    static void Main(string[] args)
    {
        Component ram1 = new Component("8GB RAM", 116);
        Component ram2 = new Component("4GB RAM", 72);

        Component hdd1 = new Component("500GB HHD", 78);
        Component hdd2 = new Component("1TB HDD", 131);
        Component hdd3 = new Component("1TB SSD", 370);

        Component gpu1 = new Component("None", 0);
        Component gpu2 = new Component("ATI 5890", 255);
        Component gpu3 = new Component("NVidia GTX Titan", 598);

        Component cpu1 = new Component("Intel Core i3 2.4 GHz", 78);
        Component cpu2 = new Component("Intel Core i5 3.2 GHz", 131);
        Component cpu3 = new Component("Intel Core i7 4.0 GHz", 515);

        Computer PC1 = new Computer("PC1", new List<Component>() { ram1, hdd1, gpu1, cpu1 });
        Computer PC2 = new Computer("PC2", new List<Component>() { ram2, hdd2, gpu2, cpu2 });
        Computer PC3 = new Computer("PC4", new List<Component>() { ram1, hdd3, gpu3, cpu3 });
        Computer PC4 = new Computer("UnknownTrash");

        List<Computer> myList = new List<Computer>() { PC1, PC2, PC3, PC4 };
        myList = myList.OrderBy(pr => pr.Price).ToList();
        foreach (var pc in myList)
        {
            Console.WriteLine(pc.ToString());
        }
    }
    static void Main()
    {
        List<Computer> catalog = new List<Computer>();
        List<Component> components = new List<Component>();
        components.Add(new Component("HDD", 250.32m));
        components.Add(new Component("CPU", 560.45m));
        components.Add(new Component("RAM", 103.50m));
        Computer lenovo = new Computer("Lenovo", components);

        List<Component> components1 = new List<Component>();
        components1.Add(new Component("CPU", 231));
        components1.Add(new Component("Motheboard", 351));
        components1.Add(new Component("Graphics card", 351));
        Computer mac = new Computer("Mac", components1);

        List<Component> components2 = new List<Component>();
        components2.Add(new Component("CPU", 134));
        components2.Add(new Component("RAM", 123.65m, "4GB"));
        Computer sony = new Computer("Sony", components2);

        catalog.Add(lenovo);
        catalog.Add(mac);
        catalog.Add(sony);

        var sortCatalog = catalog.OrderBy(computer => computer.Price);

        foreach (var computer in sortCatalog)
        {
            Console.WriteLine(computer);
        }
    }
    public static void Main()
    {
        Console.Title = "Problem 3.	PC Catalog";

        Component monitor = new Component("monitor", 200);
        Component keyboard = new Component("keyboard", 43);
        Component mouse = new Component("mouse", 15);

        Component motherboard = new Component("motherboard", "G560 Intel Motherboard LA-5752P", 540);
        Component HDD = new Component("HDD", "256GB SSD", 188);
        Component proccesor = new Component("processor", " Intel Pentium G6950 (2.80 GHz, 3 MB)", 433);

        Computer firstPC = new Computer("Lenovo", motherboard, proccesor, HDD, monitor, mouse, keyboard);
        Computer secondPC = new Computer("HP", motherboard, proccesor, HDD, monitor);
        Computer thirdPC = new Computer("Acer", motherboard, proccesor, HDD);

        Computer[] pcArr = { firstPC, secondPC, thirdPC };
        pcArr = pcArr.OrderBy(pc => pc.Price()).ToArray();

        foreach (Computer pc in pcArr)
        {
            Console.WriteLine(pc.ToString());
        }

        Console.WriteLine("{0}\nMake your best choice!", new string('.', 25));
    }
Example #29
0
    static void Main()
    {
        Computer lenovoThinkIdeaBasic = new Computer(
                name: "Lenovo ThinkIdea-Basic",
                processor: new Component("Processor", 300, "Intel Core i5 4460 3.0 GHz"),
                graphicsCard: new Component("Graphics Card", 100, "Sapphire R9 280 3GB GD5 Boost"),
                motherboard: new Component("Mother Board", 257, "Gigabyte H97-HD3"),
                ram: new Component("RAM", 500, "8GB DDR3 1600MHZ"),
                hardDisc: new Component("Hard Disc", 230, "Scorpio 1TB 7200rpm"),
                lanCard: new Component("Lan Card", 50, "Turbo-X WLN-150"),
                screen: new Component("Screen", 220, "Panasonic XR300 22 inch"),
                mouse: new Component("Mouse", 15,"Microsoft Basic"),
                keyboard: new Component("Keyboard", 25, "Lenovo Basic RG-300")
                );
        Computer lenovoThinkIdea = new Computer(
                name: "Lenovo ThinkIdea",
                processor: new Component("Processor", 233, "Intel Core i3 360 1.8 GHz"),
                graphicsCard: new Component("Graphics Card", 150, "Radeon R9 280 2GB"),
                motherboard: new Component("Mother Board", 257, "Gigabyte H97-HD3"),
                ram: new Component("RAM", 500, "8GB DDR3 1600MHZ"),
                hardDisc: new Component("Hard Disc", 230, "Scorpio 1TB 7200rpm"),
                lanCard: new Component("Lan Card", 50, "Turbo-X WLN-150")
                );
        Computer lenovoThinkPad = new Computer(
                name: "Lenovo ThinkPad",
                processor: new Component("Processor", 340, "Intel Core i5 4460 3.2 GHz"),
                graphicsCard: new Component("Graphics Card", 220, "Sapphire R9 280 3GB GD5 Boost"),
                motherboard: new Component("Mother Board", 257, "Gigabyte H97-HD3"),
                ram: new Component("RAM", 500, "8GB DDR3 1600MHZ"),
                hardDisc: new Component("Hard Disc", 230, "Scorpio 1TB 7200rpm"),
                lanCard: new Component("Lan Card", 50, "Turbo-X WLN-150")
                );
        Computer acer = new Computer(
                name: "Acer Edge",
                processor: new Component("Processor", 440, "Intel Core i7 4460 3.2 GHz"),
                graphicsCard: new Component("Graphics Card", 520, "NVIDIA GeForce 280 4GB GD5 Boost"),
                motherboard: new Component("Mother Board", 257, "Gigabyte H97-HD3"),
                ram: new Component("RAM", 500, "8GB DDR3 1600MHZ"),
                hardDisc: new Component("Hard Disc", 230, "Scorpio 1TB 7200rpm"),
                lanCard: new Component("Lan Card", 50, "Turbo-X WLN-150"),
                screen: new Component("Screen", 250, "LG Clear View 25 inch"),
                mouse: new Component("Mouse", 22),
                keyboard: new Component("Keyboard", 35)
                );

        List<Computer> compList = new List<Computer>();

        compList.Add(lenovoThinkIdea);
        compList.Add(lenovoThinkIdeaBasic);
        compList.Add(acer);
        compList.Add(lenovoThinkPad);

        List<Computer> compsOrderedPriceAscend = compList.OrderBy(o => o.Price).ToList();

        foreach (var item in compsOrderedPriceAscend)
        {
            Console.WriteLine(item + Environment.NewLine);
        }
    }
 static void Main(string[] args)
 {
     Computer computerA = new Computer(new AbstractFactoryA(), "Company A","A-2015-I");
     Computer computerB = new Computer(new AbstractFactoryB(), "Company B","B-2015-II");
     computerA.ShowInfo();
     Console.WriteLine("================");
     computerB.ShowInfo();
 }
Example #31
0
 public InputPrgm(Computer computer, string prompt) : base(computer)
 {
     _prompt = prompt;
 }
Example #32
0
 public void SetComputer(Computer computerIn)
 {
     this.computer = computerIn;
 }
Example #33
0
 public void ComputerInitializesOff()
 {
     Computer test_computer = new Computer()
 }
        public async Task Test_Create_Modify_And_Delete_Computer()
        {
            using (var client = new APIClientProvider().Client)
            {
                DateTime purchasedate = DateTime.Now;

                DateTime decomissiondate = DateTime.Now;

                Computer macbookSuperPro = new Computer
                {
                    Make            = "MacBook Super Pro",
                    Manufacturer    = "Apple",
                    PurchaseDate    = purchasedate,
                    DecomissionDate = decomissiondate
                };

                var macbookSuperProAsJSON = JsonConvert.SerializeObject(macbookSuperPro);


                var response = await client.PostAsync(
                    "/computers",
                    new StringContent(macbookSuperProAsJSON, Encoding.UTF8, "application/json")
                    );

                response.EnsureSuccessStatusCode();

                string responseBody = await response.Content.ReadAsStringAsync();

                var newmacbookSuperPro = JsonConvert.DeserializeObject <Computer>(responseBody);

                string newMake = "test number two";

                /*
                 * PUT section
                 */
                Computer modifiedComputer = new Computer
                {
                    Make            = newMake,
                    Manufacturer    = "test",
                    PurchaseDate    = purchasedate,
                    DecomissionDate = decomissiondate
                };
                var modifiedComputerAsJSON = JsonConvert.SerializeObject(modifiedComputer);

                int modifiedNewComputerId = newmacbookSuperPro.Id;

                var Modifyresponse = await client.PutAsync(
                    $"/computers/{modifiedNewComputerId}",
                    new StringContent(modifiedComputerAsJSON, Encoding.UTF8, "application/json")
                    );

                Modifyresponse.EnsureSuccessStatusCode();
                string ModifyresponseBody = await Modifyresponse.Content.ReadAsStringAsync();

                Assert.Equal(HttpStatusCode.NoContent, Modifyresponse.StatusCode);

                /*
                 *  GET section
                 */
                var getComputer = await client.GetAsync($"/computers/{modifiedNewComputerId}");

                getComputer.EnsureSuccessStatusCode();

                string getComputerBody = await getComputer.Content.ReadAsStringAsync();

                Computer newComputer = JsonConvert.DeserializeObject <Computer>(getComputerBody);

                Assert.Equal(HttpStatusCode.OK, getComputer.StatusCode);
                Assert.Equal(newMake, newComputer.Make);


                //DELETE TEST
                var deleteResponse = await client.DeleteAsync($"/computers/{modifiedNewComputerId}");

                deleteResponse.EnsureSuccessStatusCode();
                Assert.Equal(HttpStatusCode.NoContent, deleteResponse.StatusCode);
            }
        }
Example #35
0
 public void TurnOff(Computer device)
 {
     device.Shutdown();
 }
Example #36
0
 public void AddComputer(Computer dto)
 {
     computers.Add(dto);
 }
Example #37
0
 public SensorCollector(Computer computer) => _computer = computer;
        private decimal GetFunction(string function, decimal x1)
        {
            Computer comp = new Computer();

            return(comp.Compute(function, x1));
        }
Example #39
0
        public static void AddComputer(Computer[] computers)
        {
            Console.Write("What is the id of the computer? ");
            String id = Console.ReadLine();

            Console.Write("Does the device have a cellular antenna? (y/n or NA) ");
            String data    = Console.ReadLine().ToUpper();
            bool?  antenna = null;

            if (data.ToUpper() == "NA")
            {
                antenna = null;
            }
            else if (data[0] == 'Y')
            {
                antenna = true;
            }
            else
            {
                antenna = false;
            }
            Console.Write("What is the hard drive storge of the device (in GB) or null if doesn't support a hard drive? ");
            data = Console.ReadLine();
            double?storage = null;
            double store;
            bool   test = double.TryParse(data, out store);

            if (test)
            {
                storage = store;
            }
            Console.Write("How much RAM does the device have (in Bytes)? ");
            Int64 ram = Convert.ToInt64(Console.ReadLine());

            Console.Write("Is the device equipped for extra software? (y/n) ");
            data = Console.ReadLine().ToUpper();
            int?[] software;
            if (data[0] == 'Y')
            {
                software = new int?[5];
                for (int i = 0; i < software.Length; i++)
                {
                    Console.Write($"Do you have software {i + 1} installed on your computer? (y/n) ");
                    data = Console.ReadLine().ToUpper();
                    if (data[0] == 'Y')
                    {
                        Console.Write($"How many licenses do you have for software {i + 1}? ");
                        software[i] = Convert.ToInt16(Console.ReadLine());
                    }
                    else
                    {
                        software[i] = null;
                    }
                }
            }
            else
            {
                software = null;
            }

            for (int i = 0; i < computers.Length; i++)
            {
                if (computers[i] == null)
                {
                    computers[i] = new Computer(id, ram, storage, antenna, software);
                    break;
                }
            }
        }
Example #40
0
        // POST api/idf
        public void Post([FromBody] Computer value)
        {
            IDF idf = new IDF(value);

            idf.Run();
        }
Example #41
0
        private void lvwFiles_AfterLabelEdit(object sender, LabelEditEventArgs e)
        {
            string newName = e.Label;

            //选中项
            ListViewItem selectedItem = lvwFiles.SelectedItems[0];

            //如果名称为空
            if (string.IsNullOrEmpty(newName))
            {
                MessageBox.Show("文件名不能为空!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

                //显示时,恢复原来的标签
                e.CancelEdit = true;
            }
            //标签没有改动
            else if (newName == null)
            {
                return;
            }
            //标签改动了,但是最终还是和原来一样
            else if (newName == selectedItem.Text)
            {
                return;
            }
            //文件名不合法
            else if (!IsValidFileName(newName))
            {
                MessageBox.Show("文件名不能包含下列任何字符:\r\n" + "\t\\/:*?\"<>|", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

                //显示时,恢复原来的标签
                e.CancelEdit = true;
            }
            else
            {
                Computer myComputer = new Computer();

                //如果是文件
                if (File.Exists(selectedItem.Tag.ToString()))
                {
                    //如果当前路径下有同名的文件
                    if (File.Exists(Path.Combine(curFilePath, newName)))
                    {
                        MessageBox.Show("当前路径下有同名的文件!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

                        //显示时,恢复原来的标签
                        e.CancelEdit = true;
                    }
                    else
                    {
                        myComputer.FileSystem.RenameFile(selectedItem.Tag.ToString(), newName);

                        FileInfo fileInfo   = new FileInfo(selectedItem.Tag.ToString());
                        string   parentPath = Path.GetDirectoryName(fileInfo.FullName);
                        string   newPath    = Path.Combine(parentPath, newName);

                        //更新选中项的Tag
                        selectedItem.Tag = newPath;

                        //刷新左边的目录树
                        LoadChildNodes(curSelectedNode);
                    }
                }
                //如果是文件夹
                else if (Directory.Exists(selectedItem.Tag.ToString()))
                {
                    //如果当前路径下有同名的文件夹
                    if (Directory.Exists(Path.Combine(curFilePath, newName)))
                    {
                        MessageBox.Show("当前路径下有同名的文件夹!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);

                        //显示时,恢复原来的标签
                        e.CancelEdit = true;
                    }
                    else
                    {
                        myComputer.FileSystem.RenameDirectory(selectedItem.Tag.ToString(), newName);

                        DirectoryInfo directoryInfo = new DirectoryInfo(selectedItem.Tag.ToString());
                        string        parentPath    = directoryInfo.Parent.FullName;
                        string        newPath       = Path.Combine(parentPath, newName);

                        //更新选中项的Tag
                        selectedItem.Tag = newPath;

                        //刷新左边的目录树
                        LoadChildNodes(curSelectedNode);
                    }
                }
            }
        }
 public override string GetInteractionName(Sim actor, Computer target, InteractionObjectPair iop)
 {
     return(base.GetInteractionName(actor, target, new InteractionObjectPair(sOldSingleton, target)));
 }
Example #43
0
 public override void Detach()
 {
     m_computer = null;
 }
Example #44
0
        public static void StatisticsRange(Computer[] computers, Computer prototype, Computer userPrototype, int start, int end)
        {
            Int64  ram             = 0;
            int    antenna         = 0;
            int    compWithAntenna = 0;
            double storage         = 0;
            int    compWithStorage = 0;
            int    software        = 0;

            int[] licenses         = new int[5];
            int   compWithSoftware = 0;

            int[] compWithLicense = new int[5];

            int      amount = end - start + 1;
            Computer comp;

            for (int i = start - 1; i < computers.Length && i < end; i++)
            {
                comp = computers[i] ?? userPrototype ?? prototype;
                ram += comp.RAM;
                if (comp.CellularAntenna.HasValue)
                {
                    antenna += (bool)comp.CellularAntenna ? 1 : 0;
                    compWithAntenna++;
                }
                if (comp.Storage.HasValue)
                {
                    storage += (double)comp.Storage;
                    compWithStorage++;
                }
                if (comp.Software != null)
                {
                    for (int j = 0; j < comp.Software.Length; j++)
                    {
                        if (comp.Software[j] != null)
                        {
                            software++;
                            licenses[j] += (int)comp.Software[j];
                            compWithLicense[j]++;
                        }
                    }
                    compWithSoftware++;
                }
            }

            Console.WriteLine($"The average RAM of all your devices is {ram / (double)amount} Bytes");
            Console.WriteLine($"{(antenna / (double)compWithAntenna) * 100}% of your devices have a cellular antenna");
            Console.WriteLine($"The average hard drive capacity of your devices is {storage / (double)compWithStorage} GB");
            if (!double.IsNaN(software / (double)compWithSoftware))
            {
                Console.WriteLine($"The average number of software per machine is {software/(double)compWithSoftware}");
            }
            else
            {
                Console.WriteLine($"None of these devices support additional software");
            }
            Console.WriteLine("The average number of licenses for each program is as follows: ");
            for (int x = 0; x < licenses.Length; x++)
            {
                if (!double.IsNaN((double)licenses[x] / compWithLicense[x]))
                {
                    Console.WriteLine($"\tSoftware {x + 1}: {(double)licenses[x] / compWithLicense[x]}");
                }
                else
                {
                    Console.WriteLine($"\tSoftwarwe {x + 1}: No licenses on any of the devices");
                }
            }
        }
Example #45
0
 public override void Attach(Computer computer)
 {
     m_computer = computer;
 }
Example #46
0
 public static void SummaryComputer(Computer computer, Computer prototype)
 {
     computer = computer ?? prototype;
     Console.WriteLine(computer);
 }
Example #47
0
        /// <summary>
        /// Wraps the NetSessionEnum API call with a timeout and parses the
        /// </summary>
        /// <param name="computer"></param>
        /// <returns></returns>
        private static async Task <List <Session> > GetNetSessions(Computer computer)
        {
            var resumeHandle    = IntPtr.Zero;
            var sessionInfoType = typeof(SESSION_INFO_10);

            var entriesRead = 0;
            var ptrInfo     = IntPtr.Zero;

            var sessionList = new List <Session>();

            try
            {
                var task = Task.Run(() => NetSessionEnum(computer.APIName, null, null, 10,
                                                         out ptrInfo, -1, out entriesRead, out _, ref resumeHandle));

                if (await Task.WhenAny(task, Task.Delay(10000)) != task)
                {
                    if (Options.Instance.DumpComputerStatus)
                    {
                        OutputTasks.AddComputerStatus(new ComputerStatus
                        {
                            ComputerName = computer.DisplayName,
                            Status       = "Timeout",
                            Task         = "NetSessionEnum"
                        });
                    }
                    return(sessionList);
                }

                var taskResult = task.Result;

                if (taskResult != 0)
                {
                    if (Options.Instance.DumpComputerStatus)
                    {
                        OutputTasks.AddComputerStatus(new ComputerStatus
                        {
                            ComputerName = computer.DisplayName,
                            Status       = ((NetApiStatus)taskResult).ToString(),
                            Task         = "NetSessionEnum"
                        });
                    }
                    return(sessionList);
                }


                var sessions = new SESSION_INFO_10[entriesRead];
                var iterator = ptrInfo;

                for (var i = 0; i < entriesRead; i++)
                {
                    sessions[i] = (SESSION_INFO_10)Marshal.PtrToStructure(iterator, sessionInfoType);
                    iterator    = (IntPtr)(iterator.ToInt64() + Marshal.SizeOf(sessionInfoType));
                }

                if (Options.Instance.DumpComputerStatus)
                {
                    OutputTasks.AddComputerStatus(new ComputerStatus
                    {
                        ComputerName = computer.DisplayName,
                        Status       = "Success",
                        Task         = "NetSessionEnum"
                    });
                }

                foreach (var session in sessions)
                {
                    var sessionUsername = session.sesi10_username;
                    var computerName    = session.sesi10_cname;

                    if (computerName == null)
                    {
                        continue;
                    }

                    string computerSid = null;

                    //Filter out computer accounts, Anonymous Logon, empty users
                    if (sessionUsername.EndsWith(
                            "$") || sessionUsername.Trim() == "" || sessionUsername == "$" || sessionUsername ==
                        Options.Instance.CurrentUserName || sessionUsername == "ANONYMOUS LOGON")
                    {
                        continue;
                    }

                    //Remove leading backslashes
                    if (computerName.StartsWith("\\"))
                    {
                        computerName = computerName.TrimStart('\\');
                    }

                    //If the session is pointing to localhost, we already know what the SID of the computer is
                    if (computerName.Equals("[::1]") || computerName.Equals("127.0.0.1"))
                    {
                        computerSid = computer.ObjectIdentifier;
                    }

                    //Try converting the computer name to a SID
                    computerSid = computerSid ?? await Helpers.TryResolveHostToSid(computerName, computer.Domain);

                    //Try converting the username to a SID
                    var searcher = Helpers.GetDirectorySearcher(computer.Domain);
                    var sids     = await searcher.LookupUserInGC(sessionUsername);

                    if (sids.Length > 0)
                    {
                        foreach (var sid in sids)
                        {
                            sessionList.Add(new Session
                            {
                                ComputerId = computerSid,
                                UserId     = sid
                            });
                        }
                    }
                    else
                    {
                        var(sidSuccess, userSid) =
                            await Helpers.AccountNameToSid(sessionUsername, computer.Domain, false);

                        if (sidSuccess)
                        {
                            sessionList.Add(new Session
                            {
                                ComputerId = computerSid,
                                UserId     = userSid
                            });
                        }
                        else
                        {
                            sessionList.Add(new Session
                            {
                                ComputerId = computerSid,
                                UserId     = sessionUsername
                            });
                        }
                    }
                }

                return(sessionList);
            }
            finally
            {
                if (ptrInfo != IntPtr.Zero)
                {
                    NetApiBufferFree(ptrInfo);
                }
            }
        }
Example #48
0
 public CIA6526(Computer mb, UInt16 baseAddress)
 {
     _mb          = mb;
     _baseAddress = baseAddress;
 }
Example #49
0
 static public void ComputerResetChanges(Computer computer)
 {
     computer.ResetAllChangeStatus();
 }
Example #50
0
 static public bool ComputerGetChangeStatus(Computer computer, string name)
 {
     return(computer.GetChangeStatusForProperty(name));
 }
Example #51
0
 static public object ComputerGetValue(Computer computer, string name)
 {
     return(computer.GetValueForProperty(name));
 }
        private string getSnapShot()
        {
            var myComputer     = new Computer();
            var hardware_count = 0;

            myComputer.GPUEnabled           = true;
            myComputer.CPUEnabled           = true;
            myComputer.MainboardEnabled     = true;
            myComputer.FanControllerEnabled = true;
            myComputer.RAMEnabled           = true;
            myComputer.HDDEnabled           = true;
            //myComputer.Hardware.ToString();
            //myComputer.ToCode();
            myComputer.Open();
            //p.outputStream.WriteLine("{0} <br>", getUniqueID("C"));
            string json = "{\"name\":\"" + Environment.MachineName + "\",\"id\":\"" + getUniqueID("C") + "\",\"date\":\"" + DateTime.Now + "\",\"hardware\":{\"";

            foreach (var hardwareItem in myComputer.Hardware)
            {
                hardwareItem.Update();
                //System.Windows.Forms.MessageBox.Show(hardwareItem.Identifier);
                //p.outputStream.WriteLine("{0} <br>", hardwareItem.GetReport());
                if (hardwareItem.HardwareType.Equals("HDD"))
                {
                    hardware_count++;
                    //hardwareItem.Identifier
                    json += hardwareItem.HardwareType + hardware_count + "\":{\"name\":\"" + hardwareItem.Name + "\",\"sensors\":{\"";
                }
                else
                {
                    json += hardwareItem.Identifier + "\":{\"name\":\"" + hardwareItem.Name + "\",\"sensors\":{\"";
                }
                //p.outputStream.WriteLine("{0} <br>", DataDict[0]);
                foreach (var sensor in hardwareItem.Sensors)
                {
                    //json+= "name\":\""+sensor.Name;
                    json += sensor.Name + "-" + sensor.SensorType + "\":\"" + sensor.Value + "\",\"";
                }
                if (hardwareItem.Sensors.Length > 0)
                {
                    json  = json.Remove(json.Length - 1);
                    json  = json.Remove(json.Length - 1);
                    json += "}";
                }
                else
                {
                    json  = json.Remove(json.Length - 1);
                    json += "}";
                }
                if (hardwareItem.SubHardware.Length > 0)
                {
                    //json = json.Remove(json.Length - 1);
                    json += ",\"subhardware\":{\"";
                    foreach (var subHardwareItem in hardwareItem.SubHardware)
                    {
                        subHardwareItem.Update();
                        json += subHardwareItem.HardwareType + "\":{\"name\":\"" + subHardwareItem.Name + "\",\"sensors\":{\"";
                        //p.outputStream.WriteLine("&nbsp;&nbsp;{0} <br>", subHardwareItem.Name);
                        foreach (var sensor in subHardwareItem.Sensors)
                        {
                            json += sensor.Name + "-" + sensor.SensorType + "\":\"" + (int)sensor.Value + "\",\"";
                        }
                        if (subHardwareItem.Sensors.Length > 0)
                        {
                            json  = json.Remove(json.Length - 1);
                            json  = json.Remove(json.Length - 1);
                            json += "}},";
                        }
                        else
                        {
                            json  = json.Remove(json.Length - 1);
                            json += "}},";
                        }
                    }
                    json  = json.Remove(json.Length - 1);
                    json += "}";
                }
                json += "},\"";
            }

            json  = json.Remove(json.Length - 1);
            json  = json.Remove(json.Length - 1);
            json  = json.Remove(json.Length - 1);
            json += "}}},";
            return(json);
        }
Example #53
0
        public Guid Sweep(SweepExecutionViewModel param)
        {
            Guid Id = Guid.NewGuid();

            _context.Sweeps.Add(new Sweep
            {
                Id            = Id,
                Status        = "Running",
                StartTime     = DateTime.UtcNow,
                ScanCount     = param.ComputerId.Length,
                CompleteCount = 0
            });
            _context.SaveChanges();

            List <Task> tasks = new List <Task>();

            /*
             * List<Scan> scans = new List<Scan>();
             *
             * foreach (Guid compId in param.ComputerId)
             * {
             *  // Create scan object
             *  Guid scanId = Guid.NewGuid();
             *  scans.Add(new Scan
             *  {
             *      Id = scanId,
             *      Status = "Running",
             *      StartTime = DateTime.UtcNow,
             *      ComputerId = compId,
             *      SweepIdentifier = Id
             *  });
             * }
             *
             * _context.Scans.AddRange(scans);
             */

            _context.SaveChanges();

            // Get Script object
            Script script = _context.Scripts.Single(s => s.Id == param.ScriptId);

            // Create Routing Key
            string RoutingKey = string.Format("{0}{1}", script.Enrichment, script.Output);

            // Get Thumbprint
            string thumbprint = null;

            string[] lines = System.IO.File.ReadAllLines(@"C:\inetpub\ACEWebService\appsettings.Production.json");
            foreach (string l in lines)
            {
                if (l.Contains("Thumbprint"))
                {
                    thumbprint = l.Split('"')[3];
                }
            }

            foreach (Guid compid in param.ComputerId)
            {
                Guid scanId = Guid.NewGuid();

                // Retreive Computer and Credential objects from DB
                Computer   computer   = _context.Computers.Single(c => c.Id == compid);
                Credential credential = _context.Credentials.Single(c => c.Id == computer.CredentialId);

                // Kick off scan
                if (computer.WinRM)
                {
                    Console.WriteLine("==== WINRM ====");

                    // Create a PowerShell script to run PSInvestigate
                    string executionArgs = string.Format(@"-Uri {0} -SweepId {1} -ScanId {2} -RoutingKey {3} -Thumbprint {4}", param.Uri, Id, scanId, RoutingKey, thumbprint);

                    Console.WriteLine(executionArgs);

                    string psScript = string.Format(@"iex (New-Object System.Net.WebClient).DownloadString('{0}{1}'); Start-AceScript {2}", param.Uri, script.Uri, executionArgs);

                    // Base64 Encode the PowerShell script
                    string psScriptEnc = Convert.ToBase64String(Encoding.Unicode.GetBytes(psScript));

                    // Build full powershell command line to be run
                    string commandline = string.Format(@"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -EncodedCommand {0}", psScriptEnc);

                    Console.WriteLine(commandline);

                    tasks.Add(Task.Run(() => { KickOffCimAsync(computer, credential, commandline, new WSManSessionOptions()); }));
                }
                else if (computer.RPC)
                {
                    Console.WriteLine("==== RPC ====");

                    // Create a PowerShell script to run PSInvestigate
                    string executionArgs = string.Format(@"-Uri {0} -SweepId {1} -ScanId {2} -RoutingKey {3} -Thumbprint {4}", param.Uri, Id, scanId, RoutingKey, thumbprint);
                    string psScript      = string.Format(@"iex (New-Object System.Net.WebClient).DownloadString('{0}{1}'); Start-AceScript {2}", param.Uri, script.Uri, executionArgs);

                    // Base64 Encode the PowerShell script
                    string psScriptEnc = Convert.ToBase64String(Encoding.Unicode.GetBytes(psScript));

                    // Build full powershell command line to be run
                    string commandline = string.Format(@"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle Hidden -EncodedCommand {0}", psScriptEnc);

                    Console.WriteLine(commandline);

                    tasks.Add(Task.Run(() => { KickOffCimAsync(computer, credential, commandline, new DComSessionOptions()); }));
                }
                else if (computer.SSH)
                {
                    Console.WriteLine("==== SSH ====");

                    // Build command line to be run over SSH
                    string commandline = string.Format(@"curl -k {0}{1} | sudo python /dev/stdin --Server {0} --SweepId {2} --ScanId {3} --RoutingKey {4}", param.Uri, script.Uri, Id, scanId, RoutingKey);
                    //tasks.Add(Task.Run(() => { KickOffSSHAsync(computer, credential, commandline); }));
                    using (var client = new SshClient(computer.ComputerName, credential.UserName, _cryptoService.Decrypt(credential.Password)))
                    {
                        client.Connect();
                        client.RunCommand(commandline);
                        client.Disconnect();
                    }
                }
                else if (computer.SMB)
                {
                    throw new NotImplementedException();
                }
                else
                {
                    throw new Exception(string.Format("No valid protocols available for {0}", computer.ComputerName));
                }
            }

            Task.WaitAll(tasks.ToArray());

            IQueryable <Scan> scansCompleted = _context.Set <Scan>().Where(s => s.SweepIdentifier == Id && s.Status != "Running");
            IQueryable <Scan> scansFailed    = _context.Set <Scan>().Where(s => s.SweepIdentifier == Id && s.Status == "Failed");
            Sweep             sweep          = _context.Sweeps.Single(s => s.Id == Id);

            sweep.CompleteCount = scansCompleted.ToArray().Length;
            sweep.ErrorCount    = scansFailed.ToArray().Length;
            sweep.Status        = "Completed";
            _context.Sweeps.Update(sweep);
            _context.SaveChanges();

            return(Id);
        }
Example #54
0
 public ActionResult <MessageCollection> Put([FromBody] Computer computer)
 {
     return(new MessageCollection());
 }
Example #55
0
        static void Main(string[] args)
        {
            Computer facade = new Computer();

            facade.startComputer();
        }
Example #56
0
 //
 // Computer
 //
 static public void ComputerLoadValue(Computer computer, string name, object value)
 {
     computer.LoadValueIntoProperty(name, value);
 }
 public void VisitTotalDayliHours(Computer comp)
 {
     Hours += comp.Hours;
 }
Example #58
0
 public RamCollector(Computer computer) : base(GetFirstRam(computer))
 {
 }
Example #59
0
 void Start()
 {
     instance  = this;
     scoreTime = 0.2f;
 }
Example #60
0
 public GetAdminMission(string compIP, OS _os)
 {
     os     = _os;
     target = Programs.getComputer(os, compIP);
 }