コード例 #1
0
        private void Settings_FormClosing(object sender, FormClosingEventArgs e)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            try
            {
                if (_dirty)
                {
                    StringBuilder sb = new StringBuilder();
                    sb.AppendLine("Do you wish to save your changes?");
                    sb.AppendLine("  Click 'Yes' to save your changes and exit.");
                    sb.AppendLine("  Click 'No' to discard your changes and exit.");
                    sb.AppendLine("  Click 'Cancel' to return to the form.");
                    DialogResult dr = UserInteractions.AskUserYesNoCancel(sb.ToString());
                    switch (dr)
                    {
                    case DialogResult.Cancel:
                        e.Cancel = true;
                        break;

                    case DialogResult.Yes:
                        SearcherOptions.Save();
                        DialogResult = DialogResult.OK;
                        break;

                    case DialogResult.No:
                        DialogResult = DialogResult.Cancel;
                        break;
                    }
                }
            }
            catch (Exception ex)
            {
                new ReportError(Telemetry, TopLeft, module, ex).ShowDialog();
            }
        }
コード例 #2
0
ファイル: Upgrader.cs プロジェクト: zhangwenquan/Version3
        public static DialogResult UpgradeIsRequired(Word.Document doc)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            DialogResult result = DialogResult.Cancel;

            int count = LegacyChemistryCount(doc);

            if (count > 0)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine($"We have detected {count} legacy Chemistry objects in this document.");
                sb.AppendLine("Would you like them converted to the new format?");
                sb.AppendLine("");
                sb.AppendLine("  Click Yes to Upgrade then");
                sb.AppendLine("  Click No to leave them as they are");
                sb.AppendLine("");
                sb.AppendLine("This operation can't be undone.");
                result = UserInteractions.AskUserYesNo(sb.ToString());
                Globals.Chem4WordV3.Telemetry.Write(module, "Information", $"Detected {count} legacy chemistry ContentControl(s)");
            }

            return(result);
        }
コード例 #3
0
ファイル: EditLabels.cs プロジェクト: ambarishK/Version3
        private void OnSaveClick(object sender, EventArgs e)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            Globals.Chem4WordV3.Telemetry.Write(module, "Action", "Triggered");

            try
            {
                if (CanSave())
                {
                    Cml = _cmlConvertor.Export(_model);

                    DialogResult = DialogResult.OK;
                }
                else
                {
                    UserInteractions.InformUser("Can't save because at least one user defined label contains an error");
                }
            }
            catch (Exception ex)
            {
                new ReportError(Globals.Chem4WordV3.Telemetry, Globals.Chem4WordV3.WordTopLeft, module, ex).ShowDialog();
            }
        }
コード例 #4
0
        private void ImportIntoLibrary_OnClick(object sender, RoutedEventArgs e)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            Globals.Chem4WordV3.Telemetry.Write(module, "Action", "Triggered");

            try
            {
                if (Globals.Chem4WordV3.LibraryNames == null)
                {
                    Globals.Chem4WordV3.LoadNamesFromLibrary();
                }

                StringBuilder sb;

                // Start with V2 Add-In data path
                string importFolder = Path.Combine(Globals.Chem4WordV3.AddInInfo.AppDataPath, @"Chemistry Add-In for Word");
                if (Directory.Exists(importFolder))
                {
                    if (Directory.Exists(Path.Combine(importFolder, "Chemistry Gallery")))
                    {
                        importFolder = Path.Combine(importFolder, "Chemistry Gallery");
                    }
                }
                else
                {
                    importFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                }

                if (Directory.Exists(importFolder))
                {
                    // Fix scrolling to selected item by using code from https://social.msdn.microsoft.com/Forums/expression/en-US/1257aebc-22a6-44f6-975b-74f5067728bc/autoposition-showfolder-dialog?forum=vbgeneral

                    VistaFolderBrowserDialog browser = new VistaFolderBrowserDialog();

                    browser.Description            = "Select a folder to import cml files from";
                    browser.UseDescriptionForTitle = true;
                    browser.RootFolder             = Environment.SpecialFolder.Desktop;
                    browser.ShowNewFolderButton    = false;
                    browser.SelectedPath           = importFolder;
                    Forms.DialogResult dr = browser.ShowDialog();

                    if (dr == Forms.DialogResult.OK)
                    {
                        string selectedFolder = browser.SelectedPath;
                        string doneFile       = Path.Combine(selectedFolder, "library-import-done.txt");

                        sb = new StringBuilder();
                        sb.AppendLine("Do you want to import the Gallery structures into the Library?");
                        sb.AppendLine("(This cannot be undone.)");
                        dr = UserInteractions.AskUserYesNo(sb.ToString());
                        if (dr == Forms.DialogResult.Yes)
                        {
                            if (File.Exists(doneFile))
                            {
                                sb = new StringBuilder();
                                sb.AppendLine($"All files have been imported already from '{selectedFolder}'");
                                sb.AppendLine("Do you want to rerun the import?");
                                dr = UserInteractions.AskUserYesNo(sb.ToString());
                                if (dr == Forms.DialogResult.Yes)
                                {
                                    File.Delete(doneFile);
                                }
                            }
                        }

                        if (dr == Forms.DialogResult.Yes)
                        {
                            int fileCount = 0;

                            var lib         = new Database.Library();
                            var transaction = lib.StartTransaction();

                            try
                            {
                                var xmlFiles = Directory.GetFiles(selectedFolder, "*.cml").ToList();
                                xmlFiles.AddRange(Directory.GetFiles(selectedFolder, "*.mol"));
                                if (xmlFiles.Count > 0)
                                {
                                    ProgressBar.Maximum          = xmlFiles.Count;
                                    ProgressBar.Minimum          = 0;
                                    ProgressBarHolder.Visibility = Visibility.Visible;
                                    SetButtonState(false);

                                    int progress = 0;
                                    int total    = xmlFiles.Count;

                                    foreach (string cmlFile in xmlFiles)
                                    {
                                        progress++;
                                        ShowProgress(progress, cmlFile.Replace($"{selectedFolder}\\", "") + $" [{progress}/{total}]");

                                        var cml = File.ReadAllText(cmlFile);

                                        // Set second parameter to true if properties are to be calculated on import
                                        if (lib.ImportCml(cml, transaction, false))
                                        {
                                            fileCount++;
                                        }
                                    }
                                    lib.EndTransaction(transaction, false);
                                }

                                ProgressBarHolder.Visibility = Visibility.Collapsed;
                                SetButtonState(true);

                                File.WriteAllText(doneFile, $"{fileCount} cml files imported into library");
                                FileInfo fi = new FileInfo(doneFile);
                                fi.Attributes = FileAttributes.Hidden;

                                Globals.Chem4WordV3.LoadNamesFromLibrary();

                                UserInteractions.InformUser($"Successfully imported {fileCount} structures from '{selectedFolder}'.");
                            }
                            catch (Exception ex)
                            {
                                lib.EndTransaction(transaction, true);
                                ProgressBarHolder.Visibility = Visibility.Collapsed;
                                SetButtonState(true);

                                new ReportError(Globals.Chem4WordV3.Telemetry, TopLeft, module, ex).ShowDialog();
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ProgressBarHolder.Visibility = Visibility.Collapsed;
                SetButtonState(true);

                new ReportError(Globals.Chem4WordV3.Telemetry, TopLeft, module, ex).ShowDialog();
            }
        }
コード例 #5
0
ファイル: Upgrader.cs プロジェクト: austad/Version3
        public static void DoUpgrade(Word.Document doc)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            int sel = doc.Application.Selection.Range.Start;

            Globals.Chem4WordV3.DisableDocumentEvents(doc);

            try
            {
                string extension   = doc.FullName.Split('.').Last();
                string guid        = Guid.NewGuid().ToString("N");
                string timestamp   = DateTime.Now.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture);
                string destination = Path.Combine(Globals.Chem4WordV3.AddInInfo.ProductAppDataPath, "Backups", $"Chem4Word-{timestamp}-{guid}.{extension}");
                File.Copy(doc.FullName, destination);
            }
            catch (Exception ex)
            {
                // Nothing much we can do here :-(
                Debug.WriteLine(ex.Message);
            }

            Dictionary <string, CustomXMLPart> customXmlParts = new Dictionary <string, CustomXMLPart>();
            List <UpgradeTarget> targets = CollectData(doc);
            int upgradedCCs = 0;
            int upgradedXml = 0;

            foreach (var target in targets)
            {
                if (target.ContentControls.Count > 0)
                {
                    upgradedXml++;
                    upgradedCCs += target.ContentControls.Count;
                }

                foreach (var cci in target.ContentControls)
                {
                    foreach (Word.ContentControl cc in doc.ContentControls)
                    {
                        if (cc.ID.Equals(cci.Id))
                        {
                            int    start;
                            bool   isFormula;
                            string source;
                            string text;

                            switch (cci.Type)
                            {
                            case "2D":
                                cc.LockContents = false;
                                cc.Title        = Constants.ContentControlTitle;
                                cc.Tag          = target.Model.CustomXmlPartGuid;
                                cc.LockContents = true;

                                // ToDo: Regenerate converted 2D structures
                                break;

                            case "new":
                                cc.LockContents = false;
                                cc.Range.Delete();
                                start = cc.Range.Start;
                                cc.Delete();

                                doc.Application.Selection.SetRange(start - 1, start - 1);
                                var model    = new Model.Model();
                                var molecule = new Molecule();
                                molecule.ChemicalNames.Add(new ChemicalName {
                                    Id = "m1.n1", Name = cci.Text, DictRef = Constants.Chem4WordUserSynonym
                                });
                                model.Molecules.Add(molecule);
                                model.CustomXmlPartGuid = Guid.NewGuid().ToString("N");

                                var cmlConvertor = new CMLConverter();
                                doc.CustomXMLParts.Add(cmlConvertor.Export(model));

                                Word.ContentControl ccn = doc.ContentControls.Add(Word.WdContentControlType.wdContentControlRichText, ref _missing);
                                ChemistryHelper.Insert1D(ccn, cci.Text, false, $"m1.n1:{model.CustomXmlPartGuid}");
                                ccn.LockContents = true;
                                break;

                            default:
                                cc.LockContents = false;
                                cc.Range.Delete();
                                start = cc.Range.Start;
                                cc.Delete();

                                doc.Application.Selection.SetRange(start - 1, start - 1);
                                isFormula = false;
                                text      = ChemistryHelper.GetInlineText(target.Model, cci.Type, ref isFormula, out source);
                                Word.ContentControl ccr = doc.ContentControls.Add(Word.WdContentControlType.wdContentControlRichText, ref _missing);
                                ChemistryHelper.Insert1D(ccr, text, isFormula, $"{cci.Type}:{target.Model.CustomXmlPartGuid}");
                                ccr.LockContents = true;
                                break;
                            }
                        }
                    }
                }

                CMLConverter  converter = new CMLConverter();
                CustomXMLPart cxml      = doc.CustomXMLParts.SelectByID(target.CxmlPartId);
                if (customXmlParts.ContainsKey(cxml.Id))
                {
                    customXmlParts.Add(cxml.Id, cxml);
                }
                doc.CustomXMLParts.Add(converter.Export(target.Model));
            }

            EraseChemistryZones(doc);

            foreach (var kvp in customXmlParts.ToList())
            {
                kvp.Value.Delete();
            }

            Globals.Chem4WordV3.EnableDocumentEvents(doc);
            doc.Application.Selection.SetRange(sel, sel);
            if (upgradedCCs + upgradedXml > 0)
            {
                Globals.Chem4WordV3.Telemetry.Write(module, "Information", $"Upgraded {upgradedCCs} Chemistry Objects for {upgradedXml} Structures");
                UserInteractions.AlertUser($"Upgrade Completed{Environment.NewLine}{Environment.NewLine}Upgraded {upgradedCCs} Chemistry Objects for {upgradedXml} Structures");
            }
        }
コード例 #6
0
ファイル: SearchPubChem.cs プロジェクト: Chem4Word/Version3
        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);
        }
コード例 #7
0
ファイル: SearchPubChem.cs プロジェクト: Chem4Word/Version3
        private void GetData(string idlist)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            var request = (HttpWebRequest)
                          WebRequest.Create(
                string.Format(CultureInfo.InvariantCulture,
                              "{0}entrez/eutils/esummary.fcgi?db=pccompound&id={1}&retmode=xml",
                              UserOptions.PubChemWebServiceUri, idlist));

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

            var securityProtocol = ServicePointManager.SecurityProtocol;

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

            HttpWebResponse response;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
                if (HttpStatusCode.OK.Equals(response.StatusCode))
                {
                    Results.Enabled = true;

                    // we will read data via the response stream
                    using (var resStream = response.GetResponseStream())
                    {
                        var resultDocument = XDocument.Load(new StreamReader(resStream));
                        var compounds      = resultDocument.XPathSelectElements("//DocSum");
                        if (compounds.Any())
                        {
                            foreach (var compound in compounds)
                            {
                                var id   = compound.XPathSelectElement("./Id");
                                var name = compound.XPathSelectElement("./Item[@Name='IUPACName']");
                                //var smiles = compound.XPathSelectElement("./Item[@Name='CanonicalSmile']")
                                var          formula = compound.XPathSelectElement("./Item[@Name='MolecularFormula']");
                                ListViewItem lvi     = new ListViewItem(id.Value);

                                lvi.SubItems.Add(new ListViewItem.ListViewSubItem(lvi, name.Value));
                                //lvi.SubItems.Add(new ListViewItem.ListViewSubItem(lvi, smiles.ToString()))
                                lvi.SubItems.Add(new ListViewItem.ListViewSubItem(lvi, formula.Value));

                                Results.Items.Add(lvi);
                                // Add to a list view ...
                            }
                        }
                        else
                        {
                            Debug.WriteLine("Something went wrong");
                        }
                    }
                }
                else
                {
                    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;
            }
        }
コード例 #8
0
ファイル: SearchPubChem.cs プロジェクト: Chem4Word/Version3
        private void ExecuteSearch(int direction)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            if (!string.IsNullOrEmpty(SearchFor.Text))
            {
                Cursor = Cursors.WaitCursor;

                string webCall;
                if (direction == 0)
                {
                    webCall = string.Format(CultureInfo.InvariantCulture,
                                            "{0}entrez/eutils/esearch.fcgi?db=pccompound&term={1}&retmode=xml&relevanceorder=on&usehistory=y&retmax={2}",
                                            UserOptions.PubChemWebServiceUri, SearchFor.Text, UserOptions.ResultsPerCall);
                }
                else
                {
                    if (direction == 1)
                    {
                        int startFrom = firstResult + numResults;
                        webCall = string.Format(CultureInfo.InvariantCulture,
                                                "{0}entrez/eutils/esearch.fcgi?db=pccompound&term={1}&retmode=xml&relevanceorder=on&usehistory=y&retmax={2}&WebEnv={3}&RetStart={4}",
                                                UserOptions.PubChemWebServiceUri, SearchFor.Text, UserOptions.ResultsPerCall, webEnv, startFrom);
                    }
                    else
                    {
                        int startFrom = firstResult - numResults;
                        webCall = string.Format(CultureInfo.InvariantCulture,
                                                "{0}entrez/eutils/esearch.fcgi?db=pccompound&term={1}&retmode=xml&relevanceorder=on&usehistory=y&retmax={2}&WebEnv={3}&RetStart={4}",
                                                UserOptions.PubChemWebServiceUri, SearchFor.Text, UserOptions.ResultsPerCall, webEnv, startFrom);
                    }
                }

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

                var request = (HttpWebRequest)WebRequest.Create(webCall);

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

                HttpWebResponse response;
                try
                {
                    response = (HttpWebResponse)request.GetResponse();
                    if (HttpStatusCode.OK.Equals(response.StatusCode))
                    {
                        using (var resStream = response.GetResponseStream())
                        {
                            var resultDocument = XDocument.Load(new StreamReader(resStream));
                            // Get the count of results
                            resultsCount = int.Parse(resultDocument.XPathSelectElement("//Count").Value);
                            // Current position
                            firstResult = int.Parse(resultDocument.XPathSelectElement("//RetStart").Value);
                            int fetched = int.Parse(resultDocument.XPathSelectElement("//RetMax").Value);
                            lastResult = firstResult + fetched;
                            // WebEnv for history
                            webEnv = resultDocument.XPathSelectElement("//WebEnv").Value;

                            // Set flags for More/Prev buttons

                            if (lastResult > numResults)
                            {
                                PreviousButton.Enabled = true;
                            }
                            else
                            {
                                PreviousButton.Enabled = false;
                            }

                            if (lastResult < resultsCount)
                            {
                                NextButton.Enabled = true;
                            }
                            else
                            {
                                NextButton.Enabled = false;
                            }

                            var ids   = resultDocument.XPathSelectElements("//Id");
                            var count = ids.Count();
                            Results.Items.Clear();

                            if (count > 0)
                            {
                                // Set form title
                                Text = $"Search PubChem - Showing {firstResult + 1} to {lastResult} [of {resultsCount}]";
                                Refresh();

                                var sb = new StringBuilder();
                                for (var i = 0; i < count; i++)
                                {
                                    var id = ids.ElementAt(i);
                                    if (i > 0)
                                    {
                                        sb.Append(",");
                                    }
                                    sb.Append(id.Value);
                                }
                                GetData(sb.ToString());
                            }
                            else
                            {
                                // Set error box
                                ErrorsAndWarnings.Text = "Sorry, no results were found.";
                            }
                        }
                    }
                    else
                    {
                        StringBuilder sb = new StringBuilder();
                        sb.AppendLine($"Status code {response.StatusCode} was returned by the server");
                        Telemetry.Write(module, "Warning", sb.ToString());
                        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;
                }
            }
        }
コード例 #9
0
        /// <summary>
        /// Add this to the OnMouseLeftButtonDown attribute
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UIElementOnMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            dynamic clobberedElement = sender;

            UserInteractions.InformUser(clobberedElement.ID);
        }
コード例 #10
0
        private void EditorHost_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (DialogResult != DialogResult.OK && e.CloseReason == CloseReason.UserClosing)
            {
                StringBuilder sb = new StringBuilder();
                sb.AppendLine("Do you wish to save your changes?");
                sb.AppendLine("  Click 'Yes' to save your changes and exit.");
                sb.AppendLine("  Click 'No' to discard your changes and exit.");
                sb.AppendLine("  Click 'Cancel' to return to the form.");

                CMLConverter cc = new CMLConverter();

                switch (_editorType)
                {
                case "ACME":
                    if (elementHost1.Child is Editor acmeEditor &&
                        acmeEditor.IsDirty)
                    {
                        DialogResult dr = UserInteractions.AskUserYesNoCancel(sb.ToString());
                        switch (dr)
                        {
                        case DialogResult.Cancel:
                            e.Cancel = true;
                            break;

                        case DialogResult.Yes:
                            DialogResult = DialogResult.OK;
                            var model = acmeEditor.EditedModel;
                            model.RescaleForCml();
                            // Replace any temporary Ids which are Guids
                            model.ReLabelGuids();
                            OutputValue = cc.Export(model);
                            Hide();
                            break;

                        case DialogResult.No:
                            break;
                        }
                    }
                    break;

                case "LABELS":
                    if (elementHost1.Child is LabelsEditor labelsEditor &&
                        labelsEditor.IsDirty)
                    {
                        DialogResult dr = UserInteractions.AskUserYesNoCancel(sb.ToString());
                        switch (dr)
                        {
                        case DialogResult.Cancel:
                            e.Cancel = true;
                            break;

                        case DialogResult.Yes:
                            DialogResult = DialogResult.OK;
                            OutputValue  = cc.Export(labelsEditor.EditedModel);
                            Hide();
                            break;

                        case DialogResult.No:
                            break;
                        }
                    }
                    break;

                default:
                    if (elementHost1.Child is CmlEditor editor &&
                        editor.IsDirty)
                    {
                        DialogResult dr = UserInteractions.AskUserYesNoCancel(sb.ToString());
                        switch (dr)
                        {
                        case DialogResult.Cancel:
                            e.Cancel = true;
                            break;

                        case DialogResult.Yes:
                            DialogResult = DialogResult.OK;
                            OutputValue  = cc.Export(editor.EditedModel);
                            Hide();
                            break;

                        case DialogResult.No:
                            break;
                        }
                    }
                    break;
                }
            }
        }
コード例 #11
0
ファイル: NavigatorSupport.cs プロジェクト: alan008/Version3
        public static void InsertChemistry(bool isCopy, Application app, FlexDisplay flexDisplay)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            Document       doc = app.ActiveDocument;
            Selection      sel = app.Selection;
            ContentControl cc  = null;

            if (Globals.Chem4WordV3.SystemOptions == null)
            {
                Globals.Chem4WordV3.LoadOptions();
            }

            bool   allowed = true;
            string reason  = "";

            if (Globals.Chem4WordV3.ChemistryAllowed)
            {
                if (sel.ContentControls.Count > 0)
                {
                    cc = sel.ContentControls[1];
                    if (cc.Title != null && cc.Title.Equals(Constants.ContentControlTitle))
                    {
                        reason  = "a chemistry object is selected";
                        allowed = false;
                    }
                }
            }
            else
            {
                reason  = Globals.Chem4WordV3.ChemistryProhibitedReason;
                allowed = false;
            }

            if (allowed)
            {
                app.ScreenUpdating = false;
                Globals.Chem4WordV3.DisableDocumentEvents(doc);

                try
                {
                    CMLConverter cmlConverter = new CMLConverter();
                    Model.Model  chem         = cmlConverter.Import(flexDisplay.Chemistry);
                    double       before       = chem.MeanBondLength;
                    if (before < Constants.MinimumBondLength - Constants.BondLengthTolerance ||
                        before > Constants.MaximumBondLength + Constants.BondLengthTolerance)
                    {
                        chem.ScaleToAverageBondLength(Constants.StandardBondLength);
                        double after = chem.MeanBondLength;
                        Globals.Chem4WordV3.Telemetry.Write(module, "Information", $"Structure rescaled from {before.ToString("#0.00")} to {after.ToString("#0.00")}");
                    }

                    if (isCopy)
                    {
                        // Always generate new Guid on Import
                        chem.CustomXmlPartGuid = Guid.NewGuid().ToString("N");
                    }

                    string guidString   = chem.CustomXmlPartGuid;
                    string bookmarkName = "C4W_" + guidString;

                    if (Globals.Chem4WordV3.SystemOptions == null)
                    {
                        Globals.Chem4WordV3.LoadOptions();
                    }
                    Globals.Chem4WordV3.SystemOptions.WordTopLeft = Globals.Chem4WordV3.WordTopLeft;
                    IChem4WordRenderer renderer =
                        Globals.Chem4WordV3.GetRendererPlugIn(
                            Globals.Chem4WordV3.SystemOptions.SelectedRendererPlugIn);

                    if (renderer == null)
                    {
                        UserInteractions.WarnUser("Unable to find a Renderer Plug-In");
                    }
                    else
                    {
                        // Export just incase the CustomXmlPartGuid has been changed
                        string cml = cmlConverter.Export(chem);
                        renderer.Properties = new Dictionary <string, string>();
                        renderer.Properties.Add("Guid", guidString);
                        renderer.Cml = cml;

                        string tempfileName = renderer.Render();
                        if (File.Exists(tempfileName))
                        {
                            cc = CustomRibbon.Insert2D(doc, tempfileName, bookmarkName, guidString);

                            if (isCopy)
                            {
                                doc.CustomXMLParts.Add(cml);
                            }

                            try
                            {
                                // Delete the temporary file now we are finished with it
                                File.Delete(tempfileName);
                            }
                            catch
                            {
                                // Not much we can do here
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    new ReportError(Globals.Chem4WordV3.Telemetry, Globals.Chem4WordV3.WordTopLeft, module, ex)
                    .ShowDialog();
                }
                finally
                {
                    // Tidy Up - Resume Screen Updating and Enable Document Event Handlers
                    app.ScreenUpdating = true;
                    Globals.Chem4WordV3.EnableDocumentEvents(doc);

                    if (cc != null)
                    {
                        // Move selection point into the Content Control which was just edited or added
                        app.Selection.SetRange(cc.Range.Start, cc.Range.End);
                    }
                }
            }
            else
            {
                UserInteractions.WarnUser($"You can't insert a chemistry object because {reason}");
            }
        }
コード例 #12
0
        static void Main(string[] args)
        {
            UserInteractions displayer = new UserInteractions();

            displayer.Run();
        }
コード例 #13
0
ファイル: Upgrader.cs プロジェクト: zhangwenquan/Version3
        public static void DoUpgrade(Word.Document doc)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            int sel = doc.Application.Selection.Range.Start;

            Globals.Chem4WordV3.DisableDocumentEvents(doc);

            List <UpgradeTarget> targets = CollectData(doc);
            int upgradedCCs = 0;
            int upgradedXml = 0;

            foreach (var target in targets)
            {
                if (target.ContentControls.Count > 0)
                {
                    upgradedXml++;
                    upgradedCCs += target.ContentControls.Count;
                }
                foreach (var cci in target.ContentControls)
                {
                    foreach (Word.ContentControl cc in doc.ContentControls)
                    {
                        if (cc.ID.Equals(cci.Id))
                        {
                            if (cci.Type.Equals("2D"))
                            {
                                cc.LockContents = false;
                                cc.Title        = Constants.ContentControlTitle;
                                cc.Tag          = target.Model.CustomXmlPartGuid;
                                cc.LockContents = true;
                            }
                            else
                            {
                                cc.LockContents = false;
                                cc.Range.Delete();
                                int start = cc.Range.Start;
                                cc.Delete();
                                doc.Application.Selection.SetRange(start - 1, start - 1);
                                bool   isFormula = false;
                                string source;
                                string text             = CustomRibbon.GetInlineText(target.Model, cci.Type, ref isFormula, out source);
                                Word.ContentControl ccn = CustomRibbon.Insert1D(doc.Application, doc, text, isFormula, $"{cci.Type}:{target.Model.CustomXmlPartGuid}");
                                ccn.LockContents = true;
                            }
                        }
                    }
                }

                CMLConverter  converter = new CMLConverter();
                CustomXMLPart cxml      = doc.CustomXMLParts.SelectByID(target.CxmlPartId);
                cxml.Delete();
                doc.CustomXMLParts.Add(converter.Export(target.Model));
            }

            EraseChemistryZones(doc);

            Globals.Chem4WordV3.EnableDocumentEvents(doc);
            doc.Application.Selection.SetRange(sel, sel);
            if (upgradedCCs + upgradedXml > 0)
            {
                Globals.Chem4WordV3.Telemetry.Write(module, "Information", $"Upgraded {upgradedCCs} Chemistry Objects for {upgradedXml} Structures");
                UserInteractions.AlertUser($"Upgrade Completed{Environment.NewLine}{Environment.NewLine}Upgraded {upgradedCCs} Chemistry Objects for {upgradedXml} Structures");
            }
        }
コード例 #14
0
 public abstract void Configure(UserInteractions ui);
コード例 #15
0
        private void ExportFromLibrary_OnClick(object sender, RoutedEventArgs e)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            Globals.Chem4WordV3.Telemetry.Write(module, "Action", "Triggered");

            try
            {
                string exportFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                VistaFolderBrowserDialog browser = new VistaFolderBrowserDialog();

                browser.Description            = "Select a folder to export your Library's structures as cml files";
                browser.UseDescriptionForTitle = true;
                browser.RootFolder             = Environment.SpecialFolder.Desktop;
                browser.ShowNewFolderButton    = false;
                browser.SelectedPath           = exportFolder;
                Forms.DialogResult dr = browser.ShowDialog();

                if (dr == Forms.DialogResult.OK)
                {
                    exportFolder = browser.SelectedPath;

                    if (Directory.Exists(exportFolder))
                    {
                        Forms.DialogResult doExport         = Forms.DialogResult.Yes;
                        string[]           existingCmlFiles = Directory.GetFiles(exportFolder, "*.cml");
                        if (existingCmlFiles.Length > 0)
                        {
                            StringBuilder sb = new StringBuilder();
                            sb.AppendLine($"This folder contains {existingCmlFiles.Length} cml files.");
                            sb.AppendLine("Do you wish to continue?");
                            doExport = UserInteractions.AskUserYesNo(sb.ToString(), Forms.MessageBoxDefaultButton.Button2);
                        }
                        if (doExport == Forms.DialogResult.Yes)
                        {
                            Database.Library lib = new Database.Library();

                            int exported = 0;
                            int progress = 0;

                            List <ChemistryDTO> dto = lib.GetAllChemistry(null);
                            int total = dto.Count;
                            if (total > 0)
                            {
                                ProgressBar.Maximum          = dto.Count;
                                ProgressBar.Minimum          = 0;
                                ProgressBarHolder.Visibility = Visibility.Visible;
                                SetButtonState(false);

                                var converter = new CMLConverter();

                                foreach (var obj in dto)
                                {
                                    progress++;
                                    ShowProgress(progress, $"Structure #{obj.Id} [{progress}/{total}]");

                                    var filename = Path.Combine(browser.SelectedPath, $"Chem4Word-{obj.Id:000000000}.cml");

                                    Model model = converter.Import(obj.Cml);

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

                                    File.WriteAllText(filename, converter.Export(model));
                                    exported++;
                                }
                            }

                            ProgressBarHolder.Visibility = Visibility.Collapsed;
                            SetButtonState(true);

                            if (exported > 0)
                            {
                                UserInteractions.InformUser($"Exported {exported} structures to {browser.SelectedPath}");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ProgressBarHolder.Visibility = Visibility.Collapsed;
                SetButtonState(true);

                new ReportError(Globals.Chem4WordV3.Telemetry, TopLeft, module, ex).ShowDialog();
            }
        }
コード例 #16
0
ファイル: Upgrader.cs プロジェクト: alan008/Version3
        public static void DoUpgrade(Word.Document doc)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            int sel = doc.Application.Selection.Range.Start;

            Globals.Chem4WordV3.DisableDocumentEvents(doc);

            try
            {
                string extension   = doc.FullName.Split('.').Last();
                string guid        = Guid.NewGuid().ToString("N");
                string timestamp   = DateTime.Now.ToString("yyyyMMdd-HHmmss", CultureInfo.InvariantCulture);
                string destination = Path.Combine(Globals.Chem4WordV3.AddInInfo.ProductAppDataPath, "Backups", $"Chem4Word-{timestamp}-{guid}.{extension}");
                File.Copy(doc.FullName, destination);
            }
            catch (Exception ex)
            {
                // Nothing much we can do here :-(
                Debug.WriteLine(ex.Message);
            }

            List <UpgradeTarget> targets = CollectData(doc);
            int upgradedCCs = 0;
            int upgradedXml = 0;

            foreach (var target in targets)
            {
                if (target.ContentControls.Count > 0)
                {
                    upgradedXml++;
                    upgradedCCs += target.ContentControls.Count;
                }
                foreach (var cci in target.ContentControls)
                {
                    foreach (Word.ContentControl cc in doc.ContentControls)
                    {
                        if (cc.ID.Equals(cci.Id))
                        {
                            if (cci.Type.Equals("2D"))
                            {
                                cc.LockContents = false;
                                cc.Title        = Constants.ContentControlTitle;
                                cc.Tag          = target.Model.CustomXmlPartGuid;
                                cc.LockContents = true;
                            }
                            else
                            {
                                cc.LockContents = false;
                                cc.Range.Delete();
                                int start = cc.Range.Start;
                                cc.Delete();
                                doc.Application.Selection.SetRange(start - 1, start - 1);
                                bool   isFormula = false;
                                string source;
                                string text             = CustomRibbon.GetInlineText(target.Model, cci.Type, ref isFormula, out source);
                                Word.ContentControl ccn = CustomRibbon.Insert1D(doc.Application, doc, text, isFormula, $"{cci.Type}:{target.Model.CustomXmlPartGuid}");
                                ccn.LockContents = true;
                            }
                        }
                    }
                }

                CMLConverter  converter = new CMLConverter();
                CustomXMLPart cxml      = doc.CustomXMLParts.SelectByID(target.CxmlPartId);
                cxml.Delete();
                doc.CustomXMLParts.Add(converter.Export(target.Model));
            }

            EraseChemistryZones(doc);

            Globals.Chem4WordV3.EnableDocumentEvents(doc);
            doc.Application.Selection.SetRange(sel, sel);
            if (upgradedCCs + upgradedXml > 0)
            {
                Globals.Chem4WordV3.Telemetry.Write(module, "Information", $"Upgraded {upgradedCCs} Chemistry Objects for {upgradedXml} Structures");
                UserInteractions.AlertUser($"Upgrade Completed{Environment.NewLine}{Environment.NewLine}Upgraded {upgradedCCs} Chemistry Objects for {upgradedXml} Structures");
            }
        }
コード例 #17
0
        public static void InsertChemistry(bool isCopy, Application app, Display display, bool fromLibrary)
        {
            string module = $"{_product}.{_class}.{MethodBase.GetCurrentMethod().Name}()";

            Document       doc = app.ActiveDocument;
            Selection      sel = app.Selection;
            ContentControl cc  = null;

            if (Globals.Chem4WordV3.SystemOptions == null)
            {
                Globals.Chem4WordV3.LoadOptions();
            }

            bool   allowed = true;
            string reason  = "";

            if (Globals.Chem4WordV3.ChemistryAllowed)
            {
                if (sel.ContentControls.Count > 0)
                {
                    cc = sel.ContentControls[1];
                    if (cc.Title != null && cc.Title.Equals(Constants.ContentControlTitle))
                    {
                        reason  = "a chemistry object is selected";
                        allowed = false;
                    }
                }
            }
            else
            {
                reason  = Globals.Chem4WordV3.ChemistryProhibitedReason;
                allowed = false;
            }

            if (allowed)
            {
                try
                {
                    CMLConverter cmlConverter = new CMLConverter();
                    var          model        = cmlConverter.Import(display.Chemistry.ToString());

                    if (fromLibrary)
                    {
                        if (Globals.Chem4WordV3.SystemOptions.RemoveExplicitHydrogensOnImportFromLibrary)
                        {
                            var targets = model.GetHydrogenTargets();

                            if (targets.Atoms.Any())
                            {
                                foreach (var bond in targets.Bonds)
                                {
                                    bond.Parent.RemoveBond(bond);
                                }
                                foreach (var atom in targets.Atoms)
                                {
                                    atom.Parent.RemoveAtom(atom);
                                }
                            }
                        }

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

                    cc = ChemistryHelper.Insert2DChemistry(doc, cmlConverter.Export(model), isCopy);
                }
                catch (Exception ex)
                {
                    new ReportError(Globals.Chem4WordV3.Telemetry, Globals.Chem4WordV3.WordTopLeft, module, ex).ShowDialog();
                }
                finally
                {
                    if (cc != null)
                    {
                        // Move selection point into the Content Control which was just edited or added
                        app.Selection.SetRange(cc.Range.Start, cc.Range.End);
                    }
                }
            }
            else
            {
                UserInteractions.WarnUser($"You can't insert a chemistry object because {reason}");
            }
        }