private static string GetContent([NotNull] EnvDTE.TextDocument document) { Contract.Requires(document != null); Contract.Ensures(Contract.Result <string>() != null); return(document.StartPoint.CreateEditPoint().GetText(document.EndPoint)); }
/// <summary> /// This function is the callback used to execute the command when the menu item is clicked. /// See the constructor to see how the menu item is associated with this function using /// OleMenuCommandService service and MenuCommand class. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event args.</param> private void Execute(object sender, EventArgs e) { try { ThreadHelper.ThrowIfNotOnUIThread(); EnvDTE.TextDocument activeTextDocument = (EnvDTE.TextDocument) this.GetDTE().ActiveDocument.Object("TextDocument"); EnvDTE.TextSelection selection = activeTextDocument.Selection; this.SubstituteStringFromSelection_RemoveCheckSteps(activeTextDocument); } catch (InvalidOperationException) { VsShellUtilities.ShowMessageBox(this.package, "The code selection is unbalanced; please try again selecting in the correct lines of code for a complete set of one or more check steps, including balanced parens.", "Error in Text Selection", OLEMSGICON.OLEMSGICON_INFO, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST); } catch (Exception ex) { VsShellUtilities.ShowMessageBox(this.package, string.Format("Exception type='{0}', Message='{1}'", ex.GetType().ToString(), ex.Message), "Exception", OLEMSGICON.OLEMSGICON_INFO, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST); } }
public void OpenScriptInNewWindow(string script) { ServiceCache.ScriptFactory.CreateNewBlankScript(Microsoft.SqlServer.Management.UI.VSIntegration.Editors.ScriptType.Sql); EnvDTE.TextDocument doc = (EnvDTE.TextDocument)ServiceCache.ExtensibilityModel.Application.ActiveDocument.Object(null); doc.EndPoint.CreateEditPoint().Insert(script); }
/// <summary> /// This function is the callback used to execute the command when the menu item is clicked. /// See the constructor to see how the menu item is associated with this function using /// OleMenuCommandService service and MenuCommand class. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event args.</param> private void Execute(object sender, EventArgs e) { ThreadHelper.ThrowIfNotOnUIThread(); EnvDTE.TextDocument activeTextDocument = (EnvDTE.TextDocument) this.GetDTE().ActiveDocument.Object("TextDocument"); EnvDTE.TextSelection selection = activeTextDocument.Selection; this.SubstituteStringFromSelection_AddCheckStep(activeTextDocument); }
public Selection([NotNull] EnvDTE.TextDocument textDocument, [NotNull] string line, [CanBeNull] EnvDTE.FileCodeModel codeModel) { Contract.Requires(textDocument != null); Contract.Requires(line != null); _textDocument = textDocument; _line = line; _codeModel = codeModel; }
/// <summary> /// Marks a region of code for extraction. It pastes the correct comment characters for the /// file type at the top and bottom of the region. If the user has selected to add 'TODO' comments /// and the editor for this file type supports commenting regions, it will also prompt /// the user for a TODO comment and place that comment above the region of code to be /// marked for extraction. /// </summary> public void Exec(EnvDTE.vsCommandExecOption executeOption, ref object varIn, ref object varOut) { try { // First, get ahold of the necessary items to get the data we need CommentPair comments = GetCurrentComments(); if (comments == null) { return; } // Get the document EnvDTE.EditPoint startPoint, endPoint; EnvDTE.TextDocument textDocument = m_applicationObject.ActiveDocument.Object("TextDocument") as EnvDTE.TextDocument; if (textDocument != null) { if (textDocument.Selection.BottomPoint.AtStartOfLine && textDocument.Selection.IsActiveEndGreater) { // People whom select a whole section of text often also get the first // not-character of the next line (because that's how windows mouse-selection // works!). They only want to go around the highlighted section... textDocument.Selection.CharLeft(true, 1); } textDocument.Selection.Insert(comments.BeginComment + "\n", (int)EnvDTE.vsInsertFlags.vsInsertFlagsInsertAtStart); textDocument.Selection.Insert("\n" + comments.EndComment, (int)EnvDTE.vsInsertFlags.vsInsertFlagsInsertAtEnd); // Store away the selection for use after the TODO comment // is added. Create new EditPoint objects here because they // cause the editor to keep track of the markers in the text, even // when the selection changes. startPoint = textDocument.Selection.TopPoint.CreateEditPoint(); endPoint = textDocument.Selection.BottomPoint.CreateEditPoint(); MaybeAddTodoComment(textDocument.Selection); // Restore the selection textDocument.Selection.MoveToPoint(startPoint, false); textDocument.Selection.MoveToPoint(endPoint, true); // Perform the selection hiding (code collapse) only if the editor is not // in auto-select mode and if the user has enabled it in the tools options // page for the academic toolset. This is done last because some language // services move the Top and Bottom points of the Selection around when // performing an outline. if (EditorSupportsHideSelection() && ((bool)((EnvDTE.Properties)m_applicationObject.get_Properties("Assignment Manager", "Code Extractor")).Item("Collapse").Value)) { textDocument.Selection.TopPoint.CreateEditPoint().OutlineSection(textDocument.Selection.BottomPoint); } } } catch (System.Exception /*e*/) { } }
/// <summary> /// // Insert SQL definition to document & optional execute query /// </summary> /// <param name="query">query string</param> /// <param name="execute">optional execute, default is false</param> public static void CreateNewBlankScript(StringBuilder query, bool execute = false) { ServiceCache.ScriptFactory.CreateNewBlankScript(Microsoft.SqlServer.Management.UI.VSIntegration.Editors.ScriptType.Sql); EnvDTE.TextDocument doc = (EnvDTE.TextDocument)ServiceCache.ExtensibilityModel.Application.ActiveDocument.Object(null); doc.EndPoint.CreateEditPoint().Insert(query.ToString()); if (execute) { doc.DTE.ExecuteCommand("Query.Execute"); } }
/// <summary> /// Simple shell function to start off the recursion and handle any exceptions that 'bubble /// up' from recursive calls. /// </summary> private bool ExtractText(EnvDTE.TextDocument textDoc, string begin, string end, EnvDTE.ProjectItems projSourceItems) { try { return(ExtractTextHelper(textDoc.Parent, textDoc.StartPoint.CreateEditPoint(), begin, end, projSourceItems, 0)); } catch (Exception /*e*/) { return(false); } }
private static string GetDocumentText(EnvDTE.Document document) { EnvDTE.TextDocument textDocument = (EnvDTE.TextDocument)document.Object("TextDocument"); EnvDTE.EditPoint editPoint = textDocument.StartPoint.CreateEditPoint(); string context = editPoint.GetText(textDocument.EndPoint); context = context.Replace(System.Environment.NewLine, ""); context = context.Replace("\n", ""); context = System.Text.RegularExpressions.Regex.Replace(context, " {2,}", " "); //REmoves all whitespaces //context = context.Replace("<template>", "").Replace("</template>", ""); return(context.Trim()); }
public static int GetCurrentLine() { EnvDTE.Document activeDoc = Common.Instance.DTE2.ActiveDocument; if (activeDoc != null) { EnvDTE.TextDocument textDoc = (EnvDTE.TextDocument)Common.Instance.DTE2.ActiveDocument.Object("TextDocument"); if (textDoc != null) { return(textDoc.Selection.ActivePoint.Line); } } return(0); }
/// <summary> /// This function is the callback used to execute the command when the menu item is clicked. /// See the constructor to see how the menu item is associated with this function using /// OleMenuCommandService service and MenuCommand class. /// </summary> /// <param name="sender">Event sender.</param> /// <param name="e">Event args.</param> private void MenuItemCallback(object sender, EventArgs e) { var window = package.FindToolWindow(typeof(ViewerWindow), 0, true) as ViewerWindow; var content = window.Content as ViewerWindowControl; EnvDTE.DTE app = (EnvDTE.DTE) this.ServiceProvider.GetService(typeof(SDTE)); if (app.ActiveDocument != null && app.ActiveDocument.Type == "Text") { EnvDTE.TextDocument text = (EnvDTE.TextDocument)app.ActiveDocument.Object(String.Empty); if (!text.Selection.IsEmpty) { content.FindAndSelectNodesByLocation(text.Parent.FullName, text.Selection.TopPoint.Line, text.Selection.BottomPoint.Line); } } }
/// <summary> /// Put the selected lines of code inside a check step. /// This method does all modification of the text in the editor, with one string substitution /// </summary> /// <param name="document"></param> /// <param name="selection"></param> private void SubstituteStringFromSelection_RemoveCheckSteps(EnvDTE.TextDocument document) { EnvDTE.EditPoint earlierPoint = null, laterPoint = null; EditingTools.Instance.GetEditPointsForLinesToCheck(document, out earlierPoint, out laterPoint); string indentSpaces = EditingTools.Instance.GetIndentSpaces(document); string linesNoTabs = earlierPoint.GetText(laterPoint).Replace("\t", indentSpaces); linesNoTabs = linesNoTabs.TrimEnd(new char[] { '\r', '\n' }); string[] lines = linesNoTabs.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); Stack <int[]> checkStepOpenings = new Stack <int[]>(); // use for loop instead of foreach because we might have to look with multiple lines for (int lineIndex = 0; lineIndex < lines.Length; lineIndex++) { // Iterate through lines, pushing opening line(s) for Check.Step on stack in string[] if (LinesMatchCheckStepOpening(new string[] { lines[lineIndex] })) { checkStepOpenings.Push(new int[] { lineIndex }); } else if ((lineIndex + 1 < lines.Length) && LinesMatchCheckStepOpening(new string[] { lines[lineIndex], lines[lineIndex + 1] })) { checkStepOpenings.Push(new int[] { lineIndex, lineIndex + 1 }); lineIndex++; } else if (this.LineMatchesCheckStepClosing(lines[lineIndex])) { // Remove check step int[] openingLines = checkStepOpenings.Pop(); lines = RemoveCheckStepDefinition(openingLines, lineIndex, lines, indentSpaces); } } StringBuilder resultingText = new StringBuilder(); foreach (string line in lines) { if (line != null) { resultingText.Append(line); resultingText.Append(Environment.NewLine); } } earlierPoint.ReplaceText(laterPoint, resultingText.ToString(), (int)EnvDTE.vsEPReplaceTextOptions.vsEPReplaceTextAutoformat); }
/// <summary> /// The current comments are retrieved by obtaining the Properites object from the /// Tools Options window associated with the Academic toolset and walking down the /// set of registered file extensions looking for the one corresponding to /// the file type currently opened. /// </summary> private CommentPair GetCurrentComments() { EnvDTE.Document document = null; EnvDTE.TextDocument textDocument = null; EnvDTE.Properties extractorProperties = null; Extensions extensions = null; string extension; int lastIndex; try { // While we don't *do* anything with the document object, we check for its presence because // we only know how to do insertions on the TextDocument class of object. document = m_applicationObject.ActiveDocument; if ((document == null) || ((textDocument = document.Object("TextDocument") as EnvDTE.TextDocument) == null)) { return(null); } extension = m_applicationObject.ActiveDocument.Name; lastIndex = extension.LastIndexOf('.'); if (lastIndex == -1) { return(null); } extension = extension.Remove(0, lastIndex + 1); // Trim off the 'name.' part of 'name.ext' extractorProperties = m_applicationObject.get_Properties("Assignment Manager", "Code Extractor"); if (extractorProperties == null) { throw new Exception(AMResources.GetLocalizedString("CollapseMarkedInvalidInstallation")); } extensions = extractorProperties.Item("Extensions").Object as Extensions; if (extensions == null) { throw new Exception(AMResources.GetLocalizedString("CollapseMarkedInvalidInstallation")); } return(extensions[extension]); } catch (Exception) { return(null); } }
public static string GetCurrentWord() { EnvDTE.Document activeDoc = Common.Instance.DTE2.ActiveDocument; if (activeDoc != null) { EnvDTE.TextDocument textDoc = (EnvDTE.TextDocument)Common.Instance.DTE2.ActiveDocument.Object("TextDocument"); if (textDoc != null) { if (textDoc.Selection.ActivePoint.Line > 0) { string sLine = textDoc.StartPoint.CreateEditPoint().GetLines(textDoc.Selection.ActivePoint.Line, textDoc.Selection.ActivePoint.Line + 1); return(GetWord(sLine, textDoc.Selection.ActivePoint.LineCharOffset - 1)); } } } return(null); }
private void ReplaceSelectedText(String newText) { EnvDTE.DTE app = this.DTEService; if (app.ActiveDocument != null && app.ActiveDocument.Type == "Text") { Object objTtext = app.ActiveDocument.Object(String.Empty); if (objTtext != null && objTtext is EnvDTE.TextDocument) { EnvDTE.TextDocument text = (EnvDTE.TextDocument)objTtext; if (!text.Selection.IsEmpty) { text.Selection.Text = newText; } } } }
/// <summary> /// This method will be invoked when the user double-clicks on the item in /// the task list associated this instance of the object. /// </summary> public void TaskNavigated(EnvDTE.TaskItem taskItem, ref bool Navigated) { EnvDTE.Window w = null; EnvDTE.TextDocument textDoc = null; Navigated = false; try { w = dte.OpenFile(EnvDTE.Constants.vsViewKindTextView, taskItem.FileName); w.Activate(); textDoc = dte.ActiveDocument.Object("TextDocument") as EnvDTE.TextDocument; textDoc.Selection.GotoLine(taskItem.Line, false); Navigated = true; } catch (Exception /*e*/) { Navigated = false; } }
static private void CreateSQLDocument(String sqlText, SqlConnectionInfo connInfo) { if (!_uiConn.ContainsKey(connInfo.ServerName)) { var aci = ServiceCache.ScriptFactory.CurrentlyActiveWndConnectionInfo; _uiConn[connInfo.ServerName] = CreateFrom(connInfo); } var uiConn = _uiConn[connInfo.ServerName]; ServiceCache.ScriptFactory.CreateNewBlankScript(Microsoft.SqlServer.Management.UI.VSIntegration.Editors.ScriptType.Sql, uiConn, null); // create new document EnvDTE.TextDocument doc = (EnvDTE.TextDocument)ServiceCache.ExtensibilityModel.Application.ActiveDocument.Object(null); // insert SQL definition to document doc.EndPoint.CreateEditPoint().Insert(sqlText); }
private String GetSelectedText() { String result = String.Empty; EnvDTE.DTE app = this.DTEService; if (app.ActiveDocument != null && app.ActiveDocument.Type == "Text") { Object objTtext = app.ActiveDocument.Object(String.Empty); if (objTtext != null && objTtext is EnvDTE.TextDocument) { EnvDTE.TextDocument text = (EnvDTE.TextDocument)objTtext; if (!text.Selection.IsEmpty) { result = text.Selection.Text; } } } return(result); }
/// <devdoc> /// Service provider implementation. We pass this to a QI on the native text buffer. /// </devdoc> object IServiceProvider.GetService(Type serviceType) { if (textStream != null) { if (serviceType == typeof(IVsCompoundAction)) { return(textStream as IVsCompoundAction); } if (serviceType.IsInstanceOfType(textStream)) { return(textStream); } if (serviceType == typeof(EnvDTE.TextDocument)) { if (textDocument == null) { IVsExtensibleObject vsExtObj = textStream as IVsExtensibleObject; if (vsExtObj != null) { textDocument = (EnvDTE.TextDocument)vsExtObj.GetAutomationObject("TextDocument"); } else { EnvDTE.IExtensibleObject extObj = textStream as EnvDTE.IExtensibleObject; if (extObj != null) { object doc; extObj.GetAutomationObject("TextDocument", null, out doc); textDocument = doc as EnvDTE.TextDocument; } } } return(textDocument); } } return(null); }
static public IEnumerable <SymbolData> GeneratorFromDocument(EnvDTE.Document document) { if (null != document) { if (document.Saved) { return(GeneratorFromFile(document.FullName)); } else { EnvDTE.TextDocument doc = (EnvDTE.TextDocument)Common.Instance.DTE2.ActiveDocument.Object("TextDocument"); if (doc != null) { string fileContent = doc.StartPoint.CreateEditPoint().GetText(doc.EndPoint); return(GeneratorFromString(fileContent, Path.GetExtension(document.FullName))); } } } return(null); }
/* * schema:- * while condition - 0 * invariant - 1 * precondition - 2 * postcondition - 3 * body - 4+ */ private void addWhileStatement(EnvDTE.TextDocument text) { string content = text.Selection.Text; string[] del = { "==", "<", ">", "!=", ">=", "<=" }; string[] arr = content.Trim().Split('\n'); string[] s = arr[0].Split(del, StringSplitOptions.RemoveEmptyEntries); string inv = "invariant " + arr[1].Trim() + "\n"; string dec = "decreases " + s[1].Trim() + " - " + s[0].Trim(); string pre = "\nassert " + arr[2].Trim('\n', '\r', ' ') + ";\n"; string cond = "while (" + arr[0].Trim() + ")\n" + inv + dec + "\n{\n"; string body = ""; for (int i = 4; i < arr.Length; i++) { body += arr[i]; } string post = "\n}\nassert " + arr[3].Trim('\r', '\n', ' ') + ";\n"; // text.CreateEditPoint(text.EndPoint).Insert(content); text.Selection.Text = pre + cond + body + post; }
/// <summary> /// This command is available if both the file type is valid and if the document /// contains a selection of non-zero size. /// </summary> public void QueryStatus(ref EnvDTE.vsCommandStatus status) { // If there is no supported extension, remove it. If it's supported, but there's no // document selection currently, then disable it (gray-out). CommentPair comments = GetCurrentComments(); if (comments == null) { status = EnvDTE.vsCommandStatus.vsCommandStatusInvisible | EnvDTE.vsCommandStatus.vsCommandStatusUnsupported; } else { EnvDTE.TextDocument textDocument = m_applicationObject.ActiveDocument.Object("TextDocument") as EnvDTE.TextDocument; if (m_applicationObject.ActiveWindow.Document == m_applicationObject.ActiveDocument) { if (textDocument == null) { // Never can happen because of GetCurrentComments' implementation throw new Exception(); } if (textDocument.Selection.TopPoint.AbsoluteCharOffset == textDocument.Selection.BottomPoint.AbsoluteCharOffset) { status = EnvDTE.vsCommandStatus.vsCommandStatusUnsupported; } else { status = EnvDTE.vsCommandStatus.vsCommandStatusEnabled | EnvDTE.vsCommandStatus.vsCommandStatusSupported; } } else { status = EnvDTE.vsCommandStatus.vsCommandStatusUnsupported; } } }
/// <summary> /// Return a sorted array of loaded extensions /// </summary> public string[] GetLoadedExtensions(IServiceProvider serviceProvider) { string[] retVal = myLoadedExtensions; if (retVal == null) { if (myDocument == null && myProjectItem != null) { myDocument = myProjectItem.Document; } object documentExtensionManager; MethodInfo methodInfo; string itemPath = null; if (null != myDocument && null != (documentExtensionManager = ORMCustomToolUtility.GetDocumentExtension <object>(myDocument, "ORMExtensionManager", itemPath = myProjectItem.get_FileNames(0), serviceProvider)) && null != (methodInfo = documentExtensionManager.GetType().GetMethod("GetLoadedExtensions", Type.EmptyTypes))) { retVal = methodInfo.Invoke(documentExtensionManager, null) as string[]; myDocument = null; // No longer needed } Stream stream = null; if (null == retVal) { // First used the passed in stream stream = myStream; // Next use an open text document. Note that this will already have provided // an extension manager if this is an open ORM designer if (stream == null && myDocument != null) { EnvDTE.TextDocument textDoc = ORMCustomToolUtility.GetDocumentExtension <EnvDTE.TextDocument>(myDocument, "TextDocument", itemPath ?? (itemPath = myProjectItem.get_FileNames(0)), serviceProvider); if (textDoc != null) { // Note that the stream will be closed with the default reader settings of the XmlReader below stream = new MemoryStream(Encoding.UTF8.GetBytes(textDoc.StartPoint.CreateEditPoint().GetText(textDoc.EndPoint)), false); } } // Try the file directly from the project item if (stream == null && myProjectItem != null) { // Note that the stream will be closed with the default reader settings of the XmlReader below stream = new FileStream(myProjectItem.get_FileNames(0), FileMode.Open); } } if (stream != null) { // Attempt to open the stream as an Xml file to // get the required extensions from the Xml string[] namespaces = null; int namespaceCount = 0; try { XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.CloseInput = true; using (XmlReader reader = XmlReader.Create(stream, readerSettings)) { reader.MoveToContent(); if (reader.NodeType == XmlNodeType.Element) { int attributeCount = reader.AttributeCount; if (attributeCount != 0) { namespaces = new string[attributeCount]; if (reader.MoveToFirstAttribute()) { do { if (reader.Prefix == "xmlns" || reader.Name == "xmlns") { // Note that some of these are standard, not extensions, but it // isn't worth the trouble to add extra ORM knowledge here to figure it out string value = reader.Value; if (!string.IsNullOrEmpty(value)) { namespaces[namespaceCount] = reader.Value; ++namespaceCount; } } } while (reader.MoveToNextAttribute()); } } } } } catch (XmlException) { // Nothing to do } finally { if (myStream != null) { myStream.Seek(0, SeekOrigin.Begin); myStream = null; } } if (namespaceCount != 0) { if (namespaceCount != namespaces.Length) { Array.Resize(ref namespaces, namespaceCount); } retVal = namespaces; } } if (retVal == null) { retVal = new string[0]; } else { Array.Sort <string>(retVal); } myLoadedExtensions = retVal; } return(retVal); }
void item_Click(object sender, EventArgs e) { ToolStripMenuItem item = (ToolStripMenuItem)sender; string fileName = string.Empty; Action action = (Action)item.OwnerItem.Tag; Output output = (Output)item.Tag; try { string connectionString = Helper.FixConnectionString(this.Parent.Connection.ConnectionString, this.Parent.Connection.ConnectionTimeout); using (IRepository repository = new DBRepository(connectionString)) { var generator = new Generator(repository); switch (output) { case Output.Editor: // create new document ServiceCache.ScriptFactory.CreateNewBlankScript(Microsoft.SqlServer.Management.UI.VSIntegration.Editors.ScriptType.SqlCe); break; case Output.File: SaveFileDialog fd = new SaveFileDialog(); fd.AutoUpgradeEnabled = true; fd.Title = "Save generated script as"; fd.Filter = "SQL Server Compact Script (*.sqlce)|*.sqlce|SQL Server Script (*.sql)|*.sql|All Files(*.*)|"; fd.OverwritePrompt = true; fd.ValidateNames = true; if (fd.ShowDialog() == DialogResult.OK) { fileName = fd.FileName; } break; default: break; } switch (action) { case Action.Create: generator.GenerateIndexScript(this.Parent.Parent.Name, this.Parent.Name); break; case Action.Drop: generator.GenerateIndexDrop(this.Parent.Parent.Name, this.Parent.Name); break; case Action.DropAndCreate: generator.GenerateIndexDrop(this.Parent.Parent.Name, this.Parent.Name); generator.GenerateIndexScript(this.Parent.Parent.Name, this.Parent.Name); break; case Action.Statistics: generator.GenerateIndexStatistics(this.Parent.Parent.Name, this.Parent.Name); break; default: break; } switch (output) { case Output.Editor: // insert SQL script to document EnvDTE.TextDocument doc = (EnvDTE.TextDocument)ServiceCache.ExtensibilityModel.Application.ActiveDocument.Object(null); doc.EndPoint.CreateEditPoint().Insert(generator.GeneratedScript); doc.DTE.ActiveDocument.Saved = true; break; case Output.File: if (!string.IsNullOrEmpty(fileName)) { System.IO.File.WriteAllText(fileName, generator.GeneratedScript); } break; case Output.Clipboard: Clipboard.Clear(); Clipboard.SetText(generator.GeneratedScript, TextDataFormat.UnicodeText); break; default: break; } } } catch (System.Data.SqlServerCe.SqlCeException sqlCe) { Connect.ShowErrors(sqlCe); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
public EnvDTE.TextEditorEvents get_TextEditorEvents(EnvDTE.TextDocument TextDocumentFilter) { throw new Exception("The method or operation is not implemented."); }
private static string GetContent(EnvDTE.TextDocument document) { return(document.StartPoint.CreateEditPoint().GetText(document.EndPoint)); }
void item_Click(object sender, EventArgs e) { ToolStripMenuItem item = (ToolStripMenuItem)sender; string fileName = string.Empty; Action action = (Action)item.OwnerItem.Tag; Output output = (Output)item.Tag; try { string connectionString = Helper.FixConnectionString(this.Parent.Connection.ConnectionString, this.Parent.Connection.ConnectionTimeout); using (IRepository repository = new DBRepository(connectionString)) { var generator = new Generator(repository); using (ImportOptions imo = new ImportOptions(this.Parent.Name)) { imo.SampleHeader = generator.GenerateTableColumns(this.Parent.Name); imo.Separator = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ListSeparator.ToCharArray()[0]; if (imo.ShowDialog() == DialogResult.OK) { switch (output) { case Output.Editor: // create new document ServiceCache.ScriptFactory.CreateNewBlankScript(Microsoft.SqlServer.Management.UI.VSIntegration.Editors.ScriptType.SqlCe); break; case Output.File: SaveFileDialog fd = new SaveFileDialog(); fd.AutoUpgradeEnabled = true; fd.Title = "Save generated database script as"; fd.Filter = "SQL Server Compact Script (*.sqlce)|*.sqlce|SQL Server Script (*.sql)|*.sql|All Files(*.*)|"; fd.OverwritePrompt = true; fd.ValidateNames = true; if (fd.ShowDialog() == DialogResult.OK) { fileName = fd.FileName; } break; default: break; } switch (action) { case Action.Csv: using (var reader = new CsvReader(imo.FileName)) { reader.ValueSeparator = imo.Separator; HeaderRecord hr = reader.ReadHeaderRecord(); if (generator.ValidColumns(this.Parent.Name, hr.Values)) { foreach (DataRecord record in reader.DataRecords) { generator.GenerateTableInsert(this.Parent.Name, hr.Values, record.Values); } } } break; default: break; } switch (output) { case Output.Editor: // insert SQL script to document EnvDTE.TextDocument doc = (EnvDTE.TextDocument)ServiceCache.ExtensibilityModel.Application.ActiveDocument.Object(null); doc.EndPoint.CreateEditPoint().Insert(generator.GeneratedScript); doc.DTE.ActiveDocument.Saved = true; break; case Output.File: if (!string.IsNullOrEmpty(fileName)) { System.IO.File.WriteAllText(fileName, generator.GeneratedScript); } break; case Output.Clipboard: Clipboard.Clear(); Clipboard.SetText(generator.GeneratedScript, TextDataFormat.UnicodeText); break; default: break; } } } } } catch (System.Data.SqlServerCe.SqlCeException sqlCe) { Connect.ShowErrors(sqlCe); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
/// <summary> /// Put the selected lines of code inside a check step. /// This method does all modification of the text in the editor, with one string substitution /// </summary> /// <param name="document"></param> /// <param name="selection"></param> private void SubstituteStringFromSelection_AddCheckStep(EnvDTE.TextDocument document) { EnvDTE.EditPoint earlierPoint = null, laterPoint = null; EditingTools.Instance.GetEditPointsForLinesToCheck(document, out earlierPoint, out laterPoint); string indentSpaces = EditingTools.Instance.GetIndentSpaces(document); string linesNoTabs = earlierPoint.GetText(laterPoint).Replace("\t", indentSpaces); string[] lines = linesNoTabs.Split(new string[] { Environment.NewLine }, StringSplitOptions.None); StringBuilder resultingText = new StringBuilder(); bool firstLine = true; string originalIndent = string.Empty; foreach (string line in lines) { if (!firstLine) { resultingText.Append(Environment.NewLine); } firstLine = false; if (!String.IsNullOrWhiteSpace(line)) { string totalIndentSpaces = ""; int tabbedSpacesCounter = 0; // Found how many tabbed spaces precede the line text while ((line.Length >= ((tabbedSpacesCounter + 1) * document.TabSize)) && (line.Substring(tabbedSpacesCounter * document.TabSize, document.TabSize) == indentSpaces)) { totalIndentSpaces += indentSpaces; tabbedSpacesCounter++; } // find the minimum tab count, but skipping any zero-tab line if (originalIndent.Length == 0) { originalIndent = totalIndentSpaces; } else { if (totalIndentSpaces.Length < originalIndent.Length) { originalIndent = totalIndentSpaces; } } // Start the resulting line with a tab resultingText.Append(indentSpaces); } // Add the rest of the text resultingText.Append(line); } StringBuilder stringToInsert = new StringBuilder(); // strings that come before user-selected lines foreach (string beforeSelectedCode in StringResources.Instance.StringsBeforeSelectedCode) { stringToInsert.Append(originalIndent); stringToInsert.Append(beforeSelectedCode); stringToInsert.Append(Environment.NewLine); } stringToInsert.Append(resultingText); // strings that come after user-selected lines foreach (string afterSelectedCode in StringResources.Instance.StringsAfterSelectedCode) { stringToInsert.Append(originalIndent); stringToInsert.Append(afterSelectedCode); stringToInsert.Append(Environment.NewLine); } // Do replacement in Visual Studio text buffer earlierPoint.ReplaceText(laterPoint, stringToInsert.ToString(), (int)EnvDTE.vsEPReplaceTextOptions.vsEPReplaceTextAutoformat); }
public Selection([NotNull] EnvDTE.TextDocument textDocument, [NotNull] string line, [CanBeNull] EnvDTE.FileCodeModel codeModel) { _textDocument = textDocument; Line = line; _codeModel = codeModel; }
/// <summary> /// Loops through each of the items in the project, attempting to extract any sections of code /// marked. /// </summary> /// <param name="dte"> Pointer to Object Model in which all actions should be performed </param> private bool ExtractItems(EnvDTE.ProjectItems projSourceItems, EnvDTE._DTE dte, EnvDTE.ProjectItems projDestItems) { EnvDTE.ProjectItem projItem = null; EnvDTE.TextDocument textDoc = null; EnvDTE.Properties extractorProperties = null; Extensions extensions = null; CommentPair comments = null; EnvDTE.Window w = null; bool fSuccess = true; int i, nItems, nLastIndex; string strExtension; extractorProperties = m_application.get_Properties("Assignment Manager", "Code Extractor"); if (extractorProperties == null) { throw new Exception("The Academic Code Extractor is not properly installed and configured."); } extensions = extractorProperties.Item("Extensions").Object as Extensions; if (extensions == null) { throw new Exception("The Academic Code Extractor is not properly installed and configured."); } nItems = projDestItems.Count; for (i = 1; i <= nItems; i++) { projItem = projDestItems.Item(i); try { if (projItem.ProjectItems.Count > 0) { ExtractItems(projSourceItems.Item(i).ProjectItems, dte, projItem.ProjectItems); } // Note that this will *actually* be happening in an invisible // out-of-process instance of VS, so the user will not be // subjected to appearing / disappearing windows. w = projItem.Open(EnvDTE.Constants.vsViewKindTextView); textDoc = w.Document.Object("TextDocument") as EnvDTE.TextDocument; strExtension = projItem.get_FileNames(1); nLastIndex = strExtension.LastIndexOf('.'); if (nLastIndex == -1) { w.Close(EnvDTE.vsSaveChanges.vsSaveChangesNo); continue; // We have no capacity for files with no extension. } strExtension = strExtension.Remove(0, nLastIndex + 1); // Trim off the 'name.' part of 'name.ext' comments = extensions[strExtension]; if (comments == null) { w.Close(EnvDTE.vsSaveChanges.vsSaveChangesNo); continue; // This file has no associated extension type. Ignore it. } fSuccess &= ExtractText(textDoc, comments.BeginComment, comments.EndComment, projSourceItems); w.Close(EnvDTE.vsSaveChanges.vsSaveChangesYes); } catch (Exception /*e*/) { // If we end up here, that simply means that the file // has no text. Since we obviously don't want to remove the // textual tags from a file with no comments... if (w != null) { w.Close(EnvDTE.vsSaveChanges.vsSaveChangesNo); } } } return(fSuccess); }