예제 #1
0
        public ActionResult ArchiveComputer(ComputerInfo m)
        {
            try
            {
                RemoteComputer c = new RemoteComputer(m.ComputerName, @"lcps\earlyms", "Lcp$-pw1");

                c.Refresh();

                c.DBAcrchive(m, User.Identity.Name);

                return View("Index", new { name = m.ComputerName });
            }
            catch (Exception ex)
            {
                AnvilExceptionModel em = new AnvilExceptionModel(ex, "Archive Computer", "Computers", "Computers", "Index");
                return View("Error", em);
            }
        }
예제 #2
0
        static void show(string ip)
        {
            PerformanceCounter cpuCounter;
            PerformanceCounter ramCounter;
            ComputerInfo       info = new ComputerInfo();

            NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
            cpuCounter = new PerformanceCounter("Processor", "% Processor Time", "_Total");
            ramCounter = new PerformanceCounter("Memory", "Available MBytes");
            long[] previusreceivednpacket = new long[interfaces.Length];
            long[] previussentpacket      = new long[interfaces.Length];
            for (int i = 0; i < interfaces.Length; i++)
            {
                previusreceivednpacket[i] = interfaces[i].GetIPStatistics().BytesReceived;
                previussentpacket[i]      = interfaces[i].GetIPStatistics().BytesSent;
            }
            while (true)
            {
                Console.WriteLine("Binded Address: " + ip);
                Console.WriteLine("----CPU----");
                Console.WriteLine(string.Format("usage: {0}%", cpuCounter.NextValue().ToString("0.00")));
                Console.WriteLine("----RAM----");
                Console.WriteLine(((info.TotalPhysicalMemory / 1024) / 1024 - ramCounter.NextValue()) + "MB / " + (info.TotalPhysicalMemory / 1024) / 1024 + "MB");
                for (int i = 0; i < interfaces.Length; i++)
                {
                    if (interfaces[i].OperationalStatus == OperationalStatus.Up && !excludeddescriptions.Any(interfaces[i].Description.Contains))
                    {
                        Console.WriteLine("----Network Interface----");
                        Console.WriteLine(interfaces[i].Name + ":");
                        Console.WriteLine(" Description: " + interfaces[i].Description);
                        Console.WriteLine(" KBytes Received: " + (interfaces[i].GetIPStatistics().BytesReceived - previusreceivednpacket[i]));
                        Console.WriteLine(" KBytes Sent: " + (interfaces[i].GetIPStatistics().BytesSent - previussentpacket[i]));
                        Console.WriteLine(" Total KBytes Received: " + interfaces[i].GetIPStatistics().BytesReceived);
                        Console.WriteLine(" Total KBytes Sent: " + interfaces[i].GetIPStatistics().BytesSent);
                        Console.WriteLine(" Interface Max Speed: " + interfaces[i].Speed);
                        previusreceivednpacket[i] = interfaces[i].GetIPStatistics().BytesReceived;
                        previussentpacket[i]      = interfaces[i].GetIPStatistics().BytesSent;
                    }
                }
                System.Threading.Thread.Sleep(500);
                Console.Clear();
            }
        }
예제 #3
0
        public void TamanhoMaximoTeste()
        {
            // sizeof: tamanho em bytes.
            // Console.WriteLine(sizeof(bool));

            var vetorDeStrings = new string[0]; // bisonho, mas possível.
            //vetorDeStrings[0] = "teste"; // erro de execução.

            //var outroVetorDeStrings = new string[-1]; // build quebrado.

            var vetorDeBooleanos = new bool[int.MaxValue]; // OutOfMemoryException.

            var memoriaDisponivel = new ComputerInfo().AvailablePhysicalMemory * 0.65m;

            Console.WriteLine((memoriaDisponivel / 1024m / 1024m / 1024m).ToString("n2"));

            var vetorDeBytes    = new byte[Math.Min(int.MaxValue, Convert.ToInt32(memoriaDisponivel))];     // comentar o vetorDeBooleanos.
            var vetorDeInteiros = new int[Math.Min(int.MaxValue, Convert.ToInt32(memoriaDisponivel / 4m))]; // comentar o vetorDeBytes.
        }
예제 #4
0
        /// <summary>
        /// 获取授权状态
        /// </summary>
        /// <returns></returns>
        private bool GetAuthState()
        {
            string authCode = registryHelper.GetRegistryData(Registry.LocalMachine, "SOFTWARE\\QQBatchSend.IR", "License");

            if (authCode != null && authCode != "")
            {
                RSACryption cryption = new RSACryption();
                string      regCode  = cryption.RSADecrypt(RSACryption.privateKey, authCode);
                if (regCode == ComputerInfo.GetComputerInfo())
                {
                    tsslAuthState.Text      = "已授权";
                    tsslAuthState.ForeColor = Color.Green;
                    return(true);
                }
            }
            tsslAuthState.Text      = "未授权";
            tsslAuthState.ForeColor = Color.Red;
            return(false);
        }
예제 #5
0
        void SendData()
        {
            ClientDataModel cdm = new ClientDataModel();

            try
            {
                // DEBUG: Get platform
                ComputerInfo ci = new ComputerInfo();
                Console.WriteLine("Platform: " + ci.OSFullName);
                // prepare data to send
                cdm.clientKey = (string)System.Windows.Forms.Application.UserAppDataRegistry.GetValue("ClientKey");
                List <AppTimePair> atpList = new List <AppTimePair>();
                foreach (ProcessItem pi in pList.GetProcesses())
                {
                    atpList.Add(new AppTimePair()
                    {
                        appName = pi.Name, time = (int)pi.Time, platform = pi.Web == true ? "Web" : ci.OSFullName
                    });
                }
                cdm.appTimes = atpList.ToArray();
                if (SpotifyLocalAPI.IsSpotifyRunning() && SpotifyLocalAPI.IsSpotifyWebHelperRunning())
                {
                    SpotifyLocalAPI sApi = new SpotifyLocalAPI();
                    sApi.Connect();
                    cdm.currentSong    = sApi.GetStatus().Track.ArtistResource.Name + " - " + sApi.GetStatus().Track.TrackResource.Name;
                    cdm.currentSongUrl = sApi.GetStatus().Track.TrackResource.Uri;
                }

                // create a request and send it
                RestClient  rc = new RestClient(GlobalConfig.ApiBase);
                RestRequest rr = new RestRequest("InsertTrackingData", Method.POST);
                rr.AddParameter("data", JsonConvert.SerializeObject(cdm));
                IRestResponse resp = rc.Execute(rr);
                Console.WriteLine(resp.Content);

                // clear times
                pList.Clear();
            }
            catch
            {
                Console.WriteLine("Something went wrong sending data. Invalid client key maybe?");
            }
        }
        public void LicenKey()
        {
            KeyManager  km  = new KeyManager(ComputerInfo.GetComputerId());
            LicenseInfo lic = new LicenseInfo();
            //Get license information from license file
            int    value      = km.LoadSuretyFile(string.Format(@"{0}\active.lic", Application.StartupPath), ref lic);
            string productKey = lic.ProductKey;

            //Check valid
            if (km.ValidKey(ref productKey))
            {
                KeyValuesClass kv = new KeyValuesClass();
                //Decrypt license key
                if (km.DisassembleKey(productKey, ref kv))
                {
                    getLicenKey = productKey;
                }
            }
        }
예제 #7
0
        private static void SaveCrashDump(object sender, UnhandledExceptionEventArgs e)
        {
            ComputerInfo computerInfo = new ComputerInfo();
            StreamWriter sr           = new StreamWriter(Globals.CrashDumpFilePath, true);

            sr.WriteLine("Processor Count: " + Environment.ProcessorCount.ToString());
            sr.WriteLine("OS Name: " + computerInfo.OSFullName);
            sr.WriteLine("OS Platform: " + computerInfo.OSPlatform);
            sr.WriteLine("OS Version: " + computerInfo.OSVersion);
            sr.WriteLine("Working Set: " + Common.SetSizeLabel((UInt64)Environment.WorkingSet));
            sr.WriteLine("Uptime: " + ((Environment.TickCount - Program.startTick) / 1000).ToString());
            sr.WriteLine();
            sr.WriteLine(e.ExceptionObject.ToString());
            sr.Flush();
            sr.Close();
            sr.Dispose();

            MessageBox.Show(e.ExceptionObject.ToString(), Application.ProductName + " - Application Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
        }
예제 #8
0
        protected GZipper(string inFileName, string outFileName)
        {
            InFileName       = inFileName;
            OutFileName      = outFileName;
            CompInfo         = new ComputerInfo();
            InitialFreeRam   = CompInfo.AvailablePhysicalMemory;
            OutgoingChunks   = new Dictionary <int, byte[]>();
            IncomingChunks   = new Dictionary <int, byte[]>();
            ProcessSemaphore = new Semaphore(CoreCount, CoreCount);
            WritingThread    = new Thread(WriteToDisk);

            Console.CancelKeyPress += delegate
            {
                StopRequested = true;
                InFileStream?.Close();
                OutFileStream?.Close();
                Console.Write("Application's stop is requested");
            };
        }
예제 #9
0
        private void AddHeader()
        {
            var list = new List <Dictionary <string, string> >();

            list.Add(new Dictionary <string, string>
            {
                { "raw", Main.name + " Version " + Main.version + " (Fix Log)" }
            });

            var ci = CultureInfo.InstalledUICulture;

            list.Add(new Dictionary <string, string>
            {
                {
                    "raw",
                    "Running from " + Assembly.GetExecutingAssembly().Location.Substring(0, 3) + " as " +
                    WindowsIdentity.GetCurrent().Name + " on " + DateTime.Now
                }
            });

            list.Add(new Dictionary <string, string>
            {
                { "raw", "Windows Version " + Environment.OSVersion.Version + " Language " + ci.EnglishName }
            });

            double totalMemory = new ComputerInfo().TotalPhysicalMemory;

            totalMemory = totalMemory / 1000000000;

            double freeMemory = new ComputerInfo().AvailablePhysicalMemory;

            freeMemory = freeMemory / 1000000000;

            list.Add(new Dictionary <string, string>
            {
                {
                    "raw",
                    totalMemory.ToString("N1") + "GB RAM installed; " + freeMemory.ToString("N1") + "GB RAM available"
                }
            });

            results.Add(list);
        }
예제 #10
0
        public void Memory()
        {
            var info = new ComputerInfo();

            if (PlatformDetection.IsWindows)
            {
                Assert.NotEqual(0u, info.AvailablePhysicalMemory);
                Assert.NotEqual(0u, info.AvailableVirtualMemory);
                Assert.NotEqual(0u, info.TotalPhysicalMemory);
                Assert.NotEqual(0u, info.TotalVirtualMemory);
            }
            else
            {
                Assert.Throws <PlatformNotSupportedException>(() => info.AvailablePhysicalMemory);
                Assert.Throws <PlatformNotSupportedException>(() => info.AvailableVirtualMemory);
                Assert.Throws <PlatformNotSupportedException>(() => info.TotalPhysicalMemory);
                Assert.Throws <PlatformNotSupportedException>(() => info.TotalVirtualMemory);
            }
        }
예제 #11
0
        public IActionResult GetServerJson()
        {
            TData <ComputerInfo> obj          = new TData <ComputerInfo>();
            ComputerInfo         computerInfo = null;

            try
            {
                computerInfo         = ComputerHelper.GetComputerInfo();
                computerInfo.RunTime = DateTimeHelper.FormatTime(Environment.TickCount);
            }
            catch (Exception ex)
            {
                LogHelper.WriteWithTime(ex);
                obj.Message = ex.Message;
            }
            obj.Result = computerInfo;
            obj.Tag    = 1;
            return(Json(obj));
        }
예제 #12
0
        /**********************************************************************************/

        public EditApp(AppManager _am, string _app_full_name = null)
        {
            InitializeComponent();

            m_app_manager   = _am;
            m_app_full_name = _app_full_name;

            m_temp_ci        = new ComputerInfo();
            m_temp_ci.OSType = "temp";

            if (m_app_full_name != null)
            {
                m_temp_app = m_app_manager.GetApplication(m_app_full_name);

                ReloadTextBoxes();
            }

            RebindTextBoxes();
        }
예제 #13
0
        public void InitBaseModel()
        {
            Task.Run(() =>
            {
                try
                {
                    DbHelperSQLite.connectionString = "Data Source=" + Application.StartupPath + "\\IOProject\\Station.station";
                    IO_SERVER serverBll             = new IO_SERVER();
                    AddLogToMainLog("读取采集站信息......");
                    IOServer = serverBll.GetModel(ComputerInfo.GetInstall().ServerID);
                    if (IOServer == null)
                    {
                        return;
                    }
                    mServerID = IOServer.SERVER_ID;
                    //加载通道
                    AddLogToMainLog("读取采集站通道信息......");
                    IO_COMMUNICATION commBll = new IO_COMMUNICATION();
                    IOCommunications         = commBll.GetModelList(" IO_SERVER_ID='" + IOServer.SERVER_ID + "'");
                    AddLogToMainLog("读取采集站通道下的所有设备信息......");
                    IO_DEVICE deviceBll = new IO_DEVICE();
                    IODevices           = deviceBll.GetModelList(" IO_SERVER_ID='" + IOServer.SERVER_ID + "'");
                    AddLogToMainLog("数据处理中.....");

                    for (int i = 0; i < IOCommunications.Count; i++)
                    {
                        AddLogToMainLog("处理 " + IOCommunications[i].IO_COMM_NAME + "[" + IOCommunications[i].IO_COMM_LABEL + "]");
                        IOCommunications[i].Devices = IODevices.FindAll(x => x.IO_COMM_ID == IOCommunications[i].IO_COMM_ID && x.IO_SERVER_ID == IOCommunications[i].IO_SERVER_ID);
                    }
                    AddLogToMainLog("正在创建驱动.....");

                    AddLogToMainLog("读取工程完成!");
                    ProgressMaxNum = IOCommunications.Count + IODevices.Count;
                    FlowGraphEngineProject.IOServer         = IOServer;
                    FlowGraphEngineProject.IOCommunications = IOCommunications;
                }
                catch (Exception ex)
                {
                    ThrowExceptionToMain(ex);
                }
            });
        }
예제 #14
0
        public frmHome()
        {
            InitializeComponent();
            this.Text          = "الرئيسية";
            ComputerInfoString = ComputerInfo.GetComputerId();
            ProductKey         = _Reg.GetProductKey();
            string Decrypted = _Reg.Decrypt(ProductKey, "s3lw-3xr8-sqoy18");

            if (Decrypted == ComputerInfoString)
            {
                button2.Enabled = true;
                button3.Enabled = true;
                button4.Enabled = true;
                button1.Visible = false;
                panel3.Height   = button2.Height;
                panel3.Top      = button2.Top;
                this.Text       = "المشتركين";
                frmsubdata      = new FrontEnd.frmSubData();
                groupBox1.Controls.Clear();
                frmsubdata.TopLevel = false;
                groupBox1.Controls.Add(frmsubdata);
                frmsubdata.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
                frmsubdata.Dock            = DockStyle.Fill;
                frmsubdata.Show();
            }
            else
            {
                button2.Enabled = false;
                button3.Enabled = false;
                button4.Enabled = false;
                panel3.Height   = button1.Height;
                panel3.Top      = button1.Top;
                this.Text       = "الرئيسية";
                frmReg          = new FrontEnd.frmRegisteration();
                groupBox1.Controls.Clear();
                frmReg.TopLevel = false;
                groupBox1.Controls.Add(frmReg);
                frmReg.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
                frmReg.Dock            = DockStyle.Fill;
                frmReg.Show();
            }
        }
        private void FormHauptfenster_Load(object sender, EventArgs e)
        {
            RegistryKey Registrierung   = Registry.LocalMachine;
            RegistryKey Ordner          = Registrierung.OpenSubKey("HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0");
            Object      CpuNameTaktrate = Ordner.GetValue("ProcessorNameString");

            int CpuKerne = System.Environment.ProcessorCount;

            ComputerInfo PcInfo = new ComputerInfo();
            ulong        RAM    = PcInfo.TotalPhysicalMemory;

            ListboxCpuInfo.Items.Add(CpuNameTaktrate);

            if (CpuKerne >= 8)
            {
                ListboxCpuInfo.Items.Add(CpuKerne / 2 + " physische Prozessorkerne" + " / " + CpuKerne + " logische Prozessorkerne");

                if (CpuNameTaktrate.ToString().Split(' ')[0].Contains("Intel"))
                {
                    ListboxCpuInfo.Items.Add("Hyperthreading");
                }
                else
                {
                    ListboxCpuInfo.Items.Add("Simultaneous Multithreading");
                }
            }
            else
            {
                ListboxCpuInfo.Items.Add(CpuKerne + " physische Prozessorkerne");

                if (CpuNameTaktrate.ToString().Split(' ')[0].Contains("Intel"))
                {
                    ListboxCpuInfo.Items.Add("Kein Hyperthreading");
                }
                else
                {
                    ListboxCpuInfo.Items.Add("Kein Simultaneous Multithreading");
                }
            }

            ListboxRamInfo.Items.Add(RAM / (1024 * 1024) + " MB RAM");
        }
예제 #16
0
        private HardwareUtils()
        {
            ComputerInfo myCompInfo = new ComputerInfo();

            totalPhysicalRam = myCompInfo.TotalPhysicalMemory;
            freePhysicalRam  = myCompInfo.AvailablePhysicalMemory;
            totalVirtualRam  = myCompInfo.TotalVirtualMemory;
            freeVirtualRam   = myCompInfo.AvailableVirtualMemory;
            osName           = myCompInfo.OSVersion;

            DriveInfo myDriveInfo = new DriveInfo(Path.GetPathRoot(Environment.SystemDirectory));

            if (myDriveInfo.IsReady)
            {
                diskTotalSpace = myDriveInfo.TotalSize;
                diskFreeSpace  = myDriveInfo.AvailableFreeSpace;
            }

            GetPwrCapabilities(out systemPowerCapabilites);
        }
        public override bool Check()
        {
            HasCorrectVersion = false;
            Message           = $"\n{Name} not installed on your machine.";

            ComputerInfo info = new ComputerInfo();

            var totalMemoryPh = info.TotalPhysicalMemory;

            int gb            = 1073741824;
            var totalMemoryGb = Convert.ToDouble(totalMemoryPh) / gb;

            if (totalMemoryGb >= 2)
            {
                HasCorrectVersion = true;
                Message           = $"{Name}... OK\n";
            }

            return(HasCorrectVersion);
        }
예제 #18
0
        bool IsLineByLineParsing(long contLength)
        {
            var availableRam = new ComputerInfo().AvailablePhysicalMemory;

            if (contLength == -1)
            {
                return(YesNoQuery("Не удалось определить размер HTML-страницы. " +
                                  "Есть ли необходимость парсить страницу построчно?(y/n)", 'y', 'n'));
            }

            if ((ulong)contLength > availableRam)
            {
                if (MeasuredRamAllocation(contLength) > availableRam)
                {
                    throw new Exception("Свободной оперативной памяти скорее всего не хватит на обработку страницы!");
                }
                return(true);
            }
            return(false);
        }
 public MemStat()
 {
     ObjectQuery wql = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
     ManagementObjectSearcher searcher = new ManagementObjectSearcher(wql);
     ManagementObjectCollection results = searcher.Get();
     var Available = new ComputerInfo().AvailablePhysicalMemory;
     this.Available = Available;
     var Total = new ComputerInfo().TotalPhysicalMemory;
     this.Total = Total;
     var PhysicalMemoryInUse = Total - Available;
     this.PhysicalMemoryInUse = PhysicalMemoryInUse;
     Object Free = new object();
     foreach (var result in results)
     {
         Free = result["FreePhysicalMemory"];
         this.Free = ulong.Parse(Free.ToString());
     }
     var Cached = Total - PhysicalMemoryInUse - ulong.Parse(Free.ToString());
     this.Cached = Cached;
 }
예제 #20
0
        // 로컬 모니터링
        private void Handle()
        {
            ComputerInfo memoryInfo      = new ComputerInfo();
            double       totalMemory     = ((double)memoryInfo.TotalPhysicalMemory / 1048576);
            double       availableMemory = ((double)memoryInfo.AvailablePhysicalMemory / 1048576);

            memCounter = (int)(((totalMemory - availableMemory) / totalMemory) * 100);

            int cpuValue = (int)cpuCounter.NextValue();

            _logger.Info("CPU Usage : " + cpuValue + "%");
            _logger.Info("Memory Usage : " + memCounter + "%");
            LocalData localDatas = new LocalData(_localID, cpuValue, memCounter, 0, 0);

            if (serverAccessState == true)
            {
                _logger.Info(" Transfer data to the LocalServer.");
                server.Tell(new UpdateMonitor(localDatas));
            }
        }
예제 #21
0
        private void Form1_Load(object sender, EventArgs e)
        {
            ComputerInfo CI = new ComputerInfo();

            ulRAM = (CI.TotalPhysicalMemory / 1024) / 1024;

            BackColor         = Color.Black;
            BackgroundColor   = BackColor;
            AllowTransparency = true;
            timer1.Interval   = intTimer * 1000;
            ShowInTaskbar     = false;

            bTransparent      = true;
            bStayOnTop        = true;
            TopMost           = true;
            bmpSurface        = new Bitmap(ClientRectangle.Width, ClientRectangle.Height);
            objBitmapGraphics = Graphics.FromImage(bmpSurface);
            objBitmapGraphics.Clear(BackgroundColor);
            rectBounds = new Rectangle(0, 0, bmpSurface.Width, bmpSurface.Height);
        }
예제 #22
0
        //Get data that has been sent to the server
        private void GetData()
        {
            Message Data;

            while (Networking.MainClient.GetNextMessage(out Data))
            {
                switch (Data.eventType)
                {
                case EventType.Connected:
                    Console.WriteLine("Connected");
                    List <byte> ToSend = new List <byte>();
                    ToSend.Add((int)DataType.ClientTag);
                    ToSend.AddRange(Encoding.ASCII.GetBytes(ClientSettings.ClientTag));
                    Networking.MainClient.Send(ToSend.ToArray());
                    ToSend.Clear();
                    ToSend.Add((int)DataType.AntiVirusTag);
                    ToSend.AddRange(Encoding.ASCII.GetBytes(ComputerInfo.GetAntivirus()));
                    Networking.MainClient.Send(ToSend.ToArray());
                    string OperatingSystemUnDetailed = ComputerInfo.GetWindowsVersion()
                                                       .Remove(ComputerInfo.GetWindowsVersion().IndexOf('('));
                    ToSend.Clear();
                    ToSend.Add((int)DataType.WindowsVersionTag);
                    ToSend.AddRange(Encoding.ASCII.GetBytes(OperatingSystemUnDetailed));
                    Networking.MainClient.Send(ToSend.ToArray());

                    ToSend.Clear();
                    ToSend.Add((int)DataType.ClientName);
                    ToSend.AddRange(Encoding.ASCII.GetBytes(ComputerInfo.GetName()));
                    Networking.MainClient.Send(ToSend.ToArray());

                    break;

                case EventType.Disconnected:
                    break;

                case EventType.Data:
                    HandleData(Data.data);
                    break;
                }
            }
        }
        public async Task <object> SendInfo(ComputerInfo info)
        {
            try
            {
                var client  = new RestClient(url);
                var request = new RestRequest("computer", DataFormat.Json);
                var cancellationTokenSource = new CancellationTokenSource();
                request.AddHeader("Accept", "application/json");
                request.AddHeader("Content-Type", "application/json");
                request.Method = Method.POST;
                request.AddJsonBody(info);

                var restResponse = await client.ExecuteAsync(request, cancellationTokenSource.Token);

                if (restResponse.IsSuccessful)
                {
                    try
                    {
                        var desResp = JsonConvert.DeserializeObject <RetailGroupResponse>(restResponse.Content);
                        return(desResp);
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
                else
                {
                    return(new RetailGroupResponse
                    {
                        Id = info.Id,
                        ErrorCode = (int)restResponse.ResponseStatus,
                        ErrorText = restResponse.ErrorMessage
                    });
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
예제 #24
0
        public string GenerateComputerStatusIcon(ComputerInfo computer)
        {
            var cssClass   = "label-info";
            var statusText = "Online";

            if (computer.IsOnline || computer.Name.ToLower().Contains("local"))
            {
                cssClass   = "label-success";
                statusText = "Online";
            }
            else
            {
                cssClass   = "label-danger";
                statusText = "Offline";
            }

            return(String.Format("<div class=\"label {0} label-mini\">{1}</div>",
                                 cssClass,
                                 statusText
                                 ));
        }
예제 #25
0
        ///<summary>Returns specific information regarding the current version of Windows that is running.</summary>
        public static string GetOSVersionInfo()
        {
            string versionInfo = "";
            //Utilize the visual basic ComputerInfo class in order to get the most accurate OS version.
            //This is because Environment.OSVersion was always returning a version that represented Windows 8.
            ComputerInfo computerInfo = new ComputerInfo();

            versionInfo = computerInfo.OSFullName + (Environment.Is64BitOperatingSystem ? " 64-bit":" 32-bit");         //OSFullName will be blank on wine
            //This chunk is to get the correct version number.  If we use Environment.OSVersion, it will return an incorrect number.
            //This is because the application isn't manifested to windows 8.1 or 10.  As a result is will always return a version num of 6.2.
            //https://msdn.microsoft.com/en-us/library/windows/desktop/ms724832(v=vs.85).aspx
            try {
                ManagementObjectSearcher mangementQuery = new ManagementObjectSearcher("SELECT * FROM Win32_OperatingSystem");
                ManagementObject         systemInfo     = mangementQuery.Get().Cast <ManagementObject>().FirstOrDefault();
                versionInfo += " Build " + systemInfo.Properties["Version"].Value;
            }
            catch (Exception e) {
                e.DoNothing();
            }
            return(versionInfo);
        }
예제 #26
0
파일: JudgeProcess.cs 프로젝트: sdcb/sdoj
        private bool PrecheckEnvironment(SolutionPushModel _spush)
        {
            if (!CompilerProvider.IsLanguageAvailable(_spush))
            {
                _log.InfoExt(() => string.Format("Skipped compiling {0}, Because {1} compiler is not availabel.",
                                                 _spush.Id, _spush.Language));
                return(false);
            }
            var info = new ComputerInfo();

            if (info.AvailablePhysicalMemory < _spush.FullMemoryLimitMb * 1024 * 1024)
            {
                _log.InfoExt(
                    () =>
                    string.Format("Skipped judging {0}, because system memory running low(Req {1}/ Need {2}).",
                                  _spush.Id, info.AvailablePhysicalMemory, _spush.FullMemoryLimitMb * 1024 * 1024)
                    );
                return(false);
            }
            return(true);
        }
예제 #27
0
        public JsonResult Post([FromBody] ComputerInfo compInfo)
        {
            var options = new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                IgnoreNullValues     = true
            };

            try
            {
                _logger.LogInformation(JsonConvert.SerializeObject(compInfo));
                //TODO write do DB
                var response = new ResponseWS(compInfo.Id, (int)ErrorCode.OK);
                return(Json(response, options));
            }
            catch (Exception ex)
            {
                var error = new ResponseWS(compInfo.Id, (int)ErrorCode.SmthWrong, ex.Message);
                return(Json(error));
            }
        }
예제 #28
0
        static void Main(string[] args)
        {
            ComputerInfo d = new ComputerInfo();

            ulong ramDisponibileByte = d.AvailablePhysicalMemory;
            ulong ramInUsoByte       = d.TotalPhysicalMemory - d.AvailablePhysicalMemory;

            ulong ramDisponibileKiloByte = ramDisponibileByte / 1024;
            ulong ramInUsoKiloByte       = ramInUsoByte / 1024;


            ulong ramBella = (ramDisponibileByte > ramInUsoByte) ? ramDisponibileByte : ramInUsoByte;

            while (true)
            {
                Console.WriteLine("Ram in uso: {0}", ramInUsoKiloByte);
                Console.WriteLine("Ram disponibile: {0}", ramDisponibileKiloByte);
                Thread.Sleep(500);
                Console.Clear();
            }
        }
예제 #29
0
        private void OnReceive(IAsyncResult ar)
        {
            Client client = (Client)ar.AsyncState;

            try {
                int bytesReceived = client.socket.Client.EndReceive(ar);

                if (bytesReceived > 0)
                {
                    ComputerInfo info = ByteArrayToObject <ComputerInfo>(client.receiveBytes);
                    if (info != null)
                    {
                        client.lastInfo = info;
                        UpdateClient(client);
                    }
                }
            } catch (Exception)
            {
                RemoveClient(client);
            }
        }
        public Task <ResposeName <ComputerInfo> > AddMessage([FromBody] ComputerInfo computer)
        {
            ResposeName <ComputerInfo> RS = new ResposeName <ComputerInfo>();

            try
            {
                computer.Time = DateTime.Now;
                var jsonSR = JsonConvert.SerializeObject(computer);
                _db.ListLeftPush("List." + computer.Name, jsonSR);
                RS.code = 200;
                RS.data = computer;
            }
            catch (Exception e)
            {
                _logger.LogError($"/Health/GetOneByAllComputerInfo Very Important Error:{e.Message}");
                RS.code = 404;
                RS.msg  = e.Message;
                RS.data = null;
            }
            return(Task.FromResult(RS));
        }
예제 #31
0
        private void RAM_count()
        {
            ComputerInfo cpI      = new ComputerInfo();
            float        fram     = pRAM.NextValue();
            float        framCmt  = pRAMcmt.NextValue();
            float        framAvai = pRAMavai.NextValue();
            float        fCached  = pCached.NextValue();
            float        fPaged   = pPaged.NextValue();
            float        fNPaged  = pNPaged.NextValue();
            float        avaiRAM  = cpI.TotalPhysicalMemory / (1024 * 1024 * 1024); //GB

            labelRAM.Text = string.Format("{0:0.0} GB", (fram / 100) * avaiRAM);
            //labelRAM.Text += " / " + string.Format("{0:0.0} GB", avaiRAM);
            labelCmt.Text     = string.Format("{0:0.0} GB", framCmt / (1024 * 1024 * 1024));
            labelRamAvai.Text = string.Format("{0:0.0} GB", framAvai / 1024);
            labelCached.Text  = string.Format("{0:0.0} GB", fCached / (1024 * 1024 * 1024));
            labelPaged.Text   = string.Format("{0:0} MB", fPaged / (1024 * 1024));
            labelNPaged.Text  = string.Format("{0:0} MB", fNPaged / (1024 * 1024));

            chartRAM.Series["RAM"].Points.AddY(fram);
        }
            /// <summary>
            /// Gets an array of <c>ComputerInfo</c> structures describing
            /// computers matching the given contraints.
            /// </summary>
            /// <param name="serverType">server type filter.</param>
            /// <param name="domainName">domain to enumerate.</param>
            /// <param name="lastError">The last error.</param>
            /// <returns>
            /// An array of structures representing the computers 
            /// matching the given parameters.
            /// </returns>
            internal static ComputerInfo[] GetComputerInfo(
                uint serverType,
                string domainName, out string lastError)
            {
                int entriesread;  // number of entries actually read
                int totalentries; // total visible servers and workstations
                int result;		  // result of the call to NetServerEnum

                // Pointer to buffer that receives the data
                IntPtr pBuf = IntPtr.Zero;
                Type serverInfoType = typeof(SERVER_INFO_101);

                // structure containing info about the server
                SERVER_INFO_101 serverInfo;
                ComputerInfo[] computers = null;

                try
                {
                    result = NetServerEnum(
                        null,
                        101,
                        out pBuf,
                        -1,
                        out entriesread,
                        out totalentries,
                        serverType,
                        domainName,
                        IntPtr.Zero);

                    if (result == 0)
                    {
                        lastError = string.Empty;

                        computers = new ComputerInfo[entriesread];

                        int tmp = (int)pBuf;

                        for (int i = 0; i < entriesread; i++)
                        {
                            // fill struct
                            serverInfo = (SERVER_INFO_101)Marshal.PtrToStructure((IntPtr)tmp, serverInfoType);
                            computers[i] = new ComputerInfo(serverInfo);

                            // next struct
                            tmp += Marshal.SizeOf(serverInfoType);
                        }
                    }
                    else
                    {
                        switch (result)
                        {
                            case ERROR_MORE_DATA:
                                lastError = "More data is available";
                                break;
                            case ERROR_ACCESS_DENIED:
                                lastError = "Access was denied";
                                break;
                            default:
                                lastError = "Unknown error code " + result;
                                break;
                        }
                    }
                }
                finally
                {
                    // free the buffer
                    NetApiBufferFree(pBuf);
                    pBuf = IntPtr.Zero;
                }

                return computers;
            }
예제 #33
0
        private List<string> SetUpComputerInfoUsingWsman(IEnumerable<string> computerNames, CancellationToken token)
        {
            var validComputerNameList = new List<string>();
            var operationOptions = new CimOperationOptions
            {
                Timeout = TimeSpan.FromMilliseconds(2000),
                CancellationToken = token
            };
            foreach (var computer in computerNames)
            {
                try
                {
                    using (CimSession cimSession = RemoteDiscoveryHelper.CreateCimSession(computer, Credential, WsmanAuthentication, token, this))
                    {
                        bool itemRetrieved = false;
                        IEnumerable<CimInstance> mCollection = cimSession.QueryInstances(
                                                                 ComputerWMIHelper.CimOperatingSystemNamespace,
                                                                 ComputerWMIHelper.CimQueryDialect,
                                                                 "Select * from " + ComputerWMIHelper.WMI_Class_OperatingSystem,
                                                                 operationOptions);
                        foreach (CimInstance os in mCollection)
                        {
                            itemRetrieved = true;
                            if (!_computerInfos.ContainsKey(computer))
                            {
                                var info = new ComputerInfo
                                {
                                    LastBootUpTime = os.CimInstanceProperties["LastBootUpTime"].Value.ToString(),
                                    RebootComplete = false
                                };
                                _computerInfos.Add(computer, info);
                                validComputerNameList.Add(computer);
                            }
                        }

                        if (!itemRetrieved)
                        {
                            string errMsg = StringUtil.Format(ComputerResources.RestartComputerSkipped, computer, ComputerResources.CannotGetOperatingSystemObject);
                            var error = new ErrorRecord(new InvalidOperationException(errMsg), "RestartComputerSkipped",
                                                            ErrorCategory.OperationStopped, computer);
                            this.WriteError(error);
                        }
                    }
                }
                catch (CimException ex)
                {
                    string errMsg = StringUtil.Format(ComputerResources.RestartComputerSkipped, computer, ex.Message);
                    var error = new ErrorRecord(new InvalidOperationException(errMsg), "RestartComputerSkipped",
                                                        ErrorCategory.OperationStopped, computer);
                    this.WriteError(error);
                }
                catch (Exception ex)
                {
                    CommandProcessorBase.CheckForSevereException(ex);
                    string errMsg = StringUtil.Format(ComputerResources.RestartComputerSkipped, computer, ex.Message);
                    var error = new ErrorRecord(new InvalidOperationException(errMsg), "RestartComputerSkipped",
                                                        ErrorCategory.OperationStopped, computer);
                    this.WriteError(error);
                }
            }

            return validComputerNameList;
        }
예제 #34
0
        private List<string> SetUpComputerInfoUsingDcom(IEnumerable<string> computerNames, ConnectionOptions options)
        {
            var validComputerNameList = new List<string>();
            var query = new ObjectQuery("Select * From " + ComputerWMIHelper.WMI_Class_OperatingSystem);
            var enumOptions = new EnumerationOptions { UseAmendedQualifiers = true, DirectRead = true };

            foreach (var computer in computerNames)
            {
                try
                {
                    var scope = new ManagementScope(ComputerWMIHelper.GetScopeString(computer, ComputerWMIHelper.WMI_Path_CIM), options);
                    using (var searcher = new ManagementObjectSearcher(scope, query, enumOptions))
                    {
                        using (var mCollection = searcher.Get())
                        {
                            if (mCollection.Count > 0)
                            {
                                foreach (ManagementBaseObject os in mCollection)
                                {
                                    using (os)
                                    {
                                        if (!_computerInfos.ContainsKey(computer))
                                        {
                                            var info = new ComputerInfo
                                            {
                                                LastBootUpTime = os.Properties["LastBootUpTime"].Value.ToString(),
                                                RebootComplete = false
                                            };
                                            _computerInfos.Add(computer, info);
                                            validComputerNameList.Add(computer);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                string errMsg = StringUtil.Format(ComputerResources.RestartComputerSkipped, computer, ComputerResources.CannotGetOperatingSystemObject);
                                var error = new ErrorRecord(new InvalidOperationException(errMsg), "RestartComputerSkipped",
                                                                ErrorCategory.OperationStopped, computer);
                                this.WriteError(error);
                            }
                        }
                    }
                }
                catch (ManagementException ex)
                {
                    string errMsg = StringUtil.Format(ComputerResources.RestartComputerSkipped, computer, ex.Message);
                    var error = new ErrorRecord(new InvalidOperationException(errMsg), "RestartComputerSkipped",
                                                        ErrorCategory.OperationStopped, computer);
                    this.WriteError(error);
                }
                catch (COMException ex)
                {
                    string errMsg = StringUtil.Format(ComputerResources.RestartComputerSkipped, computer, ex.Message);
                    var error = new ErrorRecord(new InvalidOperationException(errMsg), "RestartComputerSkipped",
                                                        ErrorCategory.OperationStopped, computer);
                    this.WriteError(error);
                }
                catch (UnauthorizedAccessException ex)
                {
                    string errMsg = StringUtil.Format(ComputerResources.RestartComputerSkipped, computer, ex.Message);
                    var error = new ErrorRecord(new InvalidOperationException(errMsg), "RestartComputerSkipped",
                                                        ErrorCategory.OperationStopped, computer);
                    this.WriteError(error);
                }
            }

            return validComputerNameList;
        }
예제 #35
0
        public void DBAcrchive(ComputerInfo m, string author)
        {
            LcpsAdsDomain dom = LcpsAdsDomain.Default;
            string fltr = "(&(cn=" + this.ComputerName + "))";
            DirectorySearcher s = new DirectorySearcher(dom.DirectoryEntry, fltr);
            SearchResult r = s.FindOne();
            if (r.GetDirectoryEntry() == null)
                m.LDAPExists = false;
            else
            {
                m.LDAPExists = true;
                LcpsAdsComputer ldapC = new LcpsAdsComputer(r.GetDirectoryEntry());
                m.LDAPGuid = ldapC.ObjectGuid;
            }

            ComputerInfo i = new ComputerInfo()
            {
                ComputerId = Guid.NewGuid(),
                LDAPExists = m.LDAPExists,
                LDAPGuid = m.LDAPGuid,
                AcrchiveDate = DateTime.Now,
                BuildingId = m.BuildingId,
                RoomId = m.RoomId,
                UnitNumber = m.UnitNumber,
                ArchiveAuthor = author,
                ComputerName = this.ComputerName,
                ComputerType = this.ComputerType,
                Description = this.Description,
                Manufacturer = this.Manufacturer,
                Model = this.Model,
                SerialNumber = this.SerialNumber,
                OSName = this.OSName,
                OSServicePack = this.OSServicePack,
                RecordState = ComputerRecordState.Active
            };

            List<ArchiveNic> _nics = new List<ArchiveNic>();
            foreach (Win32_NetworkAdapter n in this.NetworkAdapters)
            {
                ArchiveNic archN = new ArchiveNic()
                {
                    RecordId = Guid.NewGuid(),
                    ComputerId = i.ComputerId,
                    MacAddress = n.MacAddress,
                    Manufacturer = n.Manufacturer,
                    Name = n.Name
                };
                _nics.Add(archN);
            }

            LcpsDbContext db = new LcpsDbContext();

            foreach (ComputerInfo ac in db.Computers)
            {
                ac.RecordState = ComputerRecordState.Archive;
                db.Entry(ac).State = System.Data.Entity.EntityState.Modified;
            }

            db.Computers.Add(i);
            db.ArchivedNics.AddRange(_nics);
            db.SaveChanges();
        }
예제 #36
0
 public ComputerInfo ToComputerInfo()
 {
     LcpsDbContext db = new LcpsDbContext();
     ComputerInfo dbC = db.Computers.FirstOrDefault(x => x.RecordState == ComputerRecordState.Active & x.ComputerName.ToLower() == this.ComputerName.ToLower());
     ComputerInfo wmi = new ComputerInfo(this);
     if(dbC != null)
     {
         wmi.BuildingId = dbC.BuildingId;
         wmi.RoomId = dbC.RoomId;
         wmi.UnitNumber = dbC.UnitNumber;
     }
     return wmi;
 }