Esempio n. 1
0
        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;
            }
        }
Esempio n. 2
0
        public void SdfImportBasicParafuchsin()
        {
            SdFileConverter mc = new SdFileConverter();
            Model           m  = mc.Import(ResourceHelper.GetStringResource("BasicParafuchsin.txt"));

            // Basic sanity checks
            Assert.True(m.Molecules.Count == 1, $"Expected 1 Molecule; Got {m.Molecules.Count}");

            var mol = m.Molecules.Values.First();

            Assert.True(mol.Molecules.Count == 2,
                        $"Expected 2 Child Molecules; Got {mol.Molecules.Count}");
            Assert.True(m.TotalAtomsCount == 41, $"Expected 41 Atoms; Got {m.TotalAtomsCount}");
            Assert.True(m.TotalBondsCount == 42, $"Expected 42 Bonds; Got {m.TotalBondsCount}");

            // Check that we got three rings
            var mol2 = mol.Molecules.Values.Skip(1).First();

            Assert.True(mol2.Rings.Count == 3,
                        $"Expected 3 Rings; Got {mol2.Rings.Count}");

            string molstring = mc.Export(m);

            mc = new SdFileConverter();
            Model m2 = mc.Import(molstring);
        }
Esempio n. 3
0
        private void UpdateDisplay()
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            ErrorsAndWarnings.Text = "";

            using (new WaitCursor())
            {
                var tag = ResultsListView.SelectedItems[0]?.Tag;

                if (tag is LiteEntity le && !string.IsNullOrEmpty(le.chebiId))
                {
                    ChebiId = le.chebiId;
                    var chemStructure = GetChemStructure(le);

                    if (!string.IsNullOrEmpty(chemStructure))
                    {
                        _lastMolfile = ConvertToWindows(chemStructure);

                        SdFileConverter sdConverter = new SdFileConverter();
                        _lastModel = sdConverter.Import(chemStructure);
                        if (_lastModel.AllWarnings.Count > 0 || _lastModel.AllErrors.Count > 0)
                        {
                            Telemetry.Write(module, "Exception(Data)", chemStructure);
                            List <string> lines = new List <string>();
                            if (_lastModel.AllErrors.Count > 0)
                            {
                                Telemetry.Write(module, "Exception(Data)", string.Join(Environment.NewLine, _lastModel.AllErrors));
                                lines.Add("Errors(s)");
                                lines.AddRange(_lastModel.AllErrors);
                            }
                            if (_lastModel.AllWarnings.Count > 0)
                            {
                                Telemetry.Write(module, "Exception(Data)", string.Join(Environment.NewLine, _lastModel.AllWarnings));
                                lines.Add("Warnings(s)");
                                lines.AddRange(_lastModel.AllWarnings);
                            }
                            ErrorsAndWarnings.Text = string.Join(Environment.NewLine, lines);
                        }
                        if (_lastModel.MeanBondLength < Core.Helpers.Constants.MinimumBondLength - Core.Helpers.Constants.BondLengthTolerance ||
                            _lastModel.MeanBondLength > Core.Helpers.Constants.MaximumBondLength + Core.Helpers.Constants.BondLengthTolerance)
                        {
                            _lastModel.ScaleToAverageBondLength(Core.Helpers.Constants.StandardBondLength);
                        }
                        display1.Chemistry = _lastModel;
                    }
                    else
                    {
                        _lastModel             = null;
                        _lastMolfile           = String.Empty;
                        display1.Chemistry     = null;
                        ErrorsAndWarnings.Text = "No structure available.";
                    }

                    EnableImport();
                }
            }
        }
Esempio n. 4
0
        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);
                }
            }
        }
Esempio n. 5
0
        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;
            }
        }
Esempio n. 6
0
        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);
                }
            }
        }
Esempio n. 7
0
        private void UpdateDisplay()
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            ErrorsAndWarnings.Text = "";

            using (new WaitCursor())
            {
                var tag = ResultsListView.SelectedItems[0]?.Tag;

                LiteEntity le            = (LiteEntity)tag;
                var        chemStructure = GetChemStructure(le);

                if (!string.IsNullOrEmpty(chemStructure))
                {
                    _lastMolfile = ConvertToWindows(chemStructure);

                    SdFileConverter sdConverter = new SdFileConverter();
                    _lastModel = sdConverter.Import(chemStructure);
                    if (_lastModel.AllWarnings.Count > 0 || _lastModel.AllErrors.Count > 0)
                    {
                        Telemetry.Write(module, "Exception(Data)", chemStructure);
                        List <string> lines = new List <string>();
                        if (_lastModel.AllErrors.Count > 0)
                        {
                            Telemetry.Write(module, "Exception(Data)", string.Join(Environment.NewLine, _lastModel.AllErrors));
                            lines.Add("Errors(s)");
                            lines.AddRange(_lastModel.AllErrors);
                        }
                        if (_lastModel.AllWarnings.Count > 0)
                        {
                            Telemetry.Write(module, "Exception(Data)", string.Join(Environment.NewLine, _lastModel.AllWarnings));
                            lines.Add("Warnings(s)");
                            lines.AddRange(_lastModel.AllWarnings);
                        }
                        ErrorsAndWarnings.Text = string.Join(Environment.NewLine, lines);
                    }
                    ChebiId = le.chebiId;
                    flexDisplayControl1.Chemistry = _lastModel;
                }
                else
                {
                    flexDisplayControl1.Chemistry = null;
                    ErrorsAndWarnings.Text        = "No structure available.";
                }

                EnableImport();
            }
        }
Esempio n. 8
0
        public void SdfImportBenzene()
        {
            SdFileConverter mc = new SdFileConverter();
            Model           m  = mc.Import(ResourceHelper.GetStringResource("Benzene.txt"));

            // 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 == 2, $"Expected 2 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}");
        }
Esempio n. 9
0
        public void SdfImportBenzene()
        {
            SdFileConverter mc = new SdFileConverter();
            Model           m  = mc.Import(ResourceHelper.GetStringResource("Benzene.txt"));

            // 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()}");
        }
Esempio n. 10
0
        public void SdfImportBasicParafuchsin()
        {
            SdFileConverter mc = new SdFileConverter();
            Model           m  = mc.Import(ResourceHelper.GetStringResource("BasicParafuchsin.txt"));

            // Basic sanity checks
            Assert.IsTrue(m.Molecules.Count == 2, $"Expected 2 Molecules; Got {m.Molecules.Count}");
            Assert.IsTrue(m.AllAtoms.Count == 41, $"Expected 41 Atoms; Got {m.AllAtoms.Count}");
            Assert.IsTrue(m.AllBonds.Count == 42, $"Expected 42 Bonds; Got {m.AllBonds.Count}");

            // Check that we got two rings
            Assert.IsTrue(m.Molecules.SelectMany(m1 => m1.Rings).Count() == 3, $"Expected 2 Rings; Got {m.Molecules.SelectMany(m1 => m1.Rings).Count()}");

            string molstring = mc.Export(m);

            mc = new SdFileConverter();
            Model m2 = mc.Import(molstring);
        }
Esempio n. 11
0
        private void btnConvertModel_Click(object sender, EventArgs e)
        {
            TextBoxFormat format = GetTextBoxFormat(txtStructure);

            switch (format)
            {
            case TextBoxFormat.Json:
                JSONConverter converter1 = new JSONConverter();
                Model         model1     = converter1.Import((object)txtStructure.Text);
                model1.RebuildMolecules();
                model1.Relabel();
                model1.CustomXmlPartGuid = Guid.NewGuid().ToString("N");
                CMLConverter converter2 = new CMLConverter();
                txtStructure.Text = converter2.Export(model1);
                break;

            case TextBoxFormat.Cml:
                CMLConverter converter3 = new CMLConverter();
                Model        model2     = converter3.Import((object)txtStructure.Text);
                model2.RebuildMolecules();
                model2.Relabel();
                JSONConverter converter4 = new JSONConverter();
                txtStructure.Text = converter4.Export(model2);
                break;

            case TextBoxFormat.MolFile:
                SdFileConverter converter5 = new SdFileConverter();
                Model           model3     = converter5.Import((object)txtStructure.Text);
                model3.RebuildMolecules();
                model3.Relabel();
                CMLConverter converter6 = new CMLConverter();
                txtStructure.Text = converter6.Export(model3);
                break;
            }

            EnableButtons();
        }
Esempio n. 12
0
        private void LoadStructure_Click(object sender, EventArgs e)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            try
            {
                Model model = null;

                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.Title            = "Open Structure";
                openFileDialog1.InitialDirectory = Environment.SpecialFolder.MyDocuments.ToString();
                openFileDialog1.Filter           = sb.ToString();
                openFileDialog1.FileName         = "";
                openFileDialog1.ShowHelp         = false;

                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);

                    CMLConverter    cmlConvertor    = new CMLConverter();
                    SdFileConverter sdFileConverter = new SdFileConverter();

                    switch (fileType)
                    {
                    case ".mol":
                    case ".sdf":
                        model = sdFileConverter.Import(mol);
                        break;

                    case ".cml":
                    case ".xml":
                        model = cmlConvertor.Import(mol);
                        break;
                    }

                    if (model != null)
                    {
                        model.EnsureBondLength(20, false);
                        if (string.IsNullOrEmpty(model.CustomXmlPartGuid))
                        {
                            model.CustomXmlPartGuid = Guid.NewGuid().ToString("N");
                        }

                        if (!string.IsNullOrEmpty(_lastCml))
                        {
                            var clone = cmlConvertor.Import(_lastCml);
                            Debug.WriteLine(
                                $"Pushing F: {clone.ConciseFormula} BL: {clone.MeanBondLength.ToString("#,##0.00")} onto Stack");
                            _undoStack.Push(clone);
                        }

                        _lastCml = cmlConvertor.Export(model);

                        _telemetry.Write(module, "Information", $"File: {filename}");
                        ShowChemistry(filename, model);
                    }
                }
            }
            catch (Exception exception)
            {
                _telemetry.Write(module, "Exception", $"Exception: {exception.Message}");
                _telemetry.Write(module, "Exception(Data)", $"Exception: {exception}");
                MessageBox.Show(exception.StackTrace, exception.Message);
            }
        }
Esempio n. 13
0
        private void LoadModel(string fileName)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            if (!string.IsNullOrEmpty(fileName) && File.Exists(fileName))
            {
                try
                {
                    string contents = string.Empty;
                    using (var fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        using (var textReader = new StreamReader(fileStream))
                        {
                            contents = textReader.ReadToEnd();
                        }
                    }

                    Model  model    = null;
                    string fileType = Path.GetExtension(fileName).ToLower();
                    switch (fileType)
                    {
                    case ".cml":
                        var cmlConverter = new CMLConverter();
                        model = cmlConverter.Import(contents);
                        break;

                    case ".sdf":
                    case ".mol":
                        var sdFileConverter = new SdFileConverter();
                        model = sdFileConverter.Import(contents);
                        break;

                    case ".json":
                        var jsonConverter = new JSONConverter();
                        model = jsonConverter.Import(contents);
                        break;
                    }

                    if (model != null)
                    {
                        lastModel = model;

                        // Load model into TreeView
                        foreach (var modelMolecule in model.Molecules.Values)
                        {
                            LoadTreeNode(modelMolecule);
                        }

                        model.AtomsChanged     += Model_AtomsChanged;
                        model.BondsChanged     += Model_BondsChanged;
                        model.MoleculesChanged += Model_MoleculesChanged;
                        model.PropertyChanged  += Model_PropertyChanged;

                        int atoms = model.TotalAtomsCount;
                        int bonds = model.TotalBondsCount;
                        textBox1.AppendText($"Total Atoms Count is {atoms}, Total Bonds Count is {bonds}\n");
                        var list = new List <string>();
                        list.AddRange(model.GeneralErrors);
                        list.AddRange(model.AllErrors);
                        list.AddRange(model.AllWarnings);
                        textBox1.AppendText(string.Join(Environment.NewLine, list) + "\n");
                    }
                }
                catch (Exception exception)
                {
                    _telemetry.Write(module, "Exception", $"Exception: {exception.Message}");
                    _telemetry.Write(module, "Exception(Data)", $"Exception: {exception}");
                    MessageBox.Show(exception.StackTrace, exception.Message);
                }
            }

            // Local function to allow recursive calling
            void LoadTreeNode(Molecule modelMolecule, TreeNode root = null)
            {
                TreeNode parentNode;

                if (root == null)
                {
                    //FileInfo fi = new FileInfo(fileName);
                    //parentNode = treeView1.Nodes.Add(modelMolecule.Path, fi.Name + ": " + modelMolecule.ToString());
                    parentNode = treeView1.Nodes.Add(modelMolecule.Path, modelMolecule.ToString());
                    textBox1.AppendText($"Molecule {modelMolecule.Path} added.\n");
                }
                else
                {
                    parentNode = root.Nodes.Add(modelMolecule.Path, modelMolecule.ToString());
                    textBox1.AppendText($"Molecule {modelMolecule.Path} added.\n");
                }
                parentNode.Tag = modelMolecule;

                if (modelMolecule.Atoms.Any())
                {
                    var atomsNode = parentNode.Nodes.Add(modelMolecule.Path + "/Atoms", $"Atoms: count {modelMolecule.Atoms.Count}");

                    foreach (Atom atom in modelMolecule.Atoms.Values)
                    {
                        var res = atomsNode.Nodes.Add(atom.Path, atom.ToString());
                        res.Tag = atom;
                        textBox1.AppendText($"Atom {atom.Path} added.\n");
                    }
                }

                if (modelMolecule.Bonds.Any())
                {
                    var bondsNode = parentNode.Nodes.Add(modelMolecule.Path + "/Bonds", $"Bonds: count {modelMolecule.Bonds.Count}");

                    foreach (Bond bond in modelMolecule.Bonds)
                    {
                        var res = bondsNode.Nodes.Add(bond.Path, bond.ToString());
                        res.Tag = bond;
                        textBox1.AppendText($"Bond {bond.Path} added.\n");
                    }
                }

                if (modelMolecule.Formulas.Any())
                {
                    var formulasNode = parentNode.Nodes.Add(modelMolecule.Path + "/Formulas", $"Formulas: count {modelMolecule.Formulas.Count}");
                    foreach (var formula in modelMolecule.Formulas)
                    {
                        formulasNode.Nodes.Add(formula.Id, $"Formula {formula.Id} {formula.Convention} {formula.Inline}");
                    }
                }

                if (modelMolecule.Names.Any())
                {
                    var namesNode = parentNode.Nodes.Add(modelMolecule.Path + "/Names", $"Names: count {modelMolecule.Names.Count}");
                    foreach (var name in modelMolecule.Names)
                    {
                        namesNode.Nodes.Add(name.Id, $"Name {name.Id} {name.DictRef} {name.Name}");
                    }
                }

                if (modelMolecule.Rings.Any())
                {
                    var ringsNode = parentNode.Nodes.Add(modelMolecule.Path + "/Rings", $"Rings: count {modelMolecule.Rings.Count}");

                    int ringCounter = 1;
                    foreach (Ring r in modelMolecule.Rings)
                    {
                        var ringnode = ringsNode.Nodes.Add(r.GetHashCode().ToString(), $"Ring {ringCounter++} - Priority {r.Priority} with {r.Atoms.Count} Atoms");
                        ringnode.Tag = r;
                        foreach (Atom a in r.Atoms)
                        {
                            ringnode.Nodes.Add(r.GetHashCode() + a.Id, $"{a.Id} - {a.Path}");
                        }
                    }
                }

                foreach (var childMol in modelMolecule.Molecules.Values)
                {
                    LoadTreeNode(childMol, parentNode);
                }
            }
        }
Esempio n. 14
0
        private string FetchStructure()
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            string result = lastSelected;

            ImportButton.Enabled = false;

            ListView.SelectedListViewItemCollection selected = Results.SelectedItems;
            if (selected.Count > 0)
            {
                ListViewItem item      = selected[0];
                string       pubchemId = item.Text;
                PubChemId = pubchemId;

                if (!pubchemId.Equals(lastSelected))
                {
                    Cursor = Cursors.WaitCursor;

                    // https://pubchem.ncbi.nlm.nih.gov/rest/pug/compound/cid/241/record/SDF

                    var securityProtocol = ServicePointManager.SecurityProtocol;
                    ServicePointManager.SecurityProtocol = securityProtocol | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;

                    try
                    {
                        var request = (HttpWebRequest)WebRequest.Create(
                            string.Format(CultureInfo.InvariantCulture, "{0}rest/pug/compound/cid/{1}/record/SDF",
                                          UserOptions.PubChemRestApiUri, pubchemId));

                        request.Timeout   = 30000;
                        request.UserAgent = "Chem4Word";

                        HttpWebResponse response;

                        response = (HttpWebResponse)request.GetResponse();
                        if (HttpStatusCode.OK.Equals(response.StatusCode))
                        {
                            // we will read data via the response stream
                            using (var resStream = response.GetResponseStream())
                            {
                                lastMolfile = new StreamReader(resStream).ReadToEnd();
                                SdFileConverter sdFileConverter = new SdFileConverter();
                                Model.Model     model           = sdFileConverter.Import(lastMolfile);
                                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);
                                }
                                this.display1.Chemistry = model;
                                if (model.AllWarnings.Count > 0 || model.AllErrors.Count > 0)
                                {
                                    Telemetry.Write(module, "Exception(Data)", lastMolfile);
                                    List <string> lines = new List <string>();
                                    if (model.AllErrors.Count > 0)
                                    {
                                        Telemetry.Write(module, "Exception(Data)", string.Join(Environment.NewLine, model.AllErrors));
                                        lines.Add("Errors(s)");
                                        lines.AddRange(model.AllErrors);
                                    }
                                    if (model.AllWarnings.Count > 0)
                                    {
                                        Telemetry.Write(module, "Exception(Data)", string.Join(Environment.NewLine, model.AllWarnings));
                                        lines.Add("Warnings(s)");
                                        lines.AddRange(model.AllWarnings);
                                    }
                                    ErrorsAndWarnings.Text = string.Join(Environment.NewLine, lines);
                                }
                                else
                                {
                                    CMLConverter cmlConverter = new CMLConverter();
                                    Cml = cmlConverter.Export(model);
                                    ImportButton.Enabled = true;
                                }
                            }
                            result = pubchemId;
                        }
                        else
                        {
                            result      = string.Empty;
                            lastMolfile = string.Empty;

                            StringBuilder sb = new StringBuilder();
                            sb.AppendLine($"Bad request. Status code: {response.StatusCode}");
                            UserInteractions.AlertUser(sb.ToString());
                        }
                    }
                    catch (Exception ex)
                    {
                        if (ex.Message.Equals("The operation has timed out"))
                        {
                            ErrorsAndWarnings.Text = "Please try again later - the service has timed out";
                        }
                        else
                        {
                            ErrorsAndWarnings.Text = ex.Message;
                            Telemetry.Write(module, "Exception", ex.Message);
                            Telemetry.Write(module, "Exception", ex.StackTrace);
                        }
                    }
                    finally
                    {
                        ServicePointManager.SecurityProtocol = securityProtocol;
                        Cursor = Cursors.Default;
                    }
                }
            }

            return(result);
        }
Esempio n. 15
0
        private void button1_Click(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append("All molecule files (*.mol, *.cml)|*.mol;*.cml");
            sb.Append("|CML molecule files (*.cml)|*.cml");
            sb.Append("|MDL molecule files (*.mol)|*.mol");

            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);
                Model  model    = null;

                switch (fileType)
                {
                case ".cml":
                    CMLConverter cmlConverter = new CMLConverter();
                    model = cmlConverter.Import(mol);
                    break;

                case ".mol":
                    SdFileConverter molfileConverter = new SdFileConverter();
                    model = molfileConverter.Import(mol);
                    break;
                }

                string fCml  = "";
                string fCalc = "";
                if (model != null)
                {
                    this.Text = filename;
                    foreach (var molecule in model.Molecules)
                    {
                        if (!string.IsNullOrEmpty(molecule.ConciseFormula))
                        {
                            fCml += $"{molecule.ConciseFormula} . ";
                        }
                        fCalc += $"{molecule.CalculatedFormula()} . ";
                    }

                    if (fCalc.EndsWith(" . "))
                    {
                        fCalc = fCalc.Substring(0, fCalc.Length - 3);
                    }
                    if (fCml.EndsWith(" . "))
                    {
                        fCml = fCml.Substring(0, fCml.Length - 3);
                    }
                    lblCalculated.Text = $"{fCalc}";
                    lblFromCml.Text    = $"{fCml}";
                    lblOverall.Text    = $"{model.ConciseFormula}";

                    display1.Chemistry = mol;
                }
            }
        }
Esempio n. 16
0
        public bool ImportCml(string cmlFile, SQLiteTransaction transaction, bool calculateProperties = false)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            bool result = false;

            try
            {
                Model model = null;

                if (cmlFile.StartsWith("<"))
                {
                    model = _cmlConverter.Import(cmlFile);
                }
                if (cmlFile.Contains("M  END"))
                {
                    model = _sdFileConverter.Import(cmlFile);
                }

                if (model != null)
                {
                    var outcome = model.EnsureBondLength(Globals.Chem4WordV3.SystemOptions.BondLength,
                                                         Globals.Chem4WordV3.SystemOptions.SetBondLengthOnImportFromLibrary);
                    if (Globals.Chem4WordV3.SystemOptions.RemoveExplicitHydrogensOnImportFromLibrary)
                    {
                        model.RemoveExplicitHydrogens();
                    }
                    if (!string.IsNullOrEmpty(outcome))
                    {
                        Globals.Chem4WordV3.Telemetry.Write(module, "Information", outcome);
                    }

                    if (model.TotalAtomsCount > 0 ||
                        model.TotalBondsCount > 0 && model.MeanBondLength > 0)
                    {
                        if (calculateProperties)
                        {
                            var newMolecules = model.GetAllMolecules();
                            ChemistryHelper.CalculateProperties(newMolecules);
                        }

                        model.CustomXmlPartGuid = "";

                        string chemicalName = model.ConciseFormula;
                        var    mol          = model.Molecules.Values.First();
                        if (mol.Names.Count > 0)
                        {
                            foreach (var name in mol.Names)
                            {
                                long temp;
                                if (!long.TryParse(name.Value, out temp))
                                {
                                    chemicalName = name.Value;
                                    break;
                                }
                            }
                        }

                        var conn = transaction.Connection;

                        var id = AddChemistry(conn, model, chemicalName, model.ConciseFormula);
                        foreach (var name in mol.Names)
                        {
                            AddChemicalName(conn, id, name.Value, name.FullType);
                        }

                        result = true;
                    }
                }
            }
            catch (Exception ex)
            {
                using (var form = new ReportError(Globals.Chem4WordV3.Telemetry, Globals.Chem4WordV3.WordTopLeft, module, ex))
                {
                    form.ShowDialog();
                }
            }

            return(result);
        }
Esempio n. 17
0
        private void LayoutStructure_Click(object sender, EventArgs e)
        {
            var data = new LayoutResult();

            var    cc      = new CMLConverter();
            var    sc      = new SdFileConverter();
            string molfile = sc.Export(cc.Import(_lastCml));

            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", "1.2.3.4"));
#if DEBUG
                    formData.Add(new KeyValuePair <string, string>("debug", "true"));
#endif

                    var content = new FormUrlEncodedContent(formData);

                    httpClient.Timeout = TimeSpan.FromSeconds(15);
                    httpClient.DefaultRequestHeaders.Add("user-agent", "Chem4Word");

                    try
                    {
                        var response = httpClient.PostAsync("https://chemicalservices-staging.azurewebsites.net/api/Layout", content).Result;
                        if (response.Content != null)
                        {
                            var responseContent = response.Content;
                            var jsonContent     = responseContent.ReadAsStringAsync().Result;

                            try
                            {
                                data = JsonConvert.DeserializeObject <LayoutResult>(jsonContent);
                            }
                            catch (Exception e3)
                            {
                                //Telemetry.Write(module, "Exception", e3.Message);
                                //Telemetry.Write(module, "Exception(Data)", jsonContent);
                                Debug.WriteLine(e3.Message);
                            }

                            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));
                                }

                                if (!string.IsNullOrEmpty(data.Molecule))
                                {
                                    var model = sc.Import(data.Molecule);
                                    model.EnsureBondLength(20, false);
                                    if (string.IsNullOrEmpty(model.CustomXmlPartGuid))
                                    {
                                        model.CustomXmlPartGuid = Guid.NewGuid().ToString("N");
                                    }

                                    var clone = cc.Import(_lastCml);
                                    _undoStack.Push(clone);

                                    _lastCml = cc.Export(model);
                                    ShowChemistry("", model);
                                }
                            }
                        }
                    }
                    catch (Exception e2)
                    {
                        //Telemetry.Write(module, "Exception", e2.Message);
                        //Telemetry.Write(module, "Exception", e2.ToString());
                        Debug.WriteLine(e2.Message);
                    }
                }
            }
            catch (Exception e1)
            {
                //Telemetry.Write(module, "Exception", e1.Message);
                //Telemetry.Write(module, "Exception", e1.ToString());
                Debug.WriteLine(e1.Message);
            }
        }