Beispiel #1
0
        public static string GetOutputText()
        {
            var dte = GetDTE();

            if (dte == null)
            {
                return("");
            }


            OutputWindowPane buildOutputPane = null;

            foreach (OutputWindowPane pane in dte.ToolWindows.OutputWindow.OutputWindowPanes)
            {
                if (pane.Guid == VSConstants.OutputWindowPaneGuid.BuildOutputPane_string)
                {
                    buildOutputPane = pane;
                    break;
                }
            }
            if (buildOutputPane == null)
            {
                Output.Instance.ErrorMsg("Failed to query for build output pane!");
                return(null);
            }
            TextSelection sel = buildOutputPane.TextDocument.Selection;

            sel.StartOfDocument(false);
            sel.EndOfDocument(true);

            return(sel.Text);
        }
Beispiel #2
0
        /// <summary>
        /// This returns the text contained in the given output window pane.
        /// </summary>
        /// <param name="pane">Pane to get text from.</param>
        /// <returns>Text in the window.</returns>
        public static string GetPaneText(OutputWindowPane pane)
        {
            TextSelection selection = pane.TextDocument.Selection;

            selection.StartOfDocument(false);
            selection.EndOfDocument(true);
            return(selection.Text);
        }
        public static string GetTextBetweenCurPosToLine(this TextSelection selection, int to_lineNum, bool moveToEndOfDoc = true)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            selection.MoveToLineAndOffset(to_lineNum, 1, Extend: true);
            string result = selection.Text;

            if (moveToEndOfDoc)
            {
                selection.EndOfDocument();
            }

            return(result);
        }
Beispiel #4
0
        public bool ToggleAllRegions(EnvDTE.Document doc, bool closeAll)
        {
            bool          open = false;
            TextSelection ts   = (TextSelection)doc.Selection;

            string startpattern;
            string endpattern;

            if (!this.GetPatterns(doc, out startpattern, out endpattern))
            {
                return(false);
            }
            ts.EndOfDocument(false);
            EditPoint ep = ts.ActivePoint.CreateEditPoint();
            string    line;

            while (!ep.AtStartOfDocument)
            {
                ts.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstColumn, false);
                ts.LineUp(true, 1);
                line = ts.Text.ToLower().Trim();
                if (line.StartsWith(endpattern))
                {
                    open = true;
                }
                else if (line.StartsWith(startpattern))
                {
                    if (closeAll)
                    {
                        if (open)
                        {
                            doc.DTE.ExecuteCommand("Edit.ToggleOutliningExpansion", "");
                        }
                    }
                    else
                    {
                        if (!open)
                        {
                            doc.DTE.ExecuteCommand("Edit.ToggleOutliningExpansion", "");
                        }
                    }
                    open = false;
                }
                ep = ts.ActivePoint.CreateEditPoint();
            }
            toogleRegionDocument = doc;
            ts.Cancel();
            return(true);
        }
Beispiel #5
0
        private static void AddToExisting(ProjectItem extObject, string code)
        {
            // TODO: Need to handle failure here.
            var window = extObject.Open();

            window.Activate();

            TextSelection selection = (TextSelection)extObject.Document.Selection;

            selection.SelectAll();
            var text = selection.Text;

            selection.EndOfDocument();

            selection.NewLine();
            selection.Insert(code);
        }
Beispiel #6
0
        public static string GetAllTextFromPane(EnvDTE.OutputWindowPane Pane)
        {
            if (Pane == null)
            {
                return(null);
            }

            TextDocument  doc = Pane.TextDocument;
            TextSelection sel = doc.Selection;

            sel.StartOfDocument(false);
            sel.EndOfDocument(true);

            string content = sel.Text;

            return(content);
        }
Beispiel #7
0
        public static void navigate(KnowledgeController controller, Object tag, String sourceFile)
        {
            try
            {
                log.Debug(" navigation ... ");

                string regExpression = getRegExpr(tag);
                if (regExpression == null)
                {
                    return;
                }
                string actualString = getActualString(sourceFile, regExpression);
                if (actualString == null)
                {
                    return;
                }

                Window        textEditor    = controller.environment.ApplicationObject.OpenFile(Constants.vsViewKindCode, sourceFile);
                TextSelection textSelection = (TextSelection)textEditor.Document.Selection;
                textSelection.StartOfDocument(false);
                textSelection.EndOfDocument(false);

                // TODO: textSelection.findPattern doesn't work for some reason
                if (textSelection.FindText(actualString, (int)vsFindOptions.vsFindOptionsFromStart))
                {
                    textSelection.SelectLine();
                }
                else
                {
                    log.Debug("log. actualString is not found in text file, actualString=" + actualString);
                }

                textEditor.Visible = true;
                textEditor.Activate();
                // TODO: save of the document
            }
            catch (Exception e0)
            {
                MessageBox.Show(e0.Message);
            }
        }
        private void CheckForCorrectEndOfFile(Document Document)
        {
            TextSelection selection = Document.Selection as TextSelection;

            if (selection == null)
            {
                return;
            }

            VirtualPoint originalPoint = selection.ActivePoint;

            selection.EndOfDocument(false);

            VirtualPoint bottom = selection.BottomPoint;

            selection.GotoLine(bottom.Line, true);
            if (selection.Text.Length != 0)
            {
                selection.Text += Environment.NewLine;
                Document.Save();
            }

            selection.MoveToPoint(originalPoint);
        }
        // Collapses all regions in the current document
        public static void CollapseAllRegions(DTE dte, Language language, MainPackage package, bool showErrors = true)
        {
            if (IsSupportedLanguage(language))
            {
                dte.SuppressUI = true;                 // Disable UI while we do this
                try
                {
                    // Outling must be enabled.  If Outlining is turned off then the rest of this method will get stuck in an infinite loop.
                    // It can be turned off by default from the C# advanced text editor properties, or it can be turned off by running
                    // the Edit.StopOutlining command (e.g., in the Command window or via Edit -> Outlining -> Stop Outlining).
                    // If the Edit.StartAutomaticOutlining command is available, then that means outlining needs to be turned back on.
                    const string   StartOutliningCommand = "Edit.StartAutomaticOutlining";
                    EnvDTE.Command command = dte.Commands.Item(StartOutliningCommand);
                    if (command.IsAvailable)
                    {
                        dte.ExecuteCommand(StartOutliningCommand);
                    }

                    const string ToggleOutliningExpansion = "Edit.ToggleOutliningExpansion";
                    command = dte.Commands.Item(ToggleOutliningExpansion);
                    const int MaxAttempts = 3;
                    int       maxAttempts = command.IsAvailable ? MaxAttempts : 0;

                    string regionBeginRegex = GetRegionBeginRegex(language);

                    // Sometimes VS can't collapse some regions, so we'll try the whole operation a few times if necessary.
                    bool failedToCollapse = true;
                    for (int attempt = 1; attempt <= maxAttempts && failedToCollapse; attempt++)
                    {
                        failedToCollapse = false;
                        ExpandAllRegions(dte, language);                                       // Force the expansion of all regions

                        TextSelection selection = (TextSelection)dte.ActiveDocument.Selection; // Hook up to the ActiveDocument's selection
                        selection.EndOfDocument();                                             // Shoot to the end of the document

                        // Find the first occurence of #region from the end of the document to the start of the document.
                        int       currentFindOffset  = 0;
                        int       previousFindOffset = int.MaxValue;
                        const int FindOptions        = (int)vsFindOptions.vsFindOptionsBackwards +
                                                       (int)vsFindOptions.vsFindOptionsMatchCase +
                                                       (int)vsFindOptions.vsFindOptionsRegularExpression;
                        while (selection.FindText(regionBeginRegex, FindOptions))
                        {
                            currentFindOffset = selection.TopPoint.AbsoluteCharOffset;
                            if (currentFindOffset >= previousFindOffset)
                            {
                                // I don't want to get stuck in an infinite loop.  I'd rather throw if something unexpected happens.
                                throw new InvalidOperationException(string.Format(
                                                                        "FindText did not go backward!  Previous offset: {0}; Current offset: {1}.",
                                                                        previousFindOffset,
                                                                        currentFindOffset));
                            }

                            // We can ignore matches where #region is used inside a string or single line comment.
                            // However, this still won't detect if it's used inside a multiline comment with the opening
                            // delimiter on another line.
                            selection.SelectLine();
                            string lineText = selection.Text ?? string.Empty;

                            // Make sure the region begin token is the first non-whitespace on the line.
                            Match match = Regex.Match(lineText.TrimStart(), regionBeginRegex);
                            if (match.Success && match.Index == 0)
                            {
                                // The SelectLine call above will leave the end anchor on the next line.  If there's no blank line between
                                // a #region line and an XML doc comment after it, then having the end anchor on the line with the
                                // XML doc comment will cause the comment to collapse instead of the #region.  So we'll avoid that
                                // by moving back to the find offset.
                                selection.MoveToAbsoluteOffset(currentFindOffset);

                                // Try to increase the chances that the ToggleOutliningExpansion command will be available.
                                selection.StartOfLine(vsStartOfLineOptions.vsStartOfLineOptionsFirstText);

                                // Collapse this #region.  Sometimes VS reports that the Edit.ToggleOutliningExpansion command
                                // isn't available even though it should be.  Poke it and give it a little bit of time to sync up.
                                if (!command.IsAvailable)
                                {
                                    const int WaitMilliseconds = 20;
                                    System.Threading.Thread.Sleep(WaitMilliseconds);
                                    int tempOffset = selection.TopPoint.AbsoluteCharOffset;
                                    selection.CharRight();
                                    selection.MoveToAbsoluteOffset(tempOffset);
                                    System.Threading.Thread.Sleep(WaitMilliseconds);
                                }

                                if (command.IsAvailable)
                                {
                                    // If #region is found in a multiline comment, then this will collapse the enclosing block.
                                    dte.ExecuteCommand(ToggleOutliningExpansion);
                                }
                                else
                                {
                                    // We couldn't collapse a #region.
                                    failedToCollapse = true;
                                }
                            }

                            // Move to the start of the last FindText match, so we can continue searching backward from there.
                            selection.MoveToAbsoluteOffset(currentFindOffset);
                            previousFindOffset = currentFindOffset;
                        }

                        selection.StartOfDocument();                         // All done, head back to the start of the doc
                    }

                    if (failedToCollapse && package != null && showErrors)
                    {
                        package.ShowMessageBox(
                            "Some regions couldn't be collapsed because Visual Studio's Edit.ToggleOutliningExpansion command wasn't available.",
                            true);
                    }
                }
                finally
                {
                    dte.SuppressUI = false;                     // Reenable the UI
                }
            }
        }
Beispiel #10
0
        private void _Do_0(Func <string, bool> doneToConfirmContinue = null)
        {
            if (string.IsNullOrEmpty(_Namespace))
            {
                MessageBox.Show("Please provide a namespace");
                return;
            }

            Func <MBColumn, string> _getType = c =>
            {
                switch (c.Type)
                {
                case _Types.t_bit:
                    if (c.Spec.Contains("(1)"))
                    {
                        return((c.Nullable) ? "Nullable<bool>" : "bool");
                    }
                    return((c.Nullable) ? "Nullable<bool>" : "bool");

                case _Types.t_boolean:
                    return((c.Nullable) ? "Nullable<bool>" : "bool");

                case _Types.t_tinyint:
                    if (c.Spec.EndsWith("unsigned"))
                    {
                        return((c.Nullable) ? "Nullable<byte>" : "byte");
                    }
                    return((c.Nullable) ? "Nullable<sbyte>" : "sbyte");

                case _Types.t_smallint:
                    if (c.Spec.EndsWith("unsigned"))
                    {
                        return((c.Nullable) ? "Nullable<int>" : "int");
                    }
                    return((c.Nullable) ? "Nullable<short>" : "short");

                case _Types.t_year:
                    return((c.Nullable) ? "Nullable<short>" : "short");

                case _Types.t_int:
                    if (c.Spec.EndsWith("unsigned"))
                    {
                        return((c.Nullable) ? "Nullable<long>" : "long");
                    }
                    return((c.Nullable) ? "Nullable<int>" : "int");

                case _Types.t_integer:
                    if (c.Spec.EndsWith("unsigned"))
                    {
                        return((c.Nullable) ? "Nullable<long>" : "long");
                    }
                    return((c.Nullable) ? "Nullable<int>" : "int");

                case _Types.t_mediumint:
                    return((c.Nullable) ? "Nullable<int>" : "int");

                case _Types.t_bigint:
                    if (c.Spec.EndsWith("unsigned"))
                    {
                        return((c.Nullable) ? "Nullable<decimal>" : "decimal");
                    }
                    return((c.Nullable) ? "Nullable<long>" : "long");

                case _Types.t_float:
                    if (c.Spec.EndsWith("unsigned"))
                    {
                        return((c.Nullable) ? "Nullable<decimal>" : "decimal");
                    }
                    return((c.Nullable) ? "Nullable<float>" : "float");

                case _Types.t_double:
                    if (c.Spec.EndsWith("unsigned"))
                    {
                        return((c.Nullable) ? "Nullable<decimal>" : "decimal");
                    }
                    return((c.Nullable) ? "Nullable<double>" : "double");

                case _Types.t_real:
                    return((c.Nullable) ? "Nullable<double>" : "double");

                case _Types.t_rowversion:
                    return("byte[]");

                case _Types.t_numeric:
                case _Types.t_decimal:
                case _Types.t_dec:
                case _Types.t_fixed:
                case _Types.t_serial:
                    return((c.Nullable) ? "Nullable<decimal>" : "decimal");

                case _Types.t_date:
                case _Types.t_datetime:
                case _Types.t_datetime2:
                    return((c.Nullable) ? "Nullable<DateTime>" : "DateTime");

                case _Types.t_timestamp:
                    if (_Context.IsMySql)
                    {
                        return((c.Nullable) ? "Nullable<DateTime>" : "DateTime");
                    }
                    return("byte[]");

                case _Types.t_datetimeoffset:
                    return((c.Nullable) ? "Nullable<System.DateTimeOffset>" : "System.DateTimeOffset");

                case _Types.t_time:
                    return((c.Nullable) ? "Nullable<System.TimeSpan>" : "System.TimeSpan");

                case _Types.t_smalldatetime:
                    return((c.Nullable) ? "Nullable<DateTime>" : "DateTime");

                case _Types.t_image:
                    return("byte[]");

                case _Types.t_money:
                case _Types.t_smallmoney:
                    return((c.Nullable) ? "Nullable<decimal>" : "decimal");

                case _Types.t_uniqueidentifier:
                    return((c.Nullable) ? "Nullable<Guid>" : "Guid");

                case _Types.t_char:
                    if (_Context.IsMySql && c.Spec == "char(36)")
                    {
                        // char(36) 被认为是 MySql 的一个标志性实现
                        return((c.Nullable) ? "Nullable<Guid>" : "Guid");
                    }
                    return("string");

                case _Types.t_varchar:
                case _Types.t_tinytext:
                case _Types.t_text:
                case _Types.t_mediumtext:
                case _Types.t_longtext:
                case _Types.t_set:
                case _Types.t_enum:
                case _Types.t_nchar:
                case _Types.t_nvarchar:
                case _Types.t_ntext:
                case _Types.t_xml:
                    return("string");

                case _Types.t_binary:
                case _Types.t_varbinary:
                case _Types.t_tinyblob:
                case _Types.t_blob:
                case _Types.t_mediumblob:
                case _Types.t_longblob:
                    return("byte[]");

                case _Types.t_spatial_geometry:
                    return((c.Nullable) ? "Nullable<System.Data.Spatial.DbGeometry>" : "System.Data.Spatial.DbGeometry");

                case _Types.t_spatial_geography:
                    return((c.Nullable) ? "Nullable<System.Data.Spatial.DbGeography>" : "System.Data.Spatial.DbGeography");

                case _Types.t_sql_variant:
                    return("object");
                }

                return(string.Empty);
            };

            var now      = DateTime.Now;
            var projects = (Array)_App.ActiveSolutionProjects;

            if (projects.Length > 0)
            {
                foreach (Project p in projects)
                {
                    ProjectItem folder = p.ProjectItems
                                         .AddFolder("___ENTITIES", Constants.vsProjectItemKindPhysicalFolder);
                    List <MBTable> tables =
                        _Context.Tables.Where(_Filter).OrderBy(t => t.Name).ToList();

                    // _App Configure

                    // Start typing
                    _BatchIndex = -1;
                    ProjectItem   file = null;
                    Window        win  = null;
                    TextSelection ts   = null;

                    var index = 0;
                    var count = -1;
                    for (int i = 0; i < tables.Count; i++)
                    {
                        index = i / _BatchSize;
                        count++;

                        if (index != _BatchIndex)
                        {
                            // New file and insert at the end line
                            file = folder.ProjectItems.AddFromTemplate(
                                DefaultTemplateFile, string.Format("{0}.{1}.cs", _Identifier, index.ToString("D2")));
                            win = file.Open(Constants.vsViewKindCode);
                            win.Activate();
                            win.Document.Activate();

                            ts = _App.ActiveDocument.Selection as TextSelection;
                            ts.EndOfDocument();
                            _BatchIndex = index;

                            // Update timestamp
                            ts.Insert(@"/// <summary>");
                            ts.NewLine();
                            ts.Insert(string.Format(@"{0}", now.ToString()));
                            ts.NewLine();
                            ts.Insert(@"</summary>");
                            ts.NewLine();
                            ts.SelectLine();
                            ts.Insert(" ");

                            // namespace
                            ts.Insert("namespace " + _Namespace);
                            ts.NewLine();
                            ts.Insert("{");
                            ts.NewLine();
                        }

                        MBTable       t    = tables[i];
                        List <string> keys = new List <string>();
                        if (!
                            string.IsNullOrEmpty(t.KeyInfo))
                        {
                            foreach (string part in t.KeyInfo.Split(','))
                            {
                                if (part.Trim().Length > 0)
                                {
                                    keys.Add(part.Trim());
                                }
                            }
                        }

                        var columns = _Context.Columns
                                      .Where(c => c.TableId == t.TableId).OrderBy(c => c.Name).ToList();
                        var properties = _Context.Properties
                                         .Where(d => d.TableId == t.TableId).ToList();

                        // summary
                        if (_Context.IsMySql)
                        {
                            if (!string.IsNullOrEmpty(t.Caption))
                            {
                                ts.Insert(@"/// <summary>");
                                ts.NewLine();
                                ts.Insert(string.Format(@"{0}", t.Caption.ToStringEx()));
                                ts.NewLine();
                                ts.Insert(@"</summary>");
                                ts.NewLine();
                                ts.SelectLine();
                                ts.Insert(" ");
                            }
                        }
                        else
                        {
                            properties.SingleOrDefault(d => d.TableId == t.TableId &&
                                                       d.Field == string.Empty && d.Name == FIELD_SUMMARY &&
                                                       !string.IsNullOrEmpty(d.Value)).IfNN(d =>
                            {
                                ts.Insert(@"/// <summary>");
                                ts.NewLine();
                                ts.Insert(string.Format(@"{0}", d.Value));
                                ts.NewLine();
                                ts.Insert(@"</summary>");
                                ts.NewLine();
                                ts.SelectLine();
                                ts.Insert(" ");
                            });
                        }

                        // tableName
                        ts.Insert("[Serializable]");
                        ts.NewLine();
                        ts.Insert(string.Format("[Table(\"{0}\")]", t.Name));
                        ts.NewLine();
                        ts.Insert(string.Format("public partial class TB_{0}:TBObject<TB_{0}>{{", t.Name));
                        ts.NewLine();
                        //ts.Insert(string.Format("public partial class ET_{0} {{", t.Name));
                        //ts.NewLine();
                        columns.ForEach(c =>
                        {
                            if (_Context.IsMySql)
                            {
                                if (!string.IsNullOrEmpty(c.Caption))
                                {
                                    ts.Insert(@"/// <summary>");
                                    ts.NewLine();
                                    ts.Insert(string.Format(@"{0}", c.Caption));
                                    ts.NewLine();
                                    ts.Insert(@"</summary>");
                                    ts.NewLine();
                                    ts.SelectLine();
                                    ts.Insert(" ");
                                }
                            }
                            else
                            {
                                // 说明
                                properties.SingleOrDefault(d =>
                                                           d.TableId == t.TableId &&
                                                           d.Field == c.Name && d.Name == FIELD_SUMMARY &&
                                                           !string.IsNullOrEmpty(d.Value)).IfNN(d =>
                                {
                                    ts.Insert(@"/// <summary>");
                                    ts.NewLine();
                                    ts.Insert(string.Format(@"{0}", d.Value));
                                    ts.NewLine();
                                    ts.Insert(@"</summary>");
                                    ts.NewLine();
                                    ts.SelectLine();
                                    ts.Insert(" ");
                                });
                            }

                            if (t.KeyInfo.ToStringEx(string.Empty).Contains(c.Name))
                            {
                                //var singleKey = !t.KeyInfo.ToStringEx(string.Empty).Contains(",");
                                //if (singleKey && c.Type.Contains("int"))
                                //{
                                //    ts.Insert(@"[Key*]"); // 人为编译不成功,mySql 的问题
                                //}
                                //else
                                //{
                                //    ts.Insert(@"[Key]");
                                //}

                                ts.Insert(@"[Key]");
                                ts.NewLine();
                            }

                            ts.Insert(string.Format(@"[Column(Order = {0})]", c.Ordinal));
                            ts.NewLine();

                            if (c.CharMaxLength.HasValue &&
                                !c.Type.Contains("blob") &&
                                !c.Type.Contains("long") &&
                                !c.Type.Contains("text")
                                //!c.Spec.Contains("char(36)") // guid
                                )
                            {
                                ts.Insert(string.Format(@"[MaxLength({0})]", c.CharMaxLength));
                                ts.NewLine();
                            }

                            var s = "public ";
                            s    += _getType(c) + " ";
                            s    += c.Name;
                            s    += " { get; set; }";

                            ts.Insert(s);
                            ts.NewLine();
                        });

                        ts.Insert("}");
                        ts.NewLine();

                        if (doneToConfirmContinue != null)
                        {
                            if (!doneToConfirmContinue(t.Name))
                            {
                                break;
                            }
                        }

                        if (count == _BatchSize - 1)
                        {
                            ts.Insert("}");
                            ts.NewLine();
                            ts.SelectAll();
                            _App.ExecuteCommand("Edit.FormatDocument");
                            win.Close(vsSaveChanges.vsSaveChangesYes);
                            count = -1;
                        }
                    }

                    // closing
                    if (count != -1)
                    {
                        ts.Insert("}");
                        ts.NewLine();
                        ts.SelectAll();
                        _App.ExecuteCommand("Edit.FormatDocument");
                        win.Close(vsSaveChanges.vsSaveChangesYes);
                        count = -1;
                    }
                }
            }
        }
        public bool FormatFile(EnvDTE.DTE dte)
        {
            m_CfSuccessful = false;
            DateTime localDate = DateTime.Now;
            string   localDateString;
            string   localTimeString;

            localDateString = String.Format("Date: {0:dddd, d. MMMM yyyy}", localDate);
            localTimeString = String.Format("Time: {0:HH:mm:ss}", localDate);
            //DateTime utcDate = DateTime.UtcNow;

            m_sClangExecutable = (string)mProps.Item("ClangExecutable").Value;
            m_sCfStyle         = (string)mProps.Item("CfStyle").Value;
            m_sFallbackStyle   = (string)mProps.Item("FallbackStyle").Value;
            m_sAssumeFilename  = (string)mProps.Item("AssumeFilename").Value;
            m_sCursorPosition  = (string)mProps.Item("CursorPosition").Value;;
            m_sSortIncludes    = (bool)mProps.Item("SortIncludes").Value;
            m_sSaveOnFormat    = (bool)mProps.Item("SaveOnFormat").Value;
            m_sOutputEnabled   = (bool)mProps.Item("OutputEnabled").Value;
            m_formatLinesOnly  = false;
            m_argument         = "";

            LogToOutputWindow(Environment.NewLine);
            LogToOutputWindow("[ Log " + localDateString + " ]");
            LogToOutputWindow(Environment.NewLine);
            LogToOutputWindow("[ Log " + localTimeString + " ]");
            LogToOutputWindow(Environment.NewLine);

            if (dte.ActiveDocument == null)
            {
                LogToOutputWindow("Make sure you have a document opened. Done nothing.");
                LogToOutputWindow(Environment.NewLine);
                return(false);
            }

            if (dte.ActiveDocument.Type != "Text")
            {
                LogToOutputWindow("Document type is not a text document. Done nothing.");
                LogToOutputWindow(Environment.NewLine);
                return(false);
            }

            Document tdToSave = dte.ActiveDocument;

            m_fullFileName = dte.ActiveDocument.FullName;  // full file name
            m_td           = (TextDocument)dte.ActiveDocument.Object("");
            TextSelection sel = m_td.Selection;

            VirtualPoint topPt = sel.TopPoint;

            m_dTopLine = topPt.Line;
            VirtualPoint bottomPt = sel.BottomPoint;

            m_dBottomLine = bottomPt.Line;
            VirtualPoint activePt = sel.ActivePoint; // restore this point;

            m_dCursorLine = activePt.Line;
            int restoredCursorLine = m_dTopLine;

            m_dRestoreCaret = sel.ActivePoint.AbsoluteCharOffset;

            m_dCurrentFileBuffer      = "";
            tmpOut.Length             = 0;
            cfErrOutputBuilder.Length = 0;

            if (!(sel.IsEmpty))
            {
                m_formatLinesOnly = true;
            }
            // no selection
            sel.EndOfDocument(false);
            sel.StartOfDocument(true);
            //sel.SelectAll();
            m_dCurrentFileBuffer = sel.Text; // load complete buffer

            createArgumentString();
            m_procStart.Arguments = m_argument;

            LogToOutputWindow("Buffer of file: " + m_fullFileName);
            LogToOutputWindow(Environment.NewLine);

            startProcessAndGetOutput();

            try
            {
                //// write stdout from clang-format to editor buffer
                writeOutputToEditorBuffer(sel, tdToSave);
            }
            catch
            {
                LogToOutputWindow("Caught exception, while trying to change buffer.");
                LogToOutputWindow(Environment.NewLine);
            }

            // restore cursor
            if (m_sCursorPosition == "Top")
            {
                restoredCursorLine = 1;
                sel.MoveToLineAndOffset(restoredCursorLine, 1, false);
            }
            else if (m_sCursorPosition == "Bottom")
            {
                restoredCursorLine = m_td.EndPoint.Line;
                sel.MoveToLineAndOffset(restoredCursorLine, 1, false);
            }
            else if (m_sCursorPosition == "SameLine")
            {
                restoredCursorLine = m_dCursorLine;
                if (m_td.EndPoint.Line < restoredCursorLine)
                {
                    restoredCursorLine = m_td.EndPoint.Line;
                }
                sel.MoveToLineAndOffset(restoredCursorLine, 1, false);
            }
            else if (m_sCursorPosition == "Restore")
            {
                try
                {
                    sel.MoveToAbsoluteOffset(m_dRestoreCaret, false);
                }
                catch
                {}
            }

            return(true);
        }
Beispiel #12
0
        private void _Do_1(Func <string, bool> doneToConfirmContinue = null)
        {
            if (string.IsNullOrEmpty(_Namespace))
            {
                MessageBox.Show("Please provide a namespace");
                return;
            }

            var now      = DateTime.Now;
            var projects = (Array)_App.ActiveSolutionProjects;

            if (projects.Length > 0)
            {
                foreach (Project p in projects)
                {
                    ProjectItem folder = p.ProjectItems
                                         .AddFolder("___ENTITIES", Constants.vsProjectItemKindPhysicalFolder);
                    List <MBTable> tables =
                        _Context.Tables.Where(_Filter).OrderBy(t => t.Name).ToList();

                    // _App Configure


                    // 准备插入代码
                    _BatchIndex = -1;
                    ProjectItem   file = null;
                    Window        win  = null;
                    TextSelection ts   = null;
                    StringBuilder sb   = null;

                    var index = 0;
                    var count = -1;
                    for (int i = 0; i < tables.Count; i++)
                    {
                        index = i / _BatchSize;
                        count++;

                        if (index != _BatchIndex)
                        {
                            // 创建新文件,并且在最后方插入
                            file = folder.ProjectItems.AddFromTemplate(
                                DefaultTemplateFile, string.Format("{0}.{1}.cs", _Identifier, "ALL"));
                            win = file.Open(Constants.vsViewKindCode);
                            win.Activate();
                            win.Document.Activate();

                            ts = _App.ActiveDocument.Selection as TextSelection;
                            ts.EndOfDocument();
                            _BatchIndex = index;

                            sb = new StringBuilder();

                            // 插入生成日期
                            sb.AppendLine(@"/// <summary>");
                            sb.AppendLine(string.Format(@"/// {0}", now.ToString()));
                            sb.AppendLine(@"/// </summary>");

                            // 插入 namespace 行
                            sb.AppendLine("namespace " + _Namespace);
                            sb.AppendLine("{");
                        }

                        MBTable       t    = tables[i];
                        List <string> keys = new List <string>();
                        if (!
                            string.IsNullOrEmpty(t.KeyInfo))
                        {
                            foreach (string part in t.KeyInfo.Split(','))
                            {
                                if (part.Trim().Length > 0)
                                {
                                    keys.Add(part.Trim());
                                }
                            }
                        }

                        var columns = _Context.Columns
                                      .Where(c => c.TableId == t.TableId).OrderBy(c => c.Name).ToList();
                        var properties = _Context.Properties
                                         .Where(d => d.TableId == t.TableId).ToList();

                        // 说明
                        if (_Context.IsMySql)
                        {
                            if (!string.IsNullOrEmpty(t.Caption))
                            {
                                sb.AppendLine(@"/// <summary>");
                                sb.AppendLine(string.Format(@"/// {0}", t.Caption.ToStringEx()));
                                sb.AppendLine(@"/// </summary>");
                            }
                        }
                        else
                        {
                            properties.SingleOrDefault(d => d.TableId == t.TableId &&
                                                       d.Field == string.Empty && d.Name == FIELD_SUMMARY &&
                                                       !string.IsNullOrEmpty(d.Value)).IfNN(d =>
                            {
                                sb.AppendLine(@"/// <summary>");
                                sb.AppendLine(string.Format(@"/// {0}", d.Value));
                                sb.AppendLine(@"/// </summary>");
                            });
                        }

                        // 表格名字
                        sb.AppendLine("[Serializable]");
                        sb.AppendLine(string.Format("[Table(\"{0}\")]", t.Name));
                        sb.AppendLine(string.Format("public partial class TB_{0}:TBObject<TB_{0}>{{", t.Name));
                        //sb.AppendLine(string.Format("public partial class ET_{0} {{", t.Name));
                        columns.ForEach(c =>
                        {
                            if (_Context.IsMySql)
                            {
                                if (!string.IsNullOrEmpty(c.Caption))
                                {
                                    sb.AppendLine(@"/// <summary>");
                                    sb.AppendLine(string.Format(@"/// {0}", c.Caption));
                                    sb.AppendLine(@"/// </summary>");
                                }
                            }
                            else
                            {
                                // 说明
                                properties.SingleOrDefault(d =>
                                                           d.TableId == t.TableId &&
                                                           d.Field == c.Name && d.Name == FIELD_SUMMARY &&
                                                           !string.IsNullOrEmpty(d.Value)).IfNN(d =>
                                {
                                    sb.AppendLine(@"/// <summary>");
                                    sb.AppendLine(string.Format(@"/// {0}", d.Value));
                                    sb.AppendLine(@"/// </summary>");
                                });
                            }

                            if (t.KeyInfo.ToStringEx(string.Empty).Contains(c.Name))
                            {
                                //var singleKey = !t.KeyInfo.ToStringEx(string.Empty).Contains(",");
                                //if (singleKey && c.Type.Contains("int"))
                                //{
                                //    sb.AppendLine(@"[Key*]"); // 人为编译不成功,mySql 的问题
                                //}
                                //else
                                //{
                                //    sb.AppendLine(@"[Key]");
                                //}

                                sb.AppendLine(@"[Key]");
                            }

                            sb.AppendLine(string.Format(@"[Column(Order = {0})]", c.Ordinal));

                            if (c.CharMaxLength.HasValue &&
                                !c.Type.Contains("blob") &&
                                !c.Type.Contains("long") &&
                                !c.Type.Contains("text")
                                //!c.Spec.Contains("char(36)") // guid
                                )
                            {
                                sb.AppendLine(string.Format(@"[MaxLength({0})]", c.CharMaxLength));
                            }

                            var s = "public ";
                            s    += _getType(c) + " ";
                            s    += c.Name;
                            s    += " { get; set; }";

                            sb.AppendLine(s);
                        });

                        sb.AppendLine("}");

                        if (doneToConfirmContinue != null)
                        {
                            if (!doneToConfirmContinue(t.Name))
                            {
                                break;
                            }
                        }

                        if (count == _BatchSize - 1)
                        {
                            sb.AppendLine("}");

                            ts.Insert(sb.ToString());
                            ts.SelectAll();

                            _App.ExecuteCommand("Edit.FormatDocument");
                            win.Close(vsSaveChanges.vsSaveChangesYes);
                            count = -1;
                        }
                    }

                    // closing
                    if (count != -1)
                    {
                        sb.AppendLine("}");

                        ts.Insert(sb.ToString());
                        ts.SelectAll();

                        _App.ExecuteCommand("Edit.FormatDocument");
                        win.Close(vsSaveChanges.vsSaveChangesYes);
                        count = -1;
                    }
                }
            }
        }
Beispiel #13
0
        private void EnterTextToActiveDocument(string text)
        {
            if (Statics.DTE.ActiveDocument == null)
            {
                MessageBox.Show("No active document is visible to write the generated code in, copying to clipboard instead (press ctrl-v on the document you want to place the code into)", "No Active Document", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                Clipboard.Clear();
                if (!string.IsNullOrEmpty(text))
                {
                    Clipboard.SetText(text);
                }
                return;
            }
            TextSelection sel   = (TextSelection)Statics.DTE.ActiveDocument.Selection;
            TextRanges    dummy = null;

            if (Statics.Language == ProjectLanguage.CSharp)
            {
                bool isRegionExists = false;

                sel.StartOfDocument(true);
                if (sel.FindPattern("#region Temporary Recording", (int)vsFindOptions.vsFindOptionsMatchInHiddenText, ref dummy))
                {
                    isRegionExists = true;
                }

                sel.EndOfDocument(true);

                sel.FindPattern("}", (int)(vsFindOptions.vsFindOptionsBackwards | vsFindOptions.vsFindOptionsMatchInHiddenText), ref dummy);
                sel.FindPattern("}", (int)(vsFindOptions.vsFindOptionsBackwards | vsFindOptions.vsFindOptionsMatchInHiddenText), ref dummy);
                if (isRegionExists)
                {
                    sel.FindPattern("#endregion", (int)(vsFindOptions.vsFindOptionsBackwards | vsFindOptions.vsFindOptionsMatchInHiddenText), ref dummy);
                }
                sel.LineUp(true, 1);
                if (!isRegionExists)
                {
                    sel.Insert("\t\t#region Temporary Recording Code\r\n", (int)vsInsertFlags.vsInsertFlagsCollapseToEnd);
                }
                sel.Insert("\t\tprivate void " + GetAvailableMethodName() + "()\r\n", (int)vsInsertFlags.vsInsertFlagsCollapseToEnd);
                sel.Insert("\t\t{\r\n", (int)vsInsertFlags.vsInsertFlagsCollapseToEnd);
                sel.Insert(text, (int)vsInsertFlags.vsInsertFlagsCollapseToEnd);
                sel.Insert("\r\n\t\t}\r\n", (int)vsInsertFlags.vsInsertFlagsCollapseToEnd);
                if (!isRegionExists)
                {
                    sel.Insert("\t\t#endregion\r\n", (int)vsInsertFlags.vsInsertFlagsCollapseToEnd);
                    sel.Insert("\t}\r\n", (int)vsInsertFlags.vsInsertFlagsCollapseToEnd);
                }
            }
            else if (Statics.Language == ProjectLanguage.VB)
            {
                sel.EndOfDocument(true);

                sel.FindPattern("End Class", (int)(vsFindOptions.vsFindOptionsBackwards | vsFindOptions.vsFindOptionsMatchInHiddenText), ref dummy);
                //sel.LineUp(true, 1);
                sel.Insert("\tPrivate Sub " + GetAvailableMethodName() + "()\r\n", (int)vsInsertFlags.vsInsertFlagsCollapseToEnd);
                sel.Insert(text, (int)vsInsertFlags.vsInsertFlagsCollapseToEnd);
                sel.Insert("\tEnd Sub\r\n", (int)vsInsertFlags.vsInsertFlagsCollapseToEnd);
                sel.Insert("End Class\r\n", (int)vsInsertFlags.vsInsertFlagsCollapseToEnd);
            }


            //sel.SelectAll();
            Statics.DTE.ActiveDocument.Activate();
            System.Threading.Thread.Sleep(200);
            Statics.DTE.ExecuteCommand("Edit.FormatDocument", string.Empty);
        }
Beispiel #14
0
        public void ListWindows()
        {
            OutputWindow outWindow = _dte.ToolWindows.OutputWindow;

            outWindow.Parent.AutoHides = false;
            outWindow.Parent.Activate();

            //string test = window.ActivePane.Name;

            OutputWindowPane buildPane = null;

            try
            {
                buildPane = outWindow.OutputWindowPanes.Item("Build");
            }
            catch
            {
                buildPane = outWindow.OutputWindowPanes.Add("Build");
            }
            finally
            {
                //buildPane.Clear();
            }



            for (int i = count; i < count + 20; ++i)
            {
                buildPane.OutputString("Line " + i + "\n");
            }


            buildPane.Activate();

            try
            {
                if (buildPane.TextDocument != null)
                {
                    TextDocument  doc = buildPane.TextDocument;
                    TextSelection sel = doc.Selection;

                    sel.StartOfDocument(false);
                    sel.EndOfDocument(true);

                    count += 20;


                    sel.GotoLine(count - 5);


                    try
                    {
                        sel.ActivePoint.TryToShow(vsPaneShowHow.vsPaneShowCentered, null);
                    }
                    catch (System.Exception ex)
                    {
                        Console.WriteLine("Exception! " + ex.ToString());
                    }
                }
            }
            catch (System.Exception ex)
            {
                Console.WriteLine("Exception! " + ex.ToString());
            }
        }
Beispiel #15
0
        private void _Do_3(Func <string, bool> doneToConfirmContinue = null)
        {
            if (string.IsNullOrEmpty(_Namespace))
            {
                MessageBox.Show("Please provide a namespace");
                return;
            }

            var template = GetTemplatePath("ABP.DTO");
            var now      = DateTime.Now;
            var projects = (Array)_App.ActiveSolutionProjects;

            // 准备插入代码
            ProjectItem   file = null;
            Window        win  = null;
            TextSelection ts   = null;
            StringBuilder sb   = null;

            var batchIndex = -1;
            var batchSize  = 50;
            var saved      = true;

            Action <ProjectItem> _newFile = f =>
            {
                batchIndex++;
                file = f.ProjectItems.AddFromTemplate(template, $"DTO.{batchIndex.ToString("D4")}.cs");
                win  = file.Open(Constants.vsViewKindCode);
                sb   = new StringBuilder();

                ts = win.Document.Selection as TextSelection;
                // ts.EndOfDocument();

                // 插入生成日期
                sb.AppendLine(@"/// <summary>");
                sb.AppendLine($"/// {now}");
                sb.AppendLine(@"/// </summary>");

                // 插入 namespace 行
                sb.AppendLine("namespace " + _Namespace);
                sb.AppendLine("{");

                saved = false;
            };

            Action _saveAndClose = () =>
            {
                ts.EndOfDocument();
                ts.Insert(sb.ToString());
                ts.Insert("}");
                ts.NewLine();
                ts.SelectAll();

                win.Activate();
                win.Document.Activate();

                _App.ExecuteCommand("Edit.FormatDocument");

                win.Close(vsSaveChanges.vsSaveChangesYes);
                saved = true;
            };

            if (projects.Length > 0)
            {
                foreach (Project p in projects)
                {
                    ProjectItem folder = p.ProjectItems
                                         .AddFolder("_DTOs", Constants.vsProjectItemKindPhysicalFolder);
                    List <MBTable> tables =
                        _Context.Tables.Where(_Filter).OrderBy(t => t.Name).ToList();

                    for (int i = 0; i < tables.Count; i++)
                    {
                        if (i % batchSize == 0)
                        {
                            _newFile(folder);
                        }

                        var t = tables[i];

                        List <string> keys = new List <string>();
                        if (!
                            string.IsNullOrEmpty(t.KeyInfo))
                        {
                            foreach (string part in t.KeyInfo.Split(','))
                            {
                                if (part.Trim().Length > 0)
                                {
                                    keys.Add(part.Trim());
                                }
                            }
                        }

                        var columns = _Context.Columns
                                      .Where(c => c.TableId == t.TableId).OrderBy(c => c.Name).ToList();
                        var properties = _Context.Properties
                                         .Where(d => d.TableId == t.TableId).ToList();

                        // 说明
                        if (_Context.IsMySql)
                        {
                        }
                        else
                        {
                            properties.SingleOrDefault(d => d.TableId == t.TableId &&
                                                       d.Field == string.Empty && d.Name == FIELD_SUMMARY &&
                                                       !string.IsNullOrEmpty(d.Value)).IfNN(d =>
                            {
                                sb.AppendLine(@"/// <summary>");
                                sb.AppendLine($"/// {d.Value}");
                                sb.AppendLine(@"/// </summary>");
                            });
                        }

                        if (keys.Count == 0)
                        {
                            doneToConfirmContinue($"Error: no primary key found for {t.Name}");
                            continue;
                        }

                        // Decide base class
                        var isCompoundKey = keys.Count > 1;
                        var singleKeyType = string.Empty;
                        var baseType      = "EntityDto";
                        var ignoreKeys    = new List <string>();

                        if (!
                            isCompoundKey)
                        {
                            singleKeyType = _getType(columns.First(c => c.Name == keys[0]));
                            ignoreKeys.Add(keys[0]);
                        }

                        if (columns.Exists(c => c.Name == "CreationTime" && c.Type.StartsWith("datetime")) &&
                            columns.Exists(c => c.Name == "CreatorId" && c.Type.StartsWith("uniqueidentifier")))
                        {
                            baseType = "CreationAuditedEntityDto";
                            ignoreKeys.AddRange(new string[] { "CreationTime", "CreatorId" });

                            if (columns.Exists(c => c.Name == "LastModificationTime" && c.Type.StartsWith("datetime")) &&
                                columns.Exists(c => c.Name == "LastModifierId" && c.Type.StartsWith("uniqueidentifier")))
                            {
                                ignoreKeys.AddRange(new string[] { "LastModificationTime", "LastModifierId" });
                                baseType = "AuditedEntityDto";

                                if (columns.Exists(c => c.Name == "DeletionTime" && c.Type.StartsWith("datetime")) &&
                                    columns.Exists(c => c.Name == "DeleterId" && c.Type.StartsWith("uniqueidentifier")) &&
                                    columns.Exists(c => c.Name == "IsDeleted" && c.Type.StartsWith("bit")))
                                {
                                    ignoreKeys.AddRange(new string[] { "DeletionTime", "DeleterId", "IsDeleted" });
                                    baseType = "FullAuditedEntityDto";
                                }
                            }
                        }

                        if (!isCompoundKey)
                        {
                            baseType += $"<{singleKeyType}>";
                        }

                        // 表格名字
                        sb.AppendLine("[Serializable]");
                        sb.AppendLine($"public partial class {t.Name}Dto:{baseType}{{");

                        columns.ForEach(c =>
                        {
                            if (ignoreKeys.Contains(c.Name))
                            {
                                return;
                            }

                            // Summary
                            if (_Context.IsMySql)
                            {
                            }
                            else
                            {
                                // 说明
                                properties.SingleOrDefault(d =>
                                                           d.TableId == t.TableId &&
                                                           d.Field == c.Name && d.Name == FIELD_SUMMARY &&
                                                           !string.IsNullOrEmpty(d.Value)).IfNN(d =>
                                {
                                    sb.AppendLine(@"/// <summary>");
                                    sb.AppendLine($"{d.Value}");
                                    sb.AppendLine(@"</summary>");
                                });
                            }

                            if (!c.Nullable)
                            {
                                sb.AppendLine("[Required]");
                            }

                            if ((c.CharMaxLength ?? 0) > 0)
                            {
                                sb.AppendLine($"[MaxLength({c.CharMaxLength})]");
                            }

                            // Body
                            var s = "public ";
                            s    += _getType(c) + " ";
                            s    += c.Name;
                            s    += " { get; set; }";

                            sb.AppendLine(s);
                        });

                        sb.AppendLine("}");

                        if (doneToConfirmContinue != null)
                        {
                            if (!doneToConfirmContinue(t.Name))
                            {
                                break;
                            }
                        }

                        if (i > 0 && (i % batchSize) == 0)
                        {
                            _saveAndClose();
                        }
                    }

                    if (!saved)
                    {
                        _saveAndClose();
                    }
                }
            }
        }
Beispiel #16
0
        public void ThenTheProjectShouldBuildAndItsTestsRunSuccessfully()
        {
            Trace.WriteLine("Building solution");

            AutoResetEvent autoResetEvent = new AutoResetEvent(false);

            bool buildSucceeded = false;

            this.dte.Events.BuildEvents.OnBuildProjConfigDone += (project, projectConfig, platform, solutionConfig, success) =>
            {
                Trace.WriteLine(
                    string.Format(
                        "Project {0} Project Configuration {1} Platform {2} Solution Configuration {3} Success {4}",
                        project,
                        projectConfig,
                        platform,
                        solutionConfig,
                        success));

                buildSucceeded = success;

                autoResetEvent.Set();
            };

            this.dte.ExecuteCommand("Build.RebuildSolution");

            autoResetEvent.WaitOne();

            Trace.WriteLine("Done building solution");

            if (!buildSucceeded)
            {
                const string buildOutputPaneGuid = "{1BD8A850-02D1-11D1-BEE7-00A0C913D1F8}";

                Window vsWindow = this.dte.Windows.Item(Constants.vsWindowKindOutput);

                OutputWindowPane objBuildOutputWindowPane = null;

                OutputWindow vsOutputWindow = (OutputWindow)vsWindow.Object;

                foreach (OutputWindowPane objOutputWindowPane in vsOutputWindow.OutputWindowPanes)
                {
                    if (objOutputWindowPane.Guid.ToUpper() == buildOutputPaneGuid)
                    {
                        objBuildOutputWindowPane = objOutputWindowPane;
                    }
                }

                Assert.IsNotNull(objBuildOutputWindowPane);

                TextDocument  txtOutput    = objBuildOutputWindowPane.TextDocument;
                TextSelection txtSelection = txtOutput.Selection;

                txtSelection.StartOfDocument();
                txtSelection.EndOfDocument(true);

                txtSelection = txtOutput.Selection;

                Assert.IsTrue(buildSucceeded, txtSelection.Text);
            }

            this.RunAllTests();
        }
Beispiel #17
0
        public static IOsbideEvent FromCommand(string commandName, DTE2 dte)
        {
            IOsbideEvent oEvent = null;

            //debugging events
            if (debugCommands.Contains(commandName))
            {
                DebugActions action = (DebugActions)debugCommands.IndexOf(commandName);
                DebugEvent   debug  = new DebugEvent();
                debug.SolutionName = dte.Solution.FullName;
                debug.EventDate    = DateTime.UtcNow;

                //sometimes document name can be null
                try
                {
                    debug.DocumentName = dte.ActiveDocument.Name;
                }
                catch (Exception)
                {
                    debug.DocumentName = dte.Solution.FullName;
                }

                //add line number if applicable
                if (action == DebugActions.StepInto ||
                    action == DebugActions.StepOut ||
                    action == DebugActions.StepOver
                    )
                {
                    //line number can be null if there is no document open
                    try
                    {
                        TextSelection debugSelection = dte.ActiveDocument.Selection;
                        debugSelection.SelectLine();
                        int lineNumber = debugSelection.CurrentLine;
                        debug.LineNumber  = lineNumber;
                        debug.DebugOutput = debugSelection.Text;
                    }
                    catch (Exception)
                    {
                        debug.LineNumber = 0;
                    }
                }

                //kind of reappropriating this for our current use.  Consider refactoring.
                debug.ExecutionAction = (int)action;

                //throw the content of the output window into the event if we just stopped debugging
                if (action == DebugActions.StopDebugging)
                {
                    OutputWindowPane debugWindow = dte.ToolWindows.OutputWindow.OutputWindowPanes.Item("Debug");
                    if (debugWindow != null)
                    {
                        TextDocument  text      = debugWindow.TextDocument;
                        TextSelection selection = text.Selection;
                        selection.StartOfDocument();
                        selection.EndOfDocument(true);
                        debug.DebugOutput = selection.Text;
                        selection.EndOfDocument();
                    }
                }

                oEvent = debug;
            }
            else if (cutCopyPasteCommands.Contains(commandName))
            {
                CutCopyPasteEvent ccp = new CutCopyPasteEvent();
                ccp.SolutionName = dte.Solution.FullName;
                ccp.EventDate    = DateTime.UtcNow;
                ccp.EventAction  = cutCopyPasteCommands.IndexOf(commandName);
                ccp.Content      = Clipboard.GetText();
                //sometimes document name can be null
                try
                {
                    ccp.DocumentName = dte.ActiveDocument.Name;
                }
                catch (Exception)
                {
                    ccp.DocumentName = dte.Solution.FullName;
                }
                oEvent = ccp;
            }

            return(oEvent);
        }
        private void _Do_4(Func <string, bool> doneToConfirmContinue = null)
        {
            if (string.IsNullOrEmpty(_Namespace))
            {
                MessageBox.Show("Please provide a namespace:extensionClassName:objectPrefix");
                return;
            }

            if (!_Namespace.Contains(":"))
            {
                MessageBox.Show("Please provide a namespace:extensionClassName:objectPrefix");
                return;
            }

            var parts    = _Namespace.SplitEx(':');
            var template = GetTemplatePath("ABP.Context");
            var now      = DateTime.Now;
            var projects = (Array)_App.ActiveSolutionProjects;

            var boPrefix = parts[2];

            // 准备插入代码
            ProjectItem   file = null;
            Window        win  = null;
            TextSelection ts   = null;
            StringBuilder sb   = null;

            var batchIndex = -1;
            var saved      = true;

            Action <ProjectItem> _newFile = f =>
            {
                batchIndex++;
                file = f.ProjectItems.AddFromTemplate(template, $"{parts[1]}.cs");
                win  = file.Open(Constants.vsViewKindCode);
                sb   = new StringBuilder();

                ts = win.Document.Selection as TextSelection;
                // ts.EndOfDocument();

                // 插入生成日期
                sb.AppendLine(@"/// <summary>");
                sb.AppendLine($"/// {now}");
                sb.AppendLine(@"/// </summary>");

                // 插入 namespace 行
                sb.AppendLine("namespace " + parts[0]);
                sb.AppendLine("{");

                saved = false;
            };

            Action _saveAndClose = () =>
            {
                ts.EndOfDocument();
                ts.Insert(sb.ToString());
                ts.Insert("}");
                ts.NewLine();
                ts.SelectAll();

                win.Activate();
                win.Document.Activate();

                _App.ExecuteCommand("Edit.FormatDocument");

                win.Close(vsSaveChanges.vsSaveChangesYes);
                saved = true;
            };

            if (projects.Length > 0)
            {
                foreach (Project p in projects)
                {
                    ProjectItem folder = p.ProjectItems
                                         .AddFolder("_Database", Constants.vsProjectItemKindPhysicalFolder);
                    List <MBTable> tables =
                        _Context.Tables.Where(_Filter).OrderBy(t => t.Name).ToList();

                    _newFile(folder);

                    sb.AppendLine($"public static class {parts[1]}");
                    sb.AppendLine("{");

                    sb.AppendLine($"public static void ConfigureInternal(this ModelBuilder builder)");
                    sb.AppendLine("{");

                    sb.AppendLine($"Check.NotNull(builder, nameof(builder));");

                    for (int i = 0; i < tables.Count; i++)
                    {
                        var t = tables[i];

                        List <string> keys = new List <string>();
                        if (!
                            string.IsNullOrEmpty(t.KeyInfo))
                        {
                            foreach (string part in t.KeyInfo.Split(','))
                            {
                                if (part.Trim().Length > 0)
                                {
                                    keys.Add(part.Trim());
                                }
                            }
                        }

                        if (keys.Count == 0)
                        {
                            doneToConfirmContinue($"Error: no primary key found for {t.Name}");
                            continue;
                        }

                        var columns = _Context.Columns
                                      .Where(c => c.TableId == t.TableId).OrderBy(c => c.Name).ToList();
                        var properties = _Context.Properties
                                         .Where(d => d.TableId == t.TableId).ToList();


                        sb.AppendLine($"            builder.Entity<{boPrefix}_{t.Name}>(b =>");
                        sb.AppendLine("             {");
                        sb.AppendLine($"                b.ToTable(\"{t.Name}\", AbpCommonDbProperties.DbSchema);");
                        sb.AppendLine("                 b.ConfigureByConvention();");

                        if (keys.Count > 1)
                        {
                            sb.AppendLine($"                b.HasKey({ string.Join(", ", keys.Select(k => $"\"{k}\"")) });");
                        }
                        else if (keys.Count == 1)
                        {
                            sb.AppendLine($"                b.HasKey(\"Id\");");
                        }

                        columns.ForEach(c =>
                        {
                            var propConfig   = $"                b.Property(x => x.{c.Name})";
                            var shouldConfig = false;

                            if (keys.Count == 1 && c.Name == keys[0])
                            {
                                propConfig = $"                b.Property(x => x.Id)";

                                if (!c.Name.Equals("Id", StringComparison.InvariantCultureIgnoreCase))
                                {
                                    propConfig   = $"                b.Property(x => x.Id).HasColumnName(\"{(c.Name)}\")";
                                    shouldConfig = true;
                                }
                            }

                            if (!c.Nullable)
                            {
                                propConfig  += ".IsRequired()";
                                shouldConfig = true;
                            }

                            if (c.CharMaxLength.HasValue && c.CharMaxLength > 0)
                            {
                                propConfig  += $".HasMaxLength({c.CharMaxLength})";
                                shouldConfig = true;
                            }

                            if (c.Type.Contains("decimal") ||
                                c.Type.Contains("datetime2") ||
                                c.Type.Contains("numeric") ||
                                c.Type.Contains("money") ||
                                c.Type.Contains("float") ||
                                c.Type.Contains("binary") ||
                                c.Type.Contains("time")
                                )
                            {
                                propConfig  += $".HasColumnType(\"{_getSqlType(c)}\")";
                                shouldConfig = true;
                            }

                            if (shouldConfig)
                            {
                                sb.AppendLine($"                {propConfig};");
                            }
                        });

                        sb.AppendLine("            });");

                        if (doneToConfirmContinue != null)
                        {
                            if (!doneToConfirmContinue(t.Name))
                            {
                                break;
                            }
                        }
                    }

                    sb.AppendLine("}");
                    sb.AppendLine("}");

                    if (!saved)
                    {
                        _saveAndClose();
                    }
                }
            }
        }