Example #1
0
        private void GetGitStatus(object o)
        {
            var result = new List <string>();

            result.Add("Git Origin");
            result.AddRange(RunCommand("git.exe", "config --get remote.origin.url", AddInLocation));

            // Ensure status is accurate
            RunCommand("git.exe", "fetch", AddInLocation);

            // git status -s -b --porcelain == Gets Branch, Status and a List of any changed files
            var changedFiles = RunCommand("git.exe", "status -s -b --porcelain", AddInLocation);

            if (changedFiles.Any())
            {
                result.Add("Git Branch, Status & Changed files");
                result.AddRange(changedFiles);
            }
            GitStatus = string.Join(Environment.NewLine, result.ToArray());

            var message = $"GetGitStatus finished at {SafeDate.ToLongDate(DateTime.Now)}";

            StartUpTimings.Add(message);
            Debug.WriteLine(message);
        }
Example #2
0
        private void GatherBootUpTimeEtc()
        {
            LastBootUpTime = "";
            LastLoginTime  = "";

            try
            {
                var q1 = "*[System/Provider/@Name='Microsoft-Windows-Kernel-Boot' and System/EventID=27]";
                var d1 = LastEventDateTime(q1);
                LastBootUpTime = $"{SafeDate.ToLongDate(d1.ToUniversalTime())}";

                var q2 = "*[System/Provider/@Name='Microsoft-Windows-Winlogon' and System/EventID=7001]";
                var d2 = LastEventDateTime(q2);
                LastLoginTime = $"{SafeDate.ToLongDate(d2.ToUniversalTime())}";
            }
            catch
            {
                // Do Nothing
            }

            // Local Function
            DateTime LastEventDateTime(string query)
            {
                DateTime result = DateTime.MinValue;

                var eventLogQuery = new EventLogQuery("System", PathType.LogName, query);

                using (var elReader = new EventLogReader(eventLogQuery))
                {
                    EventRecord eventInstance = elReader.ReadEvent();
                    while (eventInstance != null)
                    {
                        if (eventInstance.TimeCreated.HasValue)
                        {
                            var thisTime = eventInstance.TimeCreated.Value.ToUniversalTime();
                            if (thisTime > result)
                            {
                                result = thisTime;
                            }
                            else
                            {
                                Debugger.Break();
                            }
                        }

                        eventInstance = elReader.ReadEvent();
                    }
                }

                if (result == DateTime.MinValue)
                {
                    result = DateTime.UtcNow;
                }
                return(result);
            }
        }
Example #3
0
        private void GetWin32OperatingSystemData()
        {
            ManagementObjectSearcher searcher =
                new ManagementObjectSearcher("SELECT LastBootUpTime FROM Win32_OperatingSystem");
            ManagementObjectCollection objCol = searcher.Get();

            try
            {
                foreach (var o in objCol)
                {
                    var      mgtObject  = (ManagementObject)o;
                    DateTime lastBootUp = ManagementDateTimeConverter.ToDateTime(mgtObject["LastBootUpTime"].ToString());
                    _lastBootUpTime = SafeDate.ToLongDate(lastBootUp.ToUniversalTime()) + " UTC";
                    break;
                }
            }
            catch
            {
                _lastBootUpTime = "?";
            }
        }
Example #4
0
        private void GetWin32OperatingSystemData()
        {
            ManagementObjectSearcher   searcher = new ManagementObjectSearcher(QueryOperatingSystem);
            ManagementObjectCollection objCol   = searcher.Get();

            try
            {
                foreach (var o in objCol)
                {
                    var      mgtObject  = (ManagementObject)o;
                    DateTime lastBootUp = ManagementDateTimeConverter.ToDateTime(mgtObject["LastBootUpTime"].ToString());
                    _lastBootUpTime = SafeDate.ToLongDate(lastBootUp.ToUniversalTime()) + " UTC";

                    var productType = int.Parse(mgtObject["ProductType"].ToString());
                    switch (productType)
                    {
                    case 1:
                        _productType = Workstation;
                        break;

                    case 2:
                        _productType = DomainController;
                        break;

                    case 3:
                        _productType = Server;
                        break;

                    default:
                        _productType = Unknown + $" [{productType}]";
                        break;
                    }
                }
            }
            catch
            {
                _lastBootUpTime = "?";
            }
        }
Example #5
0
        private void WriteStartUpInfo()
        {
            // Log Add-In Version
            WritePrivate("StartUp", "Information", _helper.AddInVersion); // ** Used by Andy's Knime protocol ?

            // Log Word
            WritePrivate("StartUp", "Information", _helper.WordProduct); // ** Used by Andy's Knime protocol
            if (!string.IsNullOrEmpty(_helper.Click2RunProductIds))
            {
                WritePrivate("StartUp", "Information", _helper.Click2RunProductIds);
            }
            WritePrivate("StartUp", "Information", Environment.GetCommandLineArgs()[0]);

            // Log System
            WritePrivate("StartUp", "Information", _helper.SystemOs); // ** Used by Andy's Knime protocol
            WritePrivate("StartUp", "Information", _helper.DotNetVersion);
            WritePrivate("StartUp", "Information", $"Browser Version: {_helper.BrowserVersion}");

            // Log IP Address
            WritePrivate("StartUp", "Information", _helper.IpAddress); // ** Used by Andy's Knime protocol
            WritePrivate("StartUp", "Information", _helper.IpObtainedFrom);

            if (_helper.StartUpTimings != null)
            {
                WritePrivate("StartUp", "Timing", string.Join(Environment.NewLine, _helper.StartUpTimings));
            }

            List <string> lines = new List <string>();

            // Log UtcOffsets
            lines.Add($"Server UTC DateTime is {SafeDate.ToLongDate(_helper.ServerUtcDateTime)}");
            lines.Add($"System UTC DateTime is {SafeDate.ToLongDate(_helper.SystemUtcDateTime)}");

            lines.Add($"Server Header [Date] is {_helper.ServerDateHeader}");
            lines.Add($"Server UTC DateTime raw is {_helper.ServerUtcDateRaw}");

            lines.Add($"Calculated UTC Offset is {_helper.UtcOffset}");
            if (_helper.UtcOffset > 0)
            {
                TimeSpan delta = TimeSpan.FromTicks(_helper.UtcOffset);
                lines.Add($"System UTC DateTime is {delta} ahead of Server time");
            }
            if (_helper.UtcOffset < 0)
            {
                TimeSpan delta = TimeSpan.FromTicks(0 - _helper.UtcOffset);
                lines.Add($"System UTC DateTime is {delta} behind Server time");
            }

            WritePrivate("StartUp", "Information", string.Join(Environment.NewLine, lines));

            // Log Wmi Gathered Data
            lines = new List <string>();

            lines.Add($"CPU: {_wmiHelper.CpuName}");
            lines.Add($"CPU Cores: {_wmiHelper.LogicalProcessors}");
            lines.Add($"CPU Speed: {_wmiHelper.CpuSpeed}");
            lines.Add($"Physical Memory: {_wmiHelper.PhysicalMemory}");
            lines.Add($"Booted Up: {_wmiHelper.LastLastBootUpTime}");

            // Log Screen Sizes
            lines.Add($"Screens: {_helper.Screens}");
            WritePrivate("StartUp", "Information", string.Join(Environment.NewLine, lines));

#if DEBUG
            lines = new List <string>();

            string clientName     = Environment.GetEnvironmentVariable("CLIENTNAME");
            string userDomainName = Environment.UserDomainName;
            string userName       = Environment.UserName;
            string machineName    = Environment.MachineName;
            string userSummary;

            if (userDomainName.Equals(machineName))
            {
                // Local account
                userSummary = $"Local user {userName} on {machineName}";
            }
            else
            {
                // Domain account
                userSummary = $@"Domain user {userDomainName}\{userName} on {machineName}";
            }

            // Include RDP Info if available
            if (!string.IsNullOrEmpty(clientName))
            {
                userSummary += $" via RDP from {clientName}";
            }

            lines.Add($"Debug - {userSummary}");

            lines.Add($"Debug - Environment.OSVersion: {Environment.OSVersion}");
            lines.Add($"Debug - Environment.Version: {Environment.Version}");

            lines.Add($"Debug - Environment.CommandLine: {Environment.CommandLine}");
            lines.Add($"Debug - AddIn Location: {_helper.AddInLocation}");
            lines.Add($"Debug - Environment.Is64BitOperatingSystem: {Environment.Is64BitOperatingSystem}");
            lines.Add($"Debug - Environment.Is64BitProcess: {Environment.Is64BitProcess}");

            WritePrivate("StartUp", "Information", string.Join(Environment.NewLine, lines));

            WritePrivate("StartUp", "Information", _helper.GitStatus);
#endif

            #region Log critical System Info again to ensure we get it

            // Log Add-In Version
            WritePrivate("StartUp", "Information", _helper.AddInVersion); // ** Used by Andy's Knime protocol ?

            // Log Word
            WritePrivate("StartUp", "Information", _helper.WordProduct); // ** Used by Andy's Knime protocol

            // Log System
            WritePrivate("StartUp", "Information", _helper.SystemOs); // ** Used by Andy's Knime protocol

            // Log IP Address
            WritePrivate("StartUp", "Information", _helper.IpAddress); // ** Used by Andy's Knime protocol

            #endregion Log critical System Info again to ensure we get it

            _systemInfoSent = true;
        }
Example #6
0
        private void GetExternalIpAddress(object o)
        {
            string module = $"{MethodBase.GetCurrentMethod().Name}()";

            string message = $"{module} started at {SafeDate.ToLongDate(DateTime.Now)}";

            StartUpTimings.Add(message);
            Debug.WriteLine(message);

            Stopwatch sw = new Stopwatch();

            sw.Start();

            // http://www.ipv6proxy.net/ --> "Your IP address : 2600:3c00::f03c:91ff:fe93:dcd4"

            try
            {
                foreach (var domain in Domains)
                {
                    try
                    {
                        string url = $"{domain}/{DetectionFile}";

                        Debug.WriteLine("Fetching external IpAddress from " + url + " attempt " + _retryCount);
                        IpAddress = "IpAddress 0.0.0.0";

                        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                        if (request != null)
                        {
                            request.UserAgent = "Chem4Word Add-In";
                            request.Timeout   = 2000; // 2 seconds
                            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

                            try
                            {
                                // Get Server Date header i.e. "Tue, 01 Jan 2019 19:52:46 GMT"
                                ServerDateHeader = response.Headers["date"];
                            }
                            catch
                            {
                                // Do Nothing
                            }

                            if (HttpStatusCode.OK.Equals(response.StatusCode))
                            {
                                using (var reader = new StreamReader(response.GetResponseStream()))
                                {
                                    string webPage = reader.ReadToEnd();

                                    if (webPage.StartsWith("Your IP address : "))
                                    {
                                        // Tidy Up the data
                                        webPage = webPage.Replace("Your IP address : ", "");
                                        webPage = webPage.Replace("UTC Date : ", "");
                                        webPage = webPage.Replace("<br/>", "|");
                                        webPage = webPage.Replace("<br />", "|");

                                        string[] lines = webPage.Split('|');

                                        #region Detect IPv6

                                        if (lines[0].Contains(":"))
                                        {
                                            string[] ipV6Parts = lines[0].Split(':');
                                            // Must have between 4 and 8 parts
                                            if (ipV6Parts.Length >= 4 && ipV6Parts.Length <= 8)
                                            {
                                                IpAddress      = "IpAddress " + lines[0];
                                                IpObtainedFrom = $"IpAddress V6 obtained from {url} on attempt {_retryCount + 1}";
                                            }
                                        }

                                        #endregion Detect IPv6

                                        #region Detect IPv4

                                        if (lines[0].Contains("."))
                                        {
                                            // Must have 4 parts
                                            string[] ipV4Parts = lines[0].Split('.');
                                            if (ipV4Parts.Length == 4)
                                            {
                                                IpAddress      = "IpAddress " + lines[0];
                                                IpObtainedFrom = $"IpAddress V4 obtained from {url} on attempt {_retryCount + 1}";
                                            }
                                        }

                                        #endregion Detect IPv4

                                        #region Detect Php UTC Date

                                        if (lines.Length > 1)
                                        {
                                            ServerUtcDateRaw  = lines[1];
                                            ServerUtcDateTime = FromPhpDate(lines[1]);
                                            SystemUtcDateTime = DateTime.UtcNow;

                                            UtcOffset = SystemUtcDateTime.Ticks - ServerUtcDateTime.Ticks;
                                        }

                                        #endregion Detect Php UTC Date

                                        if (!IpAddress.Contains("0.0.0.0"))
                                        {
                                            break;
                                        }
                                    }

                                    Debug.WriteLine(IpAddress);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Debug.WriteLine(ex.Message);
                        // Do Nothing
                    }
                    Thread.Sleep(500);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                // Something went wrong
                IpAddress = "IpAddress 0.0.0.0 - " + ex.Message;
            }

            if (string.IsNullOrEmpty(IpAddress) || IpAddress.Contains("0.0.0.0"))
            {
                if (_retryCount < 5)
                {
                    _retryCount++;
                    Thread.Sleep(500);
                    ParameterizedThreadStart pts = GetExternalIpAddress;
                    Thread thread = new Thread(pts);
                    thread.SetApartmentState(ApartmentState.STA);
                    thread.Start(null);
                }
            }

            sw.Stop();

            message = $"{module} took {sw.ElapsedMilliseconds.ToString("#,000")}ms";
            StartUpTimings.Add(message);
            Debug.WriteLine(message);
        }
Example #7
0
        private List <string> Initialise()
        {
            List <string> timings = new List <string>();

            string message = $"SystemHelper.Initialise() started at {SafeDate.ToLongDate(DateTime.Now)}";

            timings.Add(message);
            Debug.WriteLine(message);

            Stopwatch sw = new Stopwatch();

            sw.Start();

            WordVersion = -1;

            #region Get Machine Guid

            MachineId = GetMachineId();

            ProcessId = Process.GetCurrentProcess().Id;

            #endregion Get Machine Guid

            #region Get OS Version

            // The current code returns 6.2.* for Windows 8.1 and Windows 10 on some systems
            // https://msdn.microsoft.com/en-gb/library/windows/desktop/ms724832(v=vs.85).aspx
            // https://msdn.microsoft.com/en-gb/library/windows/desktop/dn481241(v=vs.85).aspx
            // However as we do not NEED the exact version number,
            //  I am not going to implement the above as they are too risky

            try
            {
                OperatingSystem operatingSystem = Environment.OSVersion;

                string ProductName = HKLM_GetString(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ProductName");
                string CsdVersion  = HKLM_GetString(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CSDVersion");

                if (!string.IsNullOrEmpty(ProductName))
                {
                    StringBuilder sb = new StringBuilder();
                    if (!ProductName.StartsWith("Microsoft"))
                    {
                        sb.Append("Microsoft ");
                    }
                    sb.Append(ProductName);
                    if (!string.IsNullOrEmpty(CsdVersion))
                    {
                        sb.AppendLine($" {CsdVersion}");
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(operatingSystem.ServicePack))
                        {
                            sb.Append($" {operatingSystem.ServicePack}");
                        }
                    }

                    sb.Append($" {OsBits}");
                    sb.Append($" [{operatingSystem.Version}]");
                    sb.Append($" {CultureInfo.CurrentCulture.Name}");

                    SystemOs = sb.ToString().Replace(Environment.NewLine, "").Replace("Service Pack ", "SP");
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                SystemOs = "Exception " + ex.Message;
            }

            #endregion Get OS Version

            #region Get Office/Word Version

            try
            {
                WordProduct = OfficeHelper.GetWordProduct();

                Click2RunProductIds = OfficeHelper.GetClick2RunProductIds();

                if (WordProduct.Contains("2010") || WordProduct.Contains("2013") || WordProduct.Contains("2016") || WordProduct.Contains("365"))
                {
                    // This is ok, leave as is
                }
                else
                {
                    // Use last of Click2RunProductIds which have a number in
                    var ctrVersion = "";
                    if (!string.IsNullOrEmpty(Click2RunProductIds))
                    {
                        ctrVersion = "2016";
                        var parts = Click2RunProductIds.Split(',');
                        foreach (var part in parts)
                        {
                            string numberOnly = Regex.Replace(part, "[^0-9]", "");
                            if (!string.IsNullOrEmpty(numberOnly))
                            {
                                int n = int.Parse(numberOnly);
                                if (n == 2016 || n == 2019 || n == 365)
                                {
                                    ctrVersion = numberOnly;
                                }
                            }
                        }
                    }

                    if (WordProduct.Contains("[16."))
                    {
                        if (string.IsNullOrEmpty(ctrVersion))
                        {
                            // Best guess as not ctr version found
                            WordProduct = WordProduct.Replace("Office", $"Office 2016");
                        }
                        else
                        {
                            WordProduct = WordProduct.Replace("Office", $"Office {ctrVersion}");
                        }
                    }

                    // Not 100% sure why we ever get this ???
                    if (WordProduct.Contains("[11."))
                    {
                        WordProduct = $"Microsoft Office 2003 {WordVersion}";
                    }
                }

                WordVersion = OfficeHelper.GetWinWordVersion();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                WordProduct = "Exception " + ex.Message;
            }

            #endregion Get Office/Word Version

            #region Get Product Version and Location using reflection

            Assembly assembly = Assembly.GetExecutingAssembly();
            // CodeBase is the location of the installed files
            Uri uriCodeBase = new Uri(assembly.CodeBase);
            AddInLocation = Path.GetDirectoryName(uriCodeBase.LocalPath);

            Version productVersion = assembly.GetName().Version;
            AssemblyVersionNumber = productVersion.ToString();

            AddInVersion = "Chem4Word V" + productVersion;

            #endregion Get Product Version and Location using reflection

            #region Get IpAddress

            ParameterizedThreadStart pts = GetExternalIpAddress;
            Thread thread = new Thread(pts);
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start(null);

            #endregion Get IpAddress

            GetDotNetVersionFromRegistry();

            try
            {
                BrowserVersion = new WebBrowser().Version.ToString();
            }
            catch
            {
                BrowserVersion = "?";
            }

            GetScreens();

#if DEBUG
            GetGitStatus();
#endif

            sw.Stop();

            message = $"SystemHelper.Initialise() took {sw.ElapsedMilliseconds.ToString("#,000")}ms";
            timings.Add(message);
            Debug.WriteLine(message);

            return(timings);
        }
Example #8
0
        private List <string> Initialise()
        {
            try
            {
                List <string> timings = new List <string>();

                string message = $"SystemHelper.Initialise() started at {SafeDate.ToLongDate(DateTime.Now)}";
                timings.Add(message);
                Debug.WriteLine(message);

                Stopwatch sw = new Stopwatch();
                sw.Start();

                WordVersion = -1;

                #region Get Machine Guid

                MachineId = GetMachineId();

                ProcessId = Process.GetCurrentProcess().Id;

                #endregion Get Machine Guid

                #region Get OS Version

                // The current code returns 6.2.* for Windows 8.1 and Windows 10 on some systems
                // https://msdn.microsoft.com/en-gb/library/windows/desktop/ms724832(v=vs.85).aspx
                // https://msdn.microsoft.com/en-gb/library/windows/desktop/dn481241(v=vs.85).aspx
                // However as we do not NEED the exact version number,
                //  I am not going to implement the above as they are too risky

                try
                {
                    OperatingSystem operatingSystem = Environment.OSVersion;

                    string ProductName = HKLM_GetString(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "ProductName");
                    string CsdVersion  = HKLM_GetString(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion", "CSDVersion");

                    if (!string.IsNullOrEmpty(ProductName))
                    {
                        StringBuilder sb = new StringBuilder();
                        if (!ProductName.StartsWith("Microsoft"))
                        {
                            sb.Append("Microsoft ");
                        }
                        sb.Append(ProductName);
                        if (!string.IsNullOrEmpty(CsdVersion))
                        {
                            sb.AppendLine($" {CsdVersion}");
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(operatingSystem.ServicePack))
                            {
                                sb.Append($" {operatingSystem.ServicePack}");
                            }
                        }

                        sb.Append($" {OsBits}");
                        sb.Append($" [{operatingSystem.Version}]");
                        sb.Append($" {CultureInfo.CurrentCulture.Name}");

                        SystemOs = sb.ToString().Replace(Environment.NewLine, "").Replace("Service Pack ", "SP");
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    SystemOs = "Exception " + ex.Message;
                }

                #endregion Get OS Version

                #region Get Office/Word Version

                try
                {
                    Click2RunProductIds = OfficeHelper.GetClick2RunProductIds();

                    WordVersion = OfficeHelper.GetWinWordVersionNumber();

                    WordProduct = OfficeHelper.GetWordProduct(Click2RunProductIds);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    WordProduct = "Exception " + ex.Message;
                }

                #endregion Get Office/Word Version

                #region Get Product Version and Location using reflection

                Assembly assembly = Assembly.GetExecutingAssembly();
                // CodeBase is the location of the installed files
                Uri uriCodeBase = new Uri(assembly.CodeBase);
                AddInLocation = Path.GetDirectoryName(uriCodeBase.LocalPath);

                Version productVersion = assembly.GetName().Version;
                AssemblyVersionNumber = productVersion.ToString();

                AddInVersion = "Chem4Word V" + productVersion;

                #endregion Get Product Version and Location using reflection

                #region Get IpAddress on Thread

                // These can be tested via http://www.ipv6proxy.net/

                // Our locations
                _placesToTry.Add($"https://www.chem4word.co.uk/{Constants.Chem4WordVersionFiles}/client-ip-date.php");
                _placesToTry.Add($"http://www.chem4word.com/{Constants.Chem4WordVersionFiles}/client-ip-date.php");
                _placesToTry.Add($"https://chem4word.azurewebsites.net/{Constants.Chem4WordVersionFiles}/client-ip-date.php");

                // Other Locations
                _placesToTry.Add("https://api.my-ip.io/ip");
                _placesToTry.Add("https://ip.seeip.org");
                _placesToTry.Add("https://ipapi.co/ip");
                _placesToTry.Add("https://ident.me/");
                _placesToTry.Add("https://api6.ipify.org/");
                _placesToTry.Add("https://v4v6.ipv6-test.com/api/myip.php");

                message = $"GetIpAddress started at {SafeDate.ToLongDate(DateTime.Now)}";
                StartUpTimings.Add(message);
                Debug.WriteLine(message);

                _ipStopwatch = new Stopwatch();
                _ipStopwatch.Start();

                Thread thread1 = new Thread(GetExternalIpAddress);
                thread1.SetApartmentState(ApartmentState.STA);
                thread1.Start(null);

                #endregion Get IpAddress on Thread

                GetDotNetVersionFromRegistry();

                GatherBootUpTimeEtc();

                try
                {
                    BrowserVersion = new WebBrowser().Version.ToString();
                }
                catch
                {
                    BrowserVersion = "?";
                }

                GetScreens();

#if DEBUG
                message = $"GetGitStatus started at {SafeDate.ToLongDate(DateTime.Now)}";
                StartUpTimings.Add(message);
                Debug.WriteLine(message);

                Thread thread2 = new Thread(GetGitStatus);
                thread2.SetApartmentState(ApartmentState.STA);
                thread2.Start(null);
#endif

                sw.Stop();

                message = $"SystemHelper.Initialise() took {SafeDouble.AsString0(sw.ElapsedMilliseconds)}ms";
                timings.Add(message);
                Debug.WriteLine(message);

                return(timings);
            }
            catch (ThreadAbortException threadAbortException)
            {
                // Do Nothing
                Debug.WriteLine(threadAbortException.Message);
            }

            return(new List <string>());
        }