private void LoadCdw() { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; if (!string.IsNullOrEmpty(ProductAppDataPath)) { _loading = true; // Allow extra 500ms for form to load Thread.Sleep(500); Stopwatch sw = new Stopwatch(); sw.Start(); string htmlfile = ""; if (IsSingleMolecule) { htmlfile = ResourceHelper.GetStringResource(Assembly.GetExecutingAssembly(), "ChemDoodleWeb.Single.html"); } else { htmlfile = ResourceHelper.GetStringResource(Assembly.GetExecutingAssembly(), "ChemDoodleWeb.Multi.html"); } File.WriteAllText(Path.Combine(ProductAppDataPath, "Editor.html"), htmlfile); Telemetry.Write(module, "Timing", $"Writing resources to disk took {SafeDouble.Duration(sw.ElapsedMilliseconds)}ms"); Telemetry.Write(module, "Information", "Starting browser"); WebBrowser.Navigate(Path.Combine(ProductAppDataPath, "Editor.html")); } }
/// <summary> /// Ensure that bond length is between 5 and 95, and force to default if required /// </summary> /// <param name="target">Target bond length (if force true)</param> /// <param name="force">true to force setting of bond length to target bond length</param> public string EnsureBondLength(double target, bool force) { string result = string.Empty; if (TotalBondsCount > 0 && MeanBondLength > 0) { if (Math.Abs(MeanBondLength - target) < 0.1) { result = string.Empty; } else { if (force) { result = $"Forced BondLength from {SafeDouble.AsString(MeanBondLength)} to {SafeDouble.AsString(target)}"; ScaleToAverageBondLength(target); } else { if (MeanBondLength < Constants.MinimumBondLength - Constants.BondLengthTolerance || MeanBondLength > Constants.MaximumBondLength + Constants.BondLengthTolerance) { result = $"Adjusted BondLength from {SafeDouble.AsString(MeanBondLength)} to {SafeDouble.AsString(target)}"; ScaleToAverageBondLength(target); } else { result = $"BondLength of {SafeDouble.AsString(MeanBondLength)} is within tolerance"; } } } } return(result); }
private void DeployCdw800() { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; if (!string.IsNullOrEmpty(ProductAppDataPath)) { Stopwatch sw = new Stopwatch(); sw.Start(); string markerFile = Path.Combine(ProductAppDataPath, "ChemDoodle-Web-800.txt"); string otherVersion = Path.Combine(ProductAppDataPath, "ChemDoodle-Web-702.txt"); string refreshFile = Path.Combine(ProductAppDataPath, "ChemDoodle-Web-Refresh.txt"); if (File.Exists(otherVersion)) { Telemetry.Write(module, "Information", "Deleting CDW 702 resources from disk"); File.Delete(otherVersion); DelTree(Path.Combine(ProductAppDataPath, "ChemDoodleWeb")); } if (File.Exists(refreshFile)) { Telemetry.Write(module, "Information", "Refreshing CDW 800 resources"); File.Delete(refreshFile); File.Delete(markerFile); DelTree(Path.Combine(ProductAppDataPath, "ChemDoodleWeb")); } if (!File.Exists(markerFile)) { Telemetry.Write(module, "Information", "Writing CDW 800 resources to disk"); File.WriteAllText(markerFile, "Delete this file to refresh ChemDoodle Web"); Stream stream = ResourceHelper.GetBinaryResource(Assembly.GetExecutingAssembly(), "ChemDoodleWeb.ChemDoodleWeb_800.zip"); // NB: Top level of zip file must be the folder ChemDoodleWeb using (ZipFile zip = ZipFile.Read(stream)) { zip.ExtractAll(ProductAppDataPath, ExtractExistingFileAction.OverwriteSilently); } string cssfile = ResourceHelper.GetStringResource(Assembly.GetExecutingAssembly(), "ChemDoodleWeb.Chem4Word.css"); File.WriteAllText(Path.Combine(ProductAppDataPath, "Chem4Word.css"), cssfile); string jsfile = ResourceHelper.GetStringResource(Assembly.GetExecutingAssembly(), "ChemDoodleWeb.Chem4Word.js"); File.WriteAllText(Path.Combine(ProductAppDataPath, "Chem4Word.js"), jsfile); } sw.Stop(); Telemetry.Write(module, "Timing", $"Writing resources to disk took {SafeDouble.Duration(sw.ElapsedMilliseconds)}ms"); } }
public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append($"{Text}"); sb.Append(" "); sb.Append($"at {PointHelper.AsString(BoundingBox.Location)}"); sb.Append(" "); sb.Append($"size {SafeDouble.AsString4(BoundingBox.Size.Width)}x{SafeDouble.AsString4(BoundingBox.Size.Height)}"); return(sb.ToString()); }
private void GetWin32ProcessorData() { ManagementObjectSearcher searcher = new ManagementObjectSearcher(QueryProcessor); ManagementObjectCollection objCol = searcher.Get(); foreach (var o in objCol) { var mgtObject = (ManagementObject)o; try { string temp = mgtObject["Name"].ToString(); // Replace tab with space temp = temp.Replace("\t", " "); // Replace up to 15 double spaces with single space int i = 0; while (temp.IndexOf(" ", StringComparison.InvariantCulture) != -1) { temp = temp.Replace(" ", " "); i++; if (i > 15) { break; } } _cpuName = temp; } catch { _cpuName = "?"; } try { _logicalProcessors = mgtObject["NumberOfLogicalProcessors"].ToString(); } catch { _logicalProcessors = "?"; } try { double speed = double.Parse(mgtObject["CurrentClockSpeed"].ToString()) / 1024; _cpuSpeed = SafeDouble.AsString(speed) + "GHz"; } catch { _cpuSpeed = "?"; } } }
private void WebBrowser_OnLoadCompleted(object sender, NavigationEventArgs e) { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; try { // Allow extra 500ms for document to load Thread.Sleep(500); if (!string.IsNullOrEmpty(StructureJson)) { var version = ExecuteJavaScript("GetVersion"); if (version != null) { var source = (HwndSource)PresentationSource.FromDependencyObject(WebBrowser); if (source != null) { var host = (System.Windows.Forms.Integration.ElementHost)Control.FromChildHandle(source.Handle); var form = (Form)host?.TopLevelControl; if (form != null) { form.Text = AppTitle + version; } } } // Send JSON to ChemDoodle before we do anything else ExecuteJavaScript("SetJSON", StructureJson, AverageBondLength); ExecuteJavaScript("ShowHydrogens", UserOptions.ShowHydrogens); ExecuteJavaScript("AtomsInColour", UserOptions.ColouredAtoms); ExecuteJavaScript("ShowCarbons", UserOptions.ShowCarbons); ExecuteJavaScript("ReScale", BondLength.Text); Mouse.OverrideCursor = System.Windows.Input.Cursors.Arrow; _sw.Stop(); Telemetry.Write(module, "Timing", $"ChemDoodle Web ready in {SafeDouble.Duration(_sw.ElapsedMilliseconds)}ms"); _loading = false; } } catch (Exception ex) { new ReportError(Telemetry, TopLeft, module, ex).ShowDialog(); Mouse.OverrideCursor = System.Windows.Input.Cursors.Arrow; } }
private void GetWin32PhysicalMemoryData() { ManagementObjectSearcher searcher = new ManagementObjectSearcher(QueryPhysicalMemory); ManagementObjectCollection objCol = searcher.Get(); try { UInt64 capacity = 0; foreach (var o in objCol) { var mgtObject = (ManagementObject)o; capacity += (UInt64)mgtObject["Capacity"]; } _physicalMemory = SafeDouble.AsString0((double)capacity / (1024 * 1024 * 1024)) + "GB"; } catch { _physicalMemory = "?"; } }
public ChemicalServicesResult GetChemicalServicesResult(string molfile) { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; DateTime started = DateTime.Now; ChemicalServicesResult data = null; try { using (HttpClient httpClient = new HttpClient()) { var formData = new List <KeyValuePair <string, string> >(); formData.Add(new KeyValuePair <string, string>("mol", molfile)); formData.Add(new KeyValuePair <string, string>("machine", SystemHelper.GetMachineId())); formData.Add(new KeyValuePair <string, string>("version", Globals.Chem4WordV3.AddInInfo.AssemblyVersionNumber)); var content = new FormUrlEncodedContent(formData); httpClient.Timeout = TimeSpan.FromSeconds(15); httpClient.DefaultRequestHeaders.Add("user-agent", "Chem4Word"); try { var response = httpClient.PostAsync(Constants.Chem4WordWebServiceUri, content).Result; if (response.Content != null) { var responseContent = response.Content; var jsonContent = responseContent.ReadAsStringAsync().Result; try { data = JsonConvert.DeserializeObject <ChemicalServicesResult>(jsonContent); } catch (Exception e3) { Telemetry.Write(module, "Exception", e3.Message); Telemetry.Write(module, "Exception(Data)", jsonContent); } if (data != null) { if (data.Messages.Any()) { Telemetry.Write(module, "Timing", string.Join(Environment.NewLine, data.Messages)); } if (data.Errors.Any()) { Telemetry.Write(module, "Exception(Data)", string.Join(Environment.NewLine, data.Errors)); } } } } catch (Exception e2) { Telemetry.Write(module, "Exception", e2.Message); Telemetry.Write(module, "Exception", e2.ToString()); } } } catch (Exception e1) { Telemetry.Write(module, "Exception", e1.Message); Telemetry.Write(module, "Exception", e1.ToString()); } DateTime ended = DateTime.Now; TimeSpan duration = ended - started; Telemetry.Write(module, "Timing", $"Calling Azure http Function Took {SafeDouble.Duration(duration.TotalMilliseconds)}ms"); return(data); }
private string ToJsonSingle() { // Need to store atomIds in dictionary as id of 1st atom not always a0 Dictionary <String, int> atomIds = new Dictionary <string, int>(); JObject jsonOut = new JObject(); List <XmlNode> atoms = GetAtoms(); if (atoms.Count > 0) { JArray jAtomsArray = new JArray(); JProperty jAtomsProperty = new JProperty("a", jAtomsArray); jsonOut.Add(jAtomsProperty); int atomCount = 0; foreach (XmlNode atom in atoms) { // Fetch or generate atom id string atomId = GetAttribute(atom, "id"); if (string.IsNullOrEmpty(atomId)) { atomId = "a" + atomCount; } atomIds.Add(atomId, atomCount); atomCount++; string atomLabel = GetAttribute(atom, "elementType"); // 2D co-ordinates (if present) string x2 = GetAttribute(atom, "x2"); string y2 = GetAttribute(atom, "y2"); // 3D co-ordinates (if present) string x3 = GetAttribute(atom, "x3"); string y3 = GetAttribute(atom, "y3"); string z3 = GetAttribute(atom, "z3"); JObject jAtom = new JObject(); if (string.IsNullOrEmpty(z3)) { // 2D co-ordinates supplied jAtom.Add(new JProperty("x", SafeDouble.Parse(x2))); jAtom.Add(new JProperty("y", SafeDouble.Parse(y2))); } else { // 3D co-ordinates supplied jAtom.Add(new JProperty("x", SafeDouble.Parse(x3))); jAtom.Add(new JProperty("y", SafeDouble.Parse(y3))); jAtom.Add(new JProperty("z", SafeDouble.Parse(z3))); } jAtom.Add(new JProperty("i", atomId)); if (!atomLabel.Equals("C")) { jAtom.Add(new JProperty("l", atomLabel)); } string charge = GetAttribute(atom, "formalCharge"); if (!string.IsNullOrEmpty(charge)) { jAtom.Add(new JProperty("c", Int32.Parse(charge))); } jAtomsArray.Add(jAtom); } } List <XmlNode> bonds = GetBonds(); if (bonds.Count > 0) { JArray jBondsArray = new JArray(); JProperty jBondsProperty = new JProperty("b", jBondsArray); jsonOut.Add(jBondsProperty); int bondCount = 0; foreach (XmlNode bond in bonds) { // Fetch or generate bond id string bondId = GetAttribute(bond, "id"); if (string.IsNullOrEmpty(bondId)) { bondId = "b" + bondCount; } string atomRefs2 = GetAttribute(bond, "atomRefs2"); string[] bondStartEnd = atomRefs2.Split(' '); string bondOrder = GetAttribute(bond, "order"); string bondStereo = ""; if (bond.ChildNodes.Count > 0) { XmlNode stereoNode = bond.FirstChild; bondStereo = stereoNode.InnerText; } JObject jBond = new JObject(); jBond.Add(new JProperty("i", bondId)); int atomId0 = atomIds[bondStartEnd[0]]; int atomId1 = atomIds[bondStartEnd[1]]; jBond.Add(new JProperty("b", atomId0)); jBond.Add(new JProperty("e", atomId1)); if (!string.IsNullOrEmpty(bondOrder)) { Single order = OrderToNumber(bondOrder); if (order != 1) { jBond.Add(new JProperty("o", order)); } } if (!string.IsNullOrEmpty(bondStereo)) { jBond.Add(new JProperty("s", CmlStereoToJson(bondStereo))); } jBondsArray.Add(jBond); bondCount++; } } return(jsonOut.ToString()); }
public Dictionary <string, int> GetLibraryNames() { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; var allNames = new Dictionary <string, int>(); Stopwatch sw = new Stopwatch(); sw.Start(); try { using (SQLiteConnection conn = LibraryConnection()) { using (SQLiteDataReader names = GetAllNames(conn)) { while (names.Read()) { string name = names["Name"] as string; if (!string.IsNullOrEmpty(name) && name.Length > 3) { // Exclude any purely numeric names long numeric = -1; if (!long.TryParse(name, out numeric)) { int id = int.Parse(names["ChemistryId"].ToString()); if (!allNames.ContainsKey(name)) { allNames.Add(name, id); } } } } } } } catch (Exception ex) { using (var form = new ReportError(Globals.Chem4WordV3.Telemetry, Globals.Chem4WordV3.WordTopLeft, module, ex)) { form.ShowDialog(); } } sw.Stop(); #if DEBUG // Task 810 Globals.Chem4WordV3.Telemetry.Write(module, "Timing", $"Reading {allNames.Count} Chemical names took {SafeDouble.AsString(sw.ElapsedMilliseconds)}ms"); #endif return(allNames); }
/// <summary> /// This is called via Microsoft.Office.Tools.CustomTaskPanel.OnVisibleChanged and Chem4Word.CustomRibbon.OnShowLibraryClick /// </summary> /// <param name="filter"></param> /// <returns></returns> public List <ChemistryDTO> GetAllChemistry(string filter) { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}({filter})"; var results = new List <ChemistryDTO>(); Stopwatch sw = new Stopwatch(); sw.Start(); using (SQLiteConnection conn = LibraryConnection()) { SQLiteDataReader chemistry = GetAllChemistry(conn, filter); while (chemistry.Read()) { var dto = new ChemistryDTO(); dto.Id = (long)chemistry["ID"]; dto.Cml = CmlFromBytes(chemistry["Chemistry"] as Byte[]); dto.Name = chemistry["name"] as string; dto.Formula = chemistry["formula"] as string; results.Add(dto); } chemistry.Close(); chemistry.Dispose(); } sw.Stop(); Globals.Chem4WordV3.Telemetry.Write(module, "Timing", $"Reading {results.Count} structures took {SafeDouble.AsString(sw.ElapsedMilliseconds)}ms"); return(results); }
private void GetExternalIpAddress(object o) { string module = $"{MethodBase.GetCurrentMethod().Name}()"; try { string message; IpAddress = "0.0.0.0"; for (int i = 0; i < 2; i++) { foreach (string place in _placesToTry) { _attempts++; try { message = $"Attempt #{_attempts} using '{place}'"; StartUpTimings.Add(message); Debug.WriteLine(message); if (place.Contains("chem4word")) { GetInternalVersion(place); } else { GetExternalVersion(place); } // Exit out of inner loop if (!IpAddress.Contains("0.0.0.0")) { break; } } catch (Exception exception) { Debug.WriteLine(exception.Message); StartUpTimings.Add(exception.Message); } } // Exit out of outer loop if (!IpAddress.Contains("0.0.0.0")) { break; } } if (IpAddress.Contains("0.0.0.0")) { // Handle failure IpAddress = "8.8.8.8"; } _ipStopwatch.Stop(); message = $"{module} took {SafeDouble.AsString0(_ipStopwatch.ElapsedMilliseconds)}ms"; StartUpTimings.Add(message); Debug.WriteLine(message); } catch (ThreadAbortException threadAbortException) { // Do Nothing Debug.WriteLine(threadAbortException.Message); } catch (Exception exception) { Debug.WriteLine(exception.Message); StartUpTimings.Add(exception.Message); } }
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>()); }