<commit_before>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Threading.Tasks;

using Certify.Models;
using Certify.Models.Config;
using Microsoft.ApplicationInsights;
using Microsoft.Win32;

namespace Certify.Management
{
    public class Util
    {

        /// <summary>
        /// check for problems which could affect app use
        /// </summary>
        /// <returns>  </returns>
        public static async Task<List<ActionResult>> PerformAppDiagnostics(string ntpServer = null)
        {
            var results = new List<ActionResult>();

            var tempFilePath = "";
            var tempFolder = Path.GetTempPath();

            // if current user can create temp files, attempt to create a 1MB temp file, detect if it fails
            if (!string.IsNullOrEmpty(tempFolder))
            {
                try
                {
                    tempFilePath = Path.GetTempFileName();

                    using (var fs = new FileStream(tempFilePath, FileMode.Open))
                    {
                        fs.Seek(1024 * 1024, SeekOrigin.Begin);
                        fs.WriteByte(0);
                        fs.Close();
                    }

                    File.Delete(tempFilePath);
                    results.Add(new ActionResult { IsSuccess = true, Message = $"Created test temp file OK." });
                }
                catch (Exception exp)
                {
                    results.Add(new ActionResult { Result = "tempfail", IsSuccess = false, Message = $"Could not create a temp file ({tempFilePath}). Windows has a limit of 65535 files in the temp folder ({tempFolder}). Clear temp files before proceeding. {exp.Message}" });
                }
            }

            // check free disk space
            var limit = 512;
            try
            {
                var cDrive = new DriveInfo("c");
                if (cDrive.IsReady)
                {
                    var freeSpaceBytes = cDrive.AvailableFreeSpace;

                    // Check disk has at least <limit>MB free
                    if (freeSpaceBytes < (1024L * 1024 * limit))
                    {
                        results.Add(new ActionResult { Result = "lowdiskspace", IsSuccess = false, Message = $"Drive C: has less than {limit}MB of disk space free. The application may not run correctly." });
                    }
                    else
                    {
                        results.Add(new ActionResult { IsSuccess = true, Message = $"Drive C: has more than {limit}MB of disk space free." });
                    }
                }
            }
            catch (Exception)
            {
                results.Add(new ActionResult { Result = "lowdiskspace", IsSuccess = false, Message = $"Could not check how much disk space is left on drive C:" });
            }

            // check internet time service, unless ntpServer pref set to ""

            if (ntpServer != "")
            {
                var timeResult = await CheckTimeServer(ntpServer);
                if (timeResult != null)
                {
                    var diff = timeResult - DateTime.Now;
                    if (Math.Abs(diff.Value.TotalSeconds) > 50)
                    {
                        results.Add(new ActionResult { IsSuccess = false, Message = $"Note: Your system time does not appear to be in sync with an internet time service, this can result in certificate request errors." });
                    }
                    else
                    {
                        results.Add(new ActionResult { IsSuccess = true, Message = $"System time is correct." });
                    }

                }
                else
                {
                    results.Add(new ActionResult { IsSuccess = false, Message = $"Note: Could not confirm system time is correct using NTP server ({ntpServer ?? "pool.ntp.org (default, UDP port 123)"}). You should ensure the system time is always correct to avoid certificate request errors." });
                }
            }


            // check if FIPS is enabled
            try
            {
                _ = System.Security.Cryptography.SHA256.Create();
            }
            catch (Exception)
            {
                // if creating managed SHA256 fails may be FIPS validation
                results.Add(new ActionResult { IsSuccess = false, Message = $"Your system cannot create a SHA256 Cryptography instance. You may have inadvertently have FIPS enabled, which prevents the use of some standard cryptographic functions in .Net - features such as verifying app updates will not work. " });
            }


            // check powershell version
            string subkey = @"SOFTWARE\Microsoft\PowerShell\3\PowerShellEngine";
            bool isPSAvailable = true;
            try
            {
                using (var ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64).OpenSubKey(subkey))
                {
                    var vals = (ndpKey.GetValue("PSCompatibleVersion") as string).Split(',');
                    if (!vals.Any(v => v.Trim() == "5.0"))
                    {
                        isPSAvailable = false;
                    }<commit_msg>NTP lookup fail is not an error (firewall etc)<commit_after>﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Sockets;
using System.Security.Cryptography;
using System.Threading.Tasks;

using Certify.Models;
using Certify.Models.Config;
using Microsoft.ApplicationInsights;
using Microsoft.Win32;

namespace Certify.Management
{
    public class Util
    {

        /// <summary>
        /// check for problems which could affect app use
        /// </summary>
        /// <returns>  </returns>
        public static async Task<List<ActionResult>> PerformAppDiagnostics(string ntpServer = null)
        {
            var results = new List<ActionResult>();

            var tempFilePath = "";
            var tempFolder = Path.GetTempPath();

            // if current user can create temp files, attempt to create a 1MB temp file, detect if it fails
            if (!string.IsNullOrEmpty(tempFolder))
            {
                try
                {
                    tempFilePath = Path.GetTempFileName();

                    using (var fs = new FileStream(tempFilePath, FileMode.Open))
                    {
                        fs.Seek(1024 * 1024, SeekOrigin.Begin);
                        fs.WriteByte(0);
                        fs.Close();
                    }

                    File.Delete(tempFilePath);
                    results.Add(new ActionResult { IsSuccess = true, Message = $"Created test temp file OK." });
                }
                catch (Exception exp)
                {
                    results.Add(new ActionResult { Result = "tempfail", IsSuccess = false, Message = $"Could not create a temp file ({tempFilePath}). Windows has a limit of 65535 files in the temp folder ({tempFolder}). Clear temp files before proceeding. {exp.Message}" });
                }
            }

            // check free disk space
            var limit = 512;
            try
            {
                var cDrive = new DriveInfo("c");
                if (cDrive.IsReady)
                {
                    var freeSpaceBytes = cDrive.AvailableFreeSpace;

                    // Check disk has at least <limit>MB free
                    if (freeSpaceBytes < (1024L * 1024 * limit))
                    {
                        results.Add(new ActionResult { Result = "lowdiskspace", IsSuccess = false, Message = $"Drive C: has less than {limit}MB of disk space free. The application may not run correctly." });
                    }
                    else
                    {
                        results.Add(new ActionResult { IsSuccess = true, Message = $"Drive C: has more than {limit}MB of disk space free." });
                    }
                }
            }
            catch (Exception)
            {
                results.Add(new ActionResult { Result = "lowdiskspace", IsSuccess = false, Message = $"Could not check how much disk space is left on drive C:" });
            }

            // check internet time service, unless ntpServer pref set to ""

            if (ntpServer != "")
            {
                var timeResult = await CheckTimeServer(ntpServer);
                if (timeResult != null)
                {
                    var diff = timeResult - DateTime.Now;
                    if (Math.Abs(diff.Value.TotalSeconds) > 50)
                    {
                        results.Add(new ActionResult { IsSuccess = false, Message = $"Note: Your system time does not appear to be in sync with an internet time service, this can result in certificate request errors." });
                    }
                    else
                    {
                        results.Add(new ActionResult { IsSuccess = true, Message = $"System time is correct." });
                    }

                }
                else
                {
                    // could not perform test, assume firewall limitation and assume user is syncing their time.
                    results.Add(new ActionResult { IsSuccess = true, Message = $"Note: Could not confirm system time is correct using NTP server ({ntpServer ?? "pool.ntp.org (default, UDP port 123)"}). You should ensure the system time is always correct to avoid certificate request errors." });
                }
            }


            // check if FIPS is enabled
            try
            {
                _ = System.Security.Cryptography.SHA256.Create();
            }
            catch (Exception)
            {
                // if creating managed SHA256 fails may be FIPS validation
                results.Add(new ActionResult { IsSuccess = false, Message = $"Your system cannot create a SHA256 Cryptography instance. You may have inadvertently have FIPS enabled, which prevents the use of some standard cryptographic functions in .Net - features such as verifying app updates will not work. " });
            }


            // check powershell version
            string subkey = @"SOFTWARE\Microsoft\PowerShell\3\PowerShellEngine";
            bool isPSAvailable = true;
            try
            {
                using (var ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64).OpenSubKey(subkey))
                {
                    var vals = (ndpKey.GetValue("PSCompatibleVersion") as string).Split(',');
                    if (!vals.Any(v => v.Trim() == "5.0"))
                    {
                        isPSAvailable = false;
                    }
{'fraction_non_alphanumeric': 0.08536807580174927, 'fraction_numerical': 0.008564139941690961, 'mean_word_length': 1.4806779661016949, 'pattern_counts': {'":': 0, '<': 21, '<?xml version=': 0, '>': 23, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4130184', 'n_tokens_mistral': 2712, 'n_tokens_neox': 2473, 'n_words': 852}