public static void Log(Exception e, Guid guid)
        {
            var info = new Microsoft.VisualBasic.Devices.ComputerInfo();

            String path = Path.Combine(_LogPath, guid.ToString());

            String os = String.Join(" ", "CPU:", info.OSFullName, info.OSVersion, info.OSPlatform);
            String memory = String.Concat("Memory: ", info.TotalPhysicalMemory);
            String date = String.Concat("Date: ", DateTime.Now.ToString());
            String processor = "Processor: Unknown";

            try {
                using (RegistryKey key = Registry.LocalMachine.OpenSubKey(@"HARDWARE\DESCRIPTION\System\CentralProcessor\0", false)) {
                    processor = String.Join(" ", "Processor:",
                        key.GetValue("VendorIdentifier"),
                        key.GetValue("Identifier"),
                        key.GetValue("ProcessorNameString"),
                        key.GetValue("~Mhz"), "~Mhz"
                    );
                    key.Close();
                }
            }
            catch (System.Security.SecurityException) {
            }

            String system = String.Join("\n", date, os, processor, memory);

            String data = String.Join("\n\n", system, PrintException(e));

            using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write)) {
                using (StreamWriter sw = new StreamWriter(fs)) {
                    sw.Write(data);
                }
            }
        }
Exemple #2
0
        public Win7SuperBarForm()
        {
            InitializeComponent();
            _fTotalProgress = 0.0f;
            

            //Information
            _infoUserName = System.Windows.Forms.SystemInformation.UserName;
            _infoUserDomain = System.Windows.Forms.SystemInformation.UserDomainName;
            this.textBox1.Text = "UserName: "******" UserDomain: " + _infoUserDomain;

            //OS version
            OSVersionInfo osvi3 = new OSVersionInfo();
            osvi3.dwOSVersionInfoSize = (uint)Marshal.SizeOf(osvi3);
            bool result = LibWrap.GetVersionOS(ref osvi3);

            textBox5.Text = 
                "OS Build: " + osvi3.dwBuildNumber.ToString() + 
                " CSDVersion: " + osvi3.szCSDVersion;

            Microsoft.VisualBasic.Devices.ComputerInfo compInfo = new Microsoft.VisualBasic.Devices.ComputerInfo();
            textBox3.Text = compInfo.OSFullName;
            textBox4.Text = compInfo.OSVersion;
            textBox2.Text = compInfo.OSPlatform;

            listBox1.MultiColumn = true;
            listBox1.Items.Add("OS Build:   " + osvi3.dwBuildNumber.ToString());
            listBox1.Items.Add("CSDVersion: " + osvi3.szCSDVersion);
            listBox1.Items.Add("OS Full Name: " + compInfo.OSFullName);
            listBox1.Items.Add("OS Version: " + compInfo.OSVersion);
            listBox1.Items.Add("OS Platform: " + compInfo.OSPlatform);

            _osV = new Cip.CipOsVersion();

        }
Exemple #3
0
 //Get the total amount of installed physical RAM in the machine
 public static int getTotalRam()
 {
     //Use a VB library to get the total in bytes
     ulong rambytes = new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory;
     //Convert bytes to MB, cast to int for use.
     int rammeg = (int)(rambytes / 1024) / 1024;
     return rammeg;
 }
        private void UpdateTimerOnElapsed(object sender, ElapsedEventArgs elapsedEventArgs)
        {
            var ramUsed = new PerformanceCounter("Memory", "Available MBytes");
            var ramTotal = new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory / (1024 * 1024);

            if(Update != null)
                Update(this, new RamUpdateEventArgs(ramUsed.RawValue, (long)ramTotal));
        }
        public static void PrintAppAndSysProps(LoggedTextBox textBox)
        {
            TextWriter writer = textBox.GetStreamWriter();
            var ci = new Microsoft.VisualBasic.Devices.ComputerInfo();

            writer.WriteLine("<<--  Execution Environment Information -->>");
            writer.WriteLine();
            writer.WriteLine("OS-Version              -> {0}", Environment.OSVersion.ToString());
            writer.WriteLine("Runtime                 -> {0}", Environment.Version.ToString());
            writer.WriteLine("Is64BitProcess          -> {0}", Environment.Is64BitProcess);
            writer.WriteLine("Is64BitOperatingSystem  -> {0}", Environment.Is64BitOperatingSystem);
            writer.WriteLine("InstalledUICulture      -> {0}", ci.InstalledUICulture);
            writer.WriteLine("MachineName             -> {0}", Environment.MachineName);
            writer.WriteLine();
            writer.WriteLine("<<-- Application Information -->>");
            writer.WriteLine();
            writer.WriteLine("Application.name        -> Factorial Function Benchmark - C# Gui");
            writer.WriteLine("Application.id          -> Sharit.Application.Factorial");
            writer.WriteLine("Application.title       -> Factorial Function Benchmark");
            writer.WriteLine("Application.version     -> 3.1.20110620");
            writer.WriteLine("Application.vendor      -> Peter Luschny");
            writer.WriteLine("Application.homepage    -> " + @"http://www.Luschny.de/math/factorial/FastFactorialFunctions.htm");
            writer.WriteLine("Application.description -> How fast can we compute the factorial function?");
            writer.WriteLine();
            writer.WriteLine("<<-- Runtime Information -->>");
            writer.WriteLine();
            writer.WriteLine("Processor               -> {0}", ProcessorInfo());
            writer.WriteLine("ProcessorCount          -> {0}", Environment.ProcessorCount.ToString());
            writer.WriteLine("TotalPhysicalMemory     -> {0}", ci.TotalPhysicalMemory);
            writer.WriteLine("TotalVirtualMemory      -> {0}", ci.TotalVirtualMemory);
            writer.WriteLine("AvailablePhysicalMemory	-> {0}", ci.AvailablePhysicalMemory);
            writer.WriteLine("AvailableVirtualMemory	-> {0}", ci.AvailableVirtualMemory);
            writer.WriteLine();
            TimerProperties(writer);
            writer.WriteLine();
            writer.WriteLine("<<-- Use Information -->>");

            textBox.WriteLine();
            DateTimeFormatInfo dateTimeFormat = new CultureInfo("en-US", false).DateTimeFormat;
            DateTime dateTime = DateTime.Now;

            textBox.WriteLine("Application started at {0}", dateTime.ToString("u", dateTimeFormat));
            textBox.WriteLine();
            textBox.WriteLine("Hello {0}, \n \n   welcome to the Factorial Benchmark!", Environment.UserName);
            textBox.WriteLine("\n   For background information visit \n");
            textBox.WriteLine(@"http://www.luschny.de/math/factorial/FastFactorialFunctions.htm");
            textBox.WriteLine();
            textBox.WriteLine("\n   If you want to study the code and are online than click on the green button." );
            textBox.WriteLine();
            textBox.WriteLine("\n   The arithmetic used is MPIR 2.6. Make sure that the library fits your CPU!");
            // textBox.WriteLine("\n\n   Not only the timings also the relative \n   rankings can differ considerably if a \n   different arithmetic (for example \n   BigIntegers from .NET) is used!\n");
            textBox.WriteLine("\n\n   To include your own factorial function into the benchmark edit the file MyFactorial.cs and recompile.");
            textBox.WriteLine();
        }
        public string GetDetailedException(Exception exception)
        {
            var result = new StringBuilder();

            var computerInfo = new Microsoft.VisualBasic.Devices.ComputerInfo();

            result.AppendLine(string.Format("Application:       {0}", Application.ProductName));
            result.AppendLine(string.Format("Path:              {0}", Application.ExecutablePath));
            result.AppendLine(string.Format("Version:           {0}", Application.ProductVersion));
            result.AppendLine(string.Format("Date:              {0}", DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")));
            result.AppendLine(string.Format("Computer name:     {0}", SystemInformation.ComputerName));
            result.AppendLine(string.Format("User name:         {0}", SystemInformation.UserName));
            result.AppendLine(string.Format("OSVersion:         {0}", computerInfo.OSVersion));
            result.AppendLine(string.Format("OSPlatform:        {0}", (Environment.Is64BitOperatingSystem ? "X64" : "X86")));
            result.AppendLine(string.Format("OSFullName:        {0}", computerInfo.OSFullName));
            result.AppendLine(string.Format("Culture:           {0}", CultureInfo.CurrentCulture.Name));
            result.AppendLine(string.Format("Resolution:        {0}", SystemInformation.PrimaryMonitorSize));
            result.AppendLine(string.Format("System up time:    {0}", getSystemUpTime()));
            result.AppendLine(string.Format("App up time:       {0}", (DateTime.Now - Process.GetCurrentProcess().StartTime)));
            result.AppendLine(string.Format("Total memory:      {0}Mb", computerInfo.TotalPhysicalMemory / (1024 * 1024)));
            result.AppendLine(string.Format("Available memory:  {0}Mb", computerInfo.AvailablePhysicalMemory / (1024 * 1024)));
            //Getting Available Drive Space
            var currentDrive = DriveInfo.GetDrives().FirstOrDefault(x =>
                String.Equals(x.Name, Application.ExecutablePath.Substring(0, 3), StringComparison.CurrentCultureIgnoreCase));
            if (currentDrive != null)
            {
                result.AppendLine(string.Format("Drive {0}", currentDrive.Name));
                result.AppendLine(string.Format("Volume label: {0}", currentDrive.VolumeLabel));
                result.AppendLine(string.Format("File system: {0}", currentDrive.DriveFormat));
                result.AppendLine(string.Format("Available space to current user: {0} MB", currentDrive.AvailableFreeSpace / (1024 * 1024)));
                result.AppendLine(string.Format("Total available space: {0} MB", currentDrive.TotalFreeSpace / (1024 * 1024)));
                result.AppendLine(string.Format("Total size of drive: {0} MB ", currentDrive.TotalSize / (1024 * 1024)));
            }

            //Get callerInfo
            var stackTrace = new StackTrace();
            var stackFrame = stackTrace.GetFrame(2); //caller of LogExceptionToFile
            var methodBase = stackFrame.GetMethod();
            var callingType = methodBase.DeclaringType;
            if (callingType != null)
            {
                result.AppendLine(string.Format("Url: {0} -> {1}", callingType.Assembly.Location, callingType.Assembly.FullName));
                result.AppendLine(string.Format("Caller: {0} -> {1}", callingType.FullName, methodBase.Name));
            }

            result.AppendLine("Exception classes: ");
            result.AppendLine(getExceptionTypeStack(exception));
            result.AppendLine("Exception messages: ");
            result.AppendLine(GetExceptionMessageStack(exception));
            result.AppendLine("Stack Traces:");
            result.AppendLine(GetExceptionCallStack(exception));
            return result.ToString();
        }
Exemple #7
0
 private static void AppendComputerInfo(StringBuilder sb)
 {
     try
     {
         if (sb == null)
             return;
         Microsoft.VisualBasic.Devices.ComputerInfo info = new Microsoft.VisualBasic.Devices.ComputerInfo();
         sb.AppendLine("**** COMPUTER INFO ****");
         sb.AppendLine(string.Format("Physical Memory: {0:N} Avail, {1:N} Total", BytesToGb(info.AvailablePhysicalMemory), BytesToGb(info.TotalPhysicalMemory)));
         sb.AppendLine(string.Format("Virtual Memory: {0:N} Avail, {1:N} Total", BytesToGb(info.AvailableVirtualMemory), BytesToGb(info.TotalVirtualMemory)));
         sb.AppendLine(string.Format("OS Full Name: {0}", info.OSFullName));
         sb.AppendLine(string.Format("OS Platform: {0}", info.OSPlatform));
         sb.AppendLine(string.Format("OS Version: {0}", info.OSVersion));
         try
         {
             System.Windows.Forms.Screen[] screens = System.Windows.Forms.Screen.AllScreens;
             sb.AppendLine(string.Format("{0} SCREEN(s) DETECTED.", screens.Length));
             foreach (System.Windows.Forms.Screen screen in screens)
             {
                 sb.AppendLine(string.Format("  SCREEN [{0}], Primary={1}, BitsPerPixel={2}, {3}, {4}", screen.DeviceName, screen.Primary, screen.BitsPerPixel, RectangleToInfo("Bounds", screen.Bounds), RectangleToInfo("Working", screen.WorkingArea)));
             }
         }
         catch(Exception exScreens)
         {
             sb.AppendLine(string.Format("ERROR DETECTING SCREENS: {0}", DebugHelper.GetFullExceptionMessage(exScreens)));
         }
         try
         {
             string[] comPorts = System.IO.Ports.SerialPort.GetPortNames();
             if (comPorts != null)
             {
                 sb.AppendLine(string.Format("{0} COM PORT(s) DETECTED.", comPorts.Length));
                 foreach (string com in comPorts)
                 {
                     sb.AppendLine(string.Format("  {0}", com));
                 }
             }
             else
             {
                 sb.AppendLine("NO COM PORTS RETURNED!");
             }
         }
         catch(Exception exCom)
         {
             sb.AppendLine(string.Format("ERROR DETECTING COM PORTS: {0}", DebugHelper.GetFullExceptionMessage(exCom)));
         }
     }
     catch { }
 }
 private object BuildUserInfo()
 {
     var ci = new Microsoft.VisualBasic.Devices.ComputerInfo();
     return new
     {
         MachineName = System.Environment.MachineName,
         OsVersion = System.Environment.OSVersion.VersionString,
         ProcessorCount = System.Environment.ProcessorCount,
         UserDomainName = System.Environment.UserDomainName,
         UserInteractive = System.Environment.UserInteractive,
         UserName = System.Environment.UserName,
         ClrVersion = System.Environment.Version.ToString(4),
         AvailablePhysicalMemory = ci.AvailablePhysicalMemory,
         AvailableVirtualMemory = ci.AvailableVirtualMemory,
         TotalPhysicalMemory = ci.TotalPhysicalMemory,
         TotalVirtualMemory = ci.TotalVirtualMemory,
     };
 }
        public SystemInfo()
        {
            _CreatedDate        = DateTime.UtcNow.ToString();
                _MachineName        = Environment.MachineName;

                _MachineDomain      = Environment.UserDomainName;
                _UserName           = Environment.UserName;
                _OperatingSystem    = Environment.OSVersion.ToString();
                _DotNetVersion      = Environment.Version.ToString();
                _ProcessorCount     = Environment.ProcessorCount.ToString();
                _ProcessorSpeed     = GetPrimaryCpuSpeed().ToString();
                _TotalRam           = new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory;

                _IpAddresses        = new List<string>();

                foreach (IPAddress ip in Dns.GetHostEntry(SystemInformation.ComputerName).AddressList)
                    _IpAddresses.Add(ip.ToString());
        }
        private void TimerUpdate()
        {
            var info = new Microsoft.VisualBasic.Devices.ComputerInfo();

            Func<string> memNowUse = () => Math.Round((info.TotalPhysicalMemory-info.AvailablePhysicalMemory) / Math.Pow(2, 20), 2).ToString();
            Func<string> memTotal = () =>  Math.Round(info.TotalPhysicalMemory / Math.Pow(2, 20), 2).ToString();
            Func<string> memRate = () => Math.Round((Math.Round((info.TotalPhysicalMemory - info.AvailablePhysicalMemory)/Math.Pow(2, 20), 2)/
                                          Math.Round(info.TotalPhysicalMemory/Math.Pow(2, 20), 2)),3)*100+"%";

            var timer = new DispatcherTimer();
            timer.Tick += async (sender, args) =>
                {
                    textBlockMemoryUsage.Text = await Task.Run(memNowUse);
                    TextBlockTotal.Text = await Task.Run(memTotal);
                    textBlockRate.Text = await Task.Run(memRate);
                };
            timer.Interval = new TimeSpan(0, 0, 1);
            timer.Start();
        }
Exemple #11
0
 public Bitmap Draw(string argument)
 {
     ulong bytes;
     if (argument == "total") {
         bytes = new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory;
     }
     else {
         bytes = new Microsoft.VisualBasic.Devices.ComputerInfo().AvailablePhysicalMemory;
     }
     string[] sizes = { "B", "KB", "MB", "GB", "TB", "EB" };
     int magnitude = 0;
     double endresult = bytes;
     while (endresult > 1024.0f) {
         endresult /= 1024.0f;
         magnitude++;
     }
     string outString = "{0}{1:0.00}{2}{3}".With(_prepend, endresult, sizes[magnitude], _append);
     Bitmap image = makeImage(outString);
     return image;
 }
        public PerformanceCounter mem; //メモリ使用量

        public performance()
        {
            core = Environment.ProcessorCount;

            Microsoft.VisualBasic.Devices.ComputerInfo info = new Microsoft.VisualBasic.Devices.ComputerInfo();
            maxmem = info.TotalPhysicalMemory / 1000000;

            all_cpu = new PerformanceCounter("Processor", "% Processor Time", "_Total");
            //thread_cpu[core] = new PerformanceCounter();

            for (int i = 0; i < core; i++)
            {
                thread_cpu[i] = new PerformanceCounter();

                thread_cpu[i].CategoryName = "Processor";
                thread_cpu[i].CounterName = "% Processor Time";
                thread_cpu[i].InstanceName = i.ToString();
            }

            mem = new PerformanceCounter("Process", "Working Set", "_Total");
        }
Exemple #13
0
        public static string username = Environment.UserName; // device username

        #endregion Fields

        #region Methods

        /*
         *  function to get
         *  all the data which cannot be retrieved from environment variables
         *  must be called before the values are used
         */
        public static void getAllData()
        {
            ram = new  Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory.ToString();
            osInfo = new Microsoft.VisualBasic.Devices.ComputerInfo().OSFullName.ToString();
            resolution = System.Windows.Forms.Screen.PrimaryScreen.Bounds.Right.ToString() + " X " + System.Windows.Forms.Screen.PrimaryScreen.Bounds.Bottom.ToString();
            try
            {
                macAddress = GetMacAddress().ToString();
            }
            catch (Exception ex)
            {
                macAddress = "NA";
            }
            baseaddress = getBaseAddress(defaultGateway);    //method to get the baseaddress
            getIpAddress();     //method to get ip address
            rating = getDataFromXML("rating");
            location = getDataFromXML("location");
            if (location.Length == 0) location = "-NA-";
            else location = "[" + location + "]";
            hash = getDataFromXML("hash");
            files_shared = getDataFromXML("files");
        }
        private void SubmitMemoryMetrics(List<Amazon.CloudWatch.Model.MetricDatum> metrics)
        {
            Info("Adding memory metrics");

            var dimensions = new List<Amazon.CloudWatch.Model.Dimension>();
            dimensions.Add(new Amazon.CloudWatch.Model.Dimension()
            {
                Name = "InstanceId",
                Value = _instanceId
            });

            // Why is this in a visual basic namespace?
            var computerInfo = new Microsoft.VisualBasic.Devices.ComputerInfo();

            double availablePhysicalMemory = computerInfo.AvailablePhysicalMemory;
            double totalPhysicalMemory = computerInfo.TotalPhysicalMemory;
            double physicalMemoryUsed = (totalPhysicalMemory - availablePhysicalMemory);
            double physicalMemoryUtilized = (physicalMemoryUsed / totalPhysicalMemory) * 100;

            Info("\tTotal Physical Memory: {0:N0} bytes", totalPhysicalMemory);

            if (_isSubmitPhysicalMemoryUsed)
            {
                Info("\tPhysical Memory Used: {0:N0} bytes", physicalMemoryUsed);
                metrics.Add(new Amazon.CloudWatch.Model.MetricDatum()
                {
                    MetricName = "PhysicalMemoryUsed",
                    Unit = "Bytes",
                    Value = physicalMemoryUsed,
                    Dimensions = dimensions
                });
            }

            if (_isSubmitPhysicalMemoryAvailable)
            {
                Info("\tAvailable Physical Memory: {0:N0} bytes", availablePhysicalMemory);
                metrics.Add(new Amazon.CloudWatch.Model.MetricDatum()
                {
                    MetricName = "PhysicalMemoryAvailable",
                    Unit = "Bytes",
                    Value = availablePhysicalMemory,
                    Dimensions = dimensions
                });
            }

            if (_isSubmitPhysicalMemoryUtilization)
            {
                Info("\tPhysical Memory Utilization: {0:F1}%", physicalMemoryUtilized);
                metrics.Add(new Amazon.CloudWatch.Model.MetricDatum()
                {
                    MetricName = "PhysicalMemoryUtilization",
                    Unit = "Percent",
                    Value = physicalMemoryUtilized,
                    Dimensions = dimensions
                });
            }

            double availableVirtualMemory = computerInfo.AvailableVirtualMemory;
            double totalVirtualMemory = computerInfo.TotalVirtualMemory;
            double virtualMemoryUsed = (totalVirtualMemory - availableVirtualMemory);
            double virtualMemoryUtilized = (virtualMemoryUsed / totalVirtualMemory) * 100;

            Info("\tTotal Virtual Memory: {0:N0} bytes", totalVirtualMemory);

            if (_isSubmitVirtualMemoryUsed)
            {
                Info("\tVirtual Memory Used: {0:N0} bytes", physicalMemoryUsed);
                metrics.Add(new Amazon.CloudWatch.Model.MetricDatum()
                {
                    MetricName = "VirtualMemoryUsed",
                    Unit = "Bytes",
                    Value = virtualMemoryUsed,
                    Dimensions = dimensions
                });
            }

            if (_isSubmitVirtualMemoryAvailable)
            {
                Info("\tAvailable Virtual Memory: {0:N0} bytes", availableVirtualMemory);
                metrics.Add(new Amazon.CloudWatch.Model.MetricDatum()
                {
                    MetricName = "VirtualMemoryAvailable",
                    Unit = "Bytes",
                    Value = availableVirtualMemory,
                    Dimensions = dimensions
                });
            }

            if (_isSubmitVirtualMemoryUtilization)
            {
                Info("\tVirtual Memory Utilization: {0:F1}%", virtualMemoryUtilized);
                metrics.Add(new Amazon.CloudWatch.Model.MetricDatum()
                {
                    MetricName = "VirtualMemoryUtilization",
                    Unit = "Percent",
                    Value = virtualMemoryUtilized,
                    Dimensions = dimensions
                });
            }

            double availableMemory = availablePhysicalMemory + availableVirtualMemory;
            double totalMemory = totalPhysicalMemory + totalVirtualMemory;
            double memoryUsed = (totalMemory - availableMemory);
            double memoryUtilized = (memoryUsed / totalMemory) * 100;

            Info("\tTotal Memory: {0:N0} bytes", totalMemory);

            if (_isSubmitMemoryUsed)
            {
                Info("\tMemory Used: {0:N0} bytes", physicalMemoryUsed);
                metrics.Add(new Amazon.CloudWatch.Model.MetricDatum()
                {
                    MetricName = "MemoryUsed",
                    Unit = "Bytes",
                    Value = memoryUsed,
                    Dimensions = dimensions
                });
            }

            if (_isSubmitMemoryAvailable)
            {
                Info("\tAvailable Memory: {0:N0} bytes", availableMemory);
                metrics.Add(new Amazon.CloudWatch.Model.MetricDatum()
                {
                    MetricName = "MemoryAvailable",
                    Unit = "Bytes",
                    Value = availableMemory,
                    Dimensions = dimensions
                });
            }

            if (_isSubmitMemoryUtilization)
            {
                Info("\tMemory Utilization: {0:F1}%", memoryUtilized);
                metrics.Add(new Amazon.CloudWatch.Model.MetricDatum()
                {
                    MetricName = "MemoryUtilization",
                    Unit = "Percent",
                    Value = memoryUtilized,
                    Dimensions = dimensions
                });
            }
        }
        /// <summary>
        /// This method performs a preanalysis on the path to make sure there's no super high memory usage for a certain area
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="pathPosjes"></param>
        /// <param name="lineSavingProgress"></param>
        /// <param name="debugMessageCallback"></param>
        private void SaveMazeAsImageDeluxePngWithDynamicallyGeneratedPathWithAnalysis(string fileName, IEnumerable<MazePointPos> pathPosjes, Action<int, int> lineSavingProgress, Action<string> debugMessageCallback = null)
        {
            if (debugMessageCallback == null)
            {
                debugMessageCallback = (x) => { };
            }

            debugMessageCallback("Performing path analysis...");

            var pathPointsPerRow = new int[this.Height];
            long totalPathLength = 0;

            for (int i = 0; i < this.Height; i++)
            {
                pathPointsPerRow[i] = 0;
            }

            foreach (var pathPos in pathPosjes)
            {
                pathPointsPerRow[pathPos.Y]++;
                totalPathLength++;
            }

            debugMessageCallback(string.Format("Path analysis completed. Total path length: {0}, this would take up {1}mb.", totalPathLength, Math.Round(totalPathLength * 9.0 / 1024.0 / 1024.0, 2)));

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            var compinfo = new Microsoft.VisualBasic.Devices.ComputerInfo();
            var memoryFree = compinfo.AvailablePhysicalMemory;

            debugMessageCallback(string.Format("Memory free: {0}mb", memoryFree / 1024 / 1024));
            memoryFree = (ulong)(memoryFree * 0.6);
            debugMessageCallback(string.Format("Setting max usage to 60% of this: {0}mb", memoryFree / 1024 / 1024));

            debugMessageCallback("Determining desired rows to generate each path cycle...");
            int rowsPerPathDeterminingCycle = FindTheMinimalRowsToWriteForPng(debugMessageCallback, pathPointsPerRow, memoryFree);

            int tiffTileSize = HybridInnerMap.GridSize;

            if (rowsPerPathDeterminingCycle < tiffTileSize)
            {
                debugMessageCallback(string.Format("We can't work with the default tilesize of '{0}' so we have to scale it back to RowsPerCycle: '{1}'", tiffTileSize, rowsPerPathDeterminingCycle));
                tiffTileSize = rowsPerPathDeterminingCycle;
            }

            debugMessageCallback(string.Format("TiffTileSize: {0}", tiffTileSize));

            debugMessageCallback("Starting generation of Maze Path and saving maze...");

            //Should actually be Width -1 -1 but since we use the full Width it's only once -1
            //This will count the amount of tiles per line so if it's 15 Pixels we still want 2 tiles of 8
            int tilesInWidth = (((this.Width - 1) / tiffTileSize) + 1);

            ImageInfo imi = new ImageInfo(this.Width - 1, this.Height - 1, 8, false); // 8 bits per channel, no alpha
            // open image for writing
            PngWriter png = CreatePngWriter(fileName, imi);
            // add some optional metadata (chunks)
            png.GetMetadata().SetDpi(100.0);
            png.GetMetadata().SetTimeNow(0); // 0 seconds fron now = now
            png.CompLevel = 4;
            //png.GetMetadata().SetText(PngChunkTextVar.KEY_Title, "Just a text image");
            //PngChunk chunk = png.GetMetadata().SetText("my key", "my text .. bla bla");
            //chunk.Priority = true; // this chunk will be written as soon as possible

            //int stepsPerLoop = rowsPerPathDeterminingCycle;

            int partNumber = 0;

            int yChunkStart = 0;
            while (yChunkStart < this.Height - 1)
            {
                //We must use rowsperpathdeterminingcycle here instead of tifftilesize because else you might get into a scenario where the first 4 values and the second 4 values are beneath 1000. But if we would take value 2 to 6 which are also 4 values we would go above 1000.
                //And yes I thought about this pretty well, it needs to be like this because you get forced into reading 500 lines of path from for example 1000 to 1500 where the other thing is 2000, hmmmm...
                //Or not I really need to think about this a bit more. Because if the chunk size is 1000 then you can never end up reading something smaller then that which works because the rowsperpath is always bigger.
                //So yeah, because rows per path is always a multiple or equal to tifftilesize you can never go out of sync becuase no matter what happens, e.g. tifftile = 500 and perpath = 2000. When you're at 2500 you just need to read 500. And you are never forced in reading anything that was
                //not measured. Because you can't end up in having to read somewhere from 1250 to 1750 because of the multiple thingy. Ok I'm quite sure now it needs to be tiffTileSize.
                //
                //Additional note, it always needs to be a multiple of tiffTileSize because we write tiles at a time (we can't write half tiles). So that's why we don't want some stupidly small numbers here.
                int stepsThisLoop = FindTheMaxPathRowsThatWouldFitInMemoryFromHerePng(debugMessageCallback, pathPointsPerRow, yChunkStart, tiffTileSize, memoryFree);

                var yChunkEnd = Math.Min(yChunkStart + stepsThisLoop, this.Height - 1);
                stepsThisLoop = yChunkEnd - yChunkStart;

                var wObtainPathPart = Stopwatch.StartNew();

                //We don't use a ToList here because we do actually know the expected list size beforehand. This way we make sure we don't have to do any internal Array Resizing.
                var expectedPathCount = pathPointsPerRow.Skip(yChunkStart).Take(yChunkEnd - yChunkStart).Sum();
                var pathPointsHere = new List<MazePointPos>(expectedPathCount);
                int currentPathPosPoint = 0;
                foreach (var pathPos in pathPosjes.Where(t => t.Y >= yChunkStart && t.Y < yChunkEnd))
                {
                    pathPointsHere.Add(pathPos);
                    currentPathPosPoint++;
                }
                wObtainPathPart.Stop();

                if (pathPointsHere.Count != expectedPathCount)
                {
                    debugMessageCallback(string.Format("Warning: Something strange is happening where the actual path point count '{0}' is not equal to the expected path point count '{1}' (Maze will still save correctly but it uses more memory then expected)", pathPointsHere.Count, expectedPathCount));
                }

                var wSort = Stopwatch.StartNew();
                pathPointsHere.Sort((first, second) =>
                {
                    if (first.Y == second.Y)
                    {
                        return first.X - second.X;
                    }
                    return first.Y - second.Y;
                });
                wSort.Stop();

                var wGmemorifiedPieceOpMap = Stopwatch.StartNew();

                var innerMapTemporaryInMemoryCopy = new BitArreintjeFastInnerMap(this.Width, stepsThisLoop);

                for (int startY = yChunkStart; startY < yChunkEnd; startY += tiffTileSize)
                {

                    for (int startX = 0; startX < this.Width - 1; startX += tiffTileSize)
                    {
                        int yStart = startY - yChunkStart;
                        int yEnd = yStart + tiffTileSize;

                        for (int y = startY, othery = yStart; othery < yEnd; y++, othery++)
                        {
                            for (int x = startX, otherx = 0; otherx < tiffTileSize; x++, otherx++)
                            {
                                innerMapTemporaryInMemoryCopy[x, othery] = innerMap[x, y];
                            }
                        }
                    }

                }

                wGmemorifiedPieceOpMap.Stop();

                int curpos = 0;

                var wSaveAsImage = Stopwatch.StartNew();

                var yChunkMaxRealEnzo = Math.Min(yChunkEnd, this.Height - 1);

                for (int startY = yChunkStart, y = 0; startY < yChunkMaxRealEnzo; startY += 1, y++)
                {
                    ImageLine iline = new ImageLine(imi);

                    //int xMax = Math.Min(this.Width - 1 - startX, tiffTileSize);
                    int yMax = Math.Min(this.Height - 1 - startY, tiffTileSize);
                    for (int x = 0, otherx = 0; otherx < this.Width - 1; x++, otherx++)
                    {
                        byte r = 0;
                        byte g = 0;
                        byte b = 0;

                        MazePointPos curPathPos;
                        if (curpos < pathPointsHere.Count)
                        {
                            curPathPos = pathPointsHere[curpos];
                            if (curPathPos.X == x && curPathPos.Y == startY)
                            {
                                r = curPathPos.RelativePos;
                                g = (byte)(255 - curPathPos.RelativePos);
                                b = 0;
                                curpos++;
                            }
                            else if (innerMapTemporaryInMemoryCopy[x, y])
                            {
                                r = 255;
                                g = 255;
                                b = 255;
                            }
                        }
                        else if (innerMapTemporaryInMemoryCopy[x, y])
                        {
                            r = 255;
                            g = 255;
                            b = 255;
                        }

                        ImageLineHelper.SetPixel(iline, x, r, g, b);
                    }

                    //var result = tif.WriteEncodedTile(tileNumber, color_ptr, tiffTileSize * tiffTileSize * 3);
                    //var result = tif.WriteTile(color_ptr, startX / tileSize, startY / tileSize, 0, 0);
                    //var result = tif.WriteRawTile(tileNumber, color_ptr, tileSize * tileSize * 3);
                    //Result should not be -1

                    //lineSavingProgress((int)Math.Min((tileNumber + 1L) * tiffTileSize / tilesInWidth, this.Height - 2), this.Height - 2);
                    png.WriteRow(iline, y + yChunkStart);
                    lineSavingProgress(y + yChunkStart, this.Height - 2);
                }

                wSaveAsImage.Stop();

                debugMessageCallback(string.Format("{0}: YChunkStart: {1}, YChunkEnd: {2}, Rows written: {3}, Count: {4}, Time to generate this part: {5} sec, Time to sort this part: {6} sec, Time to put this part in memory: {7}, Time to save this part in the image: {8} sec, Combined time: {9} sec, Size: {10}mb",
                    partNumber,
                    yChunkStart,
                    yChunkEnd,
                    stepsThisLoop,
                    pathPointsHere.Count,
                    Math.Round(wObtainPathPart.Elapsed.TotalSeconds, 2),
                    Math.Round(wSort.Elapsed.TotalSeconds, 2),
                    Math.Round(wGmemorifiedPieceOpMap.Elapsed.TotalSeconds, 2),
                    Math.Round(wSaveAsImage.Elapsed.TotalSeconds, 2),
                    Math.Round(wObtainPathPart.Elapsed.TotalSeconds + wSort.Elapsed.TotalSeconds + wGmemorifiedPieceOpMap.Elapsed.TotalSeconds + wSaveAsImage.Elapsed.TotalSeconds, 2),
                    Math.Round(pathPointsHere.Count * 9.0 / 1024.0 / 1024.0, 3)));
                partNumber++;

                yChunkStart += stepsThisLoop;

                //Do some forced garbage collection since we're finished with this loop
                pathPointsHere = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
            }

            png.End();

            //    tif.FlushData();
            //}
        }
Exemple #16
0
        protected override void OnStart(string[] args)
        {
            try
            {
                var timersend = System.Configuration.ConfigurationManager.AppSettings.Get("TimerSend");
                var logdata   = System.Configuration.ConfigurationManager.AppSettings.Get("LogData");
                _servername = System.Configuration.ConfigurationManager.AppSettings.Get("ServerName");

                var rabbitHost               = System.Configuration.ConfigurationManager.AppSettings.Get("RabbitHost");
                var rabbitPort               = System.Configuration.ConfigurationManager.AppSettings.Get("RabbitPort");
                var rabbitUserName           = System.Configuration.ConfigurationManager.AppSettings.Get("RabbitUserName");
                var rabbitPassword           = System.Configuration.ConfigurationManager.AppSettings.Get("RabbitPassword");
                var rabbitPerformanceDataKey = System.Configuration.ConfigurationManager.AppSettings.Get("RabbitPerformanceDataKey");
                var rabbitPerformanceHighKey = System.Configuration.ConfigurationManager.AppSettings.Get("RabbitPerformanceHighKey");

                var cpuHighPercent  = System.Configuration.ConfigurationManager.AppSettings.Get("CPUHighPercent");
                var ramHighPercent  = System.Configuration.ConfigurationManager.AppSettings.Get("RAMHighPercent");
                var hddHighPercent  = System.Configuration.ConfigurationManager.AppSettings.Get("HDDHighPercent");
                var sendHigh        = System.Configuration.ConfigurationManager.AppSettings.Get("SendHigh");
                var secondHighCheck = System.Configuration.ConfigurationManager.AppSettings.Get("SecondHighCheck");
                var secondCheck     = System.Configuration.ConfigurationManager.AppSettings.Get("SecondCheck");
                _batchFileInit  = System.Configuration.ConfigurationManager.AppSettings.Get("BatchInit");
                _batchFileCheck = System.Configuration.ConfigurationManager.AppSettings.Get("BatchCheck");
                _batchFileClear = System.Configuration.ConfigurationManager.AppSettings.Get("BatchClear");

                if (!string.IsNullOrEmpty(timersend) && !string.IsNullOrEmpty(logdata) && !string.IsNullOrEmpty(_servername) && !string.IsNullOrEmpty(sendHigh) && !string.IsNullOrEmpty(secondCheck))
                {
                    int i = Convert.ToInt32(timersend);
                    _secondCheck     = Convert.ToInt32(secondCheck);
                    _secondHighCheck = Convert.ToDouble(secondHighCheck);
                    if (i > 0 && _secondCheck > 5)
                    {
                        _lstDTO     = new List <InfoData>();
                        _islog      = logdata == "true";
                        _isSendHigh = sendHigh == "true";
                        if (!string.IsNullOrEmpty(rabbitPort))
                        {
                            _rabbitPort = Convert.ToInt32(rabbitPort);
                        }
                        _rabbitHost               = rabbitHost;
                        _rabbitUserName           = rabbitUserName;
                        _rabbitPassword           = rabbitPassword;
                        _rabbitPerformanceDataKey = rabbitPerformanceDataKey;
                        _rabbitPerformanceHighKey = rabbitPerformanceHighKey;

                        _batchClear    = false;
                        _batchRun      = false;
                        _batchComplete = false;

                        if (!string.IsNullOrEmpty(cpuHighPercent))
                        {
                            _cpuHighPercent = Convert.ToSingle(cpuHighPercent);
                        }
                        if (!string.IsNullOrEmpty(ramHighPercent))
                        {
                            _ramHighPercent = Convert.ToSingle(ramHighPercent);
                        }
                        if (!string.IsNullOrEmpty(hddHighPercent))
                        {
                            _hddHighPercent = Convert.ToSingle(hddHighPercent);
                        }
                        if (_cpuHighPercent < 1 || _ramHighPercent < 1 || _hddHighPercent < 1)
                        {
                            throw new Exception("HighPercent fail");
                        }

                        HelperProcess.Init();
                        Microsoft.VisualBasic.Devices.ComputerInfo ci = new Microsoft.VisualBasic.Devices.ComputerInfo();
                        _totalPhysicalMemory = (ci.TotalPhysicalMemory / 1024) * 0.001;
                        _cpuUsage            = new PerformanceCounter("Processor", "% Processor Time", "_Total");
                        _dto = GetInfo();

                        LogInfo("Start service (" + _servername + ")");
                        _timerGet               = new System.Timers.Timer(1000);//1s
                        _timerGet.Elapsed      += TimerGet_Elapsed;
                        _timerGet.Enabled       = true;
                        _timerGetReset          = new System.Timers.Timer(600000);//10p reset
                        _timerGetReset.Enabled  = false;
                        _timerGetReset.Elapsed += TimerGetReset_Elapsed;

                        _timerSend               = new System.Timers.Timer(i);
                        _timerSend.Elapsed      += TimerSend_Elapsed;
                        _timerSend.Enabled       = true;
                        _timerSendReset          = new System.Timers.Timer(600000);//10p reset
                        _timerSendReset.Enabled  = false;
                        _timerSendReset.Elapsed += TimerSendReset_Elapsed;
                    }
                    else
                    {
                        throw new Exception("TimerSend fail");
                    }
                }
                else
                {
                    throw new Exception("Config fail");
                }
            }
            catch (Exception ex)
            {
                LogError(ex);
            }
        }
        /// <summary>
        /// Gathers error information and shows the error window
        /// </summary>
        /// <param name="errorLocation">The location of where the erorr occurred</param>
        /// <param name="errorInfo">Information about the error</param>
        /// <param name="criticalError">If set to true, then the program closes after the error hhas been shown</param>        
        public void ErrorReporting(Exception ex, bool criticalError)
        {
            string clientVersion = null;
            ulong SystemMemory = 0;
            //error information
            try
            {
                if (_formError == null || _formError.IsDisposed)
                    _formError = new FormError();

                _formError.AddInfoLine("Error: " + ex.Message + Environment.NewLine);

                if(ex.InnerException != null)
                    _formError.AddInfoLine("InnerException: " + ex.InnerException.Message + Environment.NewLine);

                _formError.AddInfoLine("Error Occured at: " + Environment.NewLine + ex.StackTrace);

                _formError.AddInfoLine(Environment.NewLine + Environment.NewLine + "Extra error information.  {");
                foreach (DictionaryEntry de in ex.Data)
                {
                    _formError.AddInfoLine(string.Format("      {0} = {1}", de.Key, de.Value));
                }
                _formError.AddInfoLine("}");

                //system information
                _formError.AddInfoLine(Environment.NewLine + "System information.  {");

                if (System.Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE") != null)
                    _formError.AddInfoLine("PROCESSOR_ARCHITECTURE = " + System.Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE"));
                else
                    _formError.AddInfoLine("PROCESSOR_ARCHITECTURE returned null");

                try
                {
                    //_formError.AddInfoLine("System memory amount deteted = " + Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory
                    SystemMemory = new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory;
                }
                catch(Exception exy){} //not interested in the error, so its just absorbed

                _formError.AddInfoLine("System memory ammount = " + SystemMemory.ToString());

                _formError.AddInfoLine("OS version: " + Environment.OSVersion);
                _formError.AddInfoLine("Environment version: " + Environment.Version.ToString());

                RegistryKey installed_versions = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP");
                string[] version_names = installed_versions.GetSubKeyNames();
                //version names start with 'v', eg, 'v3.5' which needs to be trimmed off before conversion
                double Framework = Convert.ToDouble(version_names[version_names.Length - 1].Remove(0, 1), CultureInfo.InvariantCulture);
                RegistryKey newestDotNetKey = installed_versions.OpenSubKey(version_names[version_names.Length - 1]);
                int SP = Convert.ToInt32(newestDotNetKey.GetValue("SP", 0));

                string tmpDotNETversionsString = "";
                foreach (string version in version_names)
                {
                    tmpDotNETversionsString += version + ", ";
                }
                tmpDotNETversionsString = tmpDotNETversionsString.Substring(0, tmpDotNETversionsString.Length - 2);

                _formError.AddInfoLine("Installed .NET versions: " + tmpDotNETversionsString);
                //_formError.AddInfoLine("Newest .NET version:  " + Framework + "  (SP: " + SP.ToString() + ")");

                string DotNetVersionLong = (string)newestDotNetKey.GetValue("Version", "");
                if (DotNetVersionLong == "")
                {
                    //assuming version 4 now
                    RegistryKey v4subkey = installed_versions.OpenSubKey("v4");
                    foreach (string subkey in v4subkey.GetSubKeyNames())
                    {
                        _formError.AddInfoLine(string.Format("Newest .NET version: {0}  ({1}) (SP: {2}", v4subkey.OpenSubKey(subkey).GetValue("Version", "x"), subkey, SP.ToString()));
                    }
                }
                else
                    _formError.AddInfoLine("Newest .NET version: " + Framework + "  (SP: " + SP.ToString() + ")");

                _formError.AddInfoLine("}");

                //basic information
                _formError.AddInfoLine(Environment.NewLine + "FormMain information.  {");
                //if(_formOptions != null)
                //    _formError.AddInfoLine("Client Version: " + _formOptions.GetClientVersion());
                //else
                //    _formError.AddInfoLine("Client Version: _formOptions is null");

                try
                {
                    Assembly ass = Assembly.GetExecutingAssembly();
                    if (ass != null)
                    {
                        FileVersionInfo FVI = FileVersionInfo.GetVersionInfo(ass.Location);
                        clientVersion = string.Format("{0}.{1}.{2}.{3}", FVI.FileMajorPart, FVI.FileMinorPart, FVI.FileBuildPart, FVI.FilePrivatePart);
                    }
                }
                catch (Exception exz){}

                if(clientVersion == null)
                    _formError.AddInfoLine("Client Version: clientVersion was null");
                else
                    _formError.AddInfoLine("Client Version: " + clientVersion);

                //System.Environment.GetEnvironmentVariable("ProgramFiles");

                _formError.AddInfoLine("_TweetList null?: " + (_TweetList == null).ToString());
                _formError.AddInfoLine("_formOptions null? " + (_formOptions == null).ToString());
                _formError.AddInfoLine("_formNews null? " + (_formNews == null).ToString());
                _formError.AddInfoLine("_updateFinished = " + _updateFinished.ToString());

                _formError.AddInfoLine("_globalPackDir = " + _globalPackDir);
                _formError.AddInfoLine("_abortDownload = " + _abortDownload.ToString());
                _formError.AddInfoLine("_loadingSettings = " + _loadingSettings.ToString());
                _formError.AddInfoLine("_offlineMode = " + _offlineMode.ToString());

                _formError.AddInfoLine("}");

                bool hasInternetConnection = true;
                try
                {
                    hasInternetConnection = HasInternetConnection();
                }
                catch(Exception)
                {
                    hasInternetConnection = false;
                }

                if (!hasInternetConnection)
                {
                    _formError.AddInfoLine(Environment.NewLine + "Network Inferfaces" +  "{");
                    NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
                    foreach (NetworkInterface adapter in interfaces)
                    {
                        _formError.AddInfoLine(string.Format("Name: {0}, Description: {1}, Type: {2}, State: {3}", adapter.Name, adapter.Description, adapter.NetworkInterfaceType.ToString(), adapter.OperationalStatus.ToString()));
                    }
                    _formError.AddInfoLine("}");
                }

                if (_formOptions != null)
                {
                    _formError.AddInfoLine(Environment.NewLine + "FormOptions information.  {");
                    List<string> information = _formOptions.formOptionsInformation();

                    foreach (string info in information)
                    {
                        _formError.AddInfoLine(info);
                    }
                    _formError.AddInfoLine("}");
                }

                _formError.CriticalError = criticalError;
                ShowErrorWindow(criticalError);
            }
            catch (Exception ex2)
            {
                MessageBox.Show("Woah hold on a sec. En error occurred in the error handling?. Damm this is bad. Please report this error as soon as possible" + Environment.NewLine + "Error: " + ex2.Message + Environment.NewLine + ex.StackTrace, "An Unlikely error occurred :(", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemple #18
0
        private void InitSystemInfoData()
        {
            listViewSysInfo.BeginUpdate();

            #region System.Environment

            AddEnvironmentItem(EnvGroup, "CommandLine", Environment.CommandLine);
            //AddEnvironmentItem("EnvGroup", "CurrentDirectory", Environment.CurrentDirectory);
            AddEnvironmentItem(EnvGroup, "Is64BitOperatingSystem", Environment.Is64BitOperatingSystem);
            AddEnvironmentItem(EnvGroup, "Is64BitProcess", Environment.Is64BitProcess);
            AddEnvironmentItem(EnvGroup, "MachineName", Environment.MachineName);
            AddEnvironmentItem(EnvGroup, "OSVersion", Environment.OSVersion);
            AddEnvironmentItem(EnvGroup, "ProcessorCount", Environment.ProcessorCount);
            AddEnvironmentItem(EnvGroup, "SystemDirectory", Environment.SystemDirectory);
            AddEnvironmentItem(EnvGroup, "SystemPageSize", Environment.SystemPageSize);
            AddEnvironmentItem(EnvGroup, "TickCount", Environment.TickCount);
            AddEnvironmentItem(EnvGroup, "UserDomainName", Environment.UserDomainName);
            AddEnvironmentItem(EnvGroup, "UserInteractive", Environment.UserInteractive);
            AddEnvironmentItem(EnvGroup, "UserName", Environment.UserName);
            AddEnvironmentItem(EnvGroup, "Version", Environment.Version);
            AddEnvironmentItem(EnvGroup, "WorkingSet", Environment.WorkingSet);

            #endregion

            #region WindowsIdentity

            using (WindowsIdentity identity = WindowsIdentity.GetCurrent())
            {
                string userName = identity.Name;

                WindowsPrincipal principal = new WindowsPrincipal(identity);
                bool isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);

                AddEnvironmentItem(WindowsIdentityGroup, "Name", userName);
                AddEnvironmentItem(WindowsIdentityGroup, "Администратор?", isAdmin);
            }

            #endregion

            #region System.Runtime.InteropServices.RuntimeEnvironment
            AddEnvironmentItem(RuntimeEnvGroup, "SystemConfigurationFile", RuntimeEnvironment.SystemConfigurationFile);
            AddEnvironmentItem(RuntimeEnvGroup, "RuntimeDirectory", RuntimeEnvironment.GetRuntimeDirectory());
            AddEnvironmentItem(RuntimeEnvGroup, "SystemVersion", RuntimeEnvironment.GetSystemVersion());
            #endregion

            #region System.BitConverter
            AddEnvironmentItem(BitConvGroup, "IsLittleEndian", BitConverter.IsLittleEndian);
            #endregion

            #region System.IO.Path
            AddEnvironmentItem(PathGroup, "GetTempPath()", Path.GetTempPath());
            #endregion

            //#region System.Diagnostics.Process
            //Process p = Process.GetCurrentProcess();
            //#endregion

            #region System.Globalization.CultureInfo

            AddEnvironmentItem(CultureGroup, "CurrentCulture", CultureInfo.CurrentCulture.Name);
            AddEnvironmentItem(CultureGroup, "CurrentUICulture", CultureInfo.CurrentUICulture.Name);

            #endregion

            #region System.Windows.Forms.Screen
            var allScreens = Screen.AllScreens.OrderBy(s => !s.Primary).ToArray();
            for (int i=0; i<allScreens.Length; i++)
            {
                var scr = allScreens[i];
                AddEnvironmentItem(
                    ScreenGroup,
                    string.Format("Монитор {0}", i+1),
                    string.Format("{0}x{1}, {2} bits per pixel.", scr.Bounds.Width, scr.Bounds.Height, scr.BitsPerPixel)
                );
            }
            #endregion

            #region Microsoft.VisualBasic.Devices.ComputerInfo
            var computerInfo = new Microsoft.VisualBasic.Devices.ComputerInfo();
            AddEnvironmentItem(ComputerInfoGroup, "AvailablePhysicalMemory", computerInfo.AvailablePhysicalMemory.ToString("N0"));
            AddEnvironmentItem(ComputerInfoGroup, "AvailablePhysicalMemory", computerInfo.AvailablePhysicalMemory.ToString("N0"));
            AddEnvironmentItem(ComputerInfoGroup, "OSFullName", computerInfo.OSFullName);
            AddEnvironmentItem(ComputerInfoGroup, "OSPlatform", computerInfo.OSPlatform);
            AddEnvironmentItem(ComputerInfoGroup, "OSVersion", computerInfo.OSVersion);
            AddEnvironmentItem(ComputerInfoGroup, "TotalPhysicalMemory", computerInfo.TotalPhysicalMemory.ToString("N0"));
            AddEnvironmentItem(ComputerInfoGroup, "TotalVirtualMemory", computerInfo.TotalVirtualMemory.ToString("N0"));
            #endregion

            #region System.Windows.Forms.SystemInformation

            AddEnvironmentItem(SysInfoGroup, "ActiveWindowTrackingDelay", SystemInformation.ActiveWindowTrackingDelay);
            AddEnvironmentItem(SysInfoGroup, "ArrangeDirection", SystemInformation.ArrangeDirection);
            AddEnvironmentItem(SysInfoGroup, "ArrangeStartingPosition", SystemInformation.ArrangeStartingPosition);
            AddEnvironmentItem(SysInfoGroup, "BootMode", SystemInformation.BootMode);
            AddEnvironmentItem(SysInfoGroup, "Border3DSize", SystemInformation.Border3DSize);
            AddEnvironmentItem(SysInfoGroup, "BorderMultiplierFactor", SystemInformation.BorderMultiplierFactor);
            AddEnvironmentItem(SysInfoGroup, "BorderSize", SystemInformation.BorderSize);
            AddEnvironmentItem(SysInfoGroup, "CaptionButtonSize", SystemInformation.CaptionButtonSize);
            AddEnvironmentItem(SysInfoGroup, "CaptionHeight", SystemInformation.CaptionHeight);
            AddEnvironmentItem(SysInfoGroup, "CaretBlinkTime", SystemInformation.CaretBlinkTime);
            AddEnvironmentItem(SysInfoGroup, "CaretWidth", SystemInformation.CaretWidth);
            AddEnvironmentItem(SysInfoGroup, "ComputerName", SystemInformation.ComputerName);
            AddEnvironmentItem(SysInfoGroup, "CursorSize", SystemInformation.CursorSize);
            AddEnvironmentItem(SysInfoGroup, "DbcsEnabled", SystemInformation.DbcsEnabled);
            AddEnvironmentItem(SysInfoGroup, "DebugOS", SystemInformation.DebugOS);
            AddEnvironmentItem(SysInfoGroup, "DoubleClickSize", SystemInformation.DoubleClickSize);
            AddEnvironmentItem(SysInfoGroup, "DoubleClickTime", SystemInformation.DoubleClickTime);
            AddEnvironmentItem(SysInfoGroup, "DragFullWindows", SystemInformation.DragFullWindows);
            AddEnvironmentItem(SysInfoGroup, "DragSize", SystemInformation.DragSize);
            AddEnvironmentItem(SysInfoGroup, "FixedFrameBorderSize", SystemInformation.FixedFrameBorderSize);
            AddEnvironmentItem(SysInfoGroup, "FontSmoothingContrast", SystemInformation.FontSmoothingContrast);
            AddEnvironmentItem(SysInfoGroup, "FontSmoothingType", SystemInformation.FontSmoothingType);
            AddEnvironmentItem(SysInfoGroup, "FrameBorderSize", SystemInformation.FrameBorderSize);
            AddEnvironmentItem(SysInfoGroup, "HighContrast", SystemInformation.HighContrast);
            AddEnvironmentItem(SysInfoGroup, "HorizontalFocusThickness", SystemInformation.HorizontalFocusThickness);
            AddEnvironmentItem(SysInfoGroup, "HorizontalResizeBorderThickness", SystemInformation.HorizontalResizeBorderThickness);
            AddEnvironmentItem(SysInfoGroup, "HorizontalScrollBarArrowWidth", SystemInformation.HorizontalScrollBarArrowWidth);
            AddEnvironmentItem(SysInfoGroup, "HorizontalScrollBarHeight", SystemInformation.HorizontalScrollBarHeight);
            AddEnvironmentItem(SysInfoGroup, "HorizontalScrollBarThumbWidth", SystemInformation.HorizontalScrollBarThumbWidth);
            AddEnvironmentItem(SysInfoGroup, "IconHorizontalSpacing", SystemInformation.IconHorizontalSpacing);
            AddEnvironmentItem(SysInfoGroup, "IconSize", SystemInformation.IconSize);
            AddEnvironmentItem(SysInfoGroup, "IconSpacingSize", SystemInformation.IconSpacingSize);
            AddEnvironmentItem(SysInfoGroup, "IconVerticalSpacing", SystemInformation.IconVerticalSpacing);
            AddEnvironmentItem(SysInfoGroup, "IsActiveWindowTrackingEnabled", SystemInformation.IsActiveWindowTrackingEnabled);
            AddEnvironmentItem(SysInfoGroup, "IsComboBoxAnimationEnabled", SystemInformation.IsComboBoxAnimationEnabled);
            AddEnvironmentItem(SysInfoGroup, "IsDropShadowEnabled", SystemInformation.IsDropShadowEnabled);
            AddEnvironmentItem(SysInfoGroup, "IsFlatMenuEnabled", SystemInformation.IsFlatMenuEnabled);
            AddEnvironmentItem(SysInfoGroup, "IsFontSmoothingEnabled", SystemInformation.IsFontSmoothingEnabled);
            AddEnvironmentItem(SysInfoGroup, "IsHotTrackingEnabled", SystemInformation.IsHotTrackingEnabled);
            AddEnvironmentItem(SysInfoGroup, "IsIconTitleWrappingEnabled", SystemInformation.IsIconTitleWrappingEnabled);
            AddEnvironmentItem(SysInfoGroup, "IsKeyboardPreferred", SystemInformation.IsKeyboardPreferred);
            AddEnvironmentItem(SysInfoGroup, "IsListBoxSmoothScrollingEnabled", SystemInformation.IsListBoxSmoothScrollingEnabled);
            AddEnvironmentItem(SysInfoGroup, "IsMenuAnimationEnabled", SystemInformation.IsMenuAnimationEnabled);
            AddEnvironmentItem(SysInfoGroup, "IsMenuFadeEnabled", SystemInformation.IsMenuFadeEnabled);
            AddEnvironmentItem(SysInfoGroup, "IsMinimizeRestoreAnimationEnabled", SystemInformation.IsMinimizeRestoreAnimationEnabled);
            AddEnvironmentItem(SysInfoGroup, "IsSelectionFadeEnabled", SystemInformation.IsSelectionFadeEnabled);
            AddEnvironmentItem(SysInfoGroup, "IsSnapToDefaultEnabled", SystemInformation.IsSnapToDefaultEnabled);
            AddEnvironmentItem(SysInfoGroup, "IsTitleBarGradientEnabled", SystemInformation.IsTitleBarGradientEnabled);
            AddEnvironmentItem(SysInfoGroup, "IsToolTipAnimationEnabled", SystemInformation.IsToolTipAnimationEnabled);
            AddEnvironmentItem(SysInfoGroup, "KanjiWindowHeight", SystemInformation.KanjiWindowHeight);
            AddEnvironmentItem(SysInfoGroup, "KeyboardDelay", SystemInformation.KeyboardDelay);
            AddEnvironmentItem(SysInfoGroup, "KeyboardSpeed", SystemInformation.KeyboardSpeed);
            AddEnvironmentItem(SysInfoGroup, "MaxWindowTrackSize", SystemInformation.MaxWindowTrackSize);
            AddEnvironmentItem(SysInfoGroup, "MenuAccessKeysUnderlined", SystemInformation.MenuAccessKeysUnderlined);
            AddEnvironmentItem(SysInfoGroup, "MenuBarButtonSize", SystemInformation.MenuBarButtonSize);
            AddEnvironmentItem(SysInfoGroup, "MenuButtonSize", SystemInformation.MenuButtonSize);
            AddEnvironmentItem(SysInfoGroup, "MenuCheckSize", SystemInformation.MenuCheckSize);
            AddEnvironmentItem(SysInfoGroup, "MenuFont", SystemInformation.MenuFont);
            AddEnvironmentItem(SysInfoGroup, "MenuHeight", SystemInformation.MenuHeight);
            AddEnvironmentItem(SysInfoGroup, "MenuShowDelay", SystemInformation.MenuShowDelay);
            AddEnvironmentItem(SysInfoGroup, "MidEastEnabled", SystemInformation.MidEastEnabled);
            AddEnvironmentItem(SysInfoGroup, "MinimizedWindowSize", SystemInformation.MinimizedWindowSize);
            AddEnvironmentItem(SysInfoGroup, "MinimizedWindowSpacingSize", SystemInformation.MinimizedWindowSpacingSize);
            AddEnvironmentItem(SysInfoGroup, "MinimumWindowSize", SystemInformation.MinimumWindowSize);
            AddEnvironmentItem(SysInfoGroup, "MinWindowTrackSize", SystemInformation.MinWindowTrackSize);
            AddEnvironmentItem(SysInfoGroup, "MonitorCount", SystemInformation.MonitorCount);
            AddEnvironmentItem(SysInfoGroup, "MonitorsSameDisplayFormat", SystemInformation.MonitorsSameDisplayFormat);
            AddEnvironmentItem(SysInfoGroup, "MouseButtons", SystemInformation.MouseButtons);
            AddEnvironmentItem(SysInfoGroup, "MouseButtonsSwapped", SystemInformation.MouseButtonsSwapped);
            AddEnvironmentItem(SysInfoGroup, "MouseHoverSize", SystemInformation.MouseHoverSize);
            AddEnvironmentItem(SysInfoGroup, "MouseHoverTime", SystemInformation.MouseHoverTime);
            AddEnvironmentItem(SysInfoGroup, "MousePresent", SystemInformation.MousePresent);
            AddEnvironmentItem(SysInfoGroup, "MouseSpeed", SystemInformation.MouseSpeed);
            AddEnvironmentItem(SysInfoGroup, "MouseWheelPresent", SystemInformation.MouseWheelPresent);
            AddEnvironmentItem(SysInfoGroup, "MouseWheelScrollDelta", SystemInformation.MouseWheelScrollDelta);
            AddEnvironmentItem(SysInfoGroup, "MouseWheelScrollLines", SystemInformation.MouseWheelScrollLines);
            AddEnvironmentItem(SysInfoGroup, "NativeMouseWheelSupport", SystemInformation.NativeMouseWheelSupport);
            AddEnvironmentItem(SysInfoGroup, "Network", SystemInformation.Network);
            AddEnvironmentItem(SysInfoGroup, "PenWindows", SystemInformation.PenWindows);
            AddEnvironmentItem(SysInfoGroup, "PopupMenuAlignment", SystemInformation.PopupMenuAlignment);

            AddEnvironmentItem(SysInfoGroup, "PowerStatus.BatteryChargeStatus", SystemInformation.PowerStatus.BatteryChargeStatus);
            AddEnvironmentItem(SysInfoGroup, "PowerStatus", SystemInformation.PowerStatus.BatteryFullLifetime);
            AddEnvironmentItem(SysInfoGroup, "PowerStatus.BatteryFullLifetime", SystemInformation.PowerStatus.BatteryLifePercent);
            AddEnvironmentItem(SysInfoGroup, "PowerStatus.BatteryLifeRemaining", SystemInformation.PowerStatus.BatteryLifeRemaining);
            AddEnvironmentItem(SysInfoGroup, "PowerStatus.PowerLineStatus", SystemInformation.PowerStatus.PowerLineStatus);

            AddEnvironmentItem(SysInfoGroup, "PrimaryMonitorMaximizedWindowSize", SystemInformation.PrimaryMonitorMaximizedWindowSize);
            AddEnvironmentItem(SysInfoGroup, "PrimaryMonitorSize", SystemInformation.PrimaryMonitorSize);
            AddEnvironmentItem(SysInfoGroup, "RightAlignedMenus", SystemInformation.RightAlignedMenus);
            AddEnvironmentItem(SysInfoGroup, "ScreenOrientation", SystemInformation.ScreenOrientation);
            AddEnvironmentItem(SysInfoGroup, "Secure", SystemInformation.Secure);
            AddEnvironmentItem(SysInfoGroup, "ShowSounds", SystemInformation.ShowSounds);
            AddEnvironmentItem(SysInfoGroup, "SizingBorderWidth", SystemInformation.SizingBorderWidth);
            AddEnvironmentItem(SysInfoGroup, "SmallCaptionButtonSize", SystemInformation.SmallCaptionButtonSize);
            AddEnvironmentItem(SysInfoGroup, "SmallIconSize", SystemInformation.SmallIconSize);
            AddEnvironmentItem(SysInfoGroup, "TerminalServerSession", SystemInformation.TerminalServerSession);
            AddEnvironmentItem(SysInfoGroup, "ToolWindowCaptionButtonSize", SystemInformation.ToolWindowCaptionButtonSize);
            AddEnvironmentItem(SysInfoGroup, "ToolWindowCaptionHeight", SystemInformation.ToolWindowCaptionHeight);
            AddEnvironmentItem(SysInfoGroup, "UIEffectsEnabled", SystemInformation.UIEffectsEnabled);
            AddEnvironmentItem(SysInfoGroup, "UserDomainName", SystemInformation.UserDomainName);
            AddEnvironmentItem(SysInfoGroup, "UserInteractive", SystemInformation.UserInteractive);
            AddEnvironmentItem(SysInfoGroup, "UserName", SystemInformation.UserName);
            AddEnvironmentItem(SysInfoGroup, "VerticalFocusThickness", SystemInformation.VerticalFocusThickness);
            AddEnvironmentItem(SysInfoGroup, "VerticalResizeBorderThickness", SystemInformation.VerticalResizeBorderThickness);
            AddEnvironmentItem(SysInfoGroup, "VerticalScrollBarArrowHeight", SystemInformation.VerticalScrollBarArrowHeight);
            AddEnvironmentItem(SysInfoGroup, "VerticalScrollBarThumbHeight", SystemInformation.VerticalScrollBarThumbHeight);
            AddEnvironmentItem(SysInfoGroup, "VerticalScrollBarWidth", SystemInformation.VerticalScrollBarWidth);
            AddEnvironmentItem(SysInfoGroup, "VirtualScreen", SystemInformation.VirtualScreen);
            AddEnvironmentItem(SysInfoGroup, "WorkingArea", SystemInformation.WorkingArea);

            #endregion

            listViewSysInfo.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
            listViewSysInfo.EndUpdate();
        }
Exemple #19
0
        static double parts;                                                                    //размер разбиения - 1 части

        public static int Run(string inputFile, string outputfile, Mode compressMode)
        {
            bool fileEnd = false;                            // флаг того что мы полностью считали исходный файл

            int maxThreads = Environment.ProcessorCount - 2; //Делаем количество "компрессных" потоков равными количиству ядер и -2 на чтение и запись

            if (maxThreads < 1)
            {
                maxThreads = 1;                 // на 2ух ядерном в любом  случае будет меделенно как не крути, просто подстраховка
            }
            #region ВЫЧИСЛЯЕМ РАЗМЕР БЛОКОВ
            double byteLeft = new FileInfo(inputFile).Length; //размер несчитанного файла
            if (byteLeft > 3.2e10 || byteLeft == 0)
            {
                ConsoleMesseges.FileSizeException(); return(1);
            }                                                                                          //

            double freeRam = new Microsoft.VisualBasic.Devices.ComputerInfo().AvailablePhysicalMemory; // доступная оперативка
            if (byteLeft <= freeRam / (maxThreads * 2))
            {
                parts = byteLeft / (maxThreads * 2);                                         //2 - это доп мемори стрим под каждый поток сжатия
            }
            else
            {
                parts = freeRam / (maxThreads * 2);
            }
            if (parts > 2147483646)
            {
                parts = 2147483646;                     // размер блоков: не  больше чем позволяент инт 2147483647 байт ~ 2Гб
            }
            #region Прогрессбар
            double totalParts    = byteLeft / parts;
            double preparedParts = 1;
            var    progress      = new ProgressBar();
            progress.Report(0);
            Console.WriteLine($"Max Threads: {maxThreads}");
            Console.WriteLine($"Total Parts: {(int)totalParts}");
            #endregion

            /*---------------DEBUG---------------------*/
            //Console.WriteLine($"Operation   = Compress");
            //Console.WriteLine($"InputFile   = {inputFile}");
            //Console.WriteLine($"Outputfile  = {outputfile}");
            //Console.WriteLine($"Work Threads: {maxThreads}");
            //Console.WriteLine($"File size: {byteLeft / 1024 / 1024} Mb");
            //Console.WriteLine($"Free Ram: {freeRam / 1024 / 1024} Mb");
            //Console.WriteLine($"Block size: {parts} Byte");
            //Console.WriteLine($"Block size: {parts / 1024} Kb");
            //Console.WriteLine($"Block size: {parts / 1024 / 1024} Mb");
            /*---------------DEBUG---------------------*/
            #endregion


            #region ReadThread - поток для чтения исходного файла
            Thread readThread = new Thread(() =>
            {
                using (FileStream readStream = new FileStream(inputFile, FileMode.Open))
                {
                    if (compressMode == Mode.Compress)
                    {
                        while (byteLeft != 0)
                        {
                            if (threadsBreak)
                            {
                                break;
                            }
                            if (notProcessedParts.Count < maxThreads + 1) //не закидываем в оперативу больше чем нужно тредам, с запасным
                            {
                                byte[] buf = parts < byteLeft ? new byte[(int)parts] : new byte[(int)byteLeft];
                                readStream.Read(buf, 0, buf.Length);
                                FilePart f = new FilePart(buf);
                                //Console.WriteLine($"Чтение.. {f.partId} size: {f.data.Length} Byte");
                                notProcessedParts.Enqueue(f);
                                byteLeft -= buf.Length;
                            }
                        }
                    }

                    if (compressMode == Mode.Decompress)
                    {
                        byte[] sizeIdBytes = new byte[4];
                        long curentSeek    = 0;

                        readStream.Seek(-sizeIdBytes.Length, SeekOrigin.End);
                        readStream.Read(sizeIdBytes, 0, sizeIdBytes.Length);
                        if (BitConverter.IsLittleEndian)
                        {
                            Array.Reverse(sizeIdBytes);
                        }
                        parts = BitConverter.ToInt32(sizeIdBytes, 0); // размер разжатой 1ой пачки
                        //Console.WriteLine($"part: {parts}\n");

                        readStream.Seek(-sizeIdBytes.Length - 4, SeekOrigin.End);
                        readStream.Read(sizeIdBytes, 0, sizeIdBytes.Length);
                        if (BitConverter.IsLittleEndian)
                        {
                            Array.Reverse(sizeIdBytes);
                        }
                        int partsCount = BitConverter.ToInt32(sizeIdBytes, 0); // количество сжатых блоков в файле

                        for (int i = partsCount; i > 0; i--)
                        {
                            if (threadsBreak)
                            {
                                break;
                            }
                            while (notProcessedParts.Count > maxThreads + 1)
                            {
                                Thread.Sleep(5);
                            }

                            readStream.Seek((-8 * i) - 8, SeekOrigin.End);  //чтение карты

                            readStream.Read(sizeIdBytes, 0, sizeIdBytes.Length);
                            if (BitConverter.IsLittleEndian)
                            {
                                Array.Reverse(sizeIdBytes);
                            }
                            int id = BitConverter.ToInt32(sizeIdBytes, 0);

                            readStream.Read(sizeIdBytes, 0, sizeIdBytes.Length);
                            if (BitConverter.IsLittleEndian)
                            {
                                Array.Reverse(sizeIdBytes);
                            }
                            int dataLenght = BitConverter.ToInt32(sizeIdBytes, 0);
                            //Console.WriteLine($"part {i} : id = {id}; dat = {dataLenght}");

                            byte[] buf = new byte[dataLenght];
                            readStream.Seek(curentSeek, SeekOrigin.Begin); //чтение частей
                            readStream.Read(buf, 0, dataLenght);
                            curentSeek += dataLenght;
                            FilePart f  = new FilePart(id, buf);
                            //Console.WriteLine($"Чтение.. {f.partId} size: {f.data.Length} Byte\n");
                            notProcessedParts.Enqueue(f);
                        }
                    }
                }
                fileEnd = true; //файл дочитан
            });
            #endregion


            #region WriteThread - поток для записи сжатого файла
            Thread writeThread = new Thread(() =>
            {
                using (FileStream writeStream = new FileStream(outputfile, FileMode.Create))
                {
                    if (compressMode == Mode.Compress)
                    {
                        byte[] partOfMap         = new byte[4];
                        Queue <byte[]> sizeAndId = new Queue <byte[]>(); //сохраняем в нее размер сжатых пачек и их айди для дальнейшей записи в "карту" файла.
                        while (true)
                        {
                            if (threadsBreak)
                            {
                                break;
                            }
                            if (fileEnd && notProcessedParts.Count == 0 && processedParts.Count == 0 && workerThreads == 0)
                            {
                                break;
                            }
                            if (processedParts.Count != 0)
                            {
                                if (processedParts.TryDequeue(out FilePart f))
                                {
                                    partOfMap = BitConverter.GetBytes(f.partId);
                                    if (BitConverter.IsLittleEndian)
                                    {
                                        Array.Reverse(partOfMap);                                  // это id
                                    }
                                    sizeAndId.Enqueue(partOfMap);

                                    partOfMap = BitConverter.GetBytes(f.data.Length);
                                    if (BitConverter.IsLittleEndian)
                                    {
                                        Array.Reverse(partOfMap);                                  // потом сжатый размер
                                    }
                                    sizeAndId.Enqueue(partOfMap);

                                    writeStream.Write(f.data, 0, f.data.Length);
                                    //Console.WriteLine($"Запись.. {f.partId}"); //DEBUG
                                    f.Dispose();

                                    progress.Report(preparedParts / totalParts);     //прогрессбар
                                    preparedParts++;
                                }
                            }
                        }

                        partOfMap = BitConverter.GetBytes(sizeAndId.Count / 2);         // предпоследние 4 байта будет количество всех сжатых 4х байтных пачек содержащих id
                        if (BitConverter.IsLittleEndian)
                        {
                            Array.Reverse(partOfMap);
                        }
                        //Console.WriteLine($"Vsego id and size: {sizeAndId.Count}"); //DEBUG
                        sizeAndId.Enqueue(partOfMap);

                        partOfMap = BitConverter.GetBytes((int)parts);         // последние 4 байта размер 1ой распакованной части
                        if (BitConverter.IsLittleEndian)
                        {
                            Array.Reverse(partOfMap);
                        }
                        sizeAndId.Enqueue(partOfMap);

                        while (sizeAndId.Count != 0)
                        {
                            byte[] a = sizeAndId.Peek();
                            writeStream.Write(sizeAndId.Dequeue(), 0, 4);
                        }
                    }


                    if (compressMode == Mode.Decompress)
                    {
                        while (true)
                        {
                            if ((fileEnd && notProcessedParts.Count == 0 && processedParts.Count == 0 && workerThreads == 0) || threadsBreak)
                            {
                                break;
                            }
                            if (processedParts.Count != 0)
                            {
                                if (processedParts.TryDequeue(out FilePart f))
                                {
                                    writeStream.Seek((int)parts * (f.partId - 1), SeekOrigin.Begin);

                                    writeStream.Write(f.data, 0, f.data.Length);
                                    //Console.WriteLine($"Запись.. {f.partId}");
                                    f.Dispose();
                                    progress.Report(preparedParts / totalParts);     //прогрессбар
                                    preparedParts++;
                                }
                            }
                        }
                    }
                    threadsDone.Set();
                }
            });
            #endregion

            readThread.Start();
            writeThread.Start();

            #region Workthreads
            for (int i = 0; i < maxThreads; i++)
            {
                Thread workThread = new Thread(() =>
                {
                    lock (workerThreadsLocker) workerThreads++;

                    while (true)
                    {
                        if (threadsBreak)
                        {
                            break;
                        }
                        if (fileEnd && notProcessedParts.Count == 0)
                        {
                            break;
                        }
                        if (notProcessedParts.Count != 0)
                        {
                            if (notProcessedParts.TryDequeue(out FilePart f))
                            {
                                //Console.WriteLine($"Сжатие - {f.partId}"); //DEBUG
                                if (compressMode == Mode.Compress)
                                {
                                    Compressing <FilePart>(f);
                                }
                                else if (compressMode == Mode.Decompress)
                                {
                                    Decompressing <FilePart>(f);
                                }
                            }
                        }
                    }
                    lock (workerThreadsLocker) workerThreads--;
                });
                workThread.Start();
            }
            #endregion

            if (threadsBreak)
            {
                progress.Dispose(); return(1);
            }
            else
            {
                threadsDone.WaitOne();
                progress.Dispose();
                if (compressMode == Mode.Compress)
                {
                    Console.WriteLine("Compressing Done!");
                }
                if (compressMode == Mode.Decompress)
                {
                    Console.WriteLine("Decompressing Done!");
                }
            }
            return(0);
        }
Exemple #20
0
        /// <summary>
        /// This method performs a preanalysis on the path to make sure there's no super high memory usage for a certain area
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="pathPosjes"></param>
        /// <param name="lineSavingProgress"></param>
        /// <param name="debugMessageCallback"></param>
        private void SaveMazeAsImageDeluxePngWithDynamicallyGeneratedPathWithAnalysis(string fileName, IEnumerable <MazePointPos> pathPosjes, Action <int, int> lineSavingProgress, Action <string> debugMessageCallback = null)
        {
            if (debugMessageCallback == null)
            {
                debugMessageCallback = (x) => { };
            }

            debugMessageCallback("Performing path analysis...");

            var  pathPointsPerRow = new int[this.Height];
            long totalPathLength  = 0;

            for (int i = 0; i < this.Height; i++)
            {
                pathPointsPerRow[i] = 0;
            }

            foreach (var pathPos in pathPosjes)
            {
                pathPointsPerRow[pathPos.Y]++;
                totalPathLength++;
            }

            debugMessageCallback(string.Format("Path analysis completed. Total path length: {0}, this would take up {1}mb.", totalPathLength, Math.Round(totalPathLength * 9.0 / 1024.0 / 1024.0, 2)));

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            var compinfo   = new Microsoft.VisualBasic.Devices.ComputerInfo();
            var memoryFree = compinfo.AvailablePhysicalMemory;

            debugMessageCallback(string.Format("Memory free: {0}mb", memoryFree / 1024 / 1024));
            memoryFree = (ulong)(memoryFree * 0.6);
            debugMessageCallback(string.Format("Setting max usage to 60% of this: {0}mb", memoryFree / 1024 / 1024));

            debugMessageCallback("Determining desired rows to generate each path cycle...");
            int rowsPerPathDeterminingCycle = FindTheMinimalRowsToWriteForPng(debugMessageCallback, pathPointsPerRow, memoryFree);



            int tiffTileSize = HybridInnerMap.GridSize;

            if (rowsPerPathDeterminingCycle < tiffTileSize)
            {
                debugMessageCallback(string.Format("We can't work with the default tilesize of '{0}' so we have to scale it back to RowsPerCycle: '{1}'", tiffTileSize, rowsPerPathDeterminingCycle));
                tiffTileSize = rowsPerPathDeterminingCycle;
            }

            debugMessageCallback(string.Format("TiffTileSize: {0}", tiffTileSize));

            debugMessageCallback("Starting generation of Maze Path and saving maze...");

            //Should actually be Width -1 -1 but since we use the full Width it's only once -1
            //This will count the amount of tiles per line so if it's 15 Pixels we still want 2 tiles of 8
            int tilesInWidth = (((this.Width - 1) / tiffTileSize) + 1);



            ImageInfo imi = new ImageInfo(this.Width - 1, this.Height - 1, 8, false); // 8 bits per channel, no alpha
            // open image for writing
            PngWriter png = CreatePngWriter(fileName, imi);

            // add some optional metadata (chunks)
            png.GetMetadata().SetDpi(100.0);
            png.GetMetadata().SetTimeNow(0); // 0 seconds fron now = now
            png.CompLevel = 4;
            //png.GetMetadata().SetText(PngChunkTextVar.KEY_Title, "Just a text image");
            //PngChunk chunk = png.GetMetadata().SetText("my key", "my text .. bla bla");
            //chunk.Priority = true; // this chunk will be written as soon as possible



            //int stepsPerLoop = rowsPerPathDeterminingCycle;

            int partNumber = 0;

            int yChunkStart = 0;

            while (yChunkStart < this.Height - 1)
            {
                //We must use rowsperpathdeterminingcycle here instead of tifftilesize because else you might get into a scenario where the first 4 values and the second 4 values are beneath 1000. But if we would take value 2 to 6 which are also 4 values we would go above 1000.
                //And yes I thought about this pretty well, it needs to be like this because you get forced into reading 500 lines of path from for example 1000 to 1500 where the other thing is 2000, hmmmm...
                //Or not I really need to think about this a bit more. Because if the chunk size is 1000 then you can never end up reading something smaller then that which works because the rowsperpath is always bigger.
                //So yeah, because rows per path is always a multiple or equal to tifftilesize you can never go out of sync becuase no matter what happens, e.g. tifftile = 500 and perpath = 2000. When you're at 2500 you just need to read 500. And you are never forced in reading anything that was
                //not measured. Because you can't end up in having to read somewhere from 1250 to 1750 because of the multiple thingy. Ok I'm quite sure now it needs to be tiffTileSize.
                //
                //Additional note, it always needs to be a multiple of tiffTileSize because we write tiles at a time (we can't write half tiles). So that's why we don't want some stupidly small numbers here.
                int stepsThisLoop = FindTheMaxPathRowsThatWouldFitInMemoryFromHerePng(debugMessageCallback, pathPointsPerRow, yChunkStart, tiffTileSize, memoryFree);

                var yChunkEnd = Math.Min(yChunkStart + stepsThisLoop, this.Height - 1);
                stepsThisLoop = yChunkEnd - yChunkStart;

                var wObtainPathPart = Stopwatch.StartNew();

                //We don't use a ToList here because we do actually know the expected list size beforehand. This way we make sure we don't have to do any internal Array Resizing.
                var expectedPathCount   = pathPointsPerRow.Skip(yChunkStart).Take(yChunkEnd - yChunkStart).Sum();
                var pathPointsHere      = new List <MazePointPos>(expectedPathCount);
                int currentPathPosPoint = 0;
                foreach (var pathPos in pathPosjes.Where(t => t.Y >= yChunkStart && t.Y < yChunkEnd))
                {
                    pathPointsHere.Add(pathPos);
                    currentPathPosPoint++;
                }
                wObtainPathPart.Stop();

                if (pathPointsHere.Count != expectedPathCount)
                {
                    debugMessageCallback(string.Format("Warning: Something strange is happening where the actual path point count '{0}' is not equal to the expected path point count '{1}' (Maze will still save correctly but it uses more memory then expected)", pathPointsHere.Count, expectedPathCount));
                }

                var wSort = Stopwatch.StartNew();
                pathPointsHere.Sort((first, second) =>
                {
                    if (first.Y == second.Y)
                    {
                        return(first.X - second.X);
                    }
                    return(first.Y - second.Y);
                });
                wSort.Stop();



                var wGmemorifiedPieceOpMap = Stopwatch.StartNew();

                var innerMapTemporaryInMemoryCopy = new BitArreintjeFastInnerMap(this.Width, stepsThisLoop);



                for (int startY = yChunkStart; startY < yChunkEnd; startY += tiffTileSize)
                {
                    for (int startX = 0; startX < this.Width - 1; startX += tiffTileSize)
                    {
                        int yStart = startY - yChunkStart;
                        int yEnd   = yStart + tiffTileSize;

                        for (int y = startY, othery = yStart; othery < yEnd; y++, othery++)
                        {
                            for (int x = startX, otherx = 0; otherx < tiffTileSize; x++, otherx++)
                            {
                                innerMapTemporaryInMemoryCopy[x, othery] = innerMap[x, y];
                            }
                        }
                    }
                }



                wGmemorifiedPieceOpMap.Stop();



                int curpos = 0;

                var wSaveAsImage = Stopwatch.StartNew();

                var yChunkMaxRealEnzo = Math.Min(yChunkEnd, this.Height - 1);

                for (int startY = yChunkStart, y = 0; startY < yChunkMaxRealEnzo; startY += 1, y++)
                {
                    ImageLine iline = new ImageLine(imi);

                    //int xMax = Math.Min(this.Width - 1 - startX, tiffTileSize);
                    int yMax = Math.Min(this.Height - 1 - startY, tiffTileSize);
                    for (int x = 0, otherx = 0; otherx < this.Width - 1; x++, otherx++)
                    {
                        byte r = 0;
                        byte g = 0;
                        byte b = 0;

                        MazePointPos curPathPos;
                        if (curpos < pathPointsHere.Count)
                        {
                            curPathPos = pathPointsHere[curpos];
                            if (curPathPos.X == x && curPathPos.Y == startY)
                            {
                                r = curPathPos.RelativePos;
                                g = (byte)(255 - curPathPos.RelativePos);
                                b = 0;
                                curpos++;
                            }
                            else if (innerMapTemporaryInMemoryCopy[x, y])
                            {
                                r = 255;
                                g = 255;
                                b = 255;
                            }
                        }
                        else if (innerMapTemporaryInMemoryCopy[x, y])
                        {
                            r = 255;
                            g = 255;
                            b = 255;
                        }



                        ImageLineHelper.SetPixel(iline, x, r, g, b);
                    }



                    //var result = tif.WriteEncodedTile(tileNumber, color_ptr, tiffTileSize * tiffTileSize * 3);
                    //var result = tif.WriteTile(color_ptr, startX / tileSize, startY / tileSize, 0, 0);
                    //var result = tif.WriteRawTile(tileNumber, color_ptr, tileSize * tileSize * 3);
                    //Result should not be -1

                    //lineSavingProgress((int)Math.Min((tileNumber + 1L) * tiffTileSize / tilesInWidth, this.Height - 2), this.Height - 2);
                    png.WriteRow(iline, y + yChunkStart);
                    lineSavingProgress(y + yChunkStart, this.Height - 2);
                }



                wSaveAsImage.Stop();

                debugMessageCallback(string.Format("{0}: YChunkStart: {1}, YChunkEnd: {2}, Rows written: {3}, Count: {4}, Time to generate this part: {5} sec, Time to sort this part: {6} sec, Time to put this part in memory: {7}, Time to save this part in the image: {8} sec, Combined time: {9} sec, Size: {10}mb",
                                                   partNumber,
                                                   yChunkStart,
                                                   yChunkEnd,
                                                   stepsThisLoop,
                                                   pathPointsHere.Count,
                                                   Math.Round(wObtainPathPart.Elapsed.TotalSeconds, 2),
                                                   Math.Round(wSort.Elapsed.TotalSeconds, 2),
                                                   Math.Round(wGmemorifiedPieceOpMap.Elapsed.TotalSeconds, 2),
                                                   Math.Round(wSaveAsImage.Elapsed.TotalSeconds, 2),
                                                   Math.Round(wObtainPathPart.Elapsed.TotalSeconds + wSort.Elapsed.TotalSeconds + wGmemorifiedPieceOpMap.Elapsed.TotalSeconds + wSaveAsImage.Elapsed.TotalSeconds, 2),
                                                   Math.Round(pathPointsHere.Count * 9.0 / 1024.0 / 1024.0, 3)));
                partNumber++;

                yChunkStart += stepsThisLoop;

                //Do some forced garbage collection since we're finished with this loop
                pathPointsHere = null;
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
            }

            png.End();

            //    tif.FlushData();
            //}
        }
        /// <summary>
        /// This method performs a preanalysis on the path to make sure there's no super high memory usage for a certain area
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="pathPosjes"></param>
        /// <param name="lineSavingProgress"></param>
        /// <param name="debugMessageCallback"></param>
        private void SaveMazeAsImageDeluxeTiffWithDynamicallyGeneratedPathWithAnalysis(String fileName, IEnumerable<MazePointPos> pathPosjes, Action<int, int> lineSavingProgress, Action<string> debugMessageCallback = null)
        {
            if (debugMessageCallback == null)
            {
                debugMessageCallback = (x) => { };
            }

            debugMessageCallback("Performing path analysis...");

            var pathPointsPerRow = new int[this.Height];
            long totalPathLength = 0;

            for (int i = 0; i < this.Height; i++)
            {
                pathPointsPerRow[i] = 0;
            }

            foreach (var pathPos in pathPosjes)
            {
                pathPointsPerRow[pathPos.Y]++;
                totalPathLength++;
            }

            debugMessageCallback(string.Format("Path analysis completed. Total path length: {0}, this would take up {1}mb.", totalPathLength, Math.Round(totalPathLength * 9.0 / 1024.0 / 1024.0, 2)));

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();

            var compinfo = new Microsoft.VisualBasic.Devices.ComputerInfo();
            var memoryFree = compinfo.AvailablePhysicalMemory;

            debugMessageCallback(string.Format("Memory free: {0}mb", memoryFree / 1024 / 1024));
            memoryFree = (ulong)(memoryFree * 0.6);
            debugMessageCallback(string.Format("Setting max usage to 60% of this: {0}mb", memoryFree / 1024 / 1024));

            debugMessageCallback("Determining desired rows to generate each path cycle...");
            int rowsPerPathDeterminingCycle = FindTheMinimalRowsToWrite(debugMessageCallback, pathPointsPerRow, memoryFree);

            int tiffTileSize = HybridInnerMap.GridSize;

            if (rowsPerPathDeterminingCycle < tiffTileSize)
            {
                debugMessageCallback(string.Format("We can't work with the default tilesize of '{0}' so we have to scale it back to RowsPerCycle: '{1}'", tiffTileSize, rowsPerPathDeterminingCycle));
                tiffTileSize = rowsPerPathDeterminingCycle;
            }

            debugMessageCallback(string.Format("TiffTileSize: {0}", tiffTileSize));

            debugMessageCallback("Starting generation of Maze Path and saving maze...");

            //Should actually be Width -1 -1 but since we use the full Width it's only once -1
            //This will count the amount of tiles per line so if it's 15 Pixels we still want 2 tiles of 8
            int tilesInWidth = (((this.Width - 1) / tiffTileSize) + 1);

            using (var tif = Tiff.Open(fileName, "w"))
            {
                if (tif == null)
                {
                    throw new InvalidOperationException("Tif file could not be opened. It is probably in use: " + fileName);
                }

                tif.SetField(TiffTag.IMAGEWIDTH, this.Width - 1);
                tif.SetField(TiffTag.IMAGELENGTH, this.Height - 1);
                tif.SetField(TiffTag.BITSPERSAMPLE, 8);
                tif.SetField(TiffTag.SAMPLESPERPIXEL, 3);
                tif.SetField(TiffTag.PHOTOMETRIC, Photometric.RGB);
                tif.SetField(TiffTag.PLANARCONFIG, PlanarConfig.CONTIG);
                //tif.SetField(TiffTag.ROWSPERSTRIP, 1);
                tif.SetField(TiffTag.COMPRESSION, Compression.LZW);

                tif.SetField(TiffTag.TILEWIDTH, tiffTileSize);
                tif.SetField(TiffTag.TILELENGTH, tiffTileSize);

                byte[] color_ptr = new byte[tiffTileSize * tiffTileSize * 3];

                //int stepsPerLoop = rowsPerPathDeterminingCycle;

                int tileNumber = 0;
                int partNumber = 0;

                int yChunkStart = 0;
                while (yChunkStart < this.Height - 1)
                {
                    //We must use rowsperpathdeterminingcycle here instead of tifftilesize because else you might get into a scenario where the first 4 values and the second 4 values are beneath 1000. But if we would take value 2 to 6 which are also 4 values we would go above 1000.
                    //And yes I thought about this pretty well, it needs to be like this because you get forced into reading 500 lines of path from for example 1000 to 1500 where the other thing is 2000, hmmmm...
                    //Or not I really need to think about this a bit more. Because if the chunk size is 1000 then you can never end up reading something smaller then that which works because the rowsperpath is always bigger.
                    //So yeah, because rows per path is always a multiple or equal to tifftilesize you can never go out of sync becuase no matter what happens, e.g. tifftile = 500 and perpath = 2000. When you're at 2500 you just need to read 500. And you are never forced in reading anything that was
                    //not measured. Because you can't end up in having to read somewhere from 1250 to 1750 because of the multiple thingy. Ok I'm quite sure now it needs to be tiffTileSize.
                    //
                    //Additional note, it always needs to be a multiple of tiffTileSize because we write tiles at a time (we can't write half tiles). So that's why we don't want some stupidly small numbers here.
                    int stepsThisLoop = FindTheMaxPathRowsThatWouldFitInMemoryFromHere(debugMessageCallback, pathPointsPerRow, yChunkStart, tiffTileSize, memoryFree);

                    var yChunkEnd = Math.Min(yChunkStart + stepsThisLoop, this.Height - 1);
                    stepsThisLoop = yChunkEnd - yChunkStart;

                    var wObtainPathPart = Stopwatch.StartNew();

                    //We don't use a ToList here because we do actually know the expected list size beforehand. This way we make sure we don't have to do any internal Array Resizing.
                    var expectedPathCount = pathPointsPerRow.Skip(yChunkStart).Take(yChunkEnd - yChunkStart).Sum();
                    var pathPointsHere = new List<MazePointPos>(expectedPathCount);
                    int currentPathPosPoint = 0;
                    foreach (var pathPos in pathPosjes.Where(t => t.Y >= yChunkStart && t.Y < yChunkEnd))
                    {
                        pathPointsHere.Add(pathPos);
                        currentPathPosPoint++;
                    }
                    wObtainPathPart.Stop();

                    if (pathPointsHere.Count != expectedPathCount)
                    {
                        debugMessageCallback(string.Format("Warning: Something strange is happening where the actual path point count '{0}' is not equal to the expected path point count '{1}' (Maze will still save correctly but it uses more memory then expected)", pathPointsHere.Count, expectedPathCount));
                    }

                    var wSort = Stopwatch.StartNew();
                    pathPointsHere.Sort((first, second) =>
                    {
                        int firstXTile = first.X / tiffTileSize;
                        int firstYTile = first.Y / tiffTileSize;

                        int secondXTile = second.X / tiffTileSize;
                        int secondYTile = second.Y / tiffTileSize;

                        if (firstYTile != secondYTile)
                        {
                            return firstYTile - secondYTile;
                        }
                        if (firstXTile != secondXTile)
                        {
                            return firstXTile - secondXTile;
                        }

                        int firstXInTile = first.X % tiffTileSize;
                        int firstYInTile = first.Y % tiffTileSize;

                        int secondXInTile = second.X % tiffTileSize;
                        int secondYInTile = second.Y % tiffTileSize;

                        if (firstYInTile == secondYInTile)
                        {
                            return firstXInTile - secondXInTile;
                        }
                        return firstYInTile - secondYInTile;
                    });
                    wSort.Stop();

                    int curpos = 0;

                    var wSaveAsImage = Stopwatch.StartNew();

                    for (int startY = yChunkStart; startY < yChunkEnd; startY += tiffTileSize)
                    {

                        for (int startX = 0; startX < this.Width - 1; startX += tiffTileSize)
                        {
                            int xMax = Math.Min(this.Width - 1 - startX, tiffTileSize);
                            int yMax = Math.Min(this.Height - 1 - startY, tiffTileSize);

                            for (int y = startY, othery = 0; othery < tiffTileSize; y++, othery++)
                            {
                                for (int x = startX, otherx = 0; otherx < tiffTileSize; x++, otherx++)
                                {
                                    byte r = 0;
                                    byte g = 0;
                                    byte b = 0;
                                    if (otherx >= xMax || othery >= yMax)
                                    {
                                        //Not sure if needed but I'd like to ensure that any additional bytes
                                        //written to the image are 0.
                                    }
                                    else
                                    {
                                        MazePointPos curPathPos;
                                        if (curpos < pathPointsHere.Count)
                                        {
                                            curPathPos = pathPointsHere[curpos];
                                            if (curPathPos.X == x && curPathPos.Y == y)
                                            {
                                                r = curPathPos.RelativePos;
                                                g = (byte)(255 - curPathPos.RelativePos);
                                                b = 0;
                                                curpos++;
                                            }
                                            else if (this.innerMap[x, y])
                                            {
                                                r = 255;
                                                g = 255;
                                                b = 255;
                                            }
                                        }
                                        else if (this.innerMap[x, y])
                                        {
                                            r = 255;
                                            g = 255;
                                            b = 255;
                                        }
                                    }
                                    int startPos = othery * tiffTileSize * 3 + otherx * 3;

                                    color_ptr[startPos + 0] = r;
                                    color_ptr[startPos + 1] = g;
                                    color_ptr[startPos + 2] = b;
                                }

                            }

                            var result = tif.WriteEncodedTile(tileNumber, color_ptr, tiffTileSize * tiffTileSize * 3);
                            //var result = tif.WriteTile(color_ptr, startX / tileSize, startY / tileSize, 0, 0);
                            //var result = tif.WriteRawTile(tileNumber, color_ptr, tileSize * tileSize * 3);
                            //Result should not be -1

                            lineSavingProgress((int)Math.Min((tileNumber + 1L) * tiffTileSize / tilesInWidth, this.Height - 2), this.Height - 2);

                            tileNumber++;
                        }

                    }
                    wSaveAsImage.Stop();

                    debugMessageCallback(string.Format("{0}: YChunkStart: {1}, YChunkEnd: {2}, Rows written: {3}, Count: {4}, Time to generate this part: {5} sec, Time to sort this part: {6} sec, Time to save this part in the image: {7} sec, Combined time: {8} sec, Size: {9}mb",
                        partNumber,
                        yChunkStart,
                        yChunkEnd,
                        stepsThisLoop,
                        pathPointsHere.Count,
                        Math.Round(wObtainPathPart.Elapsed.TotalSeconds, 2),
                        Math.Round(wSort.Elapsed.TotalSeconds, 2),
                        Math.Round(wSaveAsImage.Elapsed.TotalSeconds, 2),
                        Math.Round(wObtainPathPart.Elapsed.TotalSeconds + wSort.Elapsed.TotalSeconds + wSaveAsImage.Elapsed.TotalSeconds, 2),
                        Math.Round(pathPointsHere.Count * 9.0 / 1024.0 / 1024.0, 3)));
                    partNumber++;

                    yChunkStart += stepsThisLoop;

                    //Do some forced garbage collection since we're finished with this loop
                    pathPointsHere = null;
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    GC.Collect();
                }

                tif.FlushData();
            }
        }
Exemple #22
0
        /// <summary>
        /// 檢查SN序號
        /// </summary>
        /// <param name="RegUserName">註冊的使用者名稱</param>
        /// <param name="SerialNumber">序號</param>
        /// <returns></returns>
        public bool checkSN(string RegUserName, string SerialNumber)
        {
            string[] bufcode = SerialNumber.Split('-');

            if (bufcode.Length != 5)
            {
                return(false);
            }


            //step 1
            if (bufcode[0].Substring(0, 2) != "IN")
            {
                return(false);
            }



            //step 2
            Microsoft.VisualBasic.Devices.ComputerInfo ComputerInfo = new Microsoft.VisualBasic.Devices.ComputerInfo();
            string OS = GetOSCode(ComputerInfo.OSFullName.ToString(), false);

            if (OS != bufcode[1])
            {
                return(false);
            }


            //step 3

            if (UserNameCode(RegUserName) != bufcode[2])
            {
                return(false);
            }

            //step 4
            string NIC;

            string[] networkcard = GetAdapter();
            if (networkcard != null)
            {
                NIC = GetNICCode(networkcard[0], false);
            }
            else
            {
                NIC = GetNICCode("Other NIC", false);;
            }

            if (NIC != bufcode[3])
            {
                return(false);
            }

            //step 5
            if (CheckCode(bufcode[0], bufcode[1], bufcode[2], bufcode[3]) != bufcode[4])
            {
                return(false);
            }

            return(true); //若全部都符合則傳回True
        }
Exemple #23
0
        static void Main()
        {
            // Avoid antiviruses
            if (FindEnemies.EnemiesHere())
            {
                goto End;
            }

            // detect virtual machines
            if (!Disk.HaveDDrive() || !Disk.HaveEnoughSpace())
            {
                goto End;
            }

            // detect virtual machines manufacturer
            using (var searcher = new System.Management.ManagementObjectSearcher("Select * from Win32_ComputerSystem"))
            {
                using (var items = searcher.Get())
                {
                    foreach (var item in items)
                    {
                        string manufacturer = item["Manufacturer"].ToString().ToLower();
                        if ((manufacturer == "microsoft corporation" && item["Model"].ToString().ToUpperInvariant().Contains("VIRTUAL")) ||
                            manufacturer.Contains("vmware") ||
                            item["Model"].ToString() == "VirtualBox")
                        {
                            goto End;
                        }
                    }
                }
            }

            // detect virtual network interface
            System.Net.NetworkInformation.NetworkInterface[] interfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
            foreach (System.Net.NetworkInformation.NetworkInterface n in interfaces)
            {
                if (n.OperationalStatus == System.Net.NetworkInformation.OperationalStatus.Up)
                {
                    string MAC = n.GetPhysicalAddress().ToString();
                    if (MAC.StartsWith("005056") || MAC.StartsWith("000C29") || MAC.StartsWith("001C14") || MAC.StartsWith("000569") || MAC.StartsWith("080027"))
                    {
                        goto End;
                    }
                }
            }
            // end

            // check total RAM, if it's less than 1GB, the computer is virtual, then check the processor
            ulong totalMem = new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory;

            if (totalMem / 1048576 < 1000)
            {
                goto End;
            }

            if (Environment.ProcessorCount % 2 != 0)
            {
                goto End;
            }

            if (!Connection.HaveInternet())
            {
                goto End;
            }

            AppRun abc = new AppRun();

            Application.Run();

End:
            string b = "c";
        }
Exemple #24
0
 public static void test()
 {
     Microsoft.VisualBasic.Devices.ComputerInfo toto = new Microsoft.VisualBasic.Devices.ComputerInfo();
     ulong totalRam = toto.TotalPhysicalMemory;
 }
        private void PopulateRuntimeInfo(EnvironmentInfo info)
        {
#if NETSTANDARD
            info.OSName       = GetOSName(RuntimeInformation.OSDescription);
            info.OSVersion    = GetVersion(RuntimeInformation.OSDescription)?.ToString();
            info.Architecture = RuntimeInformation.OSArchitecture.ToString();
            info.Data["FrameworkDescription"] = RuntimeInformation.FrameworkDescription;
            info.Data["ProcessArchitecture"]  = RuntimeInformation.ProcessArchitecture;
#endif

            try {
#if NET45 || NETSTANDARD1_5
                info.MachineName = Environment.MachineName;
#elif !PORTABLE && !NETSTANDARD1_2
                Process process = Process.GetCurrentProcess();
                info.MachineName = process.MachineName;
#else
                info.MachineName = Guid.NewGuid().ToString("N");
#endif
            } catch (Exception ex) {
                _log.FormattedWarn(typeof(DefaultEnvironmentInfoCollector), "Unable to get machine name. Error message: {0}", ex.Message);
            }

#if !PORTABLE && !NETSTANDARD1_2
#if NETSTANDARD
            Microsoft.Extensions.PlatformAbstractions.PlatformServices computerInfo = null;
#elif NET45
            Microsoft.VisualBasic.Devices.ComputerInfo computerInfo = null;
#endif

            try {
#if NETSTANDARD
                computerInfo = Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default;
#elif NET45
                computerInfo = new Microsoft.VisualBasic.Devices.ComputerInfo();
#endif
            } catch (Exception ex) {
                _log.FormattedWarn(typeof(DefaultEnvironmentInfoCollector), "Unable to get computer info. Error message: {0}", ex.Message);
            }

#if NETSTANDARD || NET45
            if (computerInfo == null)
            {
                return;
            }
#endif

            try {
#if NETSTANDARD
                info.RuntimeVersion = computerInfo.Application.RuntimeFramework.Version.ToString();
                info.Data["ApplicationBasePath"] = computerInfo.Application.ApplicationBasePath;
                info.Data["ApplicationName"]     = computerInfo.Application.ApplicationName;
                info.Data["RuntimeFramework"]    = computerInfo.Application.RuntimeFramework.FullName;
#elif NET45
                info.OSName         = computerInfo.OSFullName;
                info.OSVersion      = computerInfo.OSVersion;
                info.RuntimeVersion = Environment.Version.ToString();
                info.Architecture   = Is64BitOperatingSystem() ? "x64" : "x86";
#endif
            } catch (Exception ex) {
                _log.FormattedWarn(typeof(DefaultEnvironmentInfoCollector), "Unable to get populate runtime info. Error message: {0}", ex.Message);
            }
#endif
        }
Exemple #26
0
        public static void Main(string[] args)
        {
            int choice = 0;

            while (choice != -1) {
                Console.WriteLine ("");
                Console.WriteLine ("Tool kit");
                Console.WriteLine ("What do you want to do?");
                Console.WriteLine ("1. Get system configuration.");
                Console.WriteLine ("2. Check if current user is admin.");
                Console.WriteLine ("3. Block a website (User need to be an admin to do this).");
                Console.WriteLine ("4. Unblock a website.");
                Console.WriteLine ("5. Encypt a File with Password.");
                Console.WriteLine ("6. Decypt a File with Password");
                Console.WriteLine ("-1. quit.");
                Console.WriteLine ("");

                choice = Convert.ToInt32 (Console.ReadLine ());
                switch (choice) {
                case 1:
                    try {
                        Console.WriteLine ("Your current OS and its Version: {0}", Environment.OSVersion.ToString ());

                        var memory_size_byte = new Microsoft.VisualBasic.Devices.ComputerInfo ().TotalPhysicalMemory;
                        var memory_size_gb = memory_size_byte/ (1024 * 1024 * 1024);
                        Console.WriteLine ("You have {0} GB of RAM", memory_size_gb);

                        Console.WriteLine("CPU: {0}", GetCPUInfo());

                        if (AntivirusInstalled () == false)
                            Console.WriteLine ("Don't have any antivirus software installed!");
                        else
                            Console.WriteLine ("Have antivirus software installed!");

                    } catch (Exception e) {
                        Console.WriteLine (e.ToString ());
                    }
                    break;
                case 2:
                    if (IsAdmin ())
                        Console.WriteLine ("Current user is an admin");
                    else
                        Console.WriteLine ("Current user is not an admin");
                    break;
                case 3:
                    if (IsAdmin ()) {
                        Console.WriteLine ("Input the webite site you want to block:");
                        var site = Console.ReadLine ();
                        BlockWebsite (site);
                    } else {
                        Console.WriteLine ("Current user is not an admin therefore you can't use this");
                    }

                    break;
                case 4:
                    if (IsAdmin ()) {
                        Console.WriteLine ("Input the website site you want to unblock:");
                        var new_site = Console.ReadLine ();
                        UnblockWebsite (new_site);
                    } else {
                        Console.WriteLine ("Current user is not an admin therefore you can't use this");
                    }
                    break;
                case 5:
                    Console.WriteLine ("Input the file name that you want to encrpt(including path, and there should be content in the file!):");
                    var input_file_name = Console.ReadLine ();
                    Console.WriteLine ("Input password for the file: (8 characters) ");
                    var password = Console.ReadLine ();

                    EncryptFile (input_file_name, password);
                    break;
                case 6:
                    Console.WriteLine ("Input the file name that you want to decrpt(including path):");
                    var file_name = Console.ReadLine ();
                    Console.WriteLine ("Input password for the file: ");
                    var password1 = Console.ReadLine ();

                    DecryptFile (file_name, password1);
                    break;
                default:
                    Console.WriteLine ("No such choice.");
                    break;
                }
            }
        }
Exemple #27
0
        public static long GetAvailableMemory()
        {
            var freeRAM = new Microsoft.VisualBasic.Devices.ComputerInfo().AvailablePhysicalMemory;

            return((long)(freeRAM));
        }
Exemple #28
0
        private void InitSystemInfoData()
        {
            listViewSysInfo.BeginUpdate();

            #region System.Environment

            AddEnvironmentItem(EnvGroup, "CommandLine", Environment.CommandLine);
            //AddEnvironmentItem("EnvGroup", "CurrentDirectory", Environment.CurrentDirectory);
            AddEnvironmentItem(EnvGroup, "Is64BitOperatingSystem", Environment.Is64BitOperatingSystem);
            AddEnvironmentItem(EnvGroup, "Is64BitProcess", Environment.Is64BitProcess);
            AddEnvironmentItem(EnvGroup, "MachineName", Environment.MachineName);
            AddEnvironmentItem(EnvGroup, "OSVersion", Environment.OSVersion);
            AddEnvironmentItem(EnvGroup, "ProcessorCount", Environment.ProcessorCount);
            AddEnvironmentItem(EnvGroup, "SystemDirectory", Environment.SystemDirectory);
            AddEnvironmentItem(EnvGroup, "SystemPageSize", Environment.SystemPageSize);
            AddEnvironmentItem(EnvGroup, "TickCount", Environment.TickCount);
            AddEnvironmentItem(EnvGroup, "UserDomainName", Environment.UserDomainName);
            AddEnvironmentItem(EnvGroup, "UserInteractive", Environment.UserInteractive);
            AddEnvironmentItem(EnvGroup, "UserName", Environment.UserName);
            AddEnvironmentItem(EnvGroup, "Version", Environment.Version);
            AddEnvironmentItem(EnvGroup, "WorkingSet", Environment.WorkingSet);

            #endregion

            #region WindowsIdentity

            using (WindowsIdentity identity = WindowsIdentity.GetCurrent())
            {
                string userName = identity.Name;

                WindowsPrincipal principal = new WindowsPrincipal(identity);
                bool             isAdmin   = principal.IsInRole(WindowsBuiltInRole.Administrator);

                AddEnvironmentItem(WindowsIdentityGroup, "Name", userName);
                AddEnvironmentItem(WindowsIdentityGroup, "Администратор?", isAdmin);
            }

            #endregion

            #region System.Runtime.InteropServices.RuntimeEnvironment
            AddEnvironmentItem(RuntimeEnvGroup, "SystemConfigurationFile", RuntimeEnvironment.SystemConfigurationFile);
            AddEnvironmentItem(RuntimeEnvGroup, "RuntimeDirectory", RuntimeEnvironment.GetRuntimeDirectory());
            AddEnvironmentItem(RuntimeEnvGroup, "SystemVersion", RuntimeEnvironment.GetSystemVersion());
            #endregion

            #region System.Runtime.InteropServices.RuntimeInformation
            AddEnvironmentItem(RuntimeInfoGroup, "FrameworkDescription", RuntimeInformation.FrameworkDescription);
            AddEnvironmentItem(RuntimeInfoGroup, "OSArchitecture", RuntimeInformation.OSArchitecture);
            AddEnvironmentItem(RuntimeInfoGroup, "OSDescription", RuntimeInformation.OSDescription);
            AddEnvironmentItem(RuntimeInfoGroup, "ProcessArchitecture", RuntimeInformation.ProcessArchitecture);
            #endregion

            #region System.BitConverter
            AddEnvironmentItem(BitConvGroup, "IsLittleEndian", BitConverter.IsLittleEndian);
            #endregion

            #region System.Numerics.Vector
            AddEnvironmentItem(VectorGroup, "Count (size of SIMD register)", Vector <byte> .Count);
            #endregion

            #region System.IO.Path
            AddEnvironmentItem(PathGroup, "GetTempPath()", Path.GetTempPath());
            #endregion

            //#region System.Diagnostics.Process
            //Process p = Process.GetCurrentProcess();
            //#endregion

            #region System.Globalization.CultureInfo

            AddEnvironmentItem(CultureGroup, "CurrentCulture", CultureInfo.CurrentCulture.Name);
            AddEnvironmentItem(CultureGroup, "CurrentUICulture", CultureInfo.CurrentUICulture.Name);

            #endregion

            #region System.Windows.Forms.Screen
            var allScreens = Screen.AllScreens.OrderBy(s => !s.Primary).ToArray();
            for (int i = 0; i < allScreens.Length; i++)
            {
                var scr = allScreens[i];
                AddEnvironmentItem(
                    ScreenGroup,
                    string.Format("Монитор {0}", i + 1),
                    string.Format("{0}x{1}, {2} bits per pixel.", scr.Bounds.Width, scr.Bounds.Height, scr.BitsPerPixel)
                    );
            }
            #endregion

            #region Microsoft.VisualBasic.Devices.ComputerInfo
            var computerInfo = new Microsoft.VisualBasic.Devices.ComputerInfo();
            AddEnvironmentItem(ComputerInfoGroup, "AvailablePhysicalMemory", computerInfo.AvailablePhysicalMemory.ToString("N0"));
            AddEnvironmentItem(ComputerInfoGroup, "AvailablePhysicalMemory", computerInfo.AvailablePhysicalMemory.ToString("N0"));
            AddEnvironmentItem(ComputerInfoGroup, "OSFullName", computerInfo.OSFullName);
            AddEnvironmentItem(ComputerInfoGroup, "OSPlatform", computerInfo.OSPlatform);
            AddEnvironmentItem(ComputerInfoGroup, "OSVersion", computerInfo.OSVersion);
            AddEnvironmentItem(ComputerInfoGroup, "TotalPhysicalMemory", computerInfo.TotalPhysicalMemory.ToString("N0"));
            AddEnvironmentItem(ComputerInfoGroup, "TotalVirtualMemory", computerInfo.TotalVirtualMemory.ToString("N0"));
            #endregion

            #region System.Windows.Forms.SystemInformation

            AddEnvironmentItem(SysInfoGroup, "ActiveWindowTrackingDelay", SystemInformation.ActiveWindowTrackingDelay);
            AddEnvironmentItem(SysInfoGroup, "ArrangeDirection", SystemInformation.ArrangeDirection);
            AddEnvironmentItem(SysInfoGroup, "ArrangeStartingPosition", SystemInformation.ArrangeStartingPosition);
            AddEnvironmentItem(SysInfoGroup, "BootMode", SystemInformation.BootMode);
            AddEnvironmentItem(SysInfoGroup, "Border3DSize", SystemInformation.Border3DSize);
            AddEnvironmentItem(SysInfoGroup, "BorderMultiplierFactor", SystemInformation.BorderMultiplierFactor);
            AddEnvironmentItem(SysInfoGroup, "BorderSize", SystemInformation.BorderSize);
            AddEnvironmentItem(SysInfoGroup, "CaptionButtonSize", SystemInformation.CaptionButtonSize);
            AddEnvironmentItem(SysInfoGroup, "CaptionHeight", SystemInformation.CaptionHeight);
            AddEnvironmentItem(SysInfoGroup, "CaretBlinkTime", SystemInformation.CaretBlinkTime);
            AddEnvironmentItem(SysInfoGroup, "CaretWidth", SystemInformation.CaretWidth);
            AddEnvironmentItem(SysInfoGroup, "ComputerName", SystemInformation.ComputerName);
            AddEnvironmentItem(SysInfoGroup, "CursorSize", SystemInformation.CursorSize);
            AddEnvironmentItem(SysInfoGroup, "DbcsEnabled", SystemInformation.DbcsEnabled);
            AddEnvironmentItem(SysInfoGroup, "DebugOS", SystemInformation.DebugOS);
            AddEnvironmentItem(SysInfoGroup, "DoubleClickSize", SystemInformation.DoubleClickSize);
            AddEnvironmentItem(SysInfoGroup, "DoubleClickTime", SystemInformation.DoubleClickTime);
            AddEnvironmentItem(SysInfoGroup, "DragFullWindows", SystemInformation.DragFullWindows);
            AddEnvironmentItem(SysInfoGroup, "DragSize", SystemInformation.DragSize);
            AddEnvironmentItem(SysInfoGroup, "FixedFrameBorderSize", SystemInformation.FixedFrameBorderSize);
            AddEnvironmentItem(SysInfoGroup, "FontSmoothingContrast", SystemInformation.FontSmoothingContrast);
            AddEnvironmentItem(SysInfoGroup, "FontSmoothingType", SystemInformation.FontSmoothingType);
            AddEnvironmentItem(SysInfoGroup, "FrameBorderSize", SystemInformation.FrameBorderSize);
            AddEnvironmentItem(SysInfoGroup, "HighContrast", SystemInformation.HighContrast);
            AddEnvironmentItem(SysInfoGroup, "HorizontalFocusThickness", SystemInformation.HorizontalFocusThickness);
            AddEnvironmentItem(SysInfoGroup, "HorizontalResizeBorderThickness", SystemInformation.HorizontalResizeBorderThickness);
            AddEnvironmentItem(SysInfoGroup, "HorizontalScrollBarArrowWidth", SystemInformation.HorizontalScrollBarArrowWidth);
            AddEnvironmentItem(SysInfoGroup, "HorizontalScrollBarHeight", SystemInformation.HorizontalScrollBarHeight);
            AddEnvironmentItem(SysInfoGroup, "HorizontalScrollBarThumbWidth", SystemInformation.HorizontalScrollBarThumbWidth);
            AddEnvironmentItem(SysInfoGroup, "IconHorizontalSpacing", SystemInformation.IconHorizontalSpacing);
            AddEnvironmentItem(SysInfoGroup, "IconSize", SystemInformation.IconSize);
            AddEnvironmentItem(SysInfoGroup, "IconSpacingSize", SystemInformation.IconSpacingSize);
            AddEnvironmentItem(SysInfoGroup, "IconVerticalSpacing", SystemInformation.IconVerticalSpacing);
            AddEnvironmentItem(SysInfoGroup, "IsActiveWindowTrackingEnabled", SystemInformation.IsActiveWindowTrackingEnabled);
            AddEnvironmentItem(SysInfoGroup, "IsComboBoxAnimationEnabled", SystemInformation.IsComboBoxAnimationEnabled);
            AddEnvironmentItem(SysInfoGroup, "IsDropShadowEnabled", SystemInformation.IsDropShadowEnabled);
            AddEnvironmentItem(SysInfoGroup, "IsFlatMenuEnabled", SystemInformation.IsFlatMenuEnabled);
            AddEnvironmentItem(SysInfoGroup, "IsFontSmoothingEnabled", SystemInformation.IsFontSmoothingEnabled);
            AddEnvironmentItem(SysInfoGroup, "IsHotTrackingEnabled", SystemInformation.IsHotTrackingEnabled);
            AddEnvironmentItem(SysInfoGroup, "IsIconTitleWrappingEnabled", SystemInformation.IsIconTitleWrappingEnabled);
            AddEnvironmentItem(SysInfoGroup, "IsKeyboardPreferred", SystemInformation.IsKeyboardPreferred);
            AddEnvironmentItem(SysInfoGroup, "IsListBoxSmoothScrollingEnabled", SystemInformation.IsListBoxSmoothScrollingEnabled);
            AddEnvironmentItem(SysInfoGroup, "IsMenuAnimationEnabled", SystemInformation.IsMenuAnimationEnabled);
            AddEnvironmentItem(SysInfoGroup, "IsMenuFadeEnabled", SystemInformation.IsMenuFadeEnabled);
            AddEnvironmentItem(SysInfoGroup, "IsMinimizeRestoreAnimationEnabled", SystemInformation.IsMinimizeRestoreAnimationEnabled);
            AddEnvironmentItem(SysInfoGroup, "IsSelectionFadeEnabled", SystemInformation.IsSelectionFadeEnabled);
            AddEnvironmentItem(SysInfoGroup, "IsSnapToDefaultEnabled", SystemInformation.IsSnapToDefaultEnabled);
            AddEnvironmentItem(SysInfoGroup, "IsTitleBarGradientEnabled", SystemInformation.IsTitleBarGradientEnabled);
            AddEnvironmentItem(SysInfoGroup, "IsToolTipAnimationEnabled", SystemInformation.IsToolTipAnimationEnabled);
            AddEnvironmentItem(SysInfoGroup, "KanjiWindowHeight", SystemInformation.KanjiWindowHeight);
            AddEnvironmentItem(SysInfoGroup, "KeyboardDelay", SystemInformation.KeyboardDelay);
            AddEnvironmentItem(SysInfoGroup, "KeyboardSpeed", SystemInformation.KeyboardSpeed);
            AddEnvironmentItem(SysInfoGroup, "MaxWindowTrackSize", SystemInformation.MaxWindowTrackSize);
            AddEnvironmentItem(SysInfoGroup, "MenuAccessKeysUnderlined", SystemInformation.MenuAccessKeysUnderlined);
            AddEnvironmentItem(SysInfoGroup, "MenuBarButtonSize", SystemInformation.MenuBarButtonSize);
            AddEnvironmentItem(SysInfoGroup, "MenuButtonSize", SystemInformation.MenuButtonSize);
            AddEnvironmentItem(SysInfoGroup, "MenuCheckSize", SystemInformation.MenuCheckSize);
            AddEnvironmentItem(SysInfoGroup, "MenuFont", SystemInformation.MenuFont);
            AddEnvironmentItem(SysInfoGroup, "MenuHeight", SystemInformation.MenuHeight);
            AddEnvironmentItem(SysInfoGroup, "MenuShowDelay", SystemInformation.MenuShowDelay);
            AddEnvironmentItem(SysInfoGroup, "MidEastEnabled", SystemInformation.MidEastEnabled);
            AddEnvironmentItem(SysInfoGroup, "MinimizedWindowSize", SystemInformation.MinimizedWindowSize);
            AddEnvironmentItem(SysInfoGroup, "MinimizedWindowSpacingSize", SystemInformation.MinimizedWindowSpacingSize);
            AddEnvironmentItem(SysInfoGroup, "MinimumWindowSize", SystemInformation.MinimumWindowSize);
            AddEnvironmentItem(SysInfoGroup, "MinWindowTrackSize", SystemInformation.MinWindowTrackSize);
            AddEnvironmentItem(SysInfoGroup, "MonitorCount", SystemInformation.MonitorCount);
            AddEnvironmentItem(SysInfoGroup, "MonitorsSameDisplayFormat", SystemInformation.MonitorsSameDisplayFormat);
            AddEnvironmentItem(SysInfoGroup, "MouseButtons", SystemInformation.MouseButtons);
            AddEnvironmentItem(SysInfoGroup, "MouseButtonsSwapped", SystemInformation.MouseButtonsSwapped);
            AddEnvironmentItem(SysInfoGroup, "MouseHoverSize", SystemInformation.MouseHoverSize);
            AddEnvironmentItem(SysInfoGroup, "MouseHoverTime", SystemInformation.MouseHoverTime);
            AddEnvironmentItem(SysInfoGroup, "MousePresent", SystemInformation.MousePresent);
            AddEnvironmentItem(SysInfoGroup, "MouseSpeed", SystemInformation.MouseSpeed);
            AddEnvironmentItem(SysInfoGroup, "MouseWheelPresent", SystemInformation.MouseWheelPresent);
            AddEnvironmentItem(SysInfoGroup, "MouseWheelScrollDelta", SystemInformation.MouseWheelScrollDelta);
            AddEnvironmentItem(SysInfoGroup, "MouseWheelScrollLines", SystemInformation.MouseWheelScrollLines);
            AddEnvironmentItem(SysInfoGroup, "NativeMouseWheelSupport", SystemInformation.NativeMouseWheelSupport);
            AddEnvironmentItem(SysInfoGroup, "Network", SystemInformation.Network);
            AddEnvironmentItem(SysInfoGroup, "PenWindows", SystemInformation.PenWindows);
            AddEnvironmentItem(SysInfoGroup, "PopupMenuAlignment", SystemInformation.PopupMenuAlignment);

            AddEnvironmentItem(SysInfoGroup, "PowerStatus.BatteryChargeStatus", SystemInformation.PowerStatus.BatteryChargeStatus);
            AddEnvironmentItem(SysInfoGroup, "PowerStatus", SystemInformation.PowerStatus.BatteryFullLifetime);
            AddEnvironmentItem(SysInfoGroup, "PowerStatus.BatteryFullLifetime", SystemInformation.PowerStatus.BatteryLifePercent);
            AddEnvironmentItem(SysInfoGroup, "PowerStatus.BatteryLifeRemaining", SystemInformation.PowerStatus.BatteryLifeRemaining);
            AddEnvironmentItem(SysInfoGroup, "PowerStatus.PowerLineStatus", SystemInformation.PowerStatus.PowerLineStatus);

            AddEnvironmentItem(SysInfoGroup, "PrimaryMonitorMaximizedWindowSize", SystemInformation.PrimaryMonitorMaximizedWindowSize);
            AddEnvironmentItem(SysInfoGroup, "PrimaryMonitorSize", SystemInformation.PrimaryMonitorSize);
            AddEnvironmentItem(SysInfoGroup, "RightAlignedMenus", SystemInformation.RightAlignedMenus);
            AddEnvironmentItem(SysInfoGroup, "ScreenOrientation", SystemInformation.ScreenOrientation);
            AddEnvironmentItem(SysInfoGroup, "Secure", SystemInformation.Secure);
            AddEnvironmentItem(SysInfoGroup, "ShowSounds", SystemInformation.ShowSounds);
            AddEnvironmentItem(SysInfoGroup, "SizingBorderWidth", SystemInformation.SizingBorderWidth);
            AddEnvironmentItem(SysInfoGroup, "SmallCaptionButtonSize", SystemInformation.SmallCaptionButtonSize);
            AddEnvironmentItem(SysInfoGroup, "SmallIconSize", SystemInformation.SmallIconSize);
            AddEnvironmentItem(SysInfoGroup, "TerminalServerSession", SystemInformation.TerminalServerSession);
            AddEnvironmentItem(SysInfoGroup, "ToolWindowCaptionButtonSize", SystemInformation.ToolWindowCaptionButtonSize);
            AddEnvironmentItem(SysInfoGroup, "ToolWindowCaptionHeight", SystemInformation.ToolWindowCaptionHeight);
            AddEnvironmentItem(SysInfoGroup, "UIEffectsEnabled", SystemInformation.UIEffectsEnabled);
            AddEnvironmentItem(SysInfoGroup, "UserDomainName", SystemInformation.UserDomainName);
            AddEnvironmentItem(SysInfoGroup, "UserInteractive", SystemInformation.UserInteractive);
            AddEnvironmentItem(SysInfoGroup, "UserName", SystemInformation.UserName);
            AddEnvironmentItem(SysInfoGroup, "VerticalFocusThickness", SystemInformation.VerticalFocusThickness);
            AddEnvironmentItem(SysInfoGroup, "VerticalResizeBorderThickness", SystemInformation.VerticalResizeBorderThickness);
            AddEnvironmentItem(SysInfoGroup, "VerticalScrollBarArrowHeight", SystemInformation.VerticalScrollBarArrowHeight);
            AddEnvironmentItem(SysInfoGroup, "VerticalScrollBarThumbHeight", SystemInformation.VerticalScrollBarThumbHeight);
            AddEnvironmentItem(SysInfoGroup, "VerticalScrollBarWidth", SystemInformation.VerticalScrollBarWidth);
            AddEnvironmentItem(SysInfoGroup, "VirtualScreen", SystemInformation.VirtualScreen);
            AddEnvironmentItem(SysInfoGroup, "WorkingArea", SystemInformation.WorkingArea);

            #endregion

            listViewSysInfo.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);
            listViewSysInfo.EndUpdate();
        }
        private void PopulateRuntimeInfo(EnvironmentInfo info) {
#if NETSTANDARD
            info.OSName = GetOSName(RuntimeInformation.OSDescription);
            info.OSVersion = GetVersion(RuntimeInformation.OSDescription)?.ToString();
            info.Architecture = RuntimeInformation.OSArchitecture.ToString();
            info.Data["FrameworkDescription"] = RuntimeInformation.FrameworkDescription;
            info.Data["ProcessArchitecture"] = RuntimeInformation.ProcessArchitecture;
#endif

            try {
#if NET45 || NETSTANDARD1_5
                info.MachineName = Environment.MachineName;
#elif !PORTABLE && !NETSTANDARD1_2
                Process process = Process.GetCurrentProcess();
                info.MachineName = process.MachineName;
#else
                info.MachineName = Guid.NewGuid().ToString("N");
#endif
            } catch (Exception ex) {
                _log.FormattedInfo(typeof(DefaultEnvironmentInfoCollector), "Unable to get machine name. Error message: {0}", ex.Message);
            }

#if !PORTABLE && !NETSTANDARD1_2
#if NETSTANDARD
            Microsoft.Extensions.PlatformAbstractions.PlatformServices computerInfo = null;
#elif NET45
            Microsoft.VisualBasic.Devices.ComputerInfo computerInfo = null;
#endif

            try {
#if NETSTANDARD
                computerInfo = Microsoft.Extensions.PlatformAbstractions.PlatformServices.Default;
#elif NET45
                computerInfo = new Microsoft.VisualBasic.Devices.ComputerInfo();
#endif
            } catch (Exception ex) {
                _log.FormattedInfo(typeof(DefaultEnvironmentInfoCollector), "Unable to get computer info. Error message: {0}", ex.Message);
            }

#if NETSTANDARD || NET45
            if (computerInfo == null)
                return;
#endif

            try {
#if NETSTANDARD
                info.RuntimeVersion = computerInfo.Application.RuntimeFramework.Version.ToString();
                info.Data["ApplicationBasePath"] = computerInfo.Application.ApplicationBasePath;
                info.Data["ApplicationName"] = computerInfo.Application.ApplicationName;
                info.Data["RuntimeFramework"] = computerInfo.Application.RuntimeFramework.FullName;
#elif NET45
                info.OSName = computerInfo.OSFullName;
                info.OSVersion = computerInfo.OSVersion;
                info.Architecture = Is64BitOperatingSystem() ? "x64" : "x86";
                info.RuntimeVersion = Environment.Version.ToString();
#endif
            } catch (Exception ex) {
                _log.FormattedInfo(typeof(DefaultEnvironmentInfoCollector), "Unable to get populate runtime info. Error message: {0}", ex.Message);
            }
#endif
        }
Exemple #30
0
 /// <summary>
 /// Gets the total memory of the system
 /// </summary>
 /// <returns>Total memory in bytes</returns>
 private UInt64 GetTotalMemory()
 {
     #if __MonoCS__
         //mono specific code
         var pc = new PerformanceCounter("Mono Memory", "Total Physical Memory");
         return (ulong)pc.RawValue;
     #else
     var computerInfo = new Microsoft.VisualBasic.Devices.ComputerInfo();
         return computerInfo.TotalPhysicalMemory;
     #endif
 }
        private void PopulateMemoryInfo(EnvironmentInfo info) {
#if !PORTABLE && !NETSTANDARD1_2
            try {
                Process process = Process.GetCurrentProcess();
                info.ProcessMemorySize = process.PrivateMemorySize64;
            } catch (Exception ex) {
                _log.FormattedInfo(typeof(DefaultEnvironmentInfoCollector), "Unable to get process memory size. Error message: {0}", ex.Message);
            }
#endif

#if NET45
            try {
                if (IsMonoRuntime) {
                    if (PerformanceCounterCategory.Exists("Mono Memory")) {
                        var totalPhysicalMemory = new PerformanceCounter("Mono Memory", "Total Physical Memory");
                        info.TotalPhysicalMemory = Convert.ToInt64(totalPhysicalMemory.RawValue);

                        var availablePhysicalMemory = new PerformanceCounter("Mono Memory", "Available Physical Memory"); //mono 4.0+
                        info.AvailablePhysicalMemory = Convert.ToInt64(availablePhysicalMemory.RawValue);
                    }
                } else {
                    var computerInfo = new Microsoft.VisualBasic.Devices.ComputerInfo();
                    info.TotalPhysicalMemory = Convert.ToInt64(computerInfo.TotalPhysicalMemory);
                    info.AvailablePhysicalMemory = Convert.ToInt64(computerInfo.AvailablePhysicalMemory);
                }
            } catch (Exception ex) {
                _log.FormattedInfo(typeof(DefaultEnvironmentInfoCollector), "Unable to get physical memory. Error message: {0}", ex.Message);
            }
#endif
        }
        static void Main(string[] args)
        {
            IEnumerable <string> files;
            int count = 0;

            if (args.Count() >= 1)
            {
                if (args.Contains("-h"))
                {
                    Console.WriteLine("Usage: ImageComparison [Input path] [Output path] -d -h --debug\n" +
                                      "\nOptions:" +
                                      "\n\t-d\t\tDeletes matches" +
                                      "\n\t-h\t\tDisplays the help" +
                                      "\n\t--debug\t\tEnables debug mode");
                    return;
                }
                if (args.Contains("-d"))
                {
                    deleteMode = true;
                }
                if (args.Count() == 2 && !args.Contains("--debug"))
                {
                    workingDirectory = args[0];
                    outputDirectory  = args[1];

                    if (workingDirectory.Last() == '\\')
                    {
                        workingDirectory.Remove(workingDirectory.Count(), 1);
                    }
                    if (outputDirectory.Last() == '\\')
                    {
                        outputDirectory.Remove(outputDirectory.Count(), 1);
                    }
                }
                else if (args.Count() == 1)
                {
                    workingDirectory = args[0];
                }
            }

            Compare.workingDirectory = workingDirectory;
            Compare.outputDirectory  = outputDirectory;

            files = Directory.EnumerateFiles(workingDirectory);
            //int memoryUsage;
            List <Match> matches = new List <Match>();

            count = 0;
            for (int i = 1; i < files.Count(); i++)
            {
                int j = files.Count() - i;
                count += j;
            }

            System.Diagnostics.Process proc = System.Diagnostics.Process.GetCurrentProcess();

            int memsize = 0; // memsize in MB

            System.Diagnostics.PerformanceCounter PC = new System.Diagnostics.PerformanceCounter
            {
                CategoryName = "Process",
                CounterName  = "Working Set - Private",
                InstanceName = proc.ProcessName
            };
            memsize = Convert.ToInt32(PC.NextValue()) / (int)(1048576);

            DateTime tt1 = DateTime.Now;

            Task <List <Match> >[] taskArray = new Task <List <Match> > [files.Count()];
            for (int i = 0; i < taskArray.Count(); i++)
            {
                ulong availableMemory = new Microsoft.VisualBasic.Devices.ComputerInfo().AvailablePhysicalMemory / 1048576; // memsize in MB
                while (availableMemory <= leftoverMemoryMB)
                {
                    Thread.Sleep(100);
                    availableMemory = new Microsoft.VisualBasic.Devices.ComputerInfo().AvailablePhysicalMemory / 1048576; // memsize in MB
                }

                var newArray = files.ToList().GetRange(i, files.Count() - i);
                taskArray[i] = Task <List <Match> > .Factory.StartNew(() => Compare.Comparerer(newArray, 16));

                Thread.Sleep(50);
            }

            List <int> ignore = new List <int>();

            while (!taskArray.Last().IsCompleted)
            {
                for (int i = 0; i < taskArray.Count(); i++)
                {
                    if (!ignore.Contains(i) && taskArray[i].IsCompleted)
                    {
                        for (int j = 0; j < taskArray[i].Result.Count; j++)
                        {
                            Console.WriteLine("Files {0} and {1} are equal", taskArray[i].Result[j].FileName1, taskArray[i].Result[j].FileName2);
                        }
                        ignore.Add(i);
                    }
                }
                Task.WaitAll(taskArray, 5000);
            }

            Task.WaitAll(taskArray);
            PC.Close();
            PC.Dispose();

            for (int i = 0; i < taskArray.Length; i++)
            {
                matches.AddRange(taskArray[i].Result);
                taskArray[i].Dispose();
            }

            matches.Sort();
            foreach (Match item in matches)
            {
                File.AppendAllText(outputDirectory + "\\" + workingDirectory.Substring(workingDirectory.LastIndexOf('\\') + 1) + ".txt", "Files " + item.FileName1 + " and " + item.FileName2 + " are " + item.EqualElements.ToString("P") + " equal" + Environment.NewLine);
                if (item.MarkForDeletion && deleteMode)
                {
                    Compare.Delete(item);
                }
            }

            DateTime tt2       = DateTime.Now;
            TimeSpan ttimeSpan = tt2 - tt1;

            Console.WriteLine("Execution time: {0} sec", (ttimeSpan.TotalSeconds).ToString("N2"));

            Console.Write("\nDone.");
            Console.ReadLine();
            return;
        }
 /// <summary>
 /// 可用內存(MB)
 /// </summary>
 /// <returns></returns>
 private string GetMemoryInfo()
 {
     try
     {
         Microsoft.VisualBasic.Devices.ComputerInfo oComputerInfo = new Microsoft.VisualBasic.Devices.ComputerInfo();
         //取得可用虛擬內存
         long iAvailableVirtualMemory = Convert.ToInt64(oComputerInfo.AvailableVirtualMemory) / 1024 / 1024;
         //取得總共虛擬內存
         //long iTotalVirtualMemory = Convert.ToInt64(oComputerInfo.TotalVirtualMemory) / 1024 / 1024;
         //取得可用物理內存
         long iAvailablePhysicalMemory = Convert.ToInt64(oComputerInfo.AvailablePhysicalMemory) / 1024 / 1024;
         //取得總共物理內存
         //long iTotalPhysicalMemory = Convert.ToInt64(oComputerInfo.TotalPhysicalMemory) / 1024 / 1024;
         string l_strReturn = "物理可用:" + iAvailablePhysicalMemory.ToString() + "  虛擬可用:" + iAvailableVirtualMemory.ToString();
         return l_strReturn;
     }
     catch (Exception ex) { return "!!![可用內存(MB)]獲取情況異常:" + ex.Message; }
 }
Exemple #34
0
        private void BtnComputerInfo_Click(Object sender, EventArgs e)
        {
            var sb = Pool.StringBuilder.Get();

            var mi = MachineInfo.Current;

            mi.Refresh();
            sb.AppendLine(mi.ToJson(true));
            sb.AppendLine();

            var macs = GetMacs().ToList();

            if (macs.Count > 0)
            {
                sb.AppendFormat("MAC:\t{0}\r\n", macs.Join(",", x => x.ToHex("-")));
            }

            var processor = GetInfo("Win32_Processor", "Name");

            /*if (!processor.IsNullOrEmpty())*/
            sb.AppendFormat("Processor:\t{0}\t(Win32_Processor.Name)\r\n", processor);

            var cpuID = GetInfo("Win32_Processor", "ProcessorId");

            /*if (!cpuID.IsNullOrEmpty())*/
            sb.AppendFormat("ProcessorId:\t{0}\t(Win32_Processor.ProcessorId)\r\n", cpuID);

            var uuid = GetInfo("Win32_ComputerSystemProduct", "UUID");

            /*if (!uuid.IsNullOrEmpty())*/
            sb.AppendFormat("UUID:\t{0}\t(Win32_ComputerSystemProduct.UUID)\r\n", uuid);

            var id = GetInfo("Win32_ComputerSystemProduct", "IdentifyingNumber");

            /*if (!id.IsNullOrEmpty())*/
            sb.AppendFormat("IdentifyingNumber:\t{0}\t(Win32_ComputerSystemProduct.IdentifyingNumber)\r\n", id);

            var bios = GetInfo("Win32_BIOS", "SerialNumber");

            /*if (!bios.IsNullOrEmpty())*/
            sb.AppendFormat("BIOS:\t{0}\t(Win32_BIOS.SerialNumber)\r\n", bios);

            var baseBoard = GetInfo("Win32_BaseBoard", "SerialNumber");

            /*if (!baseBoard.IsNullOrEmpty())*/
            sb.AppendFormat("BaseBoard:\t{0}\t(Win32_BaseBoard.SerialNumber)\r\n", baseBoard);

            var serialNumber = GetInfo("Win32_DiskDrive", "SerialNumber");

            /*if (!serialNumber.IsNullOrEmpty())*/
            sb.AppendFormat("DiskSerial:\t{0}\t(Win32_DiskDrive.SerialNumber)\r\n", serialNumber);

            //var reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Cryptography");
            //if (reg != null)
            //{
            //    var guid = reg.GetValue("MachineGuid") + "";
            //    /*if (!guid.IsNullOrEmpty())*/
            //    sb.AppendFormat("MachineGuid:\t{0}\t(SOFTWARE\\Microsoft\\Cryptography)\r\n", guid);
            //}

#if !NET4 && !__CORE__
            sb.AppendLine();
            var ci = new Microsoft.VisualBasic.Devices.ComputerInfo();
            foreach (var pi in ci.GetType().GetProperties())
            {
                //if (sb.Length > 0) sb.AppendLine();
                sb.AppendFormat("{0}:\t{1:n0}\r\n", pi.Name, ci.GetValue(pi));
            }
#endif

            rtResult.Buffer.Text = sb.Put(true);
        }
Exemple #35
0
        private void DisplayPCInfo()
        {
            Microsoft.VisualBasic.Devices.ComputerInfo info = new Microsoft.VisualBasic.Devices.ComputerInfo();

            // Get OS version
            this.cLog.WriteLine("OS : " + info.OSFullName.ToString() + " " + System.Environment.OSVersion.ServicePack);

            // Get CPU information
            RegistryKey processor_name = Registry.LocalMachine.OpenSubKey(@"Hardware\Description\System\CentralProcessor\0",
                RegistryKeyPermissionCheck.ReadSubTree);    // This registry entry contains entry for processor information
            if (null != processor_name)
            {
                if (null != processor_name.GetValue("ProcessorNameString"))
                {
                    this.cLog.WriteLine("CPU : " + (String)processor_name.GetValue("ProcessorNameString") + " " +
                        (info.TotalPhysicalMemory / 1024.0 / 1024.0 / 1024.0).ToString("F2") + " GB");
                }
            }

            // Get disk size
            ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"c:\"");
            disk.Get();
            String strSize = disk["Size"].ToString();
            String strFree = disk["FreeSpace"].ToString();
            double Size = double.Parse(strSize) / 1024.0 / 1024.0 / 1024.0;
            double Free = double.Parse(strFree) / 1024.0 / 1024.0 / 1024.0;
            this.cLog.WriteLine("HDD : " + (Size - Free).ToString("F1") + "GB / " + Size.ToString("F1") + "GB (Use/All)");

            // Get host name
            String hostname = Dns.GetHostName();
            // Get I/P address from host name
            IPAddress[] adrList = Dns.GetHostAddresses(hostname);
            foreach (IPAddress address in adrList)
            {
                // To display only the IP address of the V4
                if (address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    this.cLog.WriteLine("Network : " + address.ToString() + " (Active)");
                }
            }
        }
Exemple #36
0
 public MaxMemoryPerformanceCounter()
 {
     Microsoft.VisualBasic.Devices.ComputerInfo ci = new Microsoft.VisualBasic.Devices.ComputerInfo();
     memory = ci.TotalPhysicalMemory;
 }
Exemple #37
0
 public MaxMemoryPerformanceCounter()
 {
     Microsoft.VisualBasic.Devices.ComputerInfo ci = new Microsoft.VisualBasic.Devices.ComputerInfo();
     memory = ci.TotalPhysicalMemory;
 }
        private void Application_Startup(object sender, StartupEventArgs e)
        {
            Task<bool>.Factory.StartNew(
                          () =>
                          {
                              try
                              {
                                  DirectoryInfo dir = new DirectoryInfo(ScoreboardConfig.SAVE_APPLICATION_FOLDER);
                                  if (!dir.Exists)
                                      dir.Create();
                                  //must create the log folder second.
                                  dir = new DirectoryInfo(ScoreboardConfig.LOG_SCOREBOARD_FOLDER);
                                  if (!dir.Exists)
                                      dir.Create();
                                  //must create the error folder thrid.
                                  dir = new DirectoryInfo(ScoreboardConfig.SAVE_ERRORS_FOLDER);
                                  if (!dir.Exists)
                                      dir.Create();

                                  dir = new DirectoryInfo(ScoreboardConfig.SAVE_BACKGROUND_IMAGES_FOLDER);
                                  if (!dir.Exists)
                                      dir.Create();

                                  dir = new DirectoryInfo(ScoreboardConfig.SAVE_FILES_FOLDER);
                                  if (!dir.Exists)
                                      dir.Create();

                                  dir = new DirectoryInfo(ScoreboardConfig.SAVE_LOGOS_FOLDER);
                                  if (!dir.Exists)
                                      dir.Create();

                                  dir = new DirectoryInfo(ScoreboardConfig.SAVE_ADVERTS_FOLDER);
                                  if (!dir.Exists)
                                      dir.Create();

                                  dir = new DirectoryInfo(ScoreboardConfig.SAVE_FEEDBACK_FOLDER);
                                  if (!dir.Exists)
                                      dir.Create();

                                  dir = new DirectoryInfo(ScoreboardConfig.LOG_SCOREBOARD_FOLDER);
                                  if (!dir.Exists)
                                      dir.Create();

                                  dir = new DirectoryInfo(ScoreboardConfig.SAVE_SLIDESHOW_FOLDER);
                                  if (!dir.Exists)
                                      dir.Create();

                                  dir = new DirectoryInfo(ScoreboardConfig.SAVE_SKATERS_PICTURE_FOLDER);
                                  if (!dir.Exists)
                                      dir.Create();

                                  dir = new DirectoryInfo(ScoreboardConfig.SAVE_INTRODUCTIONS_SLIDESHOW_FOLDER);
                                  if (!dir.Exists)
                                      dir.Create();

                                  dir = new DirectoryInfo(ScoreboardConfig.SAVE_SERVER_FILES_FOLDER);
                                  if (!dir.Exists)
                                      dir.Create();
                                  dir = new DirectoryInfo(ScoreboardConfig.SAVE_SERVER_FILES_FOLDER_CSS);
                                  if (!dir.Exists)
                                      dir.Create();
                                  dir = new DirectoryInfo(ScoreboardConfig.SAVE_SERVER_FILES_FOLDER_JS);
                                  if (!dir.Exists)
                                      dir.Create();
                                  dir = new DirectoryInfo(ScoreboardConfig.SAVE_SERVER_FILES_FOLDER_IMG);
                                  if (!dir.Exists)
                                      dir.Create();
                                  dir = new DirectoryInfo(ScoreboardConfig.SAVE_SERVER_FILES_FOLDER_IMG_WFT);
                                  if (!dir.Exists)
                                      dir.Create();
                                  //dir = new DirectoryInfo(ScoreboardConfig.SAVE_SERVER_FILES_FOLDER_JSEXT);
                                  //if (!dir.Exists)
                                  //    dir.Create();
                                  //dir = new DirectoryInfo(ScoreboardConfig.SAVE_SERVER_FILES_FOLDER_JSEXT_IMG);
                                  //if (!dir.Exists)
                                  //    dir.Create();



                                  loadNationalFlagsRDNation();
                                  loadAdvertisementForRDNation();
                                  loadServerFilesForRDNation();
                                  Logger.Instance.logMessage("Directories Created", LoggerEnum.message);



                              }
                              catch (Exception exception)
                              {
                                  ErrorViewModel.Save(exception, exception.GetType(), additionalInformation: Logger.Instance.getLoggedMessages());
                              }
                              return true;
                          });
            Task<bool>.Factory.StartNew(
                        () =>
                        {
                            try
                            {
                                ScoreboardViewModel.sendActiveInstallIdToServer();
                                LogoViewModel.Instance.LoadLogos(true);
                                ErrorViewModel.checkForOldErrors();
                            }
                            catch (Exception exception)
                            {
                                ErrorViewModel.Save(exception, exception.GetType(), additionalInformation: Logger.Instance.getLoggedMessages());
                            }
                            return true;
                        });

            Logger.Instance.logMessage("Application Opened", LoggerEnum.message);
            Logger.Instance.logMessage("Mac Address:" + Client.GetMacAddress(), LoggerEnum.message);
            try
            {
                Microsoft.VisualBasic.Devices.ComputerInfo comp = new Microsoft.VisualBasic.Devices.ComputerInfo();
                Logger.Instance.logMessage("TotalPhysicalMemory:" + RDN.Utilities.Strings.StringExt.FormatKiloBytes(Convert.ToInt64(comp.TotalPhysicalMemory)), LoggerEnum.message);
                Logger.Instance.logMessage("AvailablePhysicalMemory:" + RDN.Utilities.Strings.StringExt.FormatKiloBytes(Convert.ToInt64(comp.AvailablePhysicalMemory)), LoggerEnum.message);
                Logger.Instance.logMessage("OSFullName:" + comp.OSFullName, LoggerEnum.message);
                Logger.Instance.logMessage("OSPlatform:" + comp.OSPlatform, LoggerEnum.message);
                Logger.Instance.logMessage("OSVersion:" + comp.OSVersion, LoggerEnum.message);


            }
            catch (Exception exception)
            {
                ErrorViewModel.Save(exception, GetType(), additionalInformation: Logger.Instance.getLoggedMessages());
            }

            // Global exception handling
            Application.Current.DispatcherUnhandledException += new DispatcherUnhandledExceptionEventHandler(AppDispatcherUnhandledException);


        }
        private void SystemInfo()
        {
            double ramFree, ramTotal, ramUsed, driveTotal;

            try
            {
                Microsoft.VisualBasic.Devices.ComputerInfo RAM = new Microsoft.VisualBasic.Devices.ComputerInfo();
                PerformanceCounter cpuCounter = new PerformanceCounter();

                cpuCounter.CategoryName = "Processor";
                cpuCounter.CounterName = "% Processor Time";
                cpuCounter.InstanceName = "_Total";

                while (true)
                {
                    //Grabs Needed Info For Disk Space etc...
                    DriveInfo[] drives
                        = DriveInfo.GetDrives();

                    DriveInfo drive = drives[Config.Default.Disk];

                    //Make sure the drive is ready before trying to get info from it
                    if (drive.IsReady)
                    {
                        driveTotal = drive.TotalSize / 1073741824.004733;
                        driveSpace = drive.AvailableFreeSpace / 1073741824.004733;
                        driveUsed = driveTotal - driveSpace;
                    }

                    if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable() == true)
                    {
                        NetworkInterface ni = interfaces[Config.Default.NIC];
                        totalSent = (ni.GetIPv4Statistics().BytesSent / 1048576.0).ToString("f2") + " MB";
                        totalReceived = (ni.GetIPv4Statistics().BytesReceived / 1048576.0).ToString("f2") + " MB";
                    }

                    //Retrieve RAM total and calculate how much is being used at the moment
                    ramFree = RAM.AvailablePhysicalMemory / 1073741824.004733;
                    ramTotal = RAM.TotalPhysicalMemory / 1073741824.004733;
                    ramUsed = ramTotal - ramFree;
                    ramPercent = ramUsed / ramTotal * 100;

                    //Lets grab some CPU usage -- You have to call .NextValue() twice with a delay to actually get a reading
                    cpuCounter.NextValue();
                    Thread.Sleep(1000);
                    cpuUsage = cpuCounter.NextValue();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemple #40
0
        private void DoLoop()
        {
            _conn = new UdpClient(_options.PhoneIp, _options.PhonePort);

            var ramFreeCounter = new PerformanceCounter("Memory", "Available MBytes");
            var computerInfo = new Microsoft.VisualBasic.Devices.ComputerInfo();
            var totalRam = computerInfo.TotalPhysicalMemory / 1024 / 1024;

            CreateNetworkCounters();

            var pc = new PerformanceCounter("Processor", "% Processor Time");
            var instances = new PerformanceCounterCategory("Processor").GetInstanceNames();
            var cs = new Dictionary<string, CounterSample>();

            foreach (var s in instances)
            {
                pc.InstanceName = s;
                cs.Add(s, pc.NextSample());
            }
            Thread.Sleep(999);

            var drives = DriveInfo.GetDrives();

            var volume = new Volume();

            _getIpsBw.DoWork += GetIps;
            //_getIpsBw.RunWorkerAsync(true);

            var myipTimer = new Timer(StartBw, null, TimeSpan.Zero, TimeSpan.FromMinutes(_options.MyipInterval));

            while (_continue)
            {
                var startTime = DateTime.Now;

                var strout = ".start.";
                foreach (var s in instances)
                {
                    pc.InstanceName = s;
                    var ns = pc.NextSample();
                    if (s.Equals("_Total")) strout += s + "|" + Math.Round(CounterSample.Calculate(cs[s], ns), 2) + "\n";
                    else strout += s + "|" + Math.Round(CounterSample.Calculate(cs[s], ns), 0) + "\n";
                    cs[s] = ns;
                }
                strout += "MemUsed|" + (totalRam - ramFreeCounter.NextValue()) + "\n";
                strout += "MemTotal|" + totalRam + "\n";

                try
                {
                    strout += "NetIn|" + networkInCounter.NextValue() + "\n";
                    strout += "NetOut|" + networkOutCounter.NextValue() + "\n";
                }
                catch (Exception e)
                {
                    _mainForm.LogLine("Warning: Failed to get network activity: " + e);
                    _mainForm.LogLine("Resetting to first adapter.");
                    _options.NetIndex = 0;
                    CreateNetworkCounters();
                }
                strout += "LocalIp|" + _localIp + "\n";
                strout += "RemoteIp|" + _remoteIp + "\n";

                if (RescanDrives)
                {
                    _mainForm.LogLine("Drivechange detected, rescanning drives.", true);
                    drives = DriveInfo.GetDrives();
                    RescanDrives = false;
                }
                foreach (var drive in drives.Where(drive => drive.DriveType == DriveType.Fixed))
                {
                    try
                    {
                        strout += "DriveInfo|" + drive.Name + "|" + drive.AvailableFreeSpace + "\n";
                    }
                    catch
                    {

                    }
                }

                strout += "Np|" + GetNp() + "\n";

                var muteStatus = volume.GetMute();
                var vol = volume.GetVol();

                strout += "mute|" + (muteStatus ? "1" : "0") + "\n";
                strout += "vol|" + vol + "\n";

                SendInfo(strout);

                var duration = DateTime.Now - startTime;
                if (duration.Milliseconds > 1000)
                {
                    _mainForm.LogLine("Warning: Iterating took " + duration.Milliseconds + "ms, should be less than 1s.");
                }
                else _mainForm.LogLine("Iterating took " + duration.Milliseconds + "ms", true);
                Thread.Sleep(1000 - duration.Milliseconds);
            }

            ramFreeCounter.Close();
            pc.Close();
            myipTimer.Dispose();
            volume.Dispose();
        }
Exemple #41
0
        public void SubmitButtonClicked(object sender, EventArgs e)
        {
            if (false == _ValidateForm())
            {
                string error = "Please fill out all fields marked as required (*) and make sure your email address is valid";
                DialogResult missingFields = MessageBox.Show(error);
            }
            else
            {
                MailMessage message = new MailMessage(_emailField.Text, Settings.Default.HelpDeskEmail);

                StringBuilder body = new StringBuilder(Settings.Default.Prepend);

                body.AppendLine("\n\n Name: " + _nameField.Text);
                body.AppendLine("\n\n Email: " + _emailField.Text);

                string phone = string.IsNullOrEmpty(_phoneField.Text) ? "Field Empty" : _phoneField.Text;
                body.AppendLine("\n\n Phone Ext: " + phone);

                string cell = string.IsNullOrEmpty(_cellField.Text) ? "Field Empty" : _cellField.Text;
                body.AppendLine("\n\n Cell: " + cell);

                body.AppendLine("\n\n Issue Severity: " + _checkedButton.Text);
                body.AppendLine("\n\n Description:\n" + _descriptionField.Text);

                ulong memory = new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory;
                string showMemory;

                if (memory > 1000000000)
                {
                    showMemory = (memory / 1000000000).ToString() + " gigabytes";
                }
                else
                {
                    showMemory = (memory / 1000000).ToString() + " megabytes";
                }

                body.AppendLine("\n\n Total Memory: " + showMemory);

                string bitCount;
                if (Environment.Is64BitOperatingSystem)
                    bitCount = " 64 bit";
                else
                    bitCount = " 32 bit";

                string processorName = "Not Available";
                try
                {

                    ManagementObjectCollection compInfo = new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Processor").Get();
                    foreach (ManagementObject obj in compInfo)
                    {
                        processorName = obj["Name"].ToString();
                    }
                }
                catch { }

                body.AppendLine("\n\n OS Version: " + Environment.OSVersion.ToString() + bitCount);

                body.AppendLine("\n\n Processor: " + processorName);
                body.AppendLine("\n\n Processor Architecture: " + Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE"));
                body.AppendLine("\n\n Number of Processors: " + Environment.ProcessorCount.ToString());

                body.AppendLine("\n\n Common Language Runtime Version: " + Environment.Version.ToString());

                message.Body = body.ToString();

                DialogResult dialogResult = MessageBox.Show("Submit Ticket", "Cancel", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.Yes)
                {
                    if (false == _SendEmail(message))
                    {
                        DialogResult fail = MessageBox.Show("Ticket Submssion Failed, Unable To Send Mail");
                    }
                    else
                    {
                        DialogResult success = MessageBox.Show("Ticket Submitted Successfully");
                    }
                }
            }
        }
 public static void test()
 {
     Microsoft.VisualBasic.Devices.ComputerInfo toto = new Microsoft.VisualBasic.Devices.ComputerInfo();
     ulong totalRam = toto.TotalPhysicalMemory;
 }