Пример #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);
        }
Пример #2
0
        //private void WriteCtab(StreamWriter writer)
        //{
        //    WriteHeader(writer);
        //    WriteAtoms(writer);
        //    WriteBonds(writer);
        //    WriteProperties(writer);
        //    writer.WriteLine(MDLConstants.M_END);
        //}

        private void WriteHeader(StreamWriter writer, int atoms, int bonds)
        {
            // Line 1 - Molecule Name (80)
            writer.WriteLine("");

            // Line 2
            // 01234567890123456789012345678901234567890123456789012345678901234567890123456789
            //           1         2         3         4         5         6         7
            // IIPPPPPPPPMMDDYYHHmmddSSssssssssssEEEEEEEEEEEERRRRRR
            // A2<--A8--><---A10-->A2I2<--F10.5-><---F12.5--><-I6->
            // I == User Initials
            // P == Program Name
            // MMDDYYHHmm == Date and Time
            // d == dimensional codes
            // Ss == scaling factors
            // E == Energy
            // R == registry number
            writer.WriteLine($"  Chem4Wrd{SafeDate.ToMdlHeaderTime(DateTime.Now)}");

            // Line 3 - Comments (80)
            writer.WriteLine("");

            // Counts line
            // 01234567890123456789012345678901234567890123456789012345678901234567890123456789
            //           1         2         3         4         5         6         7
            // aaabbblll---cccsss------------mmm-vvvvv
            //   6  5  0     0  0              3 V2000
            // a == number of atoms
            // b == number of bonds
            // l == number of atom lists
            // c == chiral flag; 0=not chiral, 1=chiral
            // m == number of additional properties
            // v == version number
            writer.WriteLine($"{OutputMDLInt(atoms)}{OutputMDLInt(bonds)}  0     0  0              0 V2000");
        }
Пример #3
0
        private void AutomaticUpdate_Load(object sender, EventArgs e)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            try
            {
                using (new WaitCursor())
                {
                    if (!PointHelper.PointIsEmpty(TopLeft))
                    {
                        Left = (int)TopLeft.X;
                        Top  = (int)TopLeft.Y;
                    }

                    string   currentVersionNumber = CurrentVersion.Root.Element("Number").Value;
                    DateTime currentReleaseDate   = SafeDate.Parse(CurrentVersion.Root.Element("Released").Value);

                    lblInfo.Text = "Your current version of Chem4Word is " + currentVersionNumber + "; Released " + SafeDate.ToShortDate(currentReleaseDate);
                    _telemetry.Write(module, "AutomaticUpdate", lblInfo.Text);

                    var versions = NewVersions.XPathSelectElements("//Version");
                    foreach (var version in versions)
                    {
                        if (string.IsNullOrEmpty(_downloadUrl))
                        {
                            _downloadUrl = version.Element("Url").Value;
                        }

                        var      thisVersionNumber = version.Element("Number").Value;
                        DateTime thisVersionDate   = SafeDate.Parse(version.Element("Released").Value);

                        if (currentReleaseDate >= thisVersionDate)
                        {
                            break;
                        }

                        AddHeaderLine("Version " + thisVersionNumber + "; Released " + SafeDate.ToShortDate(thisVersionDate), Color.Blue);
                        var changes = version.XPathSelectElements("Changes/Change");
                        foreach (var change in changes)
                        {
                            if (change.Value.StartsWith("Note:"))
                            {
                                AddBulletItem(change.Value.Remove(0, 6), Color.Red);
                            }
                            else
                            {
                                AddBulletItem(change.Value, Color.Black);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                new ReportError(_telemetry, TopLeft, module, ex).ShowDialog();
            }
        }
Пример #4
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);
            }
        }
Пример #5
0
        public static bool FetchUpdateInfo()
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            bool updateRequired = false;

            Globals.Chem4WordV3.VersionsBehind = 0;

            var assembly = Assembly.GetExecutingAssembly();

            ReadThisVersion(assembly);
            if (Globals.Chem4WordV3.ThisVersion != null)
            {
                string   currentVersionNumber = Globals.Chem4WordV3.ThisVersion.Root.Element("Number").Value;
                DateTime currentReleaseDate   = SafeDate.Parse(Globals.Chem4WordV3.ThisVersion.Root.Element("Released").Value);
                Debug.WriteLine("Current Version " + currentVersionNumber + " Released " + SafeDate.ToShortDate(currentReleaseDate));

                string xml = GetVersionsXmlFile();
                if (!string.IsNullOrEmpty(xml))
                {
                    #region Got Our File

                    Globals.Chem4WordV3.AllVersions = XDocument.Parse(xml);
                    var versions = Globals.Chem4WordV3.AllVersions.XPathSelectElements("//Version");
                    foreach (var version in versions)
                    {
                        var      thisVersionNumber = version.Element("Number").Value;
                        DateTime thisVersionDate   = SafeDate.Parse(version.Element("Released").Value);
                        Debug.WriteLine("New Version " + thisVersionNumber + " Released " + SafeDate.ToShortDate(thisVersionDate));
                        if (thisVersionDate > currentReleaseDate)
                        {
                            Globals.Chem4WordV3.VersionsBehind++;
                            updateRequired = true;
                        }
                    }

                    // Save VersionsBehind and Last Checked for next start up
                    Debug.WriteLine($"Saving Versions Behind in Registry: {Globals.Chem4WordV3.VersionsBehind}");
                    RegistryKey key = Registry.CurrentUser.CreateSubKey(Constants.Chem4WordRegistryKey);
                    key?.SetValue(Constants.RegistryValueNameVersionsBehind, Globals.Chem4WordV3.VersionsBehind.ToString());

                    #endregion Got Our File
                }
            }
            else
            {
                Globals.Chem4WordV3.Telemetry.Write(module, "Error", "Failed to parse resource 'Data.This-Version.xml'");
            }

            return(updateRequired);
        }
Пример #6
0
        public void Write(string operation, string level, string message)
        {
            _counter++;

            string unwanted = "Chem4Word.V3.";

            if (operation.StartsWith(unwanted))
            {
                operation = operation.Remove(0, unwanted.Length);
            }
            unwanted = "Chem4WordV3.";
            if (operation.StartsWith(unwanted))
            {
                operation = operation.Remove(0, unwanted.Length);
            }
            unwanted = "Chem4Word.";
            if (operation.StartsWith(unwanted))
            {
                operation = operation.Remove(0, unwanted.Length);
            }

            try
            {
                string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                                               $@"Chem4Word.V3\Telemetry\{SafeDate.ToIsoShortDate(DateTime.Now)}.log");
                using (StreamWriter w = File.AppendText(fileName))
                {
                    string logMessage = $"[{SafeDate.ToShortTime(DateTime.Now)}] {operation} - {level} - {message}";
                    w.WriteLine(logMessage);
                }
            }
            catch
            {
                //
            }

            if (_permissionGranted)
            {
                WritePrivate(operation, level, message);

                if (!_systemInfoSent)
                {
                    if (_helper.IpAddress != null && !_helper.IpAddress.Contains("0.0.0.0"))
                    {
                        WriteStartUpInfo();
                    }
                }
            }
        }
Пример #7
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 = "?";
            }
        }
Пример #8
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 = "?";
            }
        }
Пример #9
0
        public void WriteMessage(ServiceBusMessage message)
        {
            try
            {
                BrokeredMessage bm = new BrokeredMessage(message.Message);
                bm.Properties["PartitionKey"]     = message.PartitionKey;
                bm.Properties["RowKey"]           = message.RowKey;
                bm.Properties["Chem4WordVersion"] = message.AssemblyVersionNumber;
                bm.Properties["MachineId"]        = message.MachineId;
                bm.Properties["Operation"]        = message.Operation;
                bm.Properties["Level"]            = message.Level;
#if DEBUG
                bm.Properties["IsDebug"] = "True";
#endif
                _client.Send(bm);
                // Small sleep between each message
                Thread.Sleep(25);
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Exception in WriteMessage: {ex.Message}");

                try
                {
                    string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                                                   $@"Chem4Word.V3\Telemetry\{SafeDate.ToIsoShortDate(DateTime.Now)}.log");
                    using (StreamWriter w = File.AppendText(fileName))
                    {
                        w.WriteLine($"[{SafeDate.ToShortTime(DateTime.Now)}] Exception in WriteMessage: {ex.Message}");
                    }
                }
                catch
                {
                    //
                }
            }
        }
Пример #10
0
        public static void ReadSavedValues()
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            try
            {
                RegistryKey key = Registry.CurrentUser.OpenSubKey(Constants.Chem4WordRegistryKey);
                if (key != null)
                {
                    var names = key.GetValueNames();

                    if (names.Contains(Constants.RegistryValueNameLastCheck))
                    {
                        try
                        {
                            var lastChecked = key.GetValue(Constants.RegistryValueNameLastCheck).ToString();
                            if (!string.IsNullOrEmpty(lastChecked))
                            {
                                DateTime last = SafeDate.Parse(lastChecked);
                                Globals.Chem4WordV3.VersionLastChecked = last;
                            }
                        }
                        catch
                        {
                            Globals.Chem4WordV3.VersionLastChecked = DateTime.Now.AddDays(-30);
                        }
                    }
                    else
                    {
                        Globals.Chem4WordV3.VersionLastChecked = DateTime.Now.AddDays(-30);
                    }

                    if (names.Contains(Constants.RegistryValueNameLastCheck))
                    {
                        try
                        {
                            var behind = key.GetValue(Constants.RegistryValueNameVersionsBehind).ToString();
                            Globals.Chem4WordV3.VersionsBehind = string.IsNullOrEmpty(behind) ? 0 : int.Parse(behind);
                        }
                        catch
                        {
                            Globals.Chem4WordV3.VersionsBehind = 0;
                        }
                    }
                    else
                    {
                        Globals.Chem4WordV3.VersionsBehind = 0;
                    }
                }
                else
                {
                    Globals.Chem4WordV3.VersionLastChecked = DateTime.Now.AddDays(-30);
                    Globals.Chem4WordV3.VersionsBehind     = 0;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                Globals.Chem4WordV3.Telemetry.Write(module, "Exception", ex.Message);
                Globals.Chem4WordV3.Telemetry.Write(module, "Exception", ex.StackTrace);
                if (ex.InnerException != null)
                {
                    Globals.Chem4WordV3.Telemetry.Write(module, "Exception", ex.InnerException.Message);
                    Globals.Chem4WordV3.Telemetry.Write(module, "Exception", ex.InnerException.StackTrace);
                }
            }
        }
Пример #11
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);
        }
Пример #12
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);
        }
Пример #13
0
        public static bool FetchUpdateInfo()
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            bool updateRequired = false;

            Globals.Chem4WordV3.VersionsBehind = 0;

            var assembly = Assembly.GetExecutingAssembly();

            ReadThisVersion(assembly);
            if (Globals.Chem4WordV3.ThisVersion != null)
            {
                DateTime currentReleaseDate = SafeDate.Parse(Globals.Chem4WordV3.ThisVersion.Root.Element("Released").Value);

                string xml = GetVersionsXmlFile();
                if (!string.IsNullOrEmpty(xml))
                {
                    #region Got Our File

                    Globals.Chem4WordV3.AllVersions = XDocument.Parse(xml);
                    RegistryKey registryKey = Registry.CurrentUser.CreateSubKey(Constants.Chem4WordRegistryKey);

                    var expires = Globals.Chem4WordV3.AllVersions.XPathSelectElements("//EndOfLife").FirstOrDefault();
                    if (expires != null)
                    {
                        var expiryDate = SafeDate.Parse(expires.Value);
                        if (DateTime.Now.ToUniversalTime() > expiryDate)
                        {
                            Globals.Chem4WordV3.IsEndOfLife = true;
                            registryKey?.SetValue(Constants.RegistryValueNameEndOfLife, "true");
                        }
                    }

                    var  versions   = Globals.Chem4WordV3.AllVersions.XPathSelectElements("//Version");
                    bool mostRecent = true;
                    foreach (var version in versions)
                    {
                        var      thisVersionNumber = version.Element("Number")?.Value;
                        DateTime thisVersionDate   = SafeDate.Parse(version.Element("Released")?.Value);

                        if (thisVersionDate > currentReleaseDate)
                        {
                            Globals.Chem4WordV3.VersionsBehind++;
                            updateRequired = true;
                        }

                        if (mostRecent)
                        {
                            Globals.Chem4WordV3.VersionAvailable = thisVersionNumber;
                            registryKey?.SetValue(Constants.RegistryValueNameAvailableVersion, thisVersionNumber);

                            var isBeta = version.Element("IsBeta")?.Value;
                            Globals.Chem4WordV3.VersionAvailableIsBeta = bool.Parse(isBeta);
                            registryKey?.SetValue(Constants.RegistryValueNameAvailableIsBeta, isBeta);

                            mostRecent = false;
                        }
                    }

                    // Save VersionsBehind and Last Checked for next start up
                    Debug.WriteLine($"Saving Versions Behind in Registry: {Globals.Chem4WordV3.VersionsBehind}");
                    registryKey?.SetValue(Constants.RegistryValueNameVersionsBehind, Globals.Chem4WordV3.VersionsBehind.ToString());

                    #endregion Got Our File
                }
            }
            else
            {
                Globals.Chem4WordV3.Telemetry.Write(module, "Error", "Failed to parse resource 'Data.This-Version.xml'");
            }

            return(updateRequired);
        }
Пример #14
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>());
        }
Пример #15
0
        public static int CheckForUpdates(int days)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            Debug.WriteLine($"{module} days: {days}");
            try
            {
                if (!string.IsNullOrEmpty(Globals.Chem4WordV3.AddInInfo.DeploymentPath))
                {
                    #region CheckForUpdate

                    bool doCheck = true;

                    RegistryKey key = Registry.CurrentUser.CreateSubKey(Constants.Chem4WordRegistryKey);

                    string lastChecked = null;
                    try
                    {
                        lastChecked = key.GetValue(Constants.RegistryValueNameLastCheck).ToString();
                    }
                    catch
                    {
                        // Should only happen if the value does not exist
                    }

                    string behind = null;
                    try
                    {
                        behind = key.GetValue(Constants.RegistryValueNameVersionsBehind).ToString();
                        Globals.Chem4WordV3.VersionsBehind = int.Parse(behind);
                    }
                    catch
                    {
                        // Should only happen if the value does not exist
                    }

                    // Bypass for testing
                    if (days > 0)
                    {
                        if (!string.IsNullOrEmpty(lastChecked))
                        {
                            DateTime last  = SafeDate.Parse(lastChecked);
                            TimeSpan delta = DateTime.Today - last;
                            if (delta.TotalDays < days)
                            {
                                doCheck = false;
                            }
                        }

                        if (doCheck)
                        {
                            key.SetValue(Constants.RegistryValueNameLastCheck, DateTime.Today.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture));
                        }
                    }

                    if (doCheck)
                    {
                        bool update = false;
                        using (new UI.WaitCursor())
                        {
                            update = FetchUpdateInfo();
                        }

                        if (update)
                        {
                            ShowUpdateForm();
                        }
                    }

                    #endregion CheckForUpdate
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
                Globals.Chem4WordV3.Telemetry.Write(module, "Exception", ex.Message);
                Globals.Chem4WordV3.Telemetry.Write(module, "Exception", ex.StackTrace);
                if (ex.InnerException != null)
                {
                    Globals.Chem4WordV3.Telemetry.Write(module, "Exception", ex.InnerException.Message);
                    Globals.Chem4WordV3.Telemetry.Write(module, "Exception", ex.InnerException.StackTrace);
                }
            }

            Globals.Chem4WordV3.SetUpdateButtonState();

            return(Globals.Chem4WordV3.VersionsBehind);
        }
Пример #16
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;
        }
Пример #17
0
        public void Write(string operation, string level, string message)
        {
            _counter++;

            string unwanted = "Chem4Word.V3.";

            if (operation.StartsWith(unwanted))
            {
                operation = operation.Remove(0, unwanted.Length);
            }
            unwanted = "Chem4WordV3.";
            if (operation.StartsWith(unwanted))
            {
                operation = operation.Remove(0, unwanted.Length);
            }
            unwanted = "Chem4Word.";
            if (operation.StartsWith(unwanted))
            {
                operation = operation.Remove(0, unwanted.Length);
            }

            try
            {
                string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
                                               $@"Chem4Word.V3\Telemetry\{SafeDate.ToIsoShortDate(DateTime.Now)}.log");
                using (StreamWriter w = File.AppendText(fileName))
                {
                    string logMessage = $"[{SafeDate.ToShortTime(DateTime.Now)}] {operation} - {level} - {message}";
                    w.WriteLine(logMessage);
                }
            }
            catch
            {
                //
            }

            if (_permissionGranted)
            {
                WritePrivate(operation, level, message);

                if (!_systemInfoSent &&
                    _helper?.IpAddress != null &&
                    !_helper.IpAddress.Contains("0.0.0.0"))
                {
                    WriteStartUpInfo();

                    if (!string.IsNullOrEmpty(_helper.GitStatus))
                    {
                        var tracking = _helper.GitStatus
                                       .Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
                                       .FirstOrDefault(l => l.StartsWith("##"));

                        if (!string.IsNullOrEmpty(tracking))
                        {
                            var idxStart = tracking.IndexOf('[');
                            var idxEnd   = tracking.IndexOf(']');
                            if (idxStart > 0 && idxEnd > 0)
                            {
                                var info = tracking.Substring(idxStart, idxEnd - idxStart + 1);

                                if (info.Contains("behind"))
                                {
                                    MessageBox.Show("Your local source code is behind origin!", "WARNING",
                                                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                }
                                if (info.Contains("gone"))
                                {
                                    MessageBox.Show("Your local source code is gone from origin!", "WARNING",
                                                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                }
                            }
                        }
                    }
                }
            }
        }