コード例 #1
1
        void InstallControl()
        {
            // Create an instance of the VS IDE,
            Type type = System.Type.GetTypeFromProgID("VisualStudio.DTE.10.0");
            DTE  dte  = (DTE)System.Activator.CreateInstance(type, true);
            // create a temporary winform project;
            string    tmpFile      = Path.GetFileNameWithoutExtension(Path.GetTempFileName());
            string    tmpDir       = string.Format("{0}{1}", Path.GetTempPath(), tmpFile);
            Solution2 solution     = dte.Solution as Solution2;
            string    templatePath = solution.GetProjectTemplate("WindowsApplication.zip", "CSharp");
            Project   proj         = solution.AddFromTemplate(templatePath, tmpDir, "dummyproj", false);

            // add the control to the toolbox.
            EnvDTE.Window     window  = dte.Windows.Item(EnvDTE.Constants.vsWindowKindToolbox);
            EnvDTE.ToolBox    toolbox = (EnvDTE.ToolBox)window.Object;
            EnvDTE.ToolBoxTab myTab   = toolbox.ToolBoxTabs.Add("Saino");
            myTab.Activate();
            myTab.ToolBoxItems.Add("MyUserControl", ctrlPath, vsToolBoxItemFormat.vsToolBoxItemFormatDotNETComponent);
            dte.Solution.Close(false);
            Marshal.ReleaseComObject(dte);
            //Console.WriteLine("Control Installed!!!");
        }
コード例 #2
0
 public static void Initialize(Window parentWindow, DTE applicationObject)
 {
     // Whole mehod is ugly as hell, and should not exist. This exists only because
     // VS integration is being a little bitch to me, and I'm retarded enough to
     // not figure out how it works.
     instance.InitializeInstance(parentWindow, applicationObject);
 }
コード例 #3
0
 public void InitializeInstance(Window parentWindow, DTE applicationObject)
 {
     this.applicationObject = applicationObject;
     this.parentWindow = parentWindow;
     timer = new DispatcherTimer();
     timer.Tick += OnTimer;
     timer.Interval = new TimeSpan(0, 0, 0, 1);
     timer.Start();
 }
        private void ActivateWindow(Window window)
        {
            activationTimer.Stop();
            activationTimer = null;

            try
            {
                window.Activate();
            }
            catch (Exception)
            {
                // bad luck...
            }
        }
        internal async Task CreateUnitTestAsync(IList <ProjectItemSummary> selectedFiles, bool addToProject = true)
        {
            var createdTestPaths = new List <string>();

            foreach (ProjectItemSummary selectedFile in selectedFiles)
            {
                string generatedTestPath = await this.TestGenerationService.GenerateUnitTestFileAsync(
                    selectedFile,
                    this.SelectedProject.Project,
                    this.SelectedTestFramework,
                    this.SelectedMockFramework);

                createdTestPaths.Add(generatedTestPath);
            }

            if (addToProject)
            {
                bool focusSet = false;
                foreach (string createdTestPath in createdTestPaths)
                {
                    // Add the file to project
                    ProjectItem testItem = this.SelectedProject.Project.ProjectItems.AddFromFile(createdTestPath);

                    Window testWindow = testItem.Open(EnvDTE.Constants.vsViewKindCode);
                    testItem.ExpandView();
                    testWindow.Visible = true;

                    if (!focusSet)
                    {
                        testWindow.SetFocus();
                        focusSet = true;
                    }
                }

                this.Settings.SaveSelectedTestProject(this.dte.Solution.FileName, this.SelectedProject.Project.FileName);
            }

            this.View?.Close();
        }
コード例 #6
0
        public CodeViewUserControl(Window window, ColumnDefinition column = null,
                                   IWpfTextView textView           = null, IOutliningManagerService outliningManagerService = null,
                                   VisualStudioWorkspace workspace = null, CodeNavMargin margin = null, DTE dte = null)
        {
            InitializeComponent();

            // Setup viewmodel as datacontext
            CodeDocumentViewModel = new CodeDocumentViewModel();
            DataContext           = CodeDocumentViewModel;

            _window  = window;
            _column  = column;
            TextView = textView;
            OutliningManagerService = outliningManagerService;
            _workspace = workspace;
            _margin    = margin;
            Dte        = dte;

            LogHelper.Dte = dte;

            VSColorTheme.ThemeChanged += VSColorTheme_ThemeChanged;
        }
コード例 #7
0
        public void WindowActivated([CanBeNull] EnvDTE.Window gotFocus, [CanBeNull] EnvDTE.Window lostFocus)
        {
            string got;
            string lost;

            try
            {
                got  = gotFocus != null ? gotFocus.ObjectKind : string.Empty;
                lost = lostFocus != null ? lostFocus.ObjectKind : string.Empty;
            }
            catch
            {
                return;
            }

            if (got == lost)
            {
                return;
            }

            if (got == @"{CBDA4D53-D53A-4AD6-8069-2A680BC178B2}")
            {
                ActiveContext.Focused = Focused.ContentTree;
            }
            else if (got == @"{C918DE4A-FB6C-4BE2-8C84-C67278ACBBF8}")
            {
                ActiveContext.Focused = Focused.ContentEditor;

                // TODO: set content editor
            }
            else if (lost == @"{CBDA4D53-D53A-4AD6-8069-2A680BC178B2}")
            {
                ActiveContext.Focused = Focused.None;
            }
            else if (lost == @"{C918DE4A-FB6C-4BE2-8C84-C67278ACBBF8}")
            {
                ActiveContext.Focused = Focused.None;
            }
        }
コード例 #8
0
ファイル: AddCopyright.cs プロジェクト: mcaden/Sweeper
        /// <summary>
        /// Performs the style task.
        /// </summary>
        /// <param name="projectItem">The project Item</param>
        /// <param name="ideWindow">The IDE window.</param>
        protected override void DoWork(ProjectItem projectItem, EnvDTE.Window ideWindow)
        {
            if (projectItem.Name.EndsWith(".cs"))
            {
                try
                {
                    TextDocument projectItemDoc = (TextDocument)ideWindow.Document.Object("TextDocument");
                    EditPoint    startPoint     = projectItemDoc.StartPoint.CreateEditPoint();
                    EditPoint    blockPoint     = startPoint.CreateEditPoint();
                    TextRanges   trs            = null;
                    bool         found          = blockPoint.FindPattern("<copyright", (int)vsFindOptions.vsFindOptionsMatchCase, ref blockPoint, ref trs);
                    if (!found || blockPoint.Line > 2)
                    {
                        Debug.WriteLine("Finding assembly info...");
                        ProjectItem  assemblyInfo = projectItem.DTE.Solution.FindProjectItem("AssemblyInfo.cs");
                        TextDocument objTextDoc   = (TextDocument)ideWindow.Document.Object("TextDocument");

                        assemblyInfo.Open(EnvDTE.Constants.vsViewKindTextView).Activate();
                        TextDocument assemblyDoc = (TextDocument)assemblyInfo.DTE.ActiveWindow.Document.Object("TextDocument");

                        string company   = RetrieveAssemblyInfoValue(assemblyDoc, "AssemblyCompany");
                        string copyright = RetrieveAssemblyInfoValue(assemblyDoc, "AssemblyCopyright");
                        string fileName  = projectItem.Name;

                        Debug.WriteLine("Adding Copyright to file: " + projectItem.Name);
                        AddCopyrightToFile(projectItemDoc, fileName, company, copyright);
                    }
                    else
                    {
                        Debug.WriteLine("Copyright detected, skipping copyright header.");
                    }
                }
                catch (Exception exc)
                {
                    Debug.WriteLine(exc.ToString());
                    Debug.WriteLine("Format failed, skipping");
                }
            }
        }
コード例 #9
0
ファイル: RemoveAndSortUsings.cs プロジェクト: mcaden/Sweeper
        /// <summary>
        /// Performs the style task.
        /// </summary>
        /// <param name="projectItem">The project Item</param>
        /// <param name="ideWindow">The IDE window.</param>
        protected override void DoWork(ProjectItem projectItem, EnvDTE.Window ideWindow)
        {
            if (projectItem.Name.EndsWith(".cs") && !IsTemporarilyDisabled)
            {
                try
                {
                    if (errorDetectionFunction != null)
                    {
                        if (errorDetectionFunction())
                        {
                            IsTemporarilyDisabled = true;
                            return;
                        }
                    }

                    Debug.WriteLine("Removing and Sorting Usings on: " + projectItem.Name);

                    Stopwatch macroWatch = new Stopwatch();
                    macroWatch.Start();

                    ideWindow.SetFocus();
                    ideWindow.DTE.ExecuteCommand("Edit.RemoveAndSort", string.Empty);

                    macroWatch.Stop();
                    if (macroWatch.ElapsedMilliseconds > 1000)
                    {
                        if (System.Windows.Forms.MessageBox.Show("Remove and Sort usings seems to be having difficulties, do you want to skip it this iteration?", "Parole", System.Windows.Forms.MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
                        {
                            IsTemporarilyDisabled = true;
                        }
                    }
                }
                catch (Exception exc)
                {
                    Debug.WriteLine(exc.ToString());
                    Debug.WriteLine("Format failed, skipping");
                }
            }
        }
コード例 #10
0
        private void WindowEventsOnWindowActivated(EnvDTE.Window gotFocus, EnvDTE.Window lostFocus)
        {
            //No solution loaded
            if (_solution.Count == 0)
            {
                ResetForm();
                return;
            }

            //WindowEventsOnWindowActivated in this project can be called when activating another window
            //so we don't want to contine further unless our window is active
            if (!HostWindow.IsCrmDevExWindow(gotFocus))
            {
                return;
            }

            if (ConnPane.CrmService != null && ConnPane.CrmService.IsReady)
            {
                SetWindowCaption(gotFocus.Caption);
                SetButtonState(true);
                LoadData();
            }
        }
コード例 #11
0
        internal static bool FindWindow(Project project, string filePath, out EnvDTE.Window window)
        {
            window = null;
            var windows = project.DTE.Windows;

            foreach (var w in windows)
            {
                if (w is EnvDTE.Window wnd)
                {
                    var projectItem = wnd.ProjectItem;
                    if ((projectItem != null) && (projectItem.FileCount != 0) /* && window.Type == vsWindowType.vsWindowTypeDocument */)
                    {
                        var fileName = projectItem.FileNames[1]; // 1-based array
                        if (fileName == filePath)
                        {
                            window = wnd;
                            return(true);
                        }
                    }
                }
            }
            return(false);
        }
コード例 #12
0
        internal TextDocument GetTextDocumentFromWindow(Window window)
        {
            TextDocument codeDoc = null;

            if (Dte != null)
            {
                Document doc = null;
                try
                {
                    doc = window.Document;
                }
                catch (ArgumentException)
                {
                    return(null); //error occured return null
                }

                if (doc != null)
                {
                    codeDoc = doc.Object(String.Empty) as TextDocument;
                }
            }
            return(codeDoc);
        }
コード例 #13
0
ファイル: UIPDebugHelper.cs プロジェクト: FSharpCSharp/UIPAB
 private static void openFile(string strFilename, int lineno)
 {
     EnvDTE.DTE dte = null;
     // try to connect to visual studio instance
     try
     {
         dte = (DTE)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE");
     }
     catch (System.Runtime.InteropServices.COMException)
     {
         return;
     }
     if (dte != null)
     {
         EnvDTE.Window w = dte.ItemOperations.OpenFile(strFilename, Constants.vsViewKindCode);
         w.Activate();
         EnvDTE.TextDocument td = (EnvDTE.TextDocument)dte.ActiveDocument.Object("TextDocument");
         td.Selection.MoveTo(lineno, 1, false);
         td.Selection.EndOfLine(false);
         td.Selection.SelectLine();
         dte.Debugger.Stop(false);
     }
 }
コード例 #14
0
ファイル: CodeNavMargin.cs プロジェクト: zhihuiweilai/CodeNav
        public CodeNavMargin(IWpfTextViewHost textViewHost, DTE dte, IOutliningManagerService outliningManagerService,
                             VisualStudioWorkspace workspace, MarginSideEnum side)
        {
            // Wire up references for the event handlers in RegisterEvents
            _dte      = dte;
            _textView = textViewHost.TextView;
            _window   = GetWindow(textViewHost, dte);
            _outliningManagerService = outliningManagerService;
            _outliningManager        = OutliningHelper.GetOutliningManager(outliningManagerService, _textView);
            _workspace = workspace;
            MarginSide = side;

            // If we can not find the window we belong to we can not do anything
            if (_window == null)
            {
                return;
            }

            // Add the view/content to the margin area
            if (side == MarginSideEnum.Top)
            {
                _codeNavGrid = CreateGridTop(textViewHost);
            }
            else
            {
                _codeNavGrid   = CreateGrid(textViewHost);
                _codeNavColumn = _codeNavGrid.ColumnDefinitions[Settings.Default.MarginSide == MarginSideEnum.Left ? 0 : 2];
            }

            Children.Add(_codeNavGrid);

            System.Windows.Threading.Dispatcher.CurrentDispatcher.VerifyAccess();

            RegisterEvents();

            UpdateSettings();
        }
コード例 #15
0
        public CodeNavMargin(IWpfTextViewHost textViewHost, DTE dte, IOutliningManager outliningManager, VisualStudioWorkspace workspace)
        {
            // Wire up references for the event handlers in RegisterEvents
            _dte              = dte;
            _textView         = textViewHost.TextView;
            _window           = GetWindow(textViewHost, dte);
            _outliningManager = outliningManager;
            _workspace        = workspace;

            // If we can not find the window we belong to we can not do anything
            if (_window == null)
            {
                return;
            }

            // Add the view/content to the margin area
            _codeNavGrid   = CreateGrid(textViewHost);
            _codeNavColumn = _codeNavGrid.ColumnDefinitions[Settings.Default.MarginSide.Equals("Left") ? 0 : 2];
            Children.Add(_codeNavGrid);

            RegisterEvents();

            LogHelper.Log($"CodeNav initialized for {_window.Caption}");
        }
コード例 #16
0
        /// <summary>Implements the OnConnection method of the IDTExtensibility2 interface. Receives notification that the Add-in is being loaded.</summary>
        /// <param term='application'>Root object of the host application.</param>
        /// <param term='connectMode'>Describes how the Add-in is being loaded.</param>
        /// <param term='addInInst'>Object representing this Add-in.</param>
        /// <seealso class='IDTExtensibility2' />
        public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)
        {
            try
            {
                applicationObject = (DTE2)application;
                addInInstance     = (AddIn)addInInst;

                object tempObject = null;

                var controlName = "MSILWindow.Window.WindowControl";

                // Change this to your path
                var assemblyPath = @"C:\Users\filip.ekberg\Documents\GitHub\MSILWindow\MSILWindow.Window\bin\Debug\MSILWindow.Window.dll";
                var controlGuid  = "{6d0f6084-69ef-4100-92c5-5e7e3a557e05}";

                toolWins = (Windows2)applicationObject.Windows;

                toolWin = toolWins.CreateToolWindow2(addInInstance,
                                                     assemblyPath, controlName, "Real-time MSIL Viewer", controlGuid,
                                                     ref tempObject);

                if (toolWin != null)
                {
                    toolWin.Visible = true;
                }

                events                        = applicationObject.Events;
                buildEvents                   = events.BuildEvents;
                buildEvents.OnBuildDone      += BuildEvents_OnBuildDone;
                textEditorEvents              = events.get_TextEditorEvents();
                textEditorEvents.LineChanged += Connect_LineChanged;

                serviceProxy = ChannelFactory <ICommandService> .CreateChannel(new NetNamedPipeBinding(), serviceAddress);
            }
            catch { }
        }
コード例 #17
0
        private void WindowEventsOnWindowActivated(EnvDTE.Window gotFocus, EnvDTE.Window lostFocus)
        {
            if (_projects == null)
            {
                _projects = _dte.Solution.Projects;
            }

            //No solution loaded
            if (_solution.Count == 0)
            {
                ResetForm();
                return;
            }

            //Lost focus
            if (gotFocus.Caption != "WebResourceDeployerWindow")
            {
                return;
            }

            Projects.IsEnabled      = true;
            AddConnection.IsEnabled = true;
            Connections.IsEnabled   = true;
        }
コード例 #18
0
ファイル: TemplateFileManager.cs プロジェクト: bordev/Tobasco
        /// <summary>
        /// Execute Visual Studio commands against the project item.
        /// </summary>
        /// <param name="item">The current project item.</param>
        /// <param name="command">The vs command as string.</param>
        /// <returns>An error message if the command fails.</returns>
        public static string ExecuteVsCommand(EnvDTE.DTE dte, EnvDTE.ProjectItem item, params string[] command)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }

            string error = String.Empty;

            try
            {
                EnvDTE.Window window = item.Open();
                window.Activate();

                foreach (var cmd in command)
                {
                    if (String.IsNullOrWhiteSpace(cmd) == true)
                    {
                        continue;
                    }

                    EnvDTE80.DTE2 dte2 = dte as EnvDTE80.DTE2;
                    dte2.ExecuteCommand(cmd, String.Empty);
                }

                item.Save();
                window.Visible = false;
                // window.Close(); // Ends VS, but not the tab :(
            }
            catch (Exception ex)
            {
                error = String.Format("Error processing file {0} {1}", item.Name, ex.Message);
            }

            return(error);
        }
コード例 #19
0
        public bool OpenFile(string filePath, int lineNumber = 0, int lineCharacterNumber = -1)
        {
            if (!HasDTE)
            {
                return(false);
            }

            EnvDTE.Window w = DTE2.ItemOperations.OpenFile(filePath, EnvDTE.Constants.vsViewKindTextView);
            if (w != null && lineNumber > 0)
            {
                var selection = (EnvDTE.TextSelection)w.Document.Selection;
                if (lineCharacterNumber >= 0)
                {
                    selection.MoveToLineAndOffset(lineNumber, lineCharacterNumber, true);
                    selection.Collapse();
                }
                else
                {
                    selection.GotoLine(lineNumber, true);
                }
                return(true);
            }
            return(false);
        }
コード例 #20
0
        //Preview
        internal EnvDTE.TextSelection OpenDocShowPreview(ResultItem resultLine, FindSettings settings, bool focus = true)
        {
            EnvDTE.TextSelection selection = null;
            if (Dte != null)
            {
                EnvDTE.Window docWindow = Dte.ItemOperations.OpenFile(resultLine.linePath, Constants.vsViewKindTextView);
                selection = GetSelection(Dte.ActiveDocument);
                if (selection != null)
                {
                    selection.SelectAll();
                    int lastLine = selection.CurrentLine;
                    FillPreviewFromDocument(dictTBPreview[settings].Document.Blocks, selection, resultLine);

                    SelectOffsetLength(selection, resultLine);

                    /* if (settings.chkRegExp == true)
                     *   Debug.Assert(false, "Brak obsługi RegExp");
                     * else
                     * {
                     *   selection.MoveToLineAndOffset(resultLine.lineNumber.Value, resultLine.resultOffset + 1, false);
                     *   selection.MoveToLineAndOffset(resultLine.lineNumber.Value, resultLine.resultOffset + 1 + resultLine.ResultLength, true);
                     * }*/
                    //Add action to set focus no doc window after finishing all action in queue (currenty there should be only double click event)
                    if (focus)
                    {
                        Action showAction = () => docWindow.Activate();
                        this.Dispatcher.BeginInvoke(showAction);
                    }
                }
            }
            else
            {
                Debug.Assert(false, "Brak DTE");
            }
            return(selection);
        }
コード例 #21
0
 private void UpdateBranchName(Window gotFocus, Window lostFocus) {
     UpdateBranchName();
 }
コード例 #22
0
        internal TextDocument GetTextDocumentFromWindow(Window window)
        {
            TextDocument codeDoc = null;
            if (Dte != null)
            {
                Document doc = null;
                try
                {
                    doc = window.Document;
                }
                catch (ArgumentException)
                {
                    return null; //error occured return null
                }

                if (doc != null)
                {
                    codeDoc = doc.Object(String.Empty) as TextDocument;
                }
            }
            return codeDoc;
        }
コード例 #23
0
        /// <summary>Implements the OnConnection method of the IDTExtensibility2 interface. Receives notification that the Add-in is being loaded.</summary>
        /// <param term='application'>Root object of the host application.</param>
        /// <param term='connectMode'>Describes how the Add-in is being loaded.</param>
        /// <param term='addInInst'>Object representing this Add-in.</param>
        /// <seealso class='IDTExtensibility2' />
        public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)
        {
            _applicationObject = (DTE2)application;
            _addInInstance = (AddIn)addInInst;

            // Only execute the startup code if the connection mode is a startup mode
            if (connectMode == ext_ConnectMode.ext_cm_AfterStartup || connectMode == ext_ConnectMode.ext_cm_Startup)
            {
                try
                {
                    // Declare variables
                    string ctrlProgID, guidStr;
                    EnvDTE80.Windows2 toolWins;
                    object objTemp = null;

                    // The Control ProgID for the user control
                    ctrlProgID = "VSTSTimeTrackerAddin.VisualUserControl";

                    // This guid must be unique for each different tool window,
                    // but you may use the same guid for the same tool window.
                    // This guid can be used for indexing the windows collection,
                    // for example: applicationObject.Windows.Item(guidstr)
                    guidStr = "{357113D6-7028-4639-AE45-16E53032008D}";

                    // Get the executing assembly...
                    System.Reflection.Assembly asm = System.Reflection.Assembly.GetExecutingAssembly();

                    // Get Visual Studio's global collection of tool windows...
                    toolWins = (Windows2)_applicationObject.Windows;

                    // Create a new tool window, embedding the Visual Time Tracker control inside it...
                    m_toolWin = toolWins.CreateToolWindow2(_addInInstance, asm.Location, ctrlProgID, "Visual Time Tracker", guidStr, ref objTemp);

                    // Pass the DTE object to the user control...
                    VisualUserControl vuc = (VisualUserControl)objTemp;
                    vuc.DTE = _applicationObject;

                    // and set the tool windows default size...
                    m_toolWin.Visible = true;		// MUST make tool window visible before using any methods or properties,
                    // otherwise exceptions will occurr.
                    //toolWin.Height = 400;
                    //toolWin.Width = 600;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                    Debug.WriteLine(ex.StackTrace);
                }
            }

            if(connectMode == ext_ConnectMode.ext_cm_UISetup)
            {
                object []contextGUIDS = new object[] { };
                Commands2 commands = (Commands2)_applicationObject.Commands;
                string toolsMenuName;

                try
                {
                    //If you would like to move the command to a different menu, change the word "Tools" to the
                    //  English version of the menu. This code will take the culture, append on the name of the menu
                    //  then add the command to that menu. You can find a list of all the top-level menus in the file
                    //  CommandBar.resx.
                    ResourceManager resourceManager = new ResourceManager("VSTSTimeTrackerAddin.CommandBar", Assembly.GetExecutingAssembly());
                    CultureInfo cultureInfo = new System.Globalization.CultureInfo(_applicationObject.LocaleID);
                    string resourceName = String.Concat(cultureInfo.TwoLetterISOLanguageName, "Tools");
                    toolsMenuName = resourceManager.GetString(resourceName);
                }
                catch
                {
                    //We tried to find a localized version of the word Tools, but one was not found.
                    //  Default to the en-US word, which may work for the current culture.
                    toolsMenuName = "Tools";
                }

                //Place the command on the tools menu.
                //Find the MenuBar command bar, which is the top-level command bar holding all the main menu items:
                Microsoft.VisualStudio.CommandBars.CommandBar menuBarCommandBar = ((Microsoft.VisualStudio.CommandBars.CommandBars)_applicationObject.CommandBars)["MenuBar"];

                //Find the Tools command bar on the MenuBar command bar:
                CommandBarControl toolsControl = menuBarCommandBar.Controls[toolsMenuName];
                CommandBarPopup toolsPopup = (CommandBarPopup)toolsControl;

                //This try/catch block can be duplicated if you wish to add multiple commands to be handled by your Add-in,
                //  just make sure you also update the QueryStatus/Exec method to include the new command names.
                try
                {
                    //Add a command to the Commands collection:
                    Command command = commands.AddNamedCommand2(_addInInstance, "VSTSTimeTrackerAddin", "VSTSTimeTrackerAddin", "Executes the command for VSTSTimeTrackerAddin", true, 59, ref contextGUIDS, (int)vsCommandStatus.vsCommandStatusSupported+(int)vsCommandStatus.vsCommandStatusEnabled, (int)vsCommandStyle.vsCommandStylePictAndText, vsCommandControlType.vsCommandControlTypeButton);

                    //Add a control for the command to the tools menu:
                    if((command != null) && (toolsPopup != null))
                    {
                        command.AddControl(toolsPopup.CommandBar, 1);
                    }
                }
                catch(System.ArgumentException)
                {
                    //If we are here, then the exception is probably because a command with that name
                    //  already exists. If so there is no need to recreate the command and we can
                    //  safely ignore the exception.
                }

                // Only execute the startup code if the connection mode is a startup mode
                if (connectMode == ext_ConnectMode.ext_cm_AfterStartup || connectMode == ext_ConnectMode.ext_cm_Startup)
                {
                    try
                    {
                        // Declare variables
                        string ctrlProgID, guidStr;
                        EnvDTE80.Windows2 toolWins;
                        object objTemp = null;

                        // Pass the DTE object to the user control...
                        VisualUserControl browser = (VisualUserControl)objTemp;
                        browser.DTE = _applicationObject;
                    }
                    catch (Exception exception)
                    {

                    }
                }
            }
        }
コード例 #24
0
ファイル: Connect.cs プロジェクト: Dervall/Dotty
        private void ShowToolWindow()
        {
            const string toolwindowGuid = "{54E3B802-AB4E-4EBF-999B-4DD19E980608}";

            try
            {
                if (myToolWindow == null) // First time, create it
                {
                    var windows2 = (Windows2)applicationObject.Windows;

                    string assembly = System.Reflection.Assembly.GetExecutingAssembly().Location;
                    object userControl = null;

                    myToolWindow = windows2.CreateToolWindow2(addInInstance, assembly,
                       typeof(ViewGraphControl).FullName, "Graph view", toolwindowGuid, ref userControl);
                    // TODO: Really ugly solution here
                    ViewGraphControl.Initialize(myToolWindow, applicationObject);
                }
                myToolWindow.Visible = true;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
コード例 #25
0
        /// <summary>
        /// Determines if the command should be displayed or not.
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        //public override bool DisplayCommand(UIHierarchyItem item)
        //{
        //    try
        //    {
        //        UIHierarchy solExplorer = this.ApplicationObject.ToolWindows.SolutionExplorer;
        //        if (((System.Array)solExplorer.SelectedItems).Length != 1)
        //            return false;

        //        UIHierarchyItem hierItem = ((UIHierarchyItem)((System.Array)solExplorer.SelectedItems).GetValue(0));
        //        return (((ProjectItem)hierItem.Object).Object is Dimension);
        //    }
        //    catch
        //    {
        //        return false;
        //    }
        //}


        public override void Exec()
        {
            try
            {
                UIHierarchy     solExplorer = this.ApplicationObject.ToolWindows.SolutionExplorer;
                UIHierarchyItem hierItem    = (UIHierarchyItem)((System.Array)solExplorer.SelectedItems).GetValue(0);
                ProjectItem     projItem    = (ProjectItem)hierItem.Object;
                Dimension       d           = (Dimension)projItem.Object;

                if (d.DataSource == null)
                {
                    if (d.Source is TimeBinding)
                    {
                        MessageBox.Show("Dimension Health Check is not supported on a Server Time dimension.");
                    }
                    else
                    {
                        MessageBox.Show("The data source for this dimension is not set. Dimension Health Check cannot be run.");
                    }
                    return;
                }
                else if (d.Source is DimensionBinding)
                {
                    MessageBox.Show("Dimension Health Check is not supported on a linked dimension.");
                    return;
                }

                ApplicationObject.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationDeploy);
                ApplicationObject.StatusBar.Progress(true, "Checking Dimension Health...", 0, d.Attributes.Count * 2);

                DimensionError[] errors = Check(d);
                if (errors == null)
                {
                    return;
                }

                this.oLastDimension = d;
                this.changesvc      = (IComponentChangeService)d.Site.GetService(typeof(IComponentChangeService));

                int    iErrorCnt = 0;
                string sCaption  = d.Name + ": Dimension Health Check";

#if YUKON || KATMAI
                EnvDTE80.Windows2 toolWins;
                object            objTemp = null;
                toolWins = (Windows2)ApplicationObject.Windows;
                if (toolWin == null)
                {
                    toolWin = toolWins.CreateToolWindow2(AddInInstance, typeof(WebBrowser).Assembly.Location, typeof(WebBrowser).FullName, sCaption, "{" + typeof(WebBrowser).GUID.ToString() + "}", ref objTemp);
                }
                else
                {
                    objTemp         = toolWin.Object;
                    toolWin.Caption = sCaption;
                }

                WebBrowser browser = (WebBrowser)objTemp;
#else
                //appear to be having some problems with .NET controls inside tool windows, even though this issue says fixed: http://connect.microsoft.com/VisualStudio/feedback/details/512181/vsip-vs-2010-beta2-width-of-add-in-toolwindow-not-changed-with-activex-hosted-control#tabs
                //so just create this inside a regular WinForm
                WebBrowser browser = new WebBrowser();
#endif

                browser.AllowNavigation = true;
                if (browser.Document != null) //idea from http://geekswithblogs.net/paulwhitblog/archive/2005/12/12/62961.aspx
                {
                    browser.Document.OpenNew(true);
                }
                else
                {
                    browser.Navigate("about:blank");
                }
                Application.DoEvents();

                browser.Document.Write("<font style='font-family:Arial;font-size:10pt'>");
                browser.Document.Write("<h3>" + d.Name + ": Dimension Health Check</h3>");
                browser.Document.Write("<i>Checks whether attribute relationships hold true according to the data.<br>Also checks definition of attribute keys to determine if they are unique.<br>Also checks whether any obvious attribute relationships are missing.</i><br><br>");
                if (errors.Length > 0)
                {
                    browser.Document.Write("<b>Problems</b><br>");
                    foreach (DimensionError e in errors)
                    {
                        iErrorCnt++;
                        browser.Document.Write("<li>");
                        browser.Document.Write(e.ErrorDescription);
                        DimensionDataError           de = e as DimensionDataError;
                        DimensionRelationshipWarning rw = e as DimensionRelationshipWarning;
                        if (de != null && de.ErrorTable != null)
                        {
                            browser.Document.Write(" <a href=\"javascript:void(null)\" id=expander" + iErrorCnt + " ErrorCnt=" + iErrorCnt + " style='color:blue'>Show/hide problem rows</a><br>\r\n");
                            browser.Document.Write("<table id=error" + iErrorCnt + " cellspacing=0 style='display:none;font-family:Arial;font-size:10pt'>");
                            browser.Document.Write("<tr><td></td>");
                            for (int i = 0; i < de.ErrorTable.Columns.Count; i++)
                            {
                                browser.Document.Write("<td nowrap><b>");
                                browser.Document.Write(System.Web.HttpUtility.HtmlEncode(de.ErrorTable.Columns[i].ColumnName));
                                browser.Document.Write("</b></td><td>&nbsp;&nbsp;</td>");
                            }
                            browser.Document.Write("</tr>\r\n");
                            foreach (DataRow dr in de.ErrorTable.Rows)
                            {
                                browser.Document.Write("<tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td>");
                                for (int i = 0; i < de.ErrorTable.Columns.Count; i++)
                                {
                                    browser.Document.Write("<td nowrap>");
                                    if (!Convert.IsDBNull(dr[i]))
                                    {
                                        browser.Document.Write(System.Web.HttpUtility.HtmlEncode(dr[i].ToString()));
                                    }
                                    else
                                    {
                                        browser.Document.Write("<font color=lightgrey>(null)</font>");
                                    }
                                    browser.Document.Write("</td><td>&nbsp;&nbsp;</td>");
                                }
                                browser.Document.Write("</tr>");
                            }
                            browser.Document.Write("</table>");
                        }
                        else if (rw != null)
                        {
                            browser.Document.Write(" <a href=\"javascript:void(null)\" id=expander" + iErrorCnt + " Attribute=\"" + rw.Attribute.ID + "\" RelatedAttribute=\"" + rw.RelatedAttribute.ID + "\" style='color:blue'>Change attribute relationship</a>\r\n");
                        }
                    }
                }
                else
                {
                    browser.Document.Write("<b>No problems found</b>");
                }
                browser.Document.Write("</font>");
                browser.IsWebBrowserContextMenuEnabled = false;
                browser.AllowWebBrowserDrop            = false;

                Application.DoEvents();

                for (int i = 1; i <= iErrorCnt; i++)
                {
                    //in some of the newer versions of Internet Explorer, javascript is not enabled
                    //so do the dynamic stuff with C# events and code
                    try
                    {
                        browser.Document.GetElementById("expander" + i).Click += new HtmlElementEventHandler(Expander_Click);
                    }
                    catch { }
                }

#if YUKON || KATMAI
                //setting IsFloating and Linkable to false makes this window tabbed
                toolWin.IsFloating = false;
                toolWin.Linkable   = false;
                toolWin.Visible    = true;
#else
                Form descForm = new Form();
                descForm.Icon          = BIDSHelper.Resources.Common.BIDSHelper;
                descForm.Text          = "BIDS Helper - " + sCaption;
                descForm.MaximizeBox   = true;
                descForm.MinimizeBox   = false;
                descForm.Width         = 600;
                descForm.Height        = 500;
                descForm.SizeGripStyle = SizeGripStyle.Show;
                descForm.MinimumSize   = new System.Drawing.Size(descForm.Width / 2, descForm.Height / 2);

                browser.Top    = 10;
                browser.Left   = 10;
                browser.Width  = descForm.Width - 30;
                browser.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom;
                browser.Dock   = DockStyle.Fill;
                browser.Height = descForm.Height - 60;
                descForm.Controls.Add(browser);
                descForm.Show();
#endif
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                ApplicationObject.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy);
                ApplicationObject.StatusBar.Progress(false, "Checking Dimension Health...", 2, 2);
            }
        }
コード例 #26
0
        public override void Exec()
        {
            try
            {
                UIHierarchy solExplorer = this.ApplicationObject.ToolWindows.SolutionExplorer;
                UIHierarchyItem hierItem = (UIHierarchyItem)((System.Array)solExplorer.SelectedItems).GetValue(0);
                ProjectItem projItem = (ProjectItem)hierItem.Object;
                Dimension d = (Dimension)projItem.Object;

                if (d.DataSource == null)
                {
                    if (d.Source is TimeBinding)
                    {
                        MessageBox.Show("Dimension Health Check is not supported on a Server Time dimension.");
                    }
                    else
                    {
                        MessageBox.Show("The data source for this dimension is not set. Dimension Health Check cannot be run.");
                    }
                    return;
                }
                else if (d.Source is DimensionBinding)
                {
                    MessageBox.Show("Dimension Health Check is not supported on a linked dimension.");
                    return;
                }

                ApplicationObject.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationDeploy);
                ApplicationObject.StatusBar.Progress(true, "Checking Dimension Health...", 0, d.Attributes.Count * 2);

                DimensionError[] errors = Check(d);
                if (errors == null) return;

                this.oLastDimension = d;
                this.changesvc = (IComponentChangeService)d.Site.GetService(typeof(IComponentChangeService));

                int iErrorCnt = 0;
                string sCaption = d.Name + ": Dimension Health Check";

#if YUKON || KATMAI
                EnvDTE80.Windows2 toolWins;
                object objTemp = null;
                toolWins = (Windows2)ApplicationObject.Windows;
                if (toolWin == null)
                {
                    toolWin = toolWins.CreateToolWindow2(AddInInstance, typeof(WebBrowser).Assembly.Location, typeof(WebBrowser).FullName, sCaption, "{" + typeof(WebBrowser).GUID.ToString() + "}", ref objTemp);
                }
                else
                {
                    objTemp = toolWin.Object;
                    toolWin.Caption = sCaption;
                }

                WebBrowser browser = (WebBrowser)objTemp;
#else
                //appear to be having some problems with .NET controls inside tool windows, even though this issue says fixed: http://connect.microsoft.com/VisualStudio/feedback/details/512181/vsip-vs-2010-beta2-width-of-add-in-toolwindow-not-changed-with-activex-hosted-control#tabs
                //so just create this inside a regular WinForm
                WebBrowser browser = new WebBrowser();
#endif

                browser.AllowNavigation = true;
                if (browser.Document != null) //idea from http://geekswithblogs.net/paulwhitblog/archive/2005/12/12/62961.aspx
                    browser.Document.OpenNew(true);
                else
                    browser.Navigate("about:blank");
                Application.DoEvents();

                browser.Document.Write("<font style='font-family:Arial;font-size:10pt'>");
                browser.Document.Write("<h3>" + d.Name + ": Dimension Health Check</h3>");
                browser.Document.Write("<i>Checks whether attribute relationships hold true according to the data.<br>Also checks definition of attribute keys to determine if they are unique.<br>Also checks whether any obvious attribute relationships are missing.</i><br><br>");
                if (errors.Length > 0)
                {
                    browser.Document.Write("<b>Problems</b><br>");
                    foreach (DimensionError e in errors)
                    {
                        iErrorCnt++;
                        browser.Document.Write("<li>");
                        browser.Document.Write(e.ErrorDescription);
                        DimensionDataError de = e as DimensionDataError;
                        DimensionRelationshipWarning rw = e as DimensionRelationshipWarning;
                        if (de != null && de.ErrorTable != null)
                        {
                            browser.Document.Write(" <a href=\"javascript:void(null)\" id=expander" + iErrorCnt + " ErrorCnt=" + iErrorCnt + " style='color:blue'>Show/hide problem rows</a><br>\r\n");
                            browser.Document.Write("<table id=error" + iErrorCnt + " cellspacing=0 style='display:none;font-family:Arial;font-size:10pt'>");
                            browser.Document.Write("<tr><td></td>");
                            for (int i = 0; i < de.ErrorTable.Columns.Count; i++)
                            {
                                browser.Document.Write("<td nowrap><b>");
                                browser.Document.Write(System.Web.HttpUtility.HtmlEncode(de.ErrorTable.Columns[i].ColumnName));
                                browser.Document.Write("</b></td><td>&nbsp;&nbsp;</td>");
                            }
                            browser.Document.Write("</tr>\r\n");
                            foreach (DataRow dr in de.ErrorTable.Rows)
                            {
                                browser.Document.Write("<tr><td>&nbsp;&nbsp;&nbsp;&nbsp;</td>");
                                for (int i = 0; i < de.ErrorTable.Columns.Count; i++)
                                {
                                    browser.Document.Write("<td nowrap>");
                                    if (!Convert.IsDBNull(dr[i]))
                                        browser.Document.Write(System.Web.HttpUtility.HtmlEncode(dr[i].ToString()));
                                    else
                                        browser.Document.Write("<font color=lightgrey>(null)</font>");
                                    browser.Document.Write("</td><td>&nbsp;&nbsp;</td>");
                                }
                                browser.Document.Write("</tr>");
                            }
                            browser.Document.Write("</table>");
                        }
                        else if (rw != null)
                        {
                            browser.Document.Write(" <a href=\"javascript:void(null)\" id=expander" + iErrorCnt + " Attribute=\"" + rw.Attribute.ID + "\" RelatedAttribute=\"" + rw.RelatedAttribute.ID + "\" style='color:blue'>Change attribute relationship</a>\r\n");
                        }
                    }
                }
                else
                {
                    browser.Document.Write("<b>No problems found</b>");
                }
                browser.Document.Write("</font>");
                browser.IsWebBrowserContextMenuEnabled = false;
                browser.AllowWebBrowserDrop = false;

                Application.DoEvents();

                for (int i = 1; i <= iErrorCnt; i++)
                {
                    //in some of the newer versions of Internet Explorer, javascript is not enabled
                    //so do the dynamic stuff with C# events and code
                    try
                    {
                        browser.Document.GetElementById("expander" + i).Click += new HtmlElementEventHandler(Expander_Click);
                    }
                    catch { }
                }

#if YUKON || KATMAI
                //setting IsFloating and Linkable to false makes this window tabbed
                toolWin.IsFloating = false;
                toolWin.Linkable = false;
                toolWin.Visible = true;
#else
                Form descForm = new Form();
                descForm.Icon = BIDSHelper.Resources.Common.BIDSHelper;
                descForm.Text = "BIDS Helper - " + sCaption;
                descForm.MaximizeBox = true;
                descForm.MinimizeBox = false;
                descForm.Width = 600;
                descForm.Height = 500;
                descForm.SizeGripStyle = SizeGripStyle.Show;
                descForm.MinimumSize = new System.Drawing.Size(descForm.Width/2, descForm.Height/2);

                browser.Top = 10;
                browser.Left = 10;
                browser.Width = descForm.Width - 30;
                browser.Anchor = AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Top | AnchorStyles.Bottom;
                browser.Dock = DockStyle.Fill;
                browser.Height = descForm.Height - 60;
                descForm.Controls.Add(browser);
                descForm.Show();
#endif
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                ApplicationObject.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy);
                ApplicationObject.StatusBar.Progress(false, "Checking Dimension Health...", 2, 2);
            }
        }
コード例 #27
0
        /// <summary>
        /// Tries to open a given project item as a Document which can be used to add or remove headers.
        /// </summary>
        /// <param name="item">The project item.</param>
        /// <param name="document">The document which was created or null if an error occured (see return value).</param>
        /// <param name="headers">A dictionary of headers using the file extension as key and the header as value or null if headers should only be removed.</param>
        /// <returns>A value indicating the result of the operation. Document will be null unless DocumentCreated is returned.</returns>
        public CreateDocumentResult TryCreateDocument(ProjectItem item, out Document document, out bool wasOpen, IDictionary <string, string[]> headers = null)
        {
            document = null;
            wasOpen  = true;

            if (!ProjectItemInspection.IsPhysicalFile(item))
            {
                return(CreateDocumentResult.NoPhysicalFile);
            }

            if (ProjectItemInspection.IsLicenseHeader(item))
            {
                return(CreateDocumentResult.LicenseHeaderDocument);
            }

            if (ProjectItemInspection.IsLink(item))
            {
                return(CreateDocumentResult.LinkedFile);
            }

            var language = _licenseHeaderExtension.LanguagesPage.Languages
                           .Where(x => x.Extensions.Any(y => item.Name.EndsWith(y, StringComparison.OrdinalIgnoreCase)))
                           .FirstOrDefault();

            if (language == null)
            {
                return(CreateDocumentResult.LanguageNotFound);
            }

            Window window = null;

            //try to open the document as a text document
            try
            {
                if (!item.IsOpen[Constants.vsViewKindTextView])
                {
                    window  = item.Open(Constants.vsViewKindTextView);
                    wasOpen = false;
                }
            }
            catch (COMException)
            {
                return(CreateDocumentResult.NoTextDocument);
            }
            catch (IOException)
            {
                return(CreateDocumentResult.NoPhysicalFile);
            }

            var itemDocument = item.Document;

            if (item.Document == null)
            {
                return(CreateDocumentResult.NoPhysicalFile);
            }


            var textDocument = itemDocument.Object("TextDocument") as TextDocument;

            if (textDocument == null)
            {
                return(CreateDocumentResult.NoTextDocument);
            }

            string[] header = null;
            if (headers != null)
            {
                var extension = headers.Keys
                                .OrderByDescending(x => x.Length)
                                .Where(x => item.Name.EndsWith(x, StringComparison.OrdinalIgnoreCase))
                                .FirstOrDefault();

                if (extension == null)
                {
                    return(CreateDocumentResult.NoHeaderFound);
                }

                header = headers[extension];

                if (header.All(string.IsNullOrEmpty))
                {
                    return(CreateDocumentResult.EmptyHeader);
                }
            }

            var optionsPage = _licenseHeaderExtension.OptionsPage;

            document = new Document(
                document: textDocument,
                language: language,
                lines: header,
                projectItem: item,
                keywords: (optionsPage.UseRequiredKeywords
            ? optionsPage.RequiredKeywords.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(k => k.Trim())
            : null),
                blacklist: (optionsPage.UseBlacklistedKeywords
            ? optionsPage.BlacklistedKeywords.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(b => b.Trim())
            : null));

            return(CreateDocumentResult.DocumentCreated);
        }
コード例 #28
0
 private void UpdateBranchName(Window window) {
     UpdateBranchName();
 }
コード例 #29
0
        private void WindowEventsOnWindowActivated(Window gotFocus, Window lostFocus)
        {
            if (Projects == null)
                Projects = _dte.Solution.Projects;

            //No solution loaded
            if (_solution.Count == 0)
            {
                ResetForm();
                return;
            }

            //WindowEventsOnWindowActivated in this project can be called when activating another window
            //so we don't want to contine further unless our window is active
            if (!gotFocus.Caption.StartsWith("CRM Developer Extensions")) return;

            ProjectsDdl.IsEnabled = true;
            AddConnection.IsEnabled = true;
            Connections.IsEnabled = true;

            foreach (var project in GetProjects())
            {
                SolutionProjectAdded(project);
            }
        }
コード例 #30
0
        public int OnElementValueChanged(uint elementid, object varValueOld, object varValueNew)
        {
            try
            {
                if (elementid == (uint)VSConstants.VSSELELEMID.SEID_WindowFrame)
                {

                    if (currentWindow == null)
                    {
                        currentWindow = Dte.ActiveWindow;
                    }
                    else if (currentWindow != Dte.ActiveWindow)
                    {
                        previousWindow = currentWindow;
                        currentWindow = Dte.ActiveWindow;
                    }

                    string lang = CurrentWindowLanguage;
                    if (StringConstants.ExportNameCSharp.Equals(lang, StringComparison.OrdinalIgnoreCase)
                        || StringConstants.ExportNameVisualBasic.Equals(lang, StringComparison.OrdinalIgnoreCase)
                        || StringConstants.ExportNameXML.Equals(lang, StringComparison.OrdinalIgnoreCase)
                        || StringConstants.ExportNameSQL.Equals(lang, StringComparison.OrdinalIgnoreCase)
                        || StringConstants.ExportNameSQL2.Equals(lang, StringComparison.OrdinalIgnoreCase)
                        || StringConstants.ExportNameJavaScript.Equals(lang, StringComparison.OrdinalIgnoreCase)
                        || StringConstants.ExportNameJavaScript2.Equals(lang, StringComparison.OrdinalIgnoreCase)
                        || StringConstants.ExportNameHTML.Equals(lang, StringComparison.OrdinalIgnoreCase)

                        // Only allow C++ if this VS is newer than VS 2010
                        || (!IsVisualStudio2010 && StringConstants.ExportNameCPP.Equals(lang, StringComparison.OrdinalIgnoreCase))

                        )
                    {
                        //make the export context menu item visible
                        snippetExportCommand.Visible = true;
                    }
                    else
                    {
                        //make the export context menu item not visible
                        snippetExportCommand.Visible = false;
                    }
                }
            }
            catch (NullReferenceException)
            {
                return VSConstants.S_FALSE;
            }
            catch (Exception ex)
            {
                Logger.Log(ex.Message, "OnElementValueChanged", ex);
                return VSConstants.S_FALSE;
            }

            return VSConstants.S_OK;
        }
コード例 #31
0
 public void SetWindow(Window window) => _window = window;
コード例 #32
0
        public void TestAutomationOnProjectItem()
        {
            UIThreadInvoker.Invoke((ThreadInvoker) delegate()
            {
                //Get the global service provider and the dte
                IServiceProvider sp = VsIdeTestHostContext.ServiceProvider;
                DTE dte             = (DTE)sp.GetService(typeof(DTE));

                string destination = Path.Combine(TestContext.TestDir, TestContext.TestName);
                Utilities.CreateMyNestedProject(sp, dte, TestContext.TestName, destination, true);

                OAProject automation = Utilities.FindExtObject(sp, Utilities.NestedProjectGuid, TestContext.TestName) as OAProject;
                Assert.IsNotNull(automation, "Failed to create a project using automation");

                ProjectNode project = automation.Project;

                // Get the AssemblyInfo.cs, try to open it and then ask using automation that it is opened.
                EnvDTE.ProjectItem item = automation.ProjectItems.Item("AssemblyInfo.cs");
                Assert.IsNotNull(item, "Could not retrieve AssemblyInfo.cs");

                EnvDTE.Window window = item.Open(VSConstants.LOGVIEWID_Primary.ToString());
                Assert.IsNotNull(window, "Could not open the AssemblyInfo.cs");
                window.Activate();

                bool isOpen = item.get_IsOpen(VSConstants.LOGVIEWID_Primary.ToString());
                Assert.IsTrue(isOpen, "The AssemblyInfo.cs file should have been opened");

                // Now save it
                item.Save("");

                Assert.IsTrue(item.Saved, "The renamed AssemblyInfo.cs has not been saved");

                // Get the Document
                EnvDTE.Document document = item.Document;
                Assert.IsNotNull(document, "Could not retrieve the document object");
                Assert.IsTrue(document.Name == "AssemblyInfo.cs", "The document for the file item is incorrect. It's name should be AssemblyInfo.cs");

                // Try the properties on a nested item
                EnvDTE.ProjectItem nestedProject     = automation.ProjectItems.Item("ANestedProject");
                EnvDTE.ProjectItem nestedProjectItem = nestedProject.ProjectItems.Item("Program.cs");
                EnvDTE.Properties nesteditemsProps   = nestedProjectItem.Properties;
                EnvDTE.Property nestedItemProperty   = nesteditemsProps.Item("BuildAction");
                Assert.IsNotNull(nestedItemProperty, "Could not retrieve the BuildAction property from the nested project item");
                nestedItemProperty.Value = BuildAction.Content;
                Assert.AreEqual((BuildAction)nestedItemProperty.Value, BuildAction.Content);

                // Now try the properties on the top project item
                EnvDTE.Properties props = item.Properties;
                Assert.IsNotNull(props, "Could not retrieve the BuildAction property from the nested project item");

                EnvDTE.Property itemProperty = props.Item("BuildAction");
                Assert.IsNotNull(itemProperty, "Could not retrieve the BuildAction property from the nested project item");
                Assert.IsFalse(itemProperty is OANullProperty, "Could not retrieve the BuildAction property from the nested project item");
                itemProperty.Value = BuildAction.Content;
                Assert.AreEqual(itemProperty.Value, BuildAction.Content);

                // Now save as
                Assert.IsTrue(item.SaveAs("AssemblyInfo1.cs"), "The file AssemblyInfo.cs could not be reanmed to AssemblyInfo1.cs");
                Assert.IsTrue(item.Name == "AssemblyInfo1.cs", "File item has been renamed to AssemblyInfo1.cs but the Name property has not");

                // Now try the Program.cs. That should not be opened
                EnvDTE.ProjectItem item1 = automation.ProjectItems.Item("Program.cs");

                Assert.IsNotNull(item1, "Could not retrieve AssemblyInfo.cs");

                isOpen = item1.get_IsOpen(VSConstants.LOGVIEWID_Primary.ToString());

                Assert.IsFalse(isOpen, "The Program.cs should not have been opened");

                // Now get the Reference folder as a project item and expand it.
                EnvDTE.ProjectItem references = automation.ProjectItems.Item("References");
                references.ExpandView();

                // Check that actually it was expanded.
                IVsUIHierarchyWindow uiHierarchy     = VsShellUtilities.GetUIHierarchyWindow(project.Site, HierarchyNode.SolutionExplorer);
                System.Reflection.MethodInfo mi      = typeof(ProjectNode).GetMethod("FindChild", BindingFlags.NonPublic | BindingFlags.Instance);
                ReferenceContainerNode containerNode = (ReferenceContainerNode)mi.Invoke(project, new object[] { "References" });

                __VSHIERARCHYITEMSTATE state;
                uint stateAsInt;
                uiHierarchy.GetItemState(project, (uint)containerNode.ID, (uint)__VSHIERARCHYITEMSTATE.HIS_Expanded, out stateAsInt);
                state = (__VSHIERARCHYITEMSTATE)stateAsInt;
                Assert.IsTrue(state == __VSHIERARCHYITEMSTATE.HIS_Expanded, "The References folder has not been expanded");
            });
        }
コード例 #33
0
 public static System.Windows.Forms.Screen CurrentScreen(this Window window)
 {
     return(System.Windows.Forms.Screen.FromPoint(new System.Drawing.Point((int)window.Left, (int)window.Top)));
 }
コード例 #34
0
        public static async Task SelectAllAsync(this Window window)
        {
            await ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();

            ((TextSelection)window.Document.Selection).SelectAll();
        }
コード例 #35
0
 public static string title(this EnvDTE.Window window)
 {
     return(new VisualStudio_2010().invokeOnThread(
                () => window.Caption));
 }
コード例 #36
0
 private void OnWindowShowing(EnvDTE.Window Window)
 {
     ChangeWindowTitleColorAsync(TitleBarColor);
 }
コード例 #37
0
        private void WindowEventsOnWindowActivated(Window gotFocus, Window lostFocus)
        {
            //No solution loaded
            if (_solution.Count == 0)
            {
                ResetForm();
                return;
            }

            //Lost focus
            if (gotFocus.Caption != PluginDeployer.Resources.ResourceManager.GetString("ToolWindowTitle")) return;

            _isIlMergeInstalled = IsIlMergeInstalled();
            SetIlMergeTooltip(_isIlMergeInstalled);
        }
コード例 #38
0
        public void WindowClosing([NotNull] EnvDTE.Window window)
        {
            Assert.ArgumentNotNull(window, nameof(window));

            AppHost.Tasks.Clear("Sitecore Layouts", window.Caption);
        }
コード例 #39
0
 private void WindowEvents_WindowActivated(Window gotFocus, Window lostFocus) => _control.UpdateDocument();
コード例 #40
0
 /// <summary>
 /// activate the window passed as a para
 /// </summary>
 /// <param name="window"></param>
 private void ActivateWindow(EnvDTE.Window window)
 {
     ThreadHelper.ThrowIfNotOnUIThread();
     window.Activate();
 }
コード例 #41
0
ファイル: Connect.cs プロジェクト: dvander/vstudio-modelines
        public void OnWindowActivated(EnvDTE.Window gotFocus, EnvDTE.Window lostFocus)
        {
            if (gotFocus.Document == null || gotFocus.Document.Type != "Text")
            {
                return;
            }

            TextDocument td = gotFocus.Document.Object() as TextDocument;

            if (td == null)
            {
                return;
            }

            Settings settings = new Settings();

            ReadModelines(td, settings);

            if (settings.et == null)
            {
                // If the language is C++, use the default tab setting (hard tabs), otherwise,
                // VS seems to like soft tabs for other languages.
                if (gotFocus.Document.Language == CodeModelLanguageConstants.vsCMLanguageVC)
                {
                    settings.et = kDefaultHardTabs;
                }
                else
                {
                    settings.et = false;
                }
            }

            if (settings.ts == null)
            {
                settings.ts = kDefaultTabSize;
            }

            // In Vim and Visual Studio, the following settings are roughly analogous:
            //    ts and TabSize
            //    sw and IndentSize
            //    noet/et and InsertTabs
            //
            // In both editors, |ts| controls how many spaces a hard tab is displayed as.
            //
            // In Vim, pressing the tab key will insert |sts| spaces if |et| is set, or a single
            // hard tab if |noet| is set. In Visual Studio, pressing the tab key will perform
            // an indentation.
            //
            // When either editor indents, the behavior is controlled InsertTabs/noet/et. If hard
            // tabs are disabled, then sw/IndentSize spaces are inserted. If hard tabs are
            // enabled, then N hard tabs are inserted, where:
            //    N = (IndentLevel * IndentSize) / TabSize
            // Spaces are inserted for the remaining width not satisfied by hard tabs.
            //
            // Since Vim does not perform indentation when pressing tab, the functionality will
            // differ if the effective tab width is different from |sw|. This also means "sts"
            // can be ignored, since there is no analog.
            //
            // [1] http://social.msdn.microsoft.com/Forums/vstudio/en-US/34cd09e5-c7b5-41cb-bee9-47bcce194260/cannot-get-the-tab-size-to-be-different-than-the-indent-size

            SetDTEProperty("TextEditor", gotFocus.Document.Language, "TabSize", settings.ts);
            SetDTEProperty("TextEditor", gotFocus.Document.Language, "IndentSize", settings.sw);
            SetDTEProperty("TextEditor", gotFocus.Document.Language, "InsertTabs", !settings.et);
        }
コード例 #42
0
        private void WindowEventsOnWindowActivated(Window gotFocus, Window lostFocus)
        {
            if (_projects == null)
                _projects = _dte.Solution.Projects;

            //No solution loaded
            if (_solution.Count == 0)
            {
                ResetForm();
                return;
            }

            //Lost focus
            if (gotFocus.Caption != PluginDeployer.Resources.ResourceManager.GetString("ToolWindowTitle")) return;

            Projects.IsEnabled = true;
            AddConnection.IsEnabled = true;
            Connections.IsEnabled = true;

            foreach (Project project in _projects)
            {
                SolutionProjectAdded(project);
            }
        }
コード例 #43
0
        private void WindowEvents_WindowActivated(EnvDTE.Window gotFocus, EnvDTE.Window lostFocus)
        {
            //Trace.WriteLine(string.Format("\n>>>> WindowEvents_WindowActivated() - '{0}' <- '{1}' ({2})\n", gotFocus.Caption, lostFocus.Caption, (m_Dte2.ActiveDocument == null) ? "null" : m_Dte2.ActiveDocument.Name));
            Debug.Print("\n>>>> WindowEvents_WindowActivated() - '{0}' <- '{1}' ({2})\n", (gotFocus == null) ? "null" : gotFocus.Caption, (lostFocus == null) ? "null" : lostFocus.Caption, (m_Dte2.ActiveDocument == null) ? "null" : m_Dte2.ActiveDocument.Name);

            if (m_StringResourceBuilder.IsBrowsing)
            {
                return;
            }

            if (!m_IsVisible)
            {
                return;
            }

            if (m_Dte2.ActiveDocument == null)
            {
                if (m_StringResourceBuilder.Window != null)
                {
                    WindowEvents_WindowClosing(m_StringResourceBuilder.Window);
                }

                return;
            } //if

            Trace.WriteLine("WindowEvents_WindowActivated()");

            if (m_TextEditorEvents != null)
            {
                m_TextEditorEvents.LineChanged -= m_TextEditorEvents_LineChanged;
                m_TextEditorEvents              = null;
            } //if

            //if (m_TextDocumentKeyPressEvents != null)
            //{
            //  m_TextDocumentKeyPressEvents.AfterKeyPress -= m_TextDocumentKeyPressEvents_AfterKeyPress;
            //  m_TextDocumentKeyPressEvents.AfterKeyPress += m_TextDocumentKeyPressEvents_AfterKeyPress;
            //  m_TextDocumentKeyPressEvents = null;
            //} //if

            EnvDTE.Window window = m_Dte2.ActiveDocument.ActiveWindow;

            bool isGotDocument  = (gotFocus != null) && (gotFocus.Document != null),
                 isLostDocument = (lostFocus != null) && (lostFocus.Document != null),
                 isGotCode      = isGotDocument && (gotFocus.Caption.EndsWith(".cs") || gotFocus.Caption.EndsWith(".vb")),
                 isLostCode     = isLostDocument && (lostFocus.Caption.EndsWith(".cs") || lostFocus.Caption.EndsWith(".vb"));

            if (!isGotDocument /*&& !isLostDocument*/ && (m_StringResourceBuilder.Window != null))
            {
                window = m_StringResourceBuilder.Window;
            }
            if (isGotCode)
            {
                window = gotFocus;
            }
            else if (!isGotDocument && isLostCode)
            {
                window = lostFocus;
            }

            if ((window != null) && (window.Document != null) && (window.Caption.EndsWith(".cs") || window.Caption.EndsWith(".vb")))
            {
                TextDocument txtDoc = window.Document.Object("TextDocument") as TextDocument;
                if (txtDoc != null)
                {
                    EnvDTE80.Events2 events = (EnvDTE80.Events2)m_Dte2.Events;

                    m_TextEditorEvents              = events.TextEditorEvents[txtDoc];
                    m_TextEditorEvents.LineChanged -= m_TextEditorEvents_LineChanged;
                    m_TextEditorEvents.LineChanged += m_TextEditorEvents_LineChanged;

                    //m_TextDocumentKeyPressEvents = events.TextDocumentKeyPressEvents[txtDoc];
                    //m_TextDocumentKeyPressEvents.AfterKeyPress -= m_TextDocumentKeyPressEvents_AfterKeyPress;
                    //m_TextDocumentKeyPressEvents.AfterKeyPress += m_TextDocumentKeyPressEvents_AfterKeyPress;

                    if (m_FocusedTextDocumentWindowHash != window.GetHashCode())
                    {
                        m_FocusedTextDocumentWindowHash = window.GetHashCode();
                        m_StringResourceBuilder.FocusedTextDocumentWindow = window;
                        this.Dispatcher.BeginInvoke(new Action(m_StringResourceBuilder.DoBrowse));
                    } //if
                }     //if
            }
            //else if (m_StringResourceBuilder.Window != null)
            //  WindowEvents_WindowClosing(m_StringResourceBuilder.Window);
        }