private void HandleChangedCml(string cml, string captionPrefix) { var cc = new CMLConverter(); if (_lastCml != EmptyCml) { var clone = cc.Import(_lastCml); Debug.WriteLine( $"Pushing F: {clone.ConciseFormula} BL: {clone.MeanBondLength.ToString("#,##0.00")} onto Stack"); _undoStack.Push(clone); } Model m = cc.Import(cml); m.Relabel(true); m.EnsureBondLength(20, false); _lastCml = cc.Export(m); // Cause re-read of settings (in case they have changed) _editorOptions = new AcmeOptions(null); SetDisplayOptions(); RedoStack.SetOptions(_editorOptions); UndoStack.SetOptions(_editorOptions); ShowChemistry($"{captionPrefix} {m.ConciseFormula}", m); }
public void CmlImportExportNested() { CMLConverter mc = new CMLConverter(); Model model_1 = mc.Import(ResourceHelper.GetStringResource("NestedMolecules.xml")); // Basic Sanity Checks Assert.True(model_1.Molecules.Count == 1, $"Expected 1 Molecule; Got {model_1.Molecules.Count}"); // Check molecule m0 has 4 child molecules and no atoms Molecule molecule_1 = model_1.Molecules.Values.First(); Assert.True(molecule_1.Molecules.Count == 4, $"Expected 4 Molecule; Got {molecule_1.Molecules.Count}"); Assert.True(molecule_1.Atoms.Count == 0, $"Expected 0 Atoms; Got {molecule_1.Atoms.Count}"); // Check molecule m2 has no child molecules and 6 atoms molecule_1 = model_1.Molecules.Values.First().Molecules.Values.ToList()[1]; Assert.True(molecule_1.Molecules.Count == 0, $"Expected 0 Molecule; Got {molecule_1.Molecules.Count}"); Assert.True(molecule_1.Atoms.Count == 6, $"Expected 6 Atoms; Got {molecule_1.Atoms.Count}"); // Check molecule m1 has 1 child molecules and no atoms molecule_1 = model_1.Molecules.Values.First().Molecules.Values.First(); Assert.True(molecule_1.Molecules.Count == 1, $"Expected 1 Molecule; Got {molecule_1.Molecules.Count}"); Assert.True(molecule_1.Atoms.Count == 0, $"Expected 0 Atoms; Got {molecule_1.Atoms.Count}"); // Check molecule m5 has 1 child molecules and 6 atoms molecule_1 = model_1.Molecules.Values.First().Molecules.Values.First().Molecules.Values.First(); Assert.True(molecule_1.Molecules.Count == 0, $"Expected 0 Molecule; Got {molecule_1.Molecules.Count}"); Assert.True(molecule_1.Atoms.Count == 6, $"Expected 6 Atoms; Got {molecule_1.Atoms.Count}"); var exported = mc.Export(model_1); Model model_2 = mc.Import(exported); // Basic Sanity Checks Assert.True(model_2.Molecules.Count == 1, $"Expected 1 Molecule; Got {model_2.Molecules.Count}"); // Check molecule m0 has 4 child molecules and no atoms Molecule molecule_2 = model_2.Molecules.Values.First(); Assert.True(molecule_2.Molecules.Count == 4, $"Expected 4 Molecule; Got {molecule_2.Molecules.Count}"); Assert.True(molecule_2.Atoms.Count == 0, $"Expected 0 Atoms; Got {molecule_2.Atoms.Count}"); // Check molecule m2 has no child molecules and 6 atoms molecule_2 = model_2.Molecules.Values.First().Molecules.Values.ToList()[1]; Assert.True(molecule_2.Molecules.Count == 0, $"Expected 0 Molecule; Got {molecule_2.Molecules.Count}"); Assert.True(molecule_2.Atoms.Count == 6, $"Expected 6 Atoms; Got {molecule_2.Atoms.Count}"); // Check molecule m1 has 1 child molecules and no atoms molecule_2 = model_2.Molecules.Values.First().Molecules.Values.First(); Assert.True(molecule_2.Molecules.Count == 1, $"Expected 1 Molecule; Got {molecule_2.Molecules.Count}"); Assert.True(molecule_2.Atoms.Count == 0, $"Expected 0 Atoms; Got {molecule_2.Atoms.Count}"); // Check molecule m5 has 1 child molecules and 6 atoms molecule_2 = model_2.Molecules.Values.First().Molecules.Values.First().Molecules.Values.First(); Assert.True(molecule_2.Molecules.Count == 0, $"Expected 0 Molecule; Got {molecule_2.Molecules.Count}"); Assert.True(molecule_2.Atoms.Count == 6, $"Expected 6 Atoms; Got {molecule_2.Atoms.Count}"); }
private void EditWithAcme_Click(object sender, EventArgs e) { #if !DEBUG string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; try { #endif if (!string.IsNullOrEmpty(_lastCml)) { using (EditorHost editorHost = new EditorHost(_lastCml, "ACME")) { editorHost.ShowDialog(this); if (editorHost.DialogResult == DialogResult.OK) { CMLConverter cc = new CMLConverter(); var clone = cc.Import(_lastCml); Debug.WriteLine( $"Pushing F: {clone.ConciseFormula} BL: {clone.MeanBondLength.ToString("#,##0.00")} onto Stack"); _undoStack.Push(clone); Model m = cc.Import(editorHost.OutputValue); m.Relabel(true); _lastCml = cc.Export(m); // Cause re-read of settings (in case they have changed) _editorOptions = new AcmeOptions(null); SetDisplayOptions(); RedoStack.SetOptions(_editorOptions); UndoStack.SetOptions(_editorOptions); ShowChemistry($"Edited {m.ConciseFormula}", m); } } TopMost = true; TopMost = false; Activate(); } #if !DEBUG } catch (Exception exception) { _telemetry.Write(module, "Exception", $"Exception: {exception.Message}"); _telemetry.Write(module, "Exception(Data)", $"Exception: {exception}"); MessageBox.Show(exception.StackTrace, exception.Message); } #endif }
public static void RefreshAllStructures(Word.Document doc) { string module = $"{Product}.{Class}.{MethodBase.GetCurrentMethod().Name}()"; if (Globals.Chem4WordV3.SystemOptions == null) { Globals.Chem4WordV3.LoadOptions(); } IChem4WordRenderer renderer = Globals.Chem4WordV3.GetRendererPlugIn( Globals.Chem4WordV3.SystemOptions.SelectedRendererPlugIn); if (renderer != null) { foreach (CustomXMLPart xmlPart in doc.CustomXMLParts) { var cml = xmlPart.XML; var cxmlId = CustomXmlPartHelper.GetCmlId(xmlPart); CMLConverter cc = new CMLConverter(); var model = cc.Import(cml); renderer.Properties = new Dictionary <string, string>(); renderer.Properties.Add("Guid", cxmlId); renderer.Cml = cml; string tempfileName = renderer.Render(); if (File.Exists(tempfileName)) { UpdateThisStructure(doc, model, cxmlId, tempfileName); } } } }
private void HandleDataContextChanged() { ChemistryModel chemistryModel = null; if (Chemistry is string) { var data = Chemistry as string; if (!string.IsNullOrEmpty(data)) { if (data.StartsWith("<")) { var conv = new CMLConverter(); chemistryModel = conv.Import(data); } if (data.Contains("M END")) { var conv = new SdFileConverter(); chemistryModel = conv.Import(data); } } } else { if (Chemistry != null && !(Chemistry is ChemistryModel)) { throw new ArgumentException("Object must be of type 'Chem4Word.Model.Model'."); } chemistryModel = Chemistry as ChemistryModel; } if (chemistryModel != null) { if (chemistryModel.AllAtoms.Count > 0) { chemistryModel.RescaleForXaml(Constants.StandardBondLength * 2); Debug.WriteLine($"Ring count == {chemistryModel.Molecules.SelectMany(m => m.Rings).Count()}"); if (ShowCarbonLabels) { foreach (var atom in chemistryModel.AllAtoms) { if (atom.Element.Equals(Globals.PeriodicTable.C)) { atom.ShowSymbol = true; } } } Placeholder.DataContext = chemistryModel; } else { Placeholder.DataContext = null; } } else { Placeholder.DataContext = null; } }
private void ProcessResponse(HttpWebResponse response) { LabelInfo.Text = ""; // read data via the response stream using (Stream resStream = response.GetResponseStream()) { if (resStream != null) { StreamReader sr = new StreamReader(resStream); string temp = sr.ReadToEnd(); CMLConverter cmlConverter = new CMLConverter(); Model.Model model = cmlConverter.Import(temp); if (model.MeanBondLength < Core.Helpers.Constants.MinimumBondLength - Core.Helpers.Constants.BondLengthTolerance || model.MeanBondLength > Core.Helpers.Constants.MaximumBondLength + Core.Helpers.Constants.BondLengthTolerance) { model.ScaleToAverageBondLength(Core.Helpers.Constants.StandardBondLength); } Cml = cmlConverter.Export(model); display1.Chemistry = Cml; ImportButton.Enabled = true; } } }
/// <summary> /// Create an OpenXml Word Document from the CML /// </summary> /// <param name="cml">Input Chemistry</param> /// <param name="guid">Bookmark to create</param> /// <param name="options"></param> /// <returns></returns> public static string CreateFromCml(string cml, string guid, Options options, IChem4WordTelemetry telemetry, Point topLeft) { CMLConverter cc = new CMLConverter(); Model.Model m = cc.Import(cml); string fileName = Path.Combine(Path.GetTempPath(), $"Chem4Word-V3-{guid}.docx"); bool canRender = m.AllAtoms.Count > 0 && (m.MeanBondLength > Constants.BondLengthTolerance / 2 || m.AllBonds.Count == 0); if (canRender) { string bookmarkName = "C4W_" + guid; // Create a Wordprocessing document. using (WordprocessingDocument package = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document)) { // Add a new main document part. MainDocumentPart mdp = package.AddMainDocumentPart(); mdp.Document = new Document(new Body()); Body docbody = package.MainDocumentPart.Document.Body; // This is for test //AddParagraph(docbody, "Hello World", bookmarkName); // This will be live AddPictureFromModel(docbody, m, bookmarkName, options, telemetry, topLeft); // Save changes to the main document part. package.MainDocumentPart.Document.Save(); } } return(fileName); }
private void Redo_Click(object sender, EventArgs e) { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; try { Model m = _redoStack.Pop(); Debug.WriteLine( $"Popped F: {m.ConciseFormula} BL: {m.MeanBondLength.ToString("#,##0.00")} from Redo Stack"); if (!string.IsNullOrEmpty(_lastCml)) { CMLConverter cc = new CMLConverter(); var clone = cc.Import(_lastCml); _lastCml = cc.Export(m); Debug.WriteLine( $"Pushing F: {clone.ConciseFormula} BL: {clone.MeanBondLength.ToString("#,##0.00")} onto Undo Stack"); _undoStack.Push(clone); } ShowChemistry($"Redo -> {m.ConciseFormula}", m); } catch (Exception exception) { _telemetry.Write(module, "Exception", $"Exception: {exception.Message}"); _telemetry.Write(module, "Exception(Data)", $"Exception: {exception}"); MessageBox.Show(exception.StackTrace, exception.Message); } }
private void EditorHost_Load(object sender, EventArgs e) { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; Cursor.Current = Cursors.WaitCursor; if (TopLeft.X != 0 && TopLeft.Y != 0) { Left = (int)TopLeft.X; Top = (int)TopLeft.Y; } CMLConverter cc = new CMLConverter(); JSONConverter jc = new JSONConverter(); Model.Model model = cc.Import(_cml); WpfChemDoodle editor = new WpfChemDoodle(); editor.Telemetry = Telemetry; editor.ProductAppDataPath = ProductAppDataPath; editor.UserOptions = UserOptions; editor.TopLeft = TopLeft; editor.StructureJson = jc.Export(model); editor.IsSingleMolecule = model.Molecules.Count == 1; editor.AverageBondLength = model.MeanBondLength; editor.InitializeComponent(); elementHost1.Child = editor; editor.OnButtonClick += OnWpfButtonClick; this.Show(); Application.DoEvents(); }
/// <summary> /// Occurs after a new custom XMl part is loaded into the document /// Useful for updating the Navigator /// </summary> /// <param name="NewPart"></param> private void OnPartAfterLoad(CustomXMLPart NewPart) { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; try { var converter = new CMLConverter(); //get the chemistry var chemModel = converter.Import(NewPart.XML); //find out which content control macthes the custom XML part try { // ReSharper disable once InconsistentNaming var matchingCC = (from ContentControl cc in _doc.ContentControls orderby cc.Range.Start where CustomXmlPartHelper.GuidFromTag(cc?.Tag) == CustomXmlPartHelper.GetCmlId(NewPart) select cc).First(); //get the ordinal position of the content control int start = 0; foreach (ContentControl cc in _doc.ContentControls) { if (cc.ID == matchingCC.ID) { break; } start += 1; } //insert the new navigator item at the ordinal position var newNavItem = new NavigatorItem() { CMLId = matchingCC?.Tag, ChemicalStructure = NewPart.XML, XMLPart = NewPart, Name = chemModel.ConciseFormula }; try { NavigatorItems.Insert(start, newNavItem); } catch (ArgumentOutOfRangeException) //can happen when there are more content controls than navigator items { //so simply insert the new navigator item at the end NavigatorItems.Add(newNavItem); } } catch (InvalidOperationException) { //sequence contains no elements - thrown on close //just ignore } } catch (Exception ex) { new ReportError(Globals.Chem4WordV3.Telemetry, Globals.Chem4WordV3.WordTopLeft, module, ex).ShowDialog(); } }
private void ClearChemistry_Click(object sender, EventArgs e) { var cc = new CMLConverter(); _undoStack.Push(cc.Import(_lastCml)); _lastCml = "<cml></cml>"; Display.Clear(); EnableUndoRedoButtons(); }
private void EditLabels_Click(object sender, EventArgs e) { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; #if !DEBUG try #endif { if (!string.IsNullOrEmpty(_lastCml)) { using (EditorHost editorHost = new EditorHost(_lastCml, "LABELS")) { editorHost.ShowDialog(this); if (editorHost.DialogResult == DialogResult.OK) { CMLConverter cc = new CMLConverter(); var clone = cc.Import(_lastCml); Debug.WriteLine( $"Pushing F: {clone.ConciseFormula} BL: {clone.MeanBondLength.ToString("#,##0.00")} onto Stack"); _undoStack.Push(clone); Model m = cc.Import(editorHost.OutputValue); m.Relabel(true); _lastCml = cc.Export(m); ShowChemistry($"Edited {m.ConciseFormula}", m); } } TopMost = true; TopMost = false; Activate(); } } #if !DEBUG catch (Exception exception) { _telemetry.Write(module, "Exception", $"Exception: {exception.Message}"); _telemetry.Write(module, "Exception(Data)", $"Exception: {exception}"); MessageBox.Show(exception.StackTrace, exception.Message); } #endif }
public void SetProperties(string cml, List <string> used1DProperties, AcmeOptions options) { CMLConverter cc = new CMLConverter(); _model = cc.Import(cml, used1DProperties); _used1DProperties = used1DProperties; EditorOptions = options; InitialiseEditor(); }
private void MainWindow_OnLoaded(object sender, RoutedEventArgs e) { CMLConverter conv = new CMLConverter(); ComboBoxItem cb1 = new ComboBoxItem(); cb1.Tag = conv.Import(ChemistryValues.TESTOSTERONE); cb1.Content = "testosterone"; SelectStructureCombo.Items.Add(cb1); ComboBoxItem cb2 = new ComboBoxItem(); cb2.Tag = ChemistryValues.PARAFUCHSIN_CARBOL; cb2.Content = "parafuchsin carbol"; SelectStructureCombo.Items.Add(cb2); ComboBoxItem cb3 = new ComboBoxItem(); cb3.Tag = conv.Import(ChemistryValues.PHTHALOCYANINE); cb3.Content = "phthalocyanine"; SelectStructureCombo.Items.Add(cb3); ComboBoxItem cb4 = new ComboBoxItem(); cb4.Tag = conv.Import(ChemistryValues.THEMONSTER); cb4.Content = "The Monster"; SelectStructureCombo.Items.Add(cb4); ComboBoxItem cb5 = new ComboBoxItem(); cb5.Tag = conv.Import(ChemistryValues.INSULIN); cb5.Content = "insulin"; SelectStructureCombo.Items.Add(cb5); ComboBoxItem cb6 = new ComboBoxItem(); cb6.Tag = conv.Import(ChemistryValues.CHARGESPLUS); cb6.Content = "lots of charges"; SelectStructureCombo.Items.Add(cb6); }
private void SaveStructure_Click(object sender, EventArgs e) { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; try { CMLConverter cmlConverter = new CMLConverter(); Model m = cmlConverter.Import(_lastCml); m.CustomXmlPartGuid = ""; string filter = "CML molecule files (*.cml, *.xml)|*.cml;*.xml|MDL molecule files (*.mol, *.sdf)|*.mol;*.sdf"; using (SaveFileDialog sfd = new SaveFileDialog { Filter = filter }) { DialogResult dr = sfd.ShowDialog(); if (dr == DialogResult.OK) { FileInfo fi = new FileInfo(sfd.FileName); _telemetry.Write(module, "Information", $"Exporting to '{fi.Name}'"); string fileType = Path.GetExtension(sfd.FileName).ToLower(); switch (fileType) { case ".cml": case ".xml": string temp = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + Environment.NewLine + cmlConverter.Export(m); File.WriteAllText(sfd.FileName, temp); break; case ".mol": case ".sdf": // https://www.chemaxon.com/marvin-archive/6.0.2/marvin/help/formats/mol-csmol-doc.html double before = m.MeanBondLength; // Set bond length to 1.54 angstroms (Å) m.ScaleToAverageBondLength(1.54); double after = m.MeanBondLength; _telemetry.Write(module, "Information", $"Structure rescaled from {before.ToString("#0.00")} to {after.ToString("#0.00")}"); SdFileConverter converter = new SdFileConverter(); File.WriteAllText(sfd.FileName, converter.Export(m)); break; } } } } catch (Exception exception) { _telemetry.Write(module, "Exception", $"Exception: {exception.Message}"); _telemetry.Write(module, "Exception(Data)", $"Exception: {exception}"); MessageBox.Show(exception.StackTrace, exception.Message); } }
private void FormEditLabels_Load(object sender, EventArgs e) { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; try { if (TopLeft.X != 0 && TopLeft.Y != 0) { Left = (int)TopLeft.X; Top = (int)TopLeft.Y; } // Load Cml into model _model = _cmlConvertor.Import(Cml); #region Display Overall Concise Formula rtbConcise.SelectionFont = new Font("Tahoma", 10); rtbConcise.Text = "Overall Concise formula for this structure is "; rtbConcise.SelectionStart = rtbConcise.TextLength; List <FormulaPart> parts = FormulaHelper.Parts(_model.ConciseFormula); foreach (var part in parts) { switch (part.Count) { case 0: // Seperator or multiplier case 1: // No Subscript rtbConcise.SelectionFont = new Font("Tahoma", 10); rtbConcise.SelectionCharOffset = 0; rtbConcise.AppendText(part.Atom); break; default: // With Subscript rtbConcise.SelectionFont = new Font("Tahoma", 10); rtbConcise.SelectionCharOffset = 0; rtbConcise.AppendText(part.Atom); rtbConcise.SelectionFont = new Font("Tahoma", 7); rtbConcise.SelectionCharOffset = -5; rtbConcise.AppendText($"{part.Count}"); break; } } #endregion Display Overall Concise Formula LoadTabsControls(); } catch (Exception ex) { new ReportError(Globals.Chem4WordV3.Telemetry, Globals.Chem4WordV3.WordTopLeft, module, ex).ShowDialog(); } }
public void CmlImportNoAtoms() { CMLConverter mc = new CMLConverter(); Model m = mc.Import(ResourceHelper.GetStringResource("NoAtoms.xml")); // Basic sanity checks Assert.True(m.Molecules.Count == 1, $"Expected 1 Molecule; Got {m.Molecules.Count}"); Assert.True(m.TotalAtomsCount == 0, $"Expected 0 Atoms; Got {m.TotalAtomsCount}"); Assert.True(m.TotalBondsCount == 0, $"Expected 0 Bonds; Got {m.TotalBondsCount}"); // Check that names and formulae have not been trashed Assert.True(m.Molecules.Values.First().Names.Count == 1, $"Expected 1 Chemical Names; Got {m.Molecules.Values.First().Names.Count}"); }
private void HandleDataContextChanged() { Model chemistryModel = null; if (Chemistry is string) { var data = Chemistry as string; if (!string.IsNullOrEmpty(data)) { if (data.StartsWith("<")) { var conv = new CMLConverter(); chemistryModel = conv.Import(data); chemistryModel.EnsureBondLength(20, false); } if (data.Contains("M END")) { var conv = new SdFileConverter(); chemistryModel = conv.Import(data); chemistryModel.EnsureBondLength(20, false); } } } else { if (Chemistry != null && !(Chemistry is Model)) { Debugger.Break(); throw new ArgumentException($"Object must be of type {nameof(Model)}."); } chemistryModel = Chemistry as Model; if (chemistryModel != null) { chemistryModel.EnsureBondLength(20, false); } } //assuming we've got this far, we should have something we can draw if (chemistryModel != null) { if (chemistryModel.TotalAtomsCount > 0) { chemistryModel.RescaleForXaml(true, Constants.StandardBondLength); CurrentViewModel = new ViewModel(chemistryModel); CurrentViewModel.SetTextParams(chemistryModel.XamlBondLength); DrawChemistry(CurrentViewModel); } } }
/// <summary> /// Create an OpenXml Word Document from the CML /// </summary> /// <param name="cml">Input Chemistry</param> /// <param name="guid">Bookmark to create</param> /// <param name="options"></param> /// <param name="telemetry"></param> /// <param name="topLeft"></param> /// <returns></returns> public static string CreateFromCml(string cml, string guid, OoXmlV4Options options, IChem4WordTelemetry telemetry, Point topLeft) { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; CMLConverter cc = new CMLConverter(); Model model = cc.Import(cml); if (model.AllErrors.Count > 0 || model.AllWarnings.Count > 0) { if (model.AllErrors.Count > 0) { telemetry.Write(module, "Exception(Data)", string.Join(Environment.NewLine, model.AllErrors)); } if (model.AllWarnings.Count > 0) { telemetry.Write(module, "Exception(Data)", string.Join(Environment.NewLine, model.AllWarnings)); } } string fileName = string.Empty; bool canRender = model.TotalAtomsCount > 0 && (model.TotalBondsCount == 0 || model.MeanBondLength > Core.Helpers.Constants.BondLengthTolerance / 2); if (canRender) { fileName = Path.Combine(Path.GetTempPath(), $"Chem4Word-V3-{guid}.docx"); string bookmarkName = Core.Helpers.Constants.OoXmlBookmarkPrefix + guid; // Create a Wordprocessing document. using (WordprocessingDocument package = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document)) { // Add a new main document part. MainDocumentPart mdp = package.AddMainDocumentPart(); mdp.Document = new Document(new Body()); Body docbody = package.MainDocumentPart.Document.Body; // This will be live AddPictureFromModel(docbody, model, bookmarkName, options, telemetry, topLeft); // Save changes to the main document part. package.MainDocumentPart.Document.Save(); } } return(fileName); }
private void button1_Click(object sender, EventArgs e) { StringBuilder sb = new StringBuilder(); sb.Append("All molecule files (*.mol, *.sdf, *.cml)|*.mol;*.sdf;*.cml"); sb.Append("|CML molecule files (*.cml)|*.cml"); sb.Append("|MDL molecule files (*.mol, *.sdf)|*.mol;*.sdf"); openFileDialog1.FileName = "*.*"; openFileDialog1.Filter = sb.ToString(); DialogResult dr = openFileDialog1.ShowDialog(); if (dr == DialogResult.OK) { string fileType = Path.GetExtension(openFileDialog1.FileName).ToLower(); string filename = Path.GetFileName(openFileDialog1.FileName); string mol = File.ReadAllText(openFileDialog1.FileName); string cml = ""; CMLConverter cmlConvertor = new CMLConverter(); SdFileConverter sdFileConverter = new SdFileConverter(); Model model = null; switch (fileType) { case ".mol": case ".sdf": model = sdFileConverter.Import(mol); model.RefreshMolecules(); model.Relabel(); cml = cmlConvertor.Export(model); //model.DumpModel("After Import"); break; case ".cml": case ".xml": model = cmlConvertor.Import(mol); model.RefreshMolecules(); model.Relabel(); cml = cmlConvertor.Export(model); break; } this.Text = filename; this.display1.Chemistry = cml; } }
/// <summary> /// Loads up the model initially from the document /// </summary> private void LoadModel() { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; try { var converter = new CMLConverter(); if (NavigatorItems.Any()) { NavigatorItems.Clear(); } if (_doc != null) { Dictionary <string, int> added = new Dictionary <string, int>(); var navItems = from ContentControl ccs in _doc.ContentControls join CustomXMLPart part in _parts on CustomXmlPartHelper.GuidFromTag(ccs?.Tag) equals CustomXmlPartHelper.GetCmlId(part) orderby ccs.Range.Start let chemModel = converter.Import(part.XML) select new NavigatorItem { CMLId = ccs?.Tag, ChemicalStructure = part.XML, XMLPart = part, Name = chemModel.ConciseFormula }; foreach (NavigatorItem navigatorItem in navItems) { string guid = CustomXmlPartHelper.GuidFromTag(navigatorItem.CMLId); if (!string.IsNullOrEmpty(guid)) { if (!added.ContainsKey(guid)) { NavigatorItems.Add(navigatorItem); added.Add(guid, 1); } } } Debug.WriteLine("Number of items loaded = {0}", NavigatorItems.Count); } } catch (Exception ex) { using (var form = new ReportError(Globals.Chem4WordV3.Telemetry, Globals.Chem4WordV3.WordTopLeft, module, ex)) { form.ShowDialog(); } } }
public override void Execute(object parameter) { CMLConverter cmlConverter = new CMLConverter(); SdFileConverter sdfConverter = new SdFileConverter(); if (Clipboard.ContainsData(Globals.FormatCML)) { string pastedCML = (string)Clipboard.GetData(Globals.FormatCML); EditViewModel.PasteCML(pastedCML); } else if (Clipboard.ContainsText()) { bool failedCML = false; bool failedSDF = false; string pastedText = Clipboard.GetText(); Model buffer = null; //try to convert the pasted text with the CML converter first try { buffer = cmlConverter.Import(pastedText); } catch { failedCML = true; } if (failedCML) { buffer = sdfConverter.Import(pastedText); failedSDF = buffer.GeneralErrors.Any(); } if (failedCML & failedSDF) { if (buffer.GeneralErrors.Any()) { Chem4Word.Core.UserInteractions.InformUser("Unable to paste text as chemistry: " + buffer.GeneralErrors[0]); } else { Chem4Word.Core.UserInteractions.InformUser("Unable to paste text as chemistry: unknown error."); } } else { EditViewModel.PasteModel(buffer); } } }
public void CmlImportCopperPhthalocyanine() { CMLConverter mc = new CMLConverter(); Model m = mc.Import(ResourceHelper.GetStringResource("CopperPhthalocyanine.xml")); // Basic Sanity Checks Assert.True(m.Molecules.Count == 1, $"Expected 1 Molecule; Got {m.Molecules.Count}"); Assert.True(m.TotalAtomsCount == 57, $"Expected 57 Atoms; Got {m.TotalAtomsCount}"); Assert.True(m.TotalBondsCount == 68, $"Expected 68 Bonds; Got {m.TotalBondsCount}"); Assert.True(m.Molecules.Values.First().Rings.Count == 12, $"Expected 12 Rings; Got {m.Molecules.Values.First().Rings.Count}"); var list = m.Molecules.Values.First().SortRingsForDBPlacement(); Assert.True(list.Count == 12, $"Expected 12 Rings; Got {list.Count}"); }
public void CmlImportPhthalocyanineThenRefresh() { CMLConverter mc = new CMLConverter(); Model m = mc.Import(ResourceHelper.GetStringResource("Phthalocyanine.xml")); // Basic Sanity Checks Assert.True(m.Molecules.Count == 1, $"Expected 1 Molecule; Got {m.Molecules.Count}"); Assert.True(m.TotalAtomsCount == 58, $"Expected 58 Atoms; Got {m.TotalAtomsCount}"); Assert.True(m.TotalBondsCount == 66, $"Expected 66 Bonds; Got {m.TotalBondsCount}"); Assert.True(m.Molecules.Values.First().Rings.Count == 9, $"Expected 9 Rings; Got {m.Molecules.Values.First().Rings.Count}"); var list = m.Molecules.Values.First().SortRingsForDBPlacement(); Assert.True(list.Count == 8, $"Expected 8 Rings; Got {list.Count}"); }
public DialogResult Edit() { string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()"; DialogResult result = DialogResult.Cancel; try { Telemetry.Write(module, "Verbose", "Called"); if (HasSettings) { LoadSettings(); } CMLConverter cmlConverter = new CMLConverter(); Model.Model model = cmlConverter.Import(Cml); JSONConverter jsonConverter = new JSONConverter(); string json = jsonConverter.Export(model); ChemDoodleWeb cdwEditor = new ChemDoodleWeb(); cdwEditor.TopLeft = TopLeft; cdwEditor.Telemetry = Telemetry; cdwEditor.ProductAppDataPath = ProductAppDataPath; cdwEditor.UserOptions = _editorOptions; cdwEditor.Before_JSON = json; cdwEditor.IsSingleMolecule = model.Molecules.Count == 1; cdwEditor.AverageBondLength = model.MeanBondLength; result = cdwEditor.ShowDialog(); if (result == DialogResult.OK) { Properties = new Dictionary <string, string>(); Properties.Add("Before_Formula", cdwEditor.Before_Formula); Properties.Add("After_Formula", cdwEditor.After_Formula); json = cdwEditor.After_JSON; cdwEditor.Close(); model = jsonConverter.Import(json); Cml = cmlConverter.Export(model); } } catch (Exception ex) { new ReportError(Telemetry, TopLeft, module, ex).ShowDialog(); } return(result); }
public void CmlImportCopperPhthalocyanineThenRefresh() { CMLConverter mc = new CMLConverter(); Model m = mc.Import(ResourceHelper.GetStringResource("CopperPhthalocyanine.xml")); m.RefreshMolecules(); // Basic Sanity Checks Assert.IsTrue(m.Molecules.Count == 1, $"Expected 1 Molecule; Got {m.Molecules.Count}"); Assert.IsTrue(m.AllAtoms.Count == 57, $"Expected 57 Atoms; Got {m.AllAtoms.Count}"); Assert.IsTrue(m.AllBonds.Count == 68, $"Expected 68 Bonds; Got {m.AllBonds.Count}"); Assert.IsTrue(m.Molecules[0].Rings.Count == 12, $"Expected 12 Rings; Got {m.Molecules[0].Rings.Count}"); var list = m.Molecules[0].SortRingsForDBPlacement(); Assert.IsTrue(list.Count == 12, $"Expected 12 Rings; Got {list.Count}"); }
public void CmlImportBenzene() { CMLConverter mc = new CMLConverter(); Model m = mc.Import(ResourceHelper.GetStringResource("Benzene.xml")); // Basic sanity checks Assert.True(m.Molecules.Count == 1, $"Expected 1 Molecule; Got {m.Molecules.Count}"); Assert.True(m.TotalAtomsCount == 6, $"Expected 6 Atoms; Got {m.TotalAtomsCount}"); Assert.True(m.TotalBondsCount == 6, $"Expected 6 Bonds; Got {m.TotalBondsCount}"); // Check that names and formulae have not been trashed Assert.True(m.Molecules.Values.First().Names.Count == 3, $"Expected 3 Chemical Names; Got {m.Molecules.Values.First().Names.Count}"); Assert.True(m.Molecules.Values.First().Formulas.Count == 2, $"Expected 2 Formulae; Got {m.Molecules.Values.First().Formulas.Count }"); // Check that we have one ring Assert.True(m.Molecules.Values.First().Rings.Count == 1, $"Expected 1 Ring; Got {m.Molecules.Values.First().Rings.Count}"); }
public void CmlImportBenzene() { CMLConverter mc = new CMLConverter(); Model m = mc.Import(ResourceHelper.GetStringResource("Benzene.xml")); // Basic sanity checks Assert.IsTrue(m.Molecules.Count == 1, $"Expected 1 Molecule; Got {m.Molecules.Count}"); Assert.IsTrue(m.AllAtoms.Count == 6, $"Expected 6 Atoms; Got {m.AllAtoms.Count}"); Assert.IsTrue(m.AllBonds.Count == 6, $"Expected 6 Bonds; Got {m.AllBonds.Count}"); // Check that names and formulae have not been trashed Assert.IsTrue(m.Molecules[0].ChemicalNames.Count == 2, $"Expected 2 Chemical Names; Got {m.Molecules[0].ChemicalNames.Count}"); Assert.IsTrue(m.Molecules[0].Formulas.Count == 2, $"Expected 2 Formulae; Got {m.Molecules[0].Formulas.Count }"); // Check that we have one ring Assert.IsTrue(m.Molecules.SelectMany(m1 => m1.Rings).Count() == 1, $"Expected 1 Ring; Got {m.Molecules.SelectMany(m1 => m1.Rings).Count()}"); }
private string CmlFromBytes(byte[] byteArray, long id) { string cml = Encoding.UTF8.GetString(byteArray); CMLConverter cc = new CMLConverter(); Model.Model m = cc.Import(cml); double before = m.MeanBondLength; if (before < Constants.MinimumBondLength - Constants.BondLengthTolerance || before > Constants.MaximumBondLength + Constants.BondLengthTolerance) { m.ScaleToAverageBondLength(Constants.StandardBondLength); double after = m.MeanBondLength; Debug.WriteLine($"Structure Id: {id} rescaled from {before.ToString("#0.00")} to {after.ToString("#0.00")}"); } return(cc.Export(m)); }
public void CmlImportTestosteroneThenRefresh() { CMLConverter mc = new CMLConverter(); Model m = mc.Import(ResourceHelper.GetStringResource("Testosterone.xml")); // Basic Sanity Checks Assert.True(m.Molecules.Count == 1, $"Expected 1 Molecule; Got {m.Molecules.Count}"); Assert.True(m.TotalAtomsCount == 25, $"Expected 25 Atoms; Got {m.TotalAtomsCount}"); Assert.True(m.TotalBondsCount == 28, $"Expected 28 Bonds; Got {m.TotalBondsCount}"); // Check that names and formulae have not been trashed Assert.True(m.Molecules.Values.First().Names.Count == 4, $"Expected 4 Chemical Names; Got {m.Molecules.Values.First().Names.Count}"); Assert.True(m.Molecules.Values.First().Formulas.Count == 2, $"Expected 2 Formulae; Got {m.Molecules.Values.First().Formulas.Count }"); Assert.True(m.Molecules.Values.First().Rings.Count == 4, $"Expected 4 Rings; Got {m.Molecules.Values.First().Rings.Count}"); var list = m.Molecules.Values.First().SortRingsForDBPlacement(); Assert.True(list.Count == 4, $"Expected 4 Rings; Got {list.Count}"); }