Esempio n. 1
0
        private void UpdateCallback(object sender, EventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();
            DTE dte = ServiceProvider.GetServiceAsync(typeof(DTE)).Result as DTE;

            if (dte == null)
            {
                return;
            }

            TextSelection section = dte.ActiveDocument.Selection as TextSelection;

            // 光标移动至第一行第一列
            section.MoveToLineAndOffset(1, 1);
            bool result = section.FindText("database", (int)vsFindOptions.vsFindOptionsRegularExpression);

            if (!result)
            {
                section.SelectAll();
                section.Delete();
            }
            else
            {
                //需要添加此操作,否则不会替换成功
                section.SelectAll();
                section.Text = "";
            }
        }
Esempio n. 2
0
        /// <summary>
        ///     A TextSelection extension method that selects one or more nodes
        ///     contained by one parent node.
        /// </summary>
        /// <param name="selection">
        ///     The target to act on.
        /// </param>
        /// <returns>
        ///     true if it succeeds, otherwise false.
        /// </returns>
        public static bool SelectNodes(this TextSelection selection)
        {
            logger.Trace("Entered SelectNodes()");
            EditorPoints ep = GetEditorPoints(selection);

            // Find the nodes that are within or that contain the ends of the selection.
            Tuple <XamlNode, XamlNode> firstAndLast =
                _rootNode.GetFirstLastNodesBetweenPoints(ep.TopPoint - 1,
                                                         ep.BottomPoint - 1);

            // Null is returned if one end of the selection is outside the root node.
            if (firstAndLast.Item1 == null || firstAndLast.Item2 == null)
            {
                // Select the root node.
                selection.SelectAll();
                selection.Trim();
                return(true);
            }

            // Select the the text for the nodes found above.
            selection.SetSelection(firstAndLast.Item2.BottomPoint + 1,
                                   firstAndLast.Item1.TopPoint + 1);

            return(true);
        }
Esempio n. 3
0
        internal void CreateNewcshtmlFile(string title, string fileContents)
        {
            DTE2 provider = Package.GetGlobalService(typeof(SDTE)) as DTE2;

            if (provider == null || provider.ActiveDocument == null)
            {
                return;
            }
            var x = provider.ActiveDocument.Path.ToString() + title + ".cshtml";

            using (var stream = new FileStream(x, FileMode.OpenOrCreate))
            {
            }
            var file = provider.ItemOperations.AddExistingItem(x).Open();

            if (file?.Document == null)
            {
                return;
            }

            file?.Document?.Activate();

            if (!String.IsNullOrEmpty(fileContents))
            {
                TextSelection selection = (TextSelection)file?.Document?.Selection;
                selection.SelectAll();
                selection.Text = "";
                selection.Insert(fileContents);
            }
        }
        /// <summary>
        /// Saves the file menu item click.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="MenuItemEventArgs" /> instance containing the event data.</param>
        protected virtual void SaveFileMenuItemClick(object sender, MenuItemEventArgs e)
        {
            IExplorerNode parentNode   = e.Owner as IExplorerNode;
            var           fileNodeInfo = parentNode.Annotations.GetValue <FileNodeInfo>();

            DTEManager.SetStatus(CKSProperties.FileUtilities_SavingFile);

            Document      file      = DTEManager.DTE.ActiveDocument;
            TextSelection selection = file.Selection as TextSelection;

            selection.SelectAll();
            fileNodeInfo.Contents = selection.Text;
            selection.StartOfDocument();

            bool result = parentNode.Context.SharePointConnection.ExecuteCommand <FileNodeInfo, bool>(FileSharePointCommandIds.SaveFileCommand, fileNodeInfo);

            if (result)
            {
                DTEManager.SetStatus(CKSProperties.FileUtilities_FileSuccessfullySaved);
            }
            else
            {
                MessageBox.Show(CKSProperties.FileUtilities_FileSaveError, CKSProperties.FileUtilities_FileSaveErrorMessageTitle, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Builds the source file.
        /// </summary>
        /// <param name="project">The project.</param>
        /// <param name="extensionSource">The extensionSource.</param>
        /// <param name="extensionDestination">The extension destination.</param>
        /// <param name="friendlyName">Name of the friendly.</param>
        internal void BuildSourceFile(
            Project project,
            string extensionSource,
            string extensionDestination,
            string friendlyName)
        {
            try
            {
                const string PlaceHolderText = "#PlaceHolder#";

                string message = string.Format("BuildSourceFile Project Name={0} friendlyName={1}", project.Name, friendlyName);

                TraceService.WriteLine(message);

                string sourceFile = friendlyName + "PluginBootstrap.cs";

                //// now we need to sort out the item template!
                project.AddToFolderFromTemplate("Bootstrap", "MvvmCross.Plugin.zip", sourceFile);

                ProjectItem projectItem = project.GetProjectItem(sourceFile);

                //// if we find the project item replace the text in it else use the find/replace window.
                if (projectItem != null)
                {
                    TextSelection textSelection = projectItem.DTE.ActiveDocument.Selection;
                    textSelection.SelectAll();
                    textSelection.ReplacePattern(PlaceHolderText, friendlyName);
                    projectItem.Save();
                }
            }
            catch (Exception exception)
            {
                TraceService.WriteError("BuildSourceFile " + exception.Message);
            }
        }
Esempio n. 6
0
        private static string GetBuildOutput()
        {
            OutputWindowPane buildWindow    = Dte.ToolWindows.OutputWindow.OutputWindowPanes.Item("Build");
            TextSelection    buildSelection = buildWindow.TextDocument.Selection;

            buildSelection.SelectAll();
            return(buildSelection.Text);
        }
        /// <summary>
        /// Replaces the pattern.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <param name="replacementText">The replacement text.</param>
        public void ReplacePattern(
            string text,
            string replacementText)
        {
            TextSelection textSelection = this.projectItem.DTE.ActiveDocument.Selection;

            textSelection.SelectAll();
            textSelection.ReplacePattern(text, replacementText);
        }
Esempio n. 8
0
        private void btnGenerateScript_Click(object sender, EventArgs e)
        {
            try
            {
                Cursor.Current = Cursors.WaitCursor;
                if (_bismNormalizerPackage.Dte != null)
                {
                    _bismNormalizerPackage.Dte.StatusBar.Text = "BISM Normalizer - creating script ...";
                }

                string   script = _comparison.ScriptDatabase(); //doing this here in case errors before opening file in VS
                Document file   = NewXmlaFile(_comparison.CompatibilityLevel >= 1200, (_comparisonInfo.ConnectionInfoTarget.UseProject ? _comparisonInfo.ConnectionInfoTarget.ProjectName : _comparisonInfo.ConnectionInfoTarget.DatabaseName));
                if (file != null)
                {
                    TextSelection selection = (TextSelection)file.Selection;
                    selection.SelectAll();
                    selection.Insert(script);
                    selection.GotoLine(1);

                    return;
                }

                //If we get here, there was a problem generating the xmla file (maybe file item templates not installed), so offer saving to a file instead
                SaveFileDialog saveFile = new SaveFileDialog();
                saveFile.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
                if (_comparison.CompatibilityLevel >= 1200)
                {
                    saveFile.Filter = "JSON Files|*.json|Text Files|*.txt|All files|*.*";
                }
                else
                {
                    saveFile.Filter = "XMLA Files|*.xmla|Text Files|*.txt|All files|*.*";
                }
                saveFile.CheckFileExists = false;
                if (saveFile.ShowDialog() == DialogResult.OK)
                {
                    File.WriteAllText(saveFile.FileName, _comparison.ScriptDatabase());

                    if (_bismNormalizerPackage.Dte != null)
                    {
                        _bismNormalizerPackage.Dte.StatusBar.Text = "BISM Normalizer - finished generating script";
                    }
                    MessageBox.Show("Created script\n" + saveFile.FileName, _bismNormalizerCaption, MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show(exc.Message, _bismNormalizerCaption, MessageBoxButtons.OK, MessageBoxIcon.Error);
                SetNotComparedState();
            }
            finally
            {
                Cursor.Current = Cursors.Default;
                _bismNormalizerPackage.Dte.StatusBar.Text = "";
            }
        }
Esempio n. 9
0
        public static void CreateNewFile(string fileType, string title, string fileContents)
        {
            Document      document      = DteService.DTE.ItemOperations.NewFile(fileType, title, "{00000000-0000-0000-0000-000000000000}").Document;
            TextSelection textSelection = document.Selection as TextSelection;

            textSelection.SelectAll();
            textSelection.Text = "";
            textSelection.Insert(fileContents, 1);
            textSelection.StartOfDocument(false);
        }
Esempio n. 10
0
        private string GetOutputWindowPaneText(OutputWindowPane outputWindowPane)
        {
            TextDocument  doc = outputWindowPane.TextDocument;
            TextSelection sel = doc.Selection;

            sel.SelectAll();
            string txt = sel.Text;

            return(txt);
        }
Esempio n. 11
0
        /// <summary>
        /// Creates the new file.
        /// </summary>
        /// <param name="fileType">Type of the file.</param>
        /// <param name="title">The title.</param>
        /// <param name="fileContents">The file contents.</param>
        public static void CreateNewFile(
            string fileType, string title, string fileContents)
        {
            Document      file      = DTE.ItemOperations.NewFile(fileType, title).Document;
            TextSelection selection = file.Selection as TextSelection;

            selection.SelectAll();
            selection.Text = "";
            selection.Insert(fileContents);
            selection.StartOfDocument();
        }
Esempio n. 12
0
        public void RemoveRegions(Proc replaceString)
        {
            Document      currentDocument     = _applicationObject.ActiveDocument;
            TextDocument  currentTextDocument = currentDocument.Object("") as TextDocument;
            TextSelection txtSel = (TextSelection)_applicationObject.ActiveDocument.Selection;

            if (currentTextDocument != null)
            {
                TextRanges refRanges = null;

                if (currentTextDocument.Language == "CSharp")
                {
                    try
                    {
                        txtSel.SelectAll();
                        txtSel.ReplacePattern(replaceString(), " ",
                                              (int)vsFindOptions.vsFindOptionsFromStart +
                                              (int)vsFindOptions.vsFindOptionsMatchInHiddenText +
                                              (int)vsFindOptions.vsFindOptionsKeepModifiedDocumentsOpen +
                                              (int)vsFindOptions.vsFindOptionsRegularExpression,
                                              ref refRanges);

                        //currentTextDocument.ReplacePattern(replaceString(), string.Empty,
                        //                                   (int) vsFindOptions.vsFindOptionsFromStart +
                        //                                   (int) vsFindOptions.vsFindOptionsMatchInHiddenText +
                        //                                   (int) vsFindOptions.vsFindOptionsKeepModifiedDocumentsOpen +
                        //                                   (int) vsFindOptions.vsFindOptionsRegularExpression,
                        //                                   ref refRanges);
                    }
                    catch (Exception e)
                    {
                        Console.Out.WriteLine("e = {0}", e);
                    }
                }

                #region some other crap

                #region inner region

                #  region

                #endregion

                #endregion

                #endregion

                #region

                #endregion
            }
        }
Esempio n. 13
0
        public static void CreateClass(this Project pro, string directory, string name, string content)
        {
            if (pro == null)
            {
                return;
            }
            var add = false;

            foreach (ProjectItem projectItem in pro.ProjectItems)
            {
                var dname = projectItem.Name;
                if (dname == directory)
                {
                    var item = projectItem.GetItem(name + ".cs");
                    if (item == null)
                    {
                        string templatePath =
                            GetSolution3().GetProjectItemTemplate("Class.zip", "CSharp");
                        projectItem.ProjectItems.AddFromTemplate(templatePath, name + ".cs");
                        TextSelection txtSel = (TextSelection)Application.ActiveDocument.Selection;
                        txtSel.SelectAll();
                        txtSel.Delete();
                        txtSel.Insert(content);
                        add = true;
                    }
                    else
                    {
                        item.Open();
                        TextSelection txtSel = (TextSelection)Application.ActiveDocument.Selection;
                        txtSel.SelectAll();
                        txtSel.Delete();
                        txtSel.Insert(content);
                        add = true;
                    }
                }
            }

            if (!add)
            {
                pro.ProjectItems.AddFolder(directory);
                var    projectItem  = pro.GetItem(directory);
                string templatePath =
                    GetSolution3().GetProjectItemTemplate("Class.zip", "CSharp");
                projectItem.ProjectItems.AddFromTemplate(templatePath, name + ".cs");
                TextSelection txtSel = (TextSelection)Application.ActiveDocument.Selection;

                txtSel.SelectAll();
                txtSel.Delete();
                txtSel.Insert(content);
                add = true;
            }
        }
Esempio n. 14
0
        private EditorPoints(TextSelection sel)
            : this()
        {
            ActivePoint        = sel.ActivePoint.AbsoluteCharOffset;
            AnchorPoint        = sel.AnchorPoint.AbsoluteCharOffset;
            BottomPoint        = sel.BottomPoint.AbsoluteCharOffset;
            TopPoint           = sel.TopPoint.AbsoluteCharOffset;
            IsActiveEndGreater = sel.IsActiveEndGreater;
            Text = sel.Text;
            sel.SelectAll();

            DocumentText = sel.Text.Replace(Environment.NewLine, "\n");
        }
        /// <summary>
        /// Adds new file to the current Solution/Project and inserts the contents
        /// </summary>
        /// <param name="fileType">File type, eg. General\XML File</param>
        /// <param name="title">File title</param>
        /// <param name="fileContents">File contents</param>
        internal static void CreateNewFile(string fileType, string title, string fileContents)
        {
            DTE2     dte  = Package.GetGlobalService(typeof(SDTE)) as DTE2;
            Document file = dte.ItemOperations.NewFile(fileType, title).Document;

            if (!String.IsNullOrEmpty(fileContents))
            {
                TextSelection selection = file.Selection;
                selection.SelectAll();
                selection.Text = "";
                selection.Insert(fileContents);
            }
        }
Esempio n. 16
0
        public void Execute(TextSelection textSelection, Func <string, string> seletionCallback)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            textSelection.GotoLine(1, true);
            textSelection.SelectAll();
            var contents   = textSelection.Text;
            var changedTxt = seletionCallback.Invoke(contents);

            textSelection.Insert(changedTxt);
            textSelection.SmartFormat();
            textSelection.GotoLine(1, false);
        }
Esempio n. 17
0
        internal void CreateFile(string fileName, string content)
        {
            DTE dte = (DTE)GetService(typeof(DTE));

            dte.ItemOperations.NewFile("General\\Text File", fileName);

            TextSelection textSel = (TextSelection)dte.ActiveDocument.Selection;
            TextDocument  textDoc = (TextDocument)dte.ActiveDocument.Object();

            textSel.SelectAll();
            textSel.Delete();
            textSel.Insert(content);

            textSel.GotoLine(1);
        }
Esempio n. 18
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);
        }
Esempio n. 19
0
 /// <summary>
 /// Reformats code file.
 /// </summary>
 public void FormatFile()
 {
     try
     {
         Solution soln = System.Activator.CreateInstance(Type.GetTypeFromProgID("VisualStudio.Solution.16.0")) as EnvDTE.Solution;
         soln.DTE.ItemOperations.OpenFile(FilePath);
         TextSelection selection = soln.DTE.ActiveDocument.Selection as TextSelection;
         selection.SelectAll();
         selection.SmartFormat();
         soln.DTE.ActiveDocument.Save();
         LoadText(File.ReadAllText(FilePath));
     }
     catch (Exception ex)
     {
         MessageBox.Show($"Failed to format file. {ex.Message}");
     }
 }
Esempio n. 20
0
        private void CreateNewFile(string filename, string content)
        {
            DTE dte = (DTE)GetService(typeof(DTE));

            dte.ItemOperations.NewFile(@"General\Visual C# Class", filename, EnvDTE.Constants.vsViewKindTextView);
            TextSelection txtSel = (TextSelection)dte.ActiveDocument.Selection;
            TextDocument  txtDoc = (TextDocument)dte.ActiveDocument.Object("");

            txtSel.SelectAll();
            txtSel.Delete();
            txtSel.Insert(content);
            //    //var dte = (EnvDTE.DTE)ServiceProvider.GlobalProvider.GetService(typeof(EnvDTE.DTE));
            //    // https://social.msdn.microsoft.com/Forums/vstudio/en-US/a7da9e48-7282-4e22-a07a-36e66426316e/add-in-trying-to-add-class-fails-with-template-invalid-for-that-project?forum=vsx
            //    EnvDTE80.DTE2 dte = Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(EnvDTE.DTE)) as EnvDTE80.DTE2;

            //    if (dte == null)
            //    {
            //        //Alert("Could not create new file.");
            //        System.Diagnostics.Debug.WriteLine("Could not get EnvDTE.DTE service.");
            //        return;
            //    }

            //    var solution = dte.Solution as EnvDTE80.Solution2;

            //    if (solution == null)
            //    {
            //        //Alert("Could not create new file.");
            //        System.Diagnostics.Debug.WriteLine("Could not get DTE solution.");
            //        return;
            //    }

            //    var x = solution.GetProjectItemTemplate(filename, "CSharp");
            //    //dte.ActiveDocument.ProjectItem.ContainingProject;


            //    //dte.ItemOperations.AddNewItem(@"Visual C# Project Items\Class", name);
            //    // http://stackoverflow.com/questions/11049758/selected-project-from-solution-explorer

            //    var txtSel = (EnvDTE.TextSelection)dte.ActiveDocument.Selection;
            //    var txtDoc = (EnvDTE.TextDocument)dte.ActiveDocument.Object();

            //    txtSel.SelectAll();
            //    txtSel.Delete();
            //    txtSel.Insert(content);
        }
        /// <summary>
        /// Replaces the text.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="text">The text.</param>
        /// <param name="replacementText">The replacement text.</param>
        /// <param name="findOptions">The find options.</param>
        public static void ReplaceText(
            this ProjectItem instance,
            string text,
            string replacementText,
            int findOptions = (int)vsFindOptions.vsFindOptionsMatchCase)
        {
            TraceService.WriteLine("ProjectItemExtensions::ReplaceText in file " + instance.Name + " from '" + text + "' to '" + replacementText + "'");

            if (instance.Kind == VSConstants.VsProjectItemKindPhysicalFolder)
            {
                foreach (ProjectItem projectItem in instance.ProjectItems.Cast <ProjectItem>())
                {
                    projectItem.ReplaceText(text, replacementText);
                }

                return;
            }

            try
            {
                Window window = instance.Open(VSConstants.VsViewKindCode);

                if (window != null)
                {
                    window.Activate();

                    TextSelection textSelection = instance.DTE.ActiveDocument.Selection;
                    textSelection.SelectAll();

                    bool replaced = textSelection.ReplacePattern(text, replacementText, findOptions);

                    TraceService.WriteLine(replaced ? "Replaced" : "NOT replaced");

                    instance.Save();
                }
                else
                {
                    TraceService.WriteLine("Could not open window to do replacement for " + instance.Name);
                }
            }
            catch (Exception exception)
            {
                TraceService.WriteError("Replacing Text failed for " + instance.Name + " exception=" + exception);
            }
        }
Esempio n. 22
0
        /// <summary>
        /// Test2: retrieve all files
        /// </summary>
        /// <returns></returns>
        public void Test2(Action <string> sink)
        {
            Action <ProjectItems> dig = items => { };

            dig = items =>
            {
                foreach (ProjectItem i in items)
                {
                    if (i.ProjectItems != null)
                    {
                        dig(i.ProjectItems);
                    }
                    if (i.SubProject != null && i.SubProject.ProjectItems != null)
                    {
                        dig(i.SubProject.ProjectItems);
                    }
                    if (i.Name.EndsWith(".aspx") ||
                        i.Name.EndsWith(".ascx") ||
                        i.Name.EndsWith(".cs"))
                    {
                        Window w = i.Open(Constants.vsViewKindCode);
                        w.Activate();
                        TextSelection ts = _App.ActiveDocument.Selection as TextSelection;
                        ts.SelectAll();
                        _App.ExecuteCommand("Edit.FormatDocument");
                        w.Close(vsSaveChanges.vsSaveChangesYes);
                        sink(i.Name);
                    }
                }
            };

            Array projects = (Array)_App.ActiveSolutionProjects;

            if (projects.Length > 0)
            {
                foreach (Project p in projects)
                {
                    if (p.ProjectItems != null)
                    {
                        dig(p.ProjectItems);
                    }
                }
            }
        }
Esempio n. 23
0
        public Form1()
        {
            InitializeComponent();
            EnvDTE.DTE DTE = Marshal.GetActiveObject("VisualStudio.DTE.14.0") as EnvDTE.DTE;

            DTEHandle h = new DTEHandle();

            EnvDTE.Project proj = h.GetProject("Test");

            foreach (EnvDTE.ProjectItem item in proj.ProjectItems)
            {
                if (item.Name == "Program.cs")
                {
                    TextSelection s = item.Document.Selection as TextSelection;
                    s.SelectAll();
                    MessageBox.Show(s.Text);
                }
            }
        }
        /// <summary>
        /// Replaces the text.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="text">The text.</param>
        /// <param name="replacementText">The replacement text.</param>
        public static void ReplaceText(
            this ProjectItem instance,
            string text,
            string replacementText)
        {
            TraceService.WriteLine("ProjectItemExtensions::ReplaceText in file " + instance.Name + " from '" + text + "' to '" + replacementText + "'");

            Window window = instance.Open(VSConstants.VsViewKindCode);

            if (window != null)
            {
                window.Activate();

                TextSelection textSelection = instance.DTE.ActiveDocument.Selection;
                textSelection.SelectAll();
                textSelection.ReplacePattern(text, replacementText, (int)vsFindOptions.vsFindOptionsMatchCase);
                instance.Save();
            }
        }
        /// <summary>
        /// takes a project item file contents and re-saves through IDE editor window, hopefully this triggers
        /// other extensions like bundlers, minifiers, linters etc to update themselves
        /// </summary>
        /// <param name="outputFile"></param>
        public static void SaveOutputFileThroughEditorWindow(string outputFile)
        {
            string jsSource = System.IO.File.ReadAllText(outputFile);
            var    dte      = TsWspPackage.DTE;
            var    item     = dte.Solution.FindProjectItem(outputFile);

            if (item != null)
            {
                // open it
                var w = item.Open(EnvDTE.Constants.vsViewKindCode);
                if (w != null)
                {
                    TextSelection ts = w.Document.Selection as TextSelection;
                    if (ts != null)
                    {
                        // replace all text with new source
                        ts.SelectAll();
                        ts.Insert(jsSource);
                        item.Save();
                        // move to top
                        ts.StartOfDocument();
                    }
                    else
                    {
                        Logger.Log("Could not update text in " + outputFile);
                    }
                }
                else
                {
                    Logger.Log("Could not open code window for " + outputFile);
                }
            }
            else
            {
                Logger.Log("Could not locate project item = " + outputFile);
            }
        }
Esempio n. 26
0
 public string GetDocument(TextSelection selection)
 {
     selection.SelectAll();
     return selection.Text;
 }
Esempio n. 27
0
        private void CreateFlowerPot(UserData userData)
        {
            DTE2 applicationObject = (DTE2)ServiceProvider.GlobalProvider.GetService(typeof(DTE));

            try
            {
                TextDocument textDoc   = (TextDocument)applicationObject.ActiveDocument.Object("TextDocument");
                EditPoint    editPoint = (EditPoint)textDoc.StartPoint.CreateEditPoint();

                string fileName = applicationObject.ItemOperations.DTE.ActiveDocument.Name;
                string version  = "1.0";

                TextSelection selection = textDoc.Selection;
                selection.SelectAll();
                string text = selection.Text;
                selection.StartOfDocument(false);

                string entity     = "Code file";
                string entityName = "";

                string[] lines = text.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);

                foreach (string line in lines)
                {
                    if (line.Contains("class "))
                    {
                        entity = "Class";
                        Regex rxClass = new Regex("^.*class (?'Class'\\w*)");
                        entityName = rxClass.Match(line).Groups["Class"].Value;
                        break;
                    }
                    else if (line.Contains("interface "))
                    {
                        entity = "Interface";
                        Regex rxInterface = new Regex("^.*interface (?'Interface'\\w*)");
                        entityName = rxInterface.Match(line).Groups["Interface"].Value;
                        break;
                    }
                    else if (line.Contains("enum "))
                    {
                        entity = "Enum";
                        Regex rxEnum = new Regex("^.*enum (?'Enum'\\w*)");
                        entityName = rxEnum.Match(line).Groups["Enum"].Value;
                        break;
                    }
                    else if (line.Contains("delegate "))
                    {
                        entity = "Delegate";
                        Regex rxDelegate = new Regex("^.*delegate (?'Delegate'\\w*)");
                        entityName = rxDelegate.Match(line).Groups["Delegate"].Value;
                        break;
                    }
                }

                string[] fileHeader = new string[8];
                fileHeader[0] = $"/{new string('*', userData.HeaderWidth - 1)}";
                fileHeader[1] = $"* File:         {fileName}";
                fileHeader[2] = $"* Contents:     {entity} {entityName}";
                fileHeader[3] = $"* Author:       {userData.AuthorName} ({userData.AuthorEmail})";
                fileHeader[4] = $"* Date:         {DateTime.Now.ToString("yyyy-MM-dd HH:mm")}";
                fileHeader[5] = $"* Version:      {version}";
                fileHeader[6] = $"* Copyright:    {userData.CompanyName} ({userData.CompanyWebsite})";
                fileHeader[7] = $"{new string('*', userData.HeaderWidth - 1)}/";

                for (int i = 1; i <= 6; i++)
                {
                    fileHeader[i] += new string(' ', userData.HeaderWidth - 1 - fileHeader[i].Length) + "*";
                }

                string strResult = string.Join("\n", fileHeader) + "\n";

                editPoint.Insert(strResult);
            }
            catch   {}
        }
Esempio n. 28
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;
                    }
                }
            }
        }
Esempio n. 29
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();
                    }
                }
            }
        }
Esempio n. 30
0
        /// <summary>
        /// Runs custom wizard logic when a project has finished generating.
        /// </summary>
        /// <param name="project"></param>
        public void ProjectFinishedGenerating(Project project)
        {
            // Iterate through the project items and
            // remove any files that begin with the word "Placeholder".
            // and the Rates class unless it's the Telescope class
            // done this way to avoid removing items from inside a foreach loop
            List <string> rems = new List <string>();

            foreach (ProjectItem item in project.ProjectItems)
            {
                if (item.Name.StartsWith("Placeholder", StringComparison.OrdinalIgnoreCase) ||
                    item.Name.StartsWith("Rate", StringComparison.OrdinalIgnoreCase) &&
                    !this.DeviceClass.Equals("Telescope", StringComparison.OrdinalIgnoreCase))
                {
                    //MessageBox.Show("adding " + item.Name);
                    rems.Add(item.Name);
                }
            }
            foreach (string item in rems)
            {
                //MessageBox.Show("Deleting " + item);
                project.ProjectItems.Item(item).Delete();
            }

            // Special handling for VB and C# driver template projects to add the interface implementation to the core driver code
            try
            {
                // Check the name of each item in the project and execute if this is a driver template project (contains Driver.vb or Driver.cs)
                foreach (ProjectItem projectItem in project.ProjectItems)
                {
                    TL.LogMessage("ProjectFinishedGenerating", "Item name: " + projectItem.Name);
                    if ((projectItem.Name.ToUpperInvariant() == "DRIVER.CS") | (projectItem.Name.ToUpperInvariant() == "DRIVER.VB"))
                    {
                        driverTemplate = projectItem; // Save the driver item
                        // This is a driver template
                        // Get the filename and directory of the Driver.xx file
                        string directory = Path.GetDirectoryName(projectItem.FileNames[1].ToString());
                        TL.LogMessage("ProjectFinishedGenerating", "File name: " + projectItem.FileNames[1].ToString() + ", Directory: " + directory);
                        TL.LogMessage("ProjectFinishedGenerating", "Found " + projectItem.Name);

                        projectItem.Open(); // Open the item for editing
                        TL.LogMessage("ProjectFinishedGenerating", "Done Open");

                        Document itemDocument = projectItem.Document; // Get the open file's document object
                        TL.LogMessage("ProjectFinishedGenerating", "Created Document");

                        itemDocument.Activate(); // Make this the current document
                        TL.LogMessage("ProjectFinishedGenerating", "Activated Document");

                        TextSelection documentSelection = (TextSelection)itemDocument.Selection; // Create a document selection
                        TL.LogMessage("ProjectFinishedGenerating", "Created Selection object");

                        const string insertionPoint = "//INTERFACECODEINSERTIONPOINT"; // Find the insertion point in the Driver.xx item
                        documentSelection.FindText(insertionPoint, (int)vsFindOptions.vsFindOptionsMatchWholeWord);
                        TL.LogMessage("ProjectFinishedGenerating", "Done INTERFACECODEINSERTIONPOINT FindText:" + documentSelection.Text);

                        // Create the name of the device interface file to be inserted
                        string insertFile = directory + "\\Device" + this.DeviceClass + Path.GetExtension(projectItem.Name);
                        TL.LogMessage("ProjectFinishedGenerating", "Opening file: " + insertFile);

                        documentSelection.InsertFromFile(insertFile); // Insert the required file at the current selection point
                        TL.LogMessage("ProjectFinishedGenerating", "Done InsertFromFile");

                        // Remove the top lines of the inserted file until we get to #Region
                        // These lines are only there to make the file error free in the template develpment project and are not required here
                        documentSelection.SelectLine(); // Select the current line
                        TL.LogMessage("ProjectFinishedGenerating", "Selected initial line: " + documentSelection.Text);
                        while (!documentSelection.Text.ToUpperInvariant().Contains("#REGION"))
                        {
                            TL.LogMessage("ProjectFinishedGenerating", "Deleting start line: " + documentSelection.Text);
                            documentSelection.Delete();     // Delete the current line
                            documentSelection.SelectLine(); // Select the new current line ready to test on the next loop
                        }

                        // Find the end of file marker that came from the inserted file
                        const string endOfInsertFile = "//ENDOFINSERTEDFILE";
                        documentSelection.FindText(endOfInsertFile, (int)vsFindOptions.vsFindOptionsMatchWholeWord);
                        TL.LogMessage("ProjectFinishedGenerating", "Done ENDOFINSERTEDFILE FindText:" + documentSelection.Text);

                        // Delete the marker line and the last 2 lines from the inserted file
                        documentSelection.SelectLine();
                        TL.LogMessage("ProjectFinishedGenerating", "Found end line: " + documentSelection.Text);
                        while (!documentSelection.Text.ToUpperInvariant().Contains("#REGION"))
                        {
                            TL.LogMessage("ProjectFinishedGenerating", "Deleting end line: " + documentSelection.Text);
                            documentSelection.Delete();     // Delete the current line
                            documentSelection.SelectLine(); // Select the new current line ready to test on the next loop
                            TL.LogMessage("ProjectFinishedGenerating", "Found end line: " + documentSelection.Text);
                        }

                        // Reformat the document to make it look pretty
                        documentSelection.SelectAll();
                        TL.LogMessage("ProjectFinishedGenerating", "Done SelectAll");
                        documentSelection.SmartFormat();
                        TL.LogMessage("ProjectFinishedGenerating", "Done SmartFormat");

                        itemDocument.Save(); // Save the edited file readyfor use!
                        TL.LogMessage("ProjectFinishedGenerating", "Done Save");
                        itemDocument.Close(vsSaveChanges.vsSaveChangesYes);
                        TL.LogMessage("ProjectFinishedGenerating", "Done Close");
                    }
                }

                // Iterate through the project items and remove any files that begin with the word "Device".
                // These are the partial device implementations that are merged in to create a complete device driver template by the code above
                // They are not required in the final project

                // Done this way to avoid removing items from inside a foreach loop
                rems = new List <string>();
                foreach (ProjectItem item in project.ProjectItems)
                {
                    if (item.Name.StartsWith("Device", StringComparison.OrdinalIgnoreCase))
                    {
                        //MessageBox.Show("adding " + item.Name);
                        rems.Add(item.Name);
                    }
                }
                foreach (string item in rems)
                {
                    TL.LogMessage("ProjectFinishedGenerating", "Deleting file: " + item);
                    project.ProjectItems.Item(item).Delete();
                }
            }
            catch (Exception ex)
            {
                TL.LogMessageCrLf("ProjectFinishedGenerating Exception", ex.ToString());                                              // Log any error message
                MessageBox.Show(ex.ToString(), "ProjectFinishedGenerating Wizard Error", MessageBoxButtons.OK, MessageBoxIcon.Error); // Show an error message
            }

            TL.LogMessage("ProjectFinishedGenerating", "End");
            TL.Enabled = false;
        }
Esempio n. 31
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;
                    }
                }
            }
        }