コード例 #1
0
        void IDTToolsOptionsPage.OnAfterCreated(DTE DTEObject)
        {
            this.Width = 395; //392
            this.Height = 290;

            lblTFS.Text = "TFS: " + (SmartDiffPlugin.TFSInstalled ? "Installed" : "Not Installed");
            lblVSS.Text = "VSS: " + (SmartDiffPlugin.VSSInstalled ? "Installed" : "Not Installed");

            if (string.IsNullOrEmpty(SmartDiffPlugin.CustomDiffViewer))
            {
                radSmartDiffDefault.Checked = true;
                txtSmartDiffCustom.Text = "\"C:\\Program Files\\Microsoft Visual Studio 9.0\\Common7\\IDE\\diffmerge.exe\" ? ? /ignoreeol /ignorespace";
            }
            else
            {
                radSmartDiffCustom.Checked = true;
                txtSmartDiffCustom.Text = SmartDiffPlugin.CustomDiffViewer;
            }
            FixSmartDiffCustomEnabled();

            btnExpressionColor.BackColor = ExpressionHighlighterPlugin.ExpressionColor;
            btnConfigurationColor.BackColor = ExpressionHighlighterPlugin.ConfigurationColor;

            txtFreeSpaceFactor.Text = MeasureGroupHealthCheckPlugin.FreeSpaceFactor.ToString();
        }
コード例 #2
0
        public PluginList()
        {
            InitializeComponent();

            _logger = new Logger();

            _dte = Package.GetGlobalService(typeof(DTE)) as DTE;
            if (_dte == null)
                return;

            _solution = _dte.Solution;
            if (_solution == null)
                return;

            _events = _dte.Events;
            var windowEvents = _events.WindowEvents;
            windowEvents.WindowActivated += WindowEventsOnWindowActivated;
            _solutionEvents = _events.SolutionEvents;
            _solutionEvents.BeforeClosing += BeforeSolutionClosing;
            _solutionEvents.BeforeClosing += SolutionBeforeClosing;
            _solutionEvents.ProjectAdded += SolutionProjectAdded;
            _solutionEvents.ProjectRemoved += SolutionProjectRemoved;
            _solutionEvents.ProjectRenamed += SolutionProjectRenamed;

            SelectedAssemblyItem.PropertyChanged += SelectedAssemblyItem_PropertyChanged;
        }
コード例 #3
0
 internal PackageRestoreManager(
     DTE dte,
     ISolutionManager solutionManager,
     IFileSystemProvider fileSystemProvider,
     IPackageRepositoryFactory packageRepositoryFactory,
     IVsPackageSourceProvider packageSourceProvider,
     IVsPackageManagerFactory packageManagerFactory,
     IVsPackageInstallerEvents packageInstallerEvents,
     IPackageRepository localCacheRepository,
     IVsThreadedWaitDialogFactory waitDialogFactory,
     ISettings settings)
 {
     Debug.Assert(solutionManager != null);
     _dte = dte;
     _fileSystemProvider = fileSystemProvider;
     _solutionManager = solutionManager;
     _packageRepositoryFactory = packageRepositoryFactory;
     _packageSourceProvider = packageSourceProvider;
     _waitDialogFactory = waitDialogFactory;
     _packageManagerFactory = packageManagerFactory;
     _localCacheRepository = localCacheRepository;
     _settings = settings;
     _solutionManager.ProjectAdded += OnProjectAdded;
     _solutionManager.SolutionOpened += OnSolutionOpenedOrClosed;
     _solutionManager.SolutionClosed += OnSolutionOpenedOrClosed;
     packageInstallerEvents.PackageReferenceAdded += OnPackageReferenceAdded;
 }
コード例 #4
0
        protected override void Initialize()
        {
            base.Initialize();

            _dte = GetGlobalService(typeof(DTE)) as DTE;
            if (_dte == null)
                return;

            OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
            if (mcs == null)
                return;

            //Solution Node
            CommandID solutionMenuCommandId = new CommandID(GuidList.GuidVsPtcCmdSet, (int)PkgCmdIdList.CmdidMyCommandSolution);
            MenuCommand solutionmMenuItem = new MenuCommand(SolutionMenuCallback, solutionMenuCommandId);
            mcs.AddCommand(solutionmMenuItem);

            //Project Node
            CommandID projectMenuCommandId = new CommandID(GuidList.GuidVsPtcCmdSet, (int)PkgCmdIdList.CmdidMyCommandProject);
            MenuCommand projectmMenuItem = new MenuCommand(ProjectMenuCallback, projectMenuCommandId);
            mcs.AddCommand(projectmMenuItem);

            //Project Item Node - File
            CommandID itemFileMenuCommandId = new CommandID(GuidList.GuidVsPtcCmdSet, (int)PkgCmdIdList.CmdidMyCommandItemFile);
            MenuCommand itemFileMenuItem = new MenuCommand(ItemFileMenuCallback, itemFileMenuCommandId);
            mcs.AddCommand(itemFileMenuItem);

            //Project Item Node - Folder
            CommandID itemFolderMenuCommandId = new CommandID(GuidList.GuidVsPtcCmdSet, (int)PkgCmdIdList.CmdidMyCommandItemFolder);
            MenuCommand itemFolderMenuItem = new MenuCommand(ItemFolderMenuCallback, itemFolderMenuCommandId);
            mcs.AddCommand(itemFolderMenuItem);
        }
コード例 #5
0
        public void OnAfterCreated(DTE DTEObject)
        {
            m_settings = new AddInSettings(DTEObject);

            lstResyncIgnoreList.Items.Clear();
            if (m_settings.ResyncIgnoreList.Length > 0)
            {
                string[] list = m_settings.ResyncIgnoreList.Split(new char[] { ';' });
                foreach (string item in list)
                {
                    if (item.Length > 0) lstResyncIgnoreList.Items.Add(item);
                }
            }
            txtResyncIgnoreList.Text = string.Empty;
            btnAddResyncIgnoreItem.Enabled = false;
            btnDeleteResyncIgnoreItem.Enabled = false;

            cbIgnoreHiddenFiles.Checked = m_settings.ResyncIgnoreHiddenFiles;

            lstSyncFolders.Items.Clear();
            if (m_settings.SyncFolderList.Length > 0)
            {
                string[] list = m_settings.SyncFolderList.Split(new char[] { ';' });
                foreach (string item in list)
                {
                    if (item.Length > 0) lstSyncFolders.Items.Add(item);
                }
            }
            txtSyncFolder.Text = string.Empty;
            btnAddSyncFolderItem.Enabled = false;
            btnDeleteSyncFolderItem.Enabled = false;
        }
コード例 #6
0
        protected override void Initialize()
        {
            base.Initialize();

            vsMonitorSelection = (IVsMonitorSelection)GetService(typeof(IVsMonitorSelection));
            dte = GetService(typeof(SDTE)) as DTE;

            if (provider == null)
            {
                var preferences = new PreferencesProvider("VisualStudio2010");
                provider = new CloudFoundryProvider(preferences);
            }

            var mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
            if (null != mcs)
            {
                mcs.AddCommand(new MenuCommand(CloudFoundryExplorer,
                               new CommandID(GuidList.guidCloudFoundryCmdSet,
                               (int)PkgCmdIDList.cmdidCloudFoundryExplorer)));

                mcs.AddCommand(new MenuCommand(PushApplication,
                               new CommandID(GuidList.guidCloudFoundryCmdSet,
                               (int)PkgCmdIDList.cmdidPushCloudFoundryApplication)));

                mcs.AddCommand(new MenuCommand(UpdateApplication,
                               new CommandID(GuidList.guidCloudFoundryCmdSet,
                               (int)PkgCmdIDList.cmdidUpdateCloudFoundryApplication)));
            }
        }
コード例 #7
0
ファイル: MDASolutionWizard.cs プロジェクト: siwiwit/andromda
 public MDASolutionWizard(DTE applicationObject, MDASolutionManager solutionManager, AddInSettings settings)
 {
     m_applicationObject = applicationObject;
     m_solutionManager = solutionManager;
     m_settings = settings;
     InitializeComponent();
 }
コード例 #8
0
ファイル: NuGetPackage.cs プロジェクト: monoman/NugetCracker
        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initialization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            base.Initialize();

            // get the UI context cookie for the debugging mode
            _vsMonitorSelection = (IVsMonitorSelection)GetService(typeof(IVsMonitorSelection));
            // get debugging context cookie
            Guid debuggingContextGuid = VSConstants.UICONTEXT_Debugging;
            _vsMonitorSelection.GetCmdUIContextCookie(ref debuggingContextGuid, out _debuggingContextCookie);

            // get the solution building cookie
            Guid solutionBuildingContextGuid = VSConstants.UICONTEXT_SolutionBuilding;
            _vsMonitorSelection.GetCmdUIContextCookie(ref solutionBuildingContextGuid, out _solutionBuildingContextCookie);

            _dte = ServiceLocator.GetInstance<DTE>();
            _consoleStatus = ServiceLocator.GetInstance<IConsoleStatus>();
            _packageRestoreManager = ServiceLocator.GetInstance<IPackageRestoreManager>();
            Debug.Assert(_packageRestoreManager != null);

            // Add our command handlers for menu (commands must exist in the .vsct file)
            AddMenuCommandHandlers();

            // when NuGet loads, if the current solution has package 
            // restore mode enabled, we make sure every thing is set up correctly.
            // For example, projects which were added outside of VS need to have
            // the <Import> element added.
            if (_packageRestoreManager.IsCurrentSolutionEnabledForRestore)
            {
                _packageRestoreManager.EnableCurrentSolutionForRestore(quietMode: true);
            }
        }
コード例 #9
0
 internal static void RedeploySolutions(DTE dte)
 {
     Helpers.ShowProgress(dte, "Redeploying solutions...", 30);
     Helpers.LogMessage(dte, dte, "*** Redeploying selected solutions ***");
     DeploymentHelpers.RedeployProject(dte, Helpers.GetSelectedDeploymentProjects(dte));
     Helpers.HideProgress(dte);
 }
コード例 #10
0
ファイル: AttachT4.cs プロジェクト: binki/Alba.Framework
        public byte[] GenerateCode (string csName, string csText, DTE dte, Func<string, Encoding> getEncoding)
        {
            string ttName = Path.ChangeExtension(csName, ".tt");

            Document ttDoc = dte.Documents.Cast<Document>().SingleOrDefault(d => d.FullName == ttName);
            if (ttDoc != null && !ttDoc.Saved)
                ttDoc.Save();

            Encoding ttEncoding;
            string ttText;

            if (File.Exists(ttName)) {
                ttEncoding = getEncoding(ttName);
                ttText = File.ReadAllText(ttName, ttEncoding);
            }
            else {
                ttEncoding = Encoding.UTF8;
                ttText = ("<#@ template hostspecific='true' debug='true' #>\n" +
                    "<#@ output extension='/' #>\n" +
                    "<#@ include file='$(SolutionDir)/Alba.Framework.CodeGeneration/Common.tt' #>\n")
                    .Replace("\n", Environment.NewLine).Replace('\'', '"');
            }

            return ttEncoding.GetBytes(ttText);
        }
コード例 #11
0
        public InformationBarMargin(IWpfTextView textView, ITextDocument document, IEditorOperations editorOperations, ITextUndoHistory undoHistory, DTE dte)
        {
            _textView = textView;
            _document = document;
            _operations = editorOperations;
            _undoHistory = undoHistory;
            _dte = dte;

            _informationBarControl = new InformationBarControl();
            _informationBarControl.Hide.Click += Hide;
            _informationBarControl.DontShowAgain.Click += DontShowAgain;
            var format = new Action(() => this.FormatDocument());
            _informationBarControl.Tabify.Click += (s, e) => this.Dispatcher.Invoke(format);

            this.Height = 0;
            this.Content = _informationBarControl;
            this.Name = MarginName;

            document.FileActionOccurred += FileActionOccurred;
            textView.Closed += TextViewClosed;

            // Delay the initial check until the view gets focus
            textView.GotAggregateFocus += GotAggregateFocus;

            this._tabDirectiveParser = new TabDirectiveParser(textView, document, dte);
            this._fileHeuristics = new FileHeuristics(textView, document, dte);

            var fix = new Action(() => this.FixFile());
            this._tabDirectiveParser.Change += (s, e) => this.Dispatcher.Invoke(fix);
        }
コード例 #12
0
       public  CodeElement GetCodeElementAtCursor(DTE dte)
        {
           try
           {
               var cursor = getCursorTextPoint(dte);
               if (cursor != null)
               {

                   var c = cursor.CodeElement[vsCMElement.vsCMElementClass];
                   if (c != null)
                   {
                       Debug.WriteLine("Found cursor in " + c.FullName);
                     
                       return c;
                   }

                   return getCodeElementAtTextPoint(vsCMElement.vsCMElementClass,
                       dte.ActiveDocument.ProjectItem.FileCodeModel.CodeElements, cursor);

               }
           }
           catch (Exception e)
           {
               _log.Error("GetCodeElementAtCursor failed", e );
           }
           return null;

        }
コード例 #13
0
ファイル: ChildWizard.cs プロジェクト: C-DUCK/Sningle
        public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
        {
            dteObject = (DTE)automationObject;
            serviceProvider = (Microsoft.VisualStudio.OLE.Interop.IServiceProvider)this.dteObject;

            IntPtr zero4 = IntPtr.Zero;
            Guid guid = typeof(SComponentModel).GUID;
            serviceProvider.QueryService(ref guid, ref IUnknownGuid, out zero4);
            componentModel = (IComponentModel)GetObjectFromNativeUnknown(zero4);

            replacementsDictionary["$ext_safeprojectname$"] = RootWizard.GlobalDictionary["$ext_safeprojectname$"];
            replacementsDictionary["$ext_projectname$"] = RootWizard.GlobalDictionary["$ext_projectname$"];

            string localDBInstance = "v11.0";
            var localDBInstances = SqlLocalDbApi.GetInstanceNames();
            if (localDBInstances.IndexOf("MSSqlLocalDB") >= 0)
                localDBInstance = "MSSqlLocalDB";
            else if (localDBInstances.IndexOf("v12.0") >= 0)
                localDBInstance = "v12.0";
            else if (localDBInstances.IndexOf("v11.0") >= 0)
                localDBInstance = "v11.0";
            else if (localDBInstances.Count > 0)
                localDBInstance = localDBInstances[0];

            replacementsDictionary["connectionString=\"Data Source=(LocalDb)\\v11.0;"] =
                "connectionString=\"Data Source=(LocalDb)\\" + localDBInstance + ";";

            if (!replacementsDictionary.TryGetValue("$wizarddata$", out wizardData))
                wizardData = null;
        }
コード例 #14
0
        protected override void Initialize()
        {
            Debug.WriteLine ("Entering Initialize() of: {0}", this);
            base.Initialize();

            _dte = (DTE)GetService(typeof(DTE));
            _events = _dte.Events;
            _documentEvents = _events.DocumentEvents;
            _documentEvents.DocumentSaved += DocumentEvents_DocumentSaved;

            var window = _dte.Windows.Item(EnvDTE.Constants.vsWindowKindOutput);

            var outputWindow = (OutputWindow)window.Object;

            _outputPane = outputWindow.OutputWindowPanes
                                      .Cast<OutputWindowPane>()
                                      .FirstOrDefault(p => p.Name == "AutoRunCustomTool")
                          ?? outputWindow.OutputWindowPanes.Add("AutoRunCustomTool");
            _errorListProvider = new ErrorListProvider(this)
                                 {
                                      ProviderName = "AutoRunCustomTool",
                                      ProviderGuid = Guid.NewGuid()
                                 };
            RegisterExtenderProvider();
        }
コード例 #15
0
        protected override void Initialize()
        {
            base.Initialize();

            _logger = new Logger();

            _dte = GetGlobalService(typeof(DTE)) as DTE;
            if (_dte == null)
                return;

            OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
            if (mcs != null)
            {
                CommandID publishCommandId = new CommandID(GuidList.GuidItemMenuCommandsCmdSet, (int)PkgCmdIdList.CmdidWebResourceDeployerPublish);
                OleMenuCommand publishMenuItem = new OleMenuCommand(PublishItemCallback, publishCommandId);
                publishMenuItem.BeforeQueryStatus += PublishItem_BeforeQueryStatus;
                publishMenuItem.Visible = false;
                mcs.AddCommand(publishMenuItem);

                CommandID editorPublishCommandId = new CommandID(GuidList.GuidEditorCommandsCmdSet, (int)PkgCmdIdList.CmdidWebResourceEditorPublish);
                OleMenuCommand editorPublishMenuItem = new OleMenuCommand(PublishItemCallback, editorPublishCommandId);
                editorPublishMenuItem.BeforeQueryStatus += PublishItem_BeforeQueryStatus;
                editorPublishMenuItem.Visible = false;
                mcs.AddCommand(editorPublishMenuItem);
            }
        }
コード例 #16
0
        protected override void Initialize()
        {
            base.Initialize();

            _logger = new Logger();

            _dte = GetGlobalService(typeof(DTE)) as DTE;
            if (_dte == null)
                return;

            // Add our command handlers for menu (commands must exist in the .vsct file)
            OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
            if (mcs != null)
            {
                // Create the command for the tool window
                CommandID windowCommandId = new CommandID(GuidList.GuidReportDeployerCmdSet, (int)PkgCmdIdList.CmdidReportDeployerWindow);
                OleMenuCommand windowItem = new OleMenuCommand(ShowToolWindow, windowCommandId);
                mcs.AddCommand(windowItem);

                // Create the command for the menu item.
                CommandID publishCommandId = new CommandID(GuidList.GuidItemMenuCommandsCmdSet, (int)PkgCmdIdList.CmdidReportDeployerPublish);
                OleMenuCommand publishMenuItem = new OleMenuCommand(PublishItemCallback, publishCommandId);
                publishMenuItem.BeforeQueryStatus += PublishItem_BeforeQueryStatus;
                publishMenuItem.Visible = false;
                mcs.AddCommand(publishMenuItem);
            }
        }
コード例 #17
0
		public BackgroundBuild2(DTE dte, OutputWindowPane pane)
		{
			_dte = dte;
			_pane = pane;
			_mainThread = SynchronizationContext.Current;
			BuildManager = new BuildManager();
		}
コード例 #18
0
 public WizardSolutionProcessor(ISynchronizeInvoke target, ConfigFile config, DTE applicationObject, AddInSettings settings)
     : base(target)
 {
     m_configuration = config;
     m_applicationObject = applicationObject;
     m_settings = settings;
 }
コード例 #19
0
 public static FileCodeModel CreateFileCodeModel(DTE dte, ProjectItem item, CodeDomProvider provider, string fileName)
 {
     if (null == item) {
         throw new ArgumentNullException("item");
     }
     return new CodeDomFileCodeModel(dte, item, provider, fileName);
 }
コード例 #20
0
        public static void ShowContextMenu(ContextMenuStrip contextMenu, DTE dte)
        {
            try
            {
                var serviceProvider = new ServiceProvider(dte as IServiceProvider);

                IVsUIShellOpenDocument sod = (IVsUIShellOpenDocument)serviceProvider.GetService(typeof(SVsUIShellOpenDocument));
                IVsUIHierarchy targetHier;
                uint[] targetId = new uint[1];
                IVsWindowFrame targetFrame;
                int isOpen;
                Guid viewId = new Guid(LogicalViewID.Primary);
                sod.IsDocumentOpen(null, 0, dte.ActiveWindow.Document.FullName,
                                   ref viewId, 0, out targetHier, targetId,
                                   out targetFrame, out isOpen);

                IVsTextView textView = VsShellUtilities.GetTextView(targetFrame);
                TextSelection selection = (TextSelection)dte.ActiveWindow.Document.Selection;
                Microsoft.VisualStudio.OLE.Interop.POINT[] interopPoint = new Microsoft.VisualStudio.OLE.Interop.POINT[1];
                textView.GetPointOfLineColumn(selection.ActivePoint.Line, selection.ActivePoint.LineCharOffset, interopPoint);

                POINT p = new POINT(interopPoint[0].x, interopPoint[0].y);

                ClientToScreen(textView.GetWindowHandle(), p);

                contextMenu.Show(new Point(p.x, p.y));
            }
            catch (Exception)
            {
                contextMenu.Show();
            }
        }
コード例 #21
0
 public WizardSolutionProcessor(ConfigFile config, DTE applicationObject, AddInSettings settings)
     : base()
 {
     m_configuration = config;
     m_applicationObject = applicationObject;
     m_settings = settings;
 }
コード例 #22
0
        protected override void Initialize()
        {
            base.Initialize();

            var mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
            if (null != mcs) {
                var id = new CommandID(GuidList.GuidCmdSet, (int)PkgCmdIDList.FormatDocumentCommand);
                _formatDocMenuCommand = new OleMenuCommand(FormatDocumentCallback, id);
                mcs.AddCommand(_formatDocMenuCommand);
                _formatDocMenuCommand.BeforeQueryStatus += OnBeforeQueryStatus;

                id = new CommandID(GuidList.GuidCmdSet, (int)PkgCmdIDList.FormatSelectionCommand);
                _formatSelMenuCommand = new OleMenuCommand(FormatSelectionCallback, id);
                mcs.AddCommand(_formatSelMenuCommand);
                _formatSelMenuCommand.BeforeQueryStatus += OnBeforeQueryStatus;
            }

            _dte = (DTE)GetService(typeof(DTE));

            _documentEventListener = new DocumentEventListener(this);
            _documentEventListener.BeforeSave += OnBeforeDocumentSave;

            if (_dte.RegistryRoot.Contains("VisualStudio")) {
                _isCSharpEnabled = true;
            }

            _props = _dte.Properties["AStyle Formatter", "General"];
            _props.Item("IsCSarpEnabled").Value = _isCSharpEnabled;
        }
コード例 #23
0
ファイル: DiagnosticsFinder.cs プロジェクト: saaadhu/naggy
 public static void Initialize(IServiceProvider serviceProvider, DTE dte)
 {
     ErrorList.Initialize(serviceProvider, dte);
     ClangServices.Initialize(dte);
     DiagnosticsBlacklist.Initialize();
     initialized = true;
 }
コード例 #24
0
 public PackageRestorer(IPackageRestorer restorer)
 {
     dte = (DTE)Package.GetGlobalService(typeof(DTE));
     buildEvents = dte.Events.BuildEvents;
     buildEvents.OnBuildBegin += BuildEvents_OnBuildBegin;
     this.restorer = restorer;
 }
コード例 #25
0
ファイル: SolutionManager.cs プロジェクト: sistoimenov/NuGet2
        internal SolutionManager(DTE dte, IVsSolution vsSolution, IVsMonitorSelection vsMonitorSelection)
        {
            if (dte == null)
            {
                throw new ArgumentNullException("dte");
            }

            _initNeeded = true;
            _dte = dte;
            _vsSolution = vsSolution;
            _vsMonitorSelection = vsMonitorSelection;

            // Keep a reference to SolutionEvents so that it doesn't get GC'ed. Otherwise, we won't receive events.
            _solutionEvents = _dte.Events.SolutionEvents;

            // can be null in unit tests
            if (vsMonitorSelection != null)
            {
                Guid solutionLoadedGuid = VSConstants.UICONTEXT.SolutionExistsAndFullyLoaded_guid;
                _vsMonitorSelection.GetCmdUIContextCookie(ref solutionLoadedGuid, out _solutionLoadedUICookie);

                uint cookie;
                int hr = _vsMonitorSelection.AdviseSelectionEvents(this, out cookie);
                ErrorHandler.ThrowOnFailure(hr);
            }
            
            _solutionEvents.BeforeClosing += OnBeforeClosing;
            _solutionEvents.AfterClosing += OnAfterClosing;
            _solutionEvents.ProjectAdded += OnProjectAdded;
            _solutionEvents.ProjectRemoved += OnProjectRemoved;
            _solutionEvents.ProjectRenamed += OnProjectRenamed;

            // Run the init on another thread to avoid an endless loop of SolutionManager -> Project System -> VSPackageManager -> SolutionManager
            ThreadPool.QueueUserWorkItem(new WaitCallback(Init));
        }
コード例 #26
0
        public DomainDispatcher(PSCmdlet cmdlet)
        {
            Contract.Requires(cmdlet != null);

            _cmdlet = cmdlet;
            _dte = (DTE)cmdlet.GetVariableValue("DTE");
        }
コード例 #27
0
        public SolutionList()
        {
            InitializeComponent();

            _logger = new Logger();

            _dte = Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(DTE)) as DTE;
            if (_dte == null)
                return;

            _dte2 = Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(DTE)) as DTE2;
            if (_dte2 == null)
                return;

            var solution = _dte.Solution;
            if (solution == null)
                return;

            var events = _dte.Events;
            var solutionEvents = events.SolutionEvents;
            solutionEvents.BeforeClosing += SolutionBeforeClosing;
            solutionEvents.ProjectRemoved += SolutionProjectRemoved;

            SetDownloadManagedEnabled(false);
            DownloadManaged.IsChecked = false;
        }
コード例 #28
0
ファイル: DriverUI.cs プロジェクト: pragmatrix/BuildOnSave
        public DriverUI(DTE dte, Window outputWindow, OutputWindowPane pane)
        {
            _dte = dte;
            _outputWindow = outputWindow;
            _pane = pane;
            _buttonTag = Guid.NewGuid().ToString();

            // http://stackoverflow.com/questions/12049362/programmatically-add-add-in-button-to-the-standard-toolbar
            // add a toolbar button to the standard toolbar
            var bar = ((CommandBars)_dte.CommandBars)["Standard"];
            if (bar != null)
            {
                var control = (CommandBarButton)bar.Controls.Add(MsoControlType.msoControlButton, Type.Missing, Type.Missing, Type.Missing, true);
                control.Style = MsoButtonStyle.msoButtonIcon;
                control.TooltipText = BarButtonControlCaption;
                control.Caption = BarButtonControlCaption;
                control.Tag = _buttonTag;
                control.BeginGroup = true;
                control.Click += (CommandBarButton ctrl, ref bool d) =>
                {
                    _outputWindow.Visible = true;
                    pane.Activate();
                };
            }
            else
            {
                Log.W("failed to add command button, no Standard command bar");
            }

            updateUI();
        }
コード例 #29
0
 public override void Execute()
 {
   dte = GetService<DTE>(true);
   RestartTimerService(dte);
   Helpers.LogMessage(dte, dte, "*** Restart OWSTimer finished ***");
   Helpers.LogMessage(dte, dte, "");
 }
コード例 #30
0
        bool TryInitialize()
        {
            try
            {
                _dte = SiteManager.GetGlobalService<DTE>();
                _running = _dte != null;
            }
            catch
            {
                _running = false;
            }
            if (!_running) return false;
            // TODO:  seen in the wild, _dte.Solution is null (?), need to schedule and restart initialization for those scenarios.
            _solution = new DteSolution(_dte.Solution);
            _solution.ProjectChanged += HandleProjectChange;
            var environment = ServiceLocator.GetService<IEnvironment>();
            _packageManager = ServiceLocator.GetService<IPackageManager>();

            _assembliesChanged = new EventWaitHandle(false, EventResetMode.AutoReset, System.Diagnostics.Process.GetCurrentProcess().Id + ASSEMBLY_NOTIFY);
            _rootDirectory = environment.DescriptorFile.Parent;
            _projectRepository = environment.ProjectRepository;
            RegisterFileListener();
            RefreshProjects();
            _timer = new Timer(_ => RefreshProjects(), null, Timeout.Infinite, Timeout.Infinite);
            return true;
        }
コード例 #31
0
 public VsProjectWrapper(IVsProject project, DTE dte, ILogger logger)
 {
     this.Project = project ?? throw new ArgumentNullException(nameof(project));
     this.Dte     = dte ?? throw new ArgumentNullException(nameof(dte));
     this.Logger  = logger;
 }
コード例 #32
0
        private void LoadHierarchy()
        {
            //For Design time only
            if (this.serviceProvider != null)
            {
                DTE vs = (DTE)this.serviceProvider.GetService(typeof(DTE));

                trvHierarchy.Nodes.Add(
                    UISolutionHierarchy.CreateHierarchy(vs.Solution,
                                                        delegate(Project project)
                {
                    return(project != null ||
                           (project != null && project.Object is SolutionFolder));
                },
                                                        delegate(ProjectItem projectItem)
                {
                    return
                    (projectItem.Kind.Equals(Constants.vsProjectItemKindPhysicalFolder) ||
                     projectItem.Name.EndsWith(SchemaExtension, StringComparison.OrdinalIgnoreCase) ||
                     projectItem.Name.EndsWith(WsdlExtension, StringComparison.OrdinalIgnoreCase));
                },
                                                        delegate(TreeNode node)
                {
                    if (node.Tag is Solution)
                    {
                        SetImage(node, 0);
                    }
                    else if (node.Tag is Project)
                    {
                        Project project = node.Tag as Project;

                        if (project.Object is SolutionFolder)
                        {
                            SetImage(node, 10);
                            return;
                        }

                        switch (project.Kind)
                        {
                        case CSharpProject:
                            if (HasProperty(project.Properties, "CurrentWebsiteLanguage"))
                            {
                                SetImage(node, 4);
                                break;
                            }

                            SetImage(node, 2);
                            break;

                        case VBProject:
                            if (HasProperty(project.Properties, "CurrentWebsiteLanguage"))
                            {
                                SetImage(node, 5);
                                break;
                            }

                            SetImage(node, 3);
                            break;

                        default:
                            SetImage(node, 2);
                            break;
                        }
                    }
                    else if (node.Tag is ProjectItem)
                    {
                        ProjectItem projectItem = node.Tag as ProjectItem;

                        if (projectItem.Kind.Equals(Constants.vsProjectItemKindPhysicalFolder))
                        {
                            SetImage(node, 1);
                        }
                        else
                        {
                            // XSD project item
                            SetImage(node, 7);
                        }
                    }
                }
                                                        ));
            }
        }
コード例 #33
0
        public VisualStudioInstance(Process hostProcess, DTE dte, ImmutableHashSet <string> supportedPackageIds, string installationPath)
        {
            HostProcess         = hostProcess;
            Dte                 = dte;
            SupportedPackageIds = supportedPackageIds;
            InstallationPath    = installationPath;

            if (System.Diagnostics.Debugger.IsAttached)
            {
                // If a Visual Studio debugger is attached to the test process, attach it to the instance running
                // integration tests as well.
                var debuggerHostDte = GetDebuggerHostDte();
                int targetProcessId = Process.GetCurrentProcess().Id;
                var localProcess    = debuggerHostDte?.Debugger.LocalProcesses.OfType <EnvDTE80.Process2>().FirstOrDefault(p => p.ProcessID == hostProcess.Id);
                if (localProcess != null)
                {
                    localProcess.Attach2("Managed");
                }
            }

            StartRemoteIntegrationService(dte);

            _integrationServiceChannel = new IpcClientChannel(GetIpcClientChannelName(HostProcess), sinkProvider: null);
            ChannelServices.RegisterChannel(_integrationServiceChannel, ensureSecurity: true);

            // Connect to a 'well defined, shouldn't conflict' IPC channel
            _integrationService = IntegrationService.GetInstanceFromHostProcess(hostProcess);

            // Create marshal-by-ref object that runs in host-process.
            _inProc = ExecuteInHostProcess <VisualStudio_InProc>(
                type: typeof(VisualStudio_InProc),
                methodName: nameof(VisualStudio_InProc.Create)
                );

            // There is a lot of VS initialization code that goes on, so we want to wait for that to 'settle' before
            // we start executing any actual code.
            _inProc.WaitForSystemIdle();

            ChangeSignatureDialog = new ChangeSignatureDialog_OutOfProc(this);
            InteractiveWindow     = new CSharpInteractiveWindow_OutOfProc(this);
            ObjectBrowserWindow   = new ObjectBrowserWindow_OutOfProc(this);
            Debugger               = new Debugger_OutOfProc(this);
            Dialog                 = new Dialog_OutOfProc(this);
            Editor                 = new Editor_OutOfProc(this);
            EncapsulateField       = new EncapsulateField_OutOfProc(this);
            ErrorList              = new ErrorList_OutOfProc(this);
            ExtractInterfaceDialog = new ExtractInterfaceDialog_OutOfProc(this);
            FindReferencesWindow   = new FindReferencesWindow_OutOfProc(this);
            GenerateTypeDialog     = new GenerateTypeDialog_OutOfProc(this);
            InlineRenameDialog     = new InlineRenameDialog_OutOfProc(this);
            ImmediateWindow        = new ImmediateWindow_OutOfProc(this);
            LocalsWindow           = new LocalsWindow_OutOfProc(this);
            MoveToNamespaceDialog  = new MoveToNamespaceDialog_OutOfProc(this);
            PickMembersDialog      = new PickMembersDialog_OutOfProc(this);
            PreviewChangesDialog   = new PreviewChangesDialog_OutOfProc(this);
            Shell            = new Shell_OutOfProc(this);
            SolutionExplorer = new SolutionExplorer_OutOfProc(this);
            Workspace        = new VisualStudioWorkspace_OutOfProc(this);
            StartPage        = new StartPage_OutOfProc(this);

            SendKeys = new SendKeys(this);

            // Ensure we are in a known 'good' state by cleaning up anything changed by the previous instance
            CleanUp();
        }
コード例 #34
0
 private void OverwriteFile(DTE vs, string fullPath, string content)
 {
     VsHelper.EnsureWriteable(vs, fullPath);
 }
コード例 #35
0
        /// <summary>
        /// Attaches the registration recipes to the package project.
        /// </summary>
        public override void Execute()
        {
            DTE vs = GetService <DTE>(true);

            vs.Solution.SolutionBuild.BuildDependencies.Item(parent).AddProject(dependencyProject.UniqueName);
        }
コード例 #36
0
        public override void Execute()
        {
            DTE dte = GetService <DTE>(true);

            int success     = 0;
            int failures    = 0;
            int overwritten = 0;

            //is item selected, then copy only the item
            if (dte.SelectedItems.Count > 0)
            {
                foreach (SelectedItem item in dte.SelectedItems)
                {
                    if (item is ProjectItem)
                    {
                        DeploymentHelpers.QuickDeployItem(dte, item as ProjectItem, ref success, ref failures, ref overwritten);
                        Helpers.LogMessage(dte, dte, "*** Quick Deploy finished: " + success.ToString() + " successfully (" + overwritten.ToString() + " overwrites), " + failures.ToString() + " failed ***" + Environment.NewLine);
                    }
                    else if (item.ProjectItem is ProjectItem)
                    {
                        DeploymentHelpers.QuickDeployItem(dte, item.ProjectItem as ProjectItem, ref success, ref failures, ref overwritten);
                        Helpers.LogMessage(dte, dte, "*** Quick Deploy finished: " + success.ToString() + " successfully (" + overwritten.ToString() + " overwrites), " + failures.ToString() + " failed ***" + Environment.NewLine);
                    }
                    else if (item.Project != null)
                    {
                        if (item.Project.Object is SolutionFolder)
                        {
                            //solution folder selected
                            SolutionFolder sfolder = item.Project.Object as SolutionFolder;
                            foreach (ProjectItem pitem in sfolder.Parent.ProjectItems)
                            {
                                if (pitem.Object is Project)
                                {
                                    DeploymentHelpers.QuickDeploy(dte, pitem.Object as Project);
                                }
                            }
                        }
                        else
                        {
                            //project selected
                            DeploymentHelpers.QuickDeploy(dte, item.Project);
                        }
                    }
                    else if ((item.Project == null) && (item.ProjectItem == null))
                    {
                        //solution selected
                        List <Project> projects = Helpers.GetSelectedDeploymentProjects(dte);
                        foreach (Project project in projects)
                        {
                            //deployEachProject
                            DeploymentHelpers.QuickDeploy(dte, project);
                        }
                    }
                }
            }
            else
            {
                List <Project> projects = Helpers.GetSelectedDeploymentProjects(dte);
                foreach (Project project in projects)
                {
                    //deployEachProject
                    DeploymentHelpers.QuickDeploy(dte, project);
                }
            }
        }
コード例 #37
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 async void Execute(object sender, EventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            DTE dte = (DTE)await this.ServiceProvider.GetServiceAsync(typeof(DTE));

            foreach (SelectedItem item in dte.SelectedItems)
            {
                ProjectItem pi   = item.ProjectItem;
                string      type = null;
                switch (pi.ContainingProject.CodeModel.Language)
                {
                case CodeModelLanguageConstants.vsCMLanguageCSharp:
                    type = "csharp_out";
                    break;

                case CodeModelLanguageConstants.vsCMLanguageVC:
                    type = "cpp_out";
                    break;

                default:
                    break;
                }
                if (type != null)
                {
                    string srcFile = pi.FileNames[0];
                    string tmpFile = Path.GetTempPath() + pi.GetHashCode() + ".proto";
                    File.Copy(srcFile, tmpFile, true);
                    this.ClearItems(pi);
                    string path = Path.GetTempPath() + pi.GetHashCode();
                    if (Directory.Exists(path))
                    {
                        Directory.Delete(path, true);
                    }
                    Directory.CreateDirectory(path);
                    ProcessStartInfo psi = new ProcessStartInfo(this.protocPath, $"\"{pi.Name}\" --{type}=\"{path}\"");
                    psi.UseShellExecute  = false;
                    psi.CreateNoWindow   = true;
                    psi.WorkingDirectory = Path.GetDirectoryName(srcFile);
                    using (Process p = Process.Start(psi))
                    {
                        if (p?.WaitForExit(10 * 1000) == true)
                        {
                            string[] dstFiles = Directory.GetFiles(path);
                            if (dstFiles.Length != 0)
                            {
                                string srcDir  = Path.GetDirectoryName(srcFile);
                                string srcName = Path.GetFileNameWithoutExtension(srcFile);
                                int    count   = 0;
                                switch (type)
                                {
                                case "csharp_out":
                                    count = 1;
                                    break;

                                case "cpp_out":
                                    srcDir   = Path.Combine(srcDir, "generate");
                                    srcName += ".pb";
                                    count    = 2;
                                    break;
                                }
                                if (dstFiles.Length == count)
                                {
                                    if (Directory.Exists(srcDir) == false)
                                    {
                                        Directory.CreateDirectory(srcDir);
                                    }
                                    for (int i = 0; i < count; i++)
                                    {
                                        string dstExt  = Path.GetExtension(dstFiles[i]);
                                        string dstFile = Path.Combine(srcDir, srcName + dstExt);
                                        File.Copy(dstFiles[i], dstFile, true);
                                        pi.ProjectItems.AddFromFile(dstFile);
                                    }
                                }
                            }
                        }
                    }
                    Directory.Delete(path, true);
                    File.Delete(tmpFile);
                }
            }
        }
コード例 #38
0
 public virtual List <NameValueItem> GetItems(DTE dte, IServiceProvider provider)
 {
     return(new List <NameValueItem>());
 }
コード例 #39
0
 public MonoVisualStudioExtension(Package package, DTE dte)
 {
     _dte = dte;
     _errorListProvider = new ErrorListProvider(package);
 }
コード例 #40
0
 public CodeDomCodeElements(DTE dte, object parent)
 {
     this.dte    = dte;
     this.parent = parent;
 }
コード例 #41
0
        /// <summary> Run started </summary>
        /// <param name="automationObject">Automation Object</param>
        /// <param name="replacementsDictionary">Replacements</param>
        /// <param name="runKind">Run Kind</param>
        /// <param name="customParams">Custom Params</param>
        public void RunStarted(object automationObject,
                               Dictionary <string, string> replacementsDictionary,
                               WizardRunKind runKind, object[] customParams)
        {
            _dte = (DTE)automationObject;

            _solutionFolder    = replacementsDictionary["$solutiondirectory$"];
            _destinationFolder = replacementsDictionary["$destinationdirectory$"];
            _safeprojectname   = replacementsDictionary["$safeprojectname$"];

            try
            {
                // Display a form to the user. The form collects
                // input for the custom message.
                var inputForm = new UserInputForm();

                // Default the location for the Kendo folder
                var webFolder = RegistryHelper.Sage300CWebFolder;
                inputForm.KendoDefaultFolder = Path.Combine(webFolder, "Scripts", "Kendo");

                var res = inputForm.ShowDialog();

                // cancel wizard
                if (res != DialogResult.OK)
                {
                    throw new WizardBackoutException();
                }

                // save parameters
                _companyName            = inputForm.ThirdPartyCompanyName.Trim();
                _applicationId          = inputForm.ThirdPartyApplicationId.Trim();
                _lowercaseapplicationId = _applicationId.ToLower();
                _namespace                 = inputForm.CompanyNamespace.Trim();
                _sage300Webfolder          = webFolder;
                _kendoFolder               = inputForm.KendoFolder.Trim();
                _includeEnglish            = inputForm.IncludeEnglish;
                _includeChineseSimplified  = inputForm.IncludeChineseSimplified;
                _includeChineseTraditional = inputForm.IncludeChineseTraditional;
                _includeSpanish            = inputForm.IncludeSpanish;
                _includeFrench             = inputForm.IncludeFrench;

                // Add custom parameters.
                replacementsDictionary.Add("$companyname$", _companyName);
                replacementsDictionary.Add("$applicationid$", _applicationId);
                replacementsDictionary.Add("$companynamespace$", _namespace);
                replacementsDictionary.Add("$sage300webfolder$", _sage300Webfolder);
                replacementsDictionary.Add("$lowercaseapplicationid$", _lowercaseapplicationId);
            }
            catch
            {
                // Clean up the template that was written to disk
                if (Directory.Exists(_solutionFolder))
                {
                    try
                    {
                        Directory.Delete(_solutionFolder);
                    }
                    catch
                    {
                        ; // don't care
                    }
                }

                throw;
            }
        }
コード例 #42
0
        public override object EditValue(ITypeDescriptorContext context,
                                         IServiceProvider provider, object value)
        {
            DTE dte = (DTE)provider.GetService(typeof(DTE));

            try
            {
                List <NameValueItem> nvitems = this.GetItems(dte, provider);

                SortItems(nvitems);

                object svc = provider.GetService(typeof(IWindowsFormsEditorService));
                if (svc == null)
                {
                    return(base.EditValue(context, provider, value));
                }

                SelectionForm form = new SelectionForm(nvitems, value, false);
                if (((IWindowsFormsEditorService)svc).ShowDialog(form) == DialogResult.OK)
                {
                    if (context.Instance != null)
                    {
                        if (context.Instance is String)
                        {
                            if (context.Instance.ToString() == "NameValueItem")
                            {
                                return(form.SelectedNameValueItem);
                            }
                        }
                    }
                    if (value is NameValueItem[])
                    {
                        return(form.SelectedNameValueItems);
                    }
                    else if (value is NameValueItem)
                    {
                        return(form.SelectedNameValueItem);
                    }
                    else
                    {
                        if (form.SelectedNameValueItem != null)
                        {
                            return(form.SelectedNameValueItem.Value);
                        }
                        else
                        {
                            return("");
                        }
                    }
                }
                else
                {
                    return(value);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            return(null);
        }
コード例 #43
0
 /// <summary>
 /// Fluent Migrator menu should only be visible if we can find a reference
 /// to the Fluent Migrator NuGet package
 /// </summary>
 /// <param name="dte"></param>
 /// <returns></returns>
 public static bool ShouldMenuBeVisible(DTE dte) =>
 HasFluentMigratorReference(GetSelectedProject(dte));
コード例 #44
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)
        {
            DTE              dte        = Package.GetGlobalService(typeof(SDTE)) as DTE;
            Solution2        currSol2   = (EnvDTE80.Solution2)dte.Solution;
            CommandUtilities util       = new CommandUtilities(this.ServiceProvider);
            ProjectItem      currItem   = null;
            ProjectItem      configItem = null;
            String           configName = "Innovator.config";

            if (dte.ActiveDocument == null)
            {
                util.showError("No active window.", "Active Window Required");
                return;
            }

            Project currProj = dte.ActiveDocument.ProjectItem.ContainingProject;

            if (string.IsNullOrEmpty(currProj.FullName))
            {
                util.showError("Method must be in a project.", "Project Required");
                return;
            }

            try
            {
                configItem = currProj.ProjectItems.Item(configName);
            }
            catch (ArgumentException)
            {
                util.showError("Required Innovator.config file not found in selected project.", "Config File Not Found");
                return;
            }

            string      configPath = configItem.FileNames[0];
            XmlDocument configXML  = new XmlDocument();

            configXML.Load(configPath);

            Dictionary <string, string> configDic = util.ReadConfigFile(configXML);
            string val = "";

            if (configDic.TryGetValue("failCheck", out val))
            {
                return;
            }

            string csTemplateName;

            configDic.TryGetValue("csTemplateName", out csTemplateName);
            string jsTemplateName;

            configDic.TryGetValue("jsTemplateName", out jsTemplateName);
            string methodInsertTag;

            configDic.TryGetValue("methodInsertTag", out methodInsertTag);
            string methodEndTag;

            configDic.TryGetValue("methodEndTag", out methodEndTag);
            string serverName;

            configDic.TryGetValue("deployment_serverName", out serverName);
            string databaseName;

            configDic.TryGetValue("deployment_databaseName", out databaseName);
            string loginName;

            configDic.TryGetValue("deployment_loginName", out loginName);
            string loginPassword;

            configDic.TryGetValue("deployment_loginPassword", out loginPassword);
            string defaultMethodSearch;

            configDic.TryGetValue("defaultMethodSearch", out defaultMethodSearch);

            string fileName   = dte.ActiveDocument.Name;
            string methodName = fileName.Substring(0, fileName.LastIndexOf('.'));

            try
            {
                currItem = dte.ActiveDocument.ProjectItem;
            }
            catch (ArgumentException)
            {
                util.showError("Method file not found in current project.", "Method File Not Found");
                return;
            }

            string filePath      = currItem.FileNames[0];
            string templateLines = File.ReadAllText(filePath);
            int    insertIndex   = templateLines.IndexOf(methodInsertTag) + methodInsertTag.Length;
            int    endIndex      = templateLines.IndexOf(methodEndTag);

            //Connect to Aras Server
            HttpServerConnection connection;

            Aras.IOM.Innovator inn;

            connection = IomFactory.CreateHttpServerConnection(serverName, databaseName, loginName, loginPassword);
            Aras.IOM.Item iLogin = connection.Login();
            if (iLogin.isError())
            {
                util.showError("Unable to connect to Aras Innovator with the deployment server, database, and login information provided in Innovator.config of the active project.", "Connection Error");
                return;
            }

            inn = new Aras.IOM.Innovator(connection);

            Item iQry = inn.newItem();

            iQry.loadAML(string.Format(@"<Item type='Method' action='lock' where=""[Method].name='{0}' and [Method].is_current='1'""  doGetItem='0'/>", methodName));
            iQry = iQry.apply();

            connection.Logout();

            if (iQry.isError())
            {
                util.showError(iQry.getErrorString(), "Error");
                return;
            }

            //string methodCode = iQry.getProperty("method_code");

            //string modifiedLines = templateLines.Substring(0, insertIndex) + "\n" + methodCode + "\n" + templateLines.Substring(endIndex);

            //File.WriteAllText(filePath, modifiedLines);

            util.setStatusBar(string.Format("Success: {0} was succesfully locked on the deployment server with method ", methodName));
        }
コード例 #45
0
ファイル: EnvHelper.cs プロジェクト: laurentkempe/TGit
 public EnvHelper(DTE dte)
 {
     _dte   = dte;
     _cache = new MemoryCache("TGIT");
 }
コード例 #46
0
        private void LoadInitialState()
        {
            if (this.template.ExtensionData.Recipe == null)
            {
                return;
            }
            DTE dte = (DTE)GetService(typeof(DTE));
            IAssetReferenceService referenceService = (IAssetReferenceService)
                                                      this.Package.GetService(typeof(IAssetReferenceService), false);

            if (referenceService != null)
            {
                IAssetReference templateAsset = null;
                try
                {
                    object target = DteHelper.GetTarget(dte);
                    templateAsset = referenceService.GetReferenceFor(this.Template.FileName, target);
                    if (templateAsset == null)
                    {
                        if (this.Template.Kind == TemplateKind.Project && target is Project)                         // If the template is been unfolded, then check the parent folder
                        {
                            Project parentProject = (target as Project).ParentProjectItem.ContainingProject;
                            if (parentProject != null)                             // Parent folder exist, check the reference to the template
                            {
                                templateAsset = referenceService.GetReferenceFor(this.Template.FileName, parentProject);
                            }
                            else                             // The parent folder is the solution root, check the reference in the solutioin root
                            {
                                templateAsset = referenceService.GetReferenceFor(this.Template.FileName, dte.Solution);
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    templateAsset = null;
                }
                if (templateAsset != null)
                {
                    IPersistenceService persistenceService = (IPersistenceService)this.Package.GetService(typeof(IPersistenceService), false);
                    if (persistenceService != null)
                    {
                        IDictionary hashStored = persistenceService.LoadState(this.Template.PackageName, templateAsset);
                        if (hashStored != null)
                        {
                            ArrayList toremove = new ArrayList(hashStored.Count);
                            foreach (DictionaryEntry keyValuePair in hashStored)
                            {
                                if (this.templateDictionary.GetValue(keyValuePair.Key) == null)
                                {
                                    try
                                    {
                                        this.templateDictionary.SetValue(keyValuePair.Key, keyValuePair.Value);
                                    }
                                    catch
                                    {
                                        string appliesTo;
                                        try
                                        {
                                            appliesTo = templateAsset.AppliesTo;
                                        }
                                        catch (Exception e)
                                        {
                                            this.TraceWarning(e.Message);
                                            appliesTo = Properties.Resources.Reference_AppliesToThrew;
                                        }
                                        // Invalid initial state should just be ignored.
                                        this.TraceWarning(Properties.Resources.Template_IgnoreKeyInitialState, keyValuePair.Key, templateAsset.AppliesTo);
                                        toremove.Add(keyValuePair.Key);
                                    }
                                }
                            }
                            foreach (object key in toremove)
                            {
                                hashStored.Remove(key);
                            }
                            if (toremove.Count != 0)
                            {
                                // Save the updated one without the offending values.
                                persistenceService.SaveState(this.template.PackageName, templateAsset, hashStored);
                            }
                        }
                    }
                }
            }
        }
コード例 #47
0
        // returns a valid Guid if the project was reloaded or an empty Guid if the project did not need to be reloaded
        static public Guid ReloadProject(Project project)
        {
            Logging.Logging.LogInfo("Attempting to reload project");

            try
            {
                if (project != null && project.Kind == EnvDTE.Constants.vsProjectKindUnmodeled)
                {
                    DTE dte = project.DTE;

                    ServiceProvider sp         = new ServiceProvider(dte as Microsoft.VisualStudio.OLE.Interop.IServiceProvider);
                    IVsSolution     vsSolution = sp.GetService(typeof(IVsSolution)) as IVsSolution;

                    IVsHierarchy hierarchy;

                    string solutionDirectory = "";
                    string solutionFile      = "";
                    string userOptions       = "";
                    vsSolution.GetSolutionInfo(out solutionDirectory, out solutionFile, out userOptions);

                    vsSolution.GetProjectOfUniqueName(solutionDirectory + project.UniqueName, out hierarchy);

                    if (hierarchy != null)
                    {
                        Guid projectGuid;

                        hierarchy.GetGuidProperty(
                            VSConstants.VSITEMID_ROOT,
                            (int)__VSHPROPID.VSHPROPID_ProjectIDGuid,
                            out projectGuid);

                        if (projectGuid != null)
                        {
                            Logging.Logging.LogInfo("Project '" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(project.Name) + "' with GUID {" + projectGuid.ToString() + "} loaded.");
                            (vsSolution as IVsSolution4).ReloadProject(projectGuid);
                            return(projectGuid);
                        }
                        else
                        {
                            Logging.Logging.LogError("Failed to load project '" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(project.Name) + "'");
                        }
                    }
                    else
                    {
                        Logging.Logging.LogError("Failed to retrieve IVsHierarchy. Can't load project '" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(project.Name) + "'");
                    }
                }
                else
                {
                    if (project == null)
                    {
                        Logging.Logging.LogWarning("Project is null");
                    }
                    else
                    {
                        Logging.Logging.LogInfo("Project '" + Logging.Obfuscation.NameObfuscator.GetObfuscatedName(project.Name) + "' is already loaded");
                    }
                }
            }
            catch (Exception e)
            {
                Logging.Logging.LogError("Exception: " + e.Message);

                return(Guid.Empty);
            }

            return(Guid.Empty);
        }
コード例 #48
0
        private static void BuildProject(DTE dte, Project project)
        {
            var solutionBuild = dte.Solution.SolutionBuild;

            solutionBuild.BuildProject(solutionBuild.ActiveConfiguration.Name, project.UniqueName, true);
        }
コード例 #49
0
ファイル: VisualStudioDebugger.cs プロジェクト: Aggror/Stride
 private VisualStudioDebugger(STAContext context, DTE dte, int processId)
 {
     this.context   = context;
     this.dte       = dte;
     this.ProcessId = processId;
 }
コード例 #50
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SolutionService"/> class.
 /// </summary>
 /// <param name="dte">The Visual Studio DTE.</param>
 public SolutionService(DTE dte)
 {
     _dte = dte;
 }
コード例 #51
0
 public static void Initialize(Package package, DTE dte)
 {
     Instance = new GoToCodeCmd(package, dte);
 }
コード例 #52
0
 public VsSolutionEvents(DTE dte, XrmToolingConnection xrmToolingConnection)
 {
     _dte = dte;
     _xrmToolingConnection = xrmToolingConnection;
 }
コード例 #53
0
        public void RunStarted(object automationObject, Dictionary <string, string> replacementsDictionary, WizardRunKind runKind,
                               object[] customParams)
        {
            dte = automationObject as DTE;
            destinationDirectory = replacementsDictionary["$destinationdirectory$"];
            solutionName         = replacementsDictionary["$specifiedsolutionname$"];
            solutionDirectory    = replacementsDictionary["$solutiondirectory$"];

            try {
                window = new WizardMainWindow(VsUtility.CreateIdentifierSafeName(replacementsDictionary["$safeprojectname$"]));

                Nullable <bool> dialogCompleted = window.ShowModal();

                if (dialogCompleted != true || !window.finished)
                {
                    throw new WizardBackoutException();
                }

                string version      = dte.Version;
                bool   winXpSupport = window.cbWinXpSupport.IsChecked == true;

                string toolsetVersion;
                if (version == "14.0")
                {
                    toolsetVersion = winXpSupport ? "v140_xp" : "v140";
                }
                else if (version == "15.0")
                {
                    toolsetVersion = winXpSupport ? "v141_xp" : "v141";
                }
                else
                {
                    toolsetVersion = winXpSupport ? "v141_xp" : "v142";
                }

                pluginType = window.cmbProjectType.SelectedIndex;

                bOnlySa = window.IsSaSelected() && !window.IsVcOrIIISelected();

                string projectConfigurations       = "";
                string propertyGroupConfigurations = "";
                string importGroupPropertySheets   = "";
                string propertyGroupDirs           = "";
                string itemDefinitionGroups        = "";

                if (window.cbSA.IsChecked == true)
                {
                    SetupConfiguration(ref projectConfigurations, ref propertyGroupConfigurations, ref importGroupPropertySheets,
                                       ref propertyGroupDirs, ref itemDefinitionGroups, "Release", false, "GTASA", "SA", toolsetVersion);
                    SetupConfiguration(ref projectConfigurations, ref propertyGroupConfigurations, ref importGroupPropertySheets,
                                       ref propertyGroupDirs, ref itemDefinitionGroups, "Debug", true, "GTASA", "SA", toolsetVersion);
                }
                if (window.cbVC.IsChecked == true)
                {
                    SetupConfiguration(ref projectConfigurations, ref propertyGroupConfigurations, ref importGroupPropertySheets,
                                       ref propertyGroupDirs, ref itemDefinitionGroups, "Release", false, "GTAVC", "VC", toolsetVersion);
                    SetupConfiguration(ref projectConfigurations, ref propertyGroupConfigurations, ref importGroupPropertySheets,
                                       ref propertyGroupDirs, ref itemDefinitionGroups, "Debug", true, "GTAVC", "VC", toolsetVersion);
                }
                if (window.cbIII.IsChecked == true)
                {
                    SetupConfiguration(ref projectConfigurations, ref propertyGroupConfigurations, ref importGroupPropertySheets,
                                       ref propertyGroupDirs, ref itemDefinitionGroups, "Release", false, "GTA3", "III", toolsetVersion);
                    SetupConfiguration(ref projectConfigurations, ref propertyGroupConfigurations, ref importGroupPropertySheets,
                                       ref propertyGroupDirs, ref itemDefinitionGroups, "Debug", true, "GTA3", "III", toolsetVersion);
                }

                replacementsDictionary.Add("$ToolsVersion$", version);
                replacementsDictionary.Add("$PluginSdkGuid$", "{B212DDA4-2A8E-45B2-914D-7BEEB31D06B1}");

                replacementsDictionary.Add("$ProjectConfigurations$", projectConfigurations);
                replacementsDictionary.Add("$PropertyGroupConfigurations$", propertyGroupConfigurations);
                replacementsDictionary.Add("$ImportGroupPropertySheets$", importGroupPropertySheets);
                replacementsDictionary.Add("$PropertyGroupDirs$", propertyGroupDirs);
                replacementsDictionary.Add("$ItemDefinitionGroups$", itemDefinitionGroups);

                string targetPlaformVersion = "";
                if (version == "14.0" || version == "15.0")
                {
                    if (winXpSupport)
                    {
                        targetPlaformVersion = "7.0";
                    }
                    else if (version == "15.0")
                    {
                        try
                        {
                            RegistryKey regKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
                            object      v      = regKey.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SDKs\Windows\v10.0").GetValue("ProductVersion");
                            if (v != null)
                            {
                                targetPlaformVersion = (v as string) + ".0";
                            }
                            else
                            {
                                v = regKey.OpenSubKey(@"SOFTWARE\Microsoft\Microsoft SDKs\Windows\v8.1").GetValue("ProductVersion");
                                if (v != null)
                                {
                                    targetPlaformVersion = "8.1";
                                }
                            }
                        }
                        catch (Exception) { }
                    }
                }
                if (!string.IsNullOrEmpty(targetPlaformVersion))
                {
                    targetPlaformVersion = "\n    <WindowsTargetPlatformVersion>" + targetPlaformVersion + "</WindowsTargetPlatformVersion>";
                }
                replacementsDictionary.Add("$TargetPlatformVersion$", targetPlaformVersion);

                string sourceFileName = window.safeProjectName + ".cpp";

                replacementsDictionary.Add("$SourceFileName$", sourceFileName);

                string headersAndSources        = "";
                string filtersHeadersAndSources = "";

                GetHeadersAndSources(ref headersAndSources, sourceFileName, false, pluginType == 2);
                GetHeadersAndSources(ref filtersHeadersAndSources, sourceFileName, true, pluginType == 2);

                replacementsDictionary.Add("$HeadersAndSources$", headersAndSources);
                replacementsDictionary.Add("$FiltersHeadersAndSources$", filtersHeadersAndSources);

                string projname  = window.safeProjectName;
                string className = VsUtility.FormatName(window.tbBaseClassName.Text, projname, projname, "", "", "", "", "", "");
                className = VsUtility.CreateIdentifierSafeName(className);
                string instanceName = "";
                if (className[0] >= 'A' && className[0] <= 'Z')
                {
                    string lowerLetter = "";
                    lowerLetter += className[0];
                    lowerLetter  = lowerLetter.ToLower();
                    instanceName = lowerLetter + className.Substring(1, className.Length - 1);
                }
                else
                {
                    if (className[0] == '_')
                    {
                        instanceName = className + "_inst";
                    }
                    else
                    {
                        instanceName = "_" + className;
                    }
                }
                replacementsDictionary.Add("$projname$", projname);
                replacementsDictionary.Add("$classname$", className);
                replacementsDictionary.Add("$classinstancename$", instanceName);
            }
            catch (Exception) {
                if (Directory.Exists(destinationDirectory))
                {
                    DirectoryInfo parentDir = Directory.GetParent(destinationDirectory);
                    if (parentDir.Exists && parentDir.Name == solutionName)
                    {
                        Directory.Delete(parentDir.FullName, true);
                    }
                    else
                    {
                        Directory.Delete(destinationDirectory, true);
                    }
                }
                throw;
            }
        }
コード例 #54
0
 public void RunStarted(object automationObject, Dictionary <string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
 {
     _dte = (DTE)automationObject;
     _destinationDirectory = replacementsDictionary[VSTemplateKeys.DestinationDirectory];
     _solutionName         = replacementsDictionary[VSTemplateKeys.SafeProjectName];
 }
コード例 #55
0
ファイル: BuildTracker.cs プロジェクト: cohenw/strokes
 /// <summary>
 /// Initializes a new instance of the <see cref="BuildTracker"/> class.
 /// </summary>
 /// <param name="dte">The DTE.</param>
 /// <param name="achievementService"></param>
 public BuildTracker(DTE dte, IAchievementService achievementService)
 {
     this.dte = dte;
     this.achievementService = achievementService;
 }
コード例 #56
0
 public CodeDomCodeStruct(DTE dte, CodeElement parent, CodeTypeDeclaration declaration)
     : base(dte, parent, (null == declaration) ? null : declaration.Name)
 {
     CodeObject = declaration;
 }
コード例 #57
0
 public ExtendedDebugTaskRunnerHostController(IUnitTestLaunchManager launchManager, IUnitTestAgentManager agentManager, util::JetBrains.Util.Lazy.Lazy <IVsDebugger2> debugger2, DTE dte, IThreading threading, IUnitTestLaunch launch, int port)
     : base(launchManager, agentManager, debugger2, dte, threading, launch, port)
 {
     this.port = port;
 }
コード例 #58
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)
        {
            DTE          dte    = Package.GetGlobalService(typeof(DTE)) as DTE;
            Document     doc    = dte.ActiveDocument;
            TextDocument txtDoc = doc.Object() as TextDocument;
            var          text   = txtDoc.CreateEditPoint(txtDoc.StartPoint).GetText(txtDoc.EndPoint);

            text = text.Replace("\r", "");

            uint cookie = 0;

            StatusBar.Progress(ref cookie, 1, string.Empty, 0, 0);

            if (txtDoc.Language == "HTMLX" || txtDoc.Language == "HTML")
            {
                var html           = text;
                var elementList    = new List <HtmlElement>();
                var parsed         = _parser.ParseHtml(html, elementList, txtDoc, StatusBar, ref cookie);
                var cssFileContent = string.Empty;

                if (elementList.Any())
                {
                    foreach (var item in elementList)
                    {
                        var cssClass = string.Empty;
                        if (string.IsNullOrEmpty(item.Class))
                        {
                            cssClass = string.Format(".{0}", string.IsNullOrEmpty(item.Id) ? CreateUniqueElementKey(item.Name, item.LineNumber) : item.Id);
                        }
                        else
                        {
                            cssClass = string.Format(".{0} .{1}", item.Class, CreateUniqueElementKey(item.Name, item.LineNumber));
                        }

                        var idAttr      = string.IsNullOrEmpty(item.Id) ? string.Empty : string.Format("id=\"{0}\"", item.Id);
                        var replaceText = string.Format("{0} {1} class=\"{2}\"", item.Name, idAttr, cssClass.Replace(".", string.Empty));

                        parsed          = parsed.Replace(item.Guid, replaceText);
                        cssFileContent += string.Format("{0}{{{1}}}\n\n", cssClass, "\n" + item.Style);
                    }

                    //css file beautification
                    cssFileContent = cssFileContent.Replace(";", ";\n");

                    //update html file
                    TextSelection txtSelHtml = (TextSelection)doc.Selection;
                    txtSelHtml.SelectAll();
                    txtSelHtml.Delete();
                    txtSelHtml.Insert(parsed);

                    //create css file
                    var docName = doc.Name.Substring(0, doc.Name.IndexOf('.'));
                    docName = string.Format("{0}.css", docName);
                    string solutionDir = System.IO.Path.GetDirectoryName(dte.Solution.FullName);
                    dte.ItemOperations.NewFile(@"General\Text File", docName, EnvDTE.Constants.vsViewKindTextView);
                    TextSelection txtSelCss = (TextSelection)dte.ActiveDocument.Selection;
                    txtSelCss.SelectAll();
                    txtSelCss.Delete();
                    txtSelCss.Insert(cssFileContent);
                }
                else
                {
                    VsShellUtilities.ShowMessageBox(this.ServiceProvider, "Not found inline css.", "That's Cool!",
                                                    OLEMSGICON.OLEMSGICON_INFO, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
                }
            }
            else
            {
                VsShellUtilities.ShowMessageBox(this.ServiceProvider, "This is not a html file!", "Oops!",
                                                OLEMSGICON.OLEMSGICON_WARNING, OLEMSGBUTTON.OLEMSGBUTTON_OK, OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST);
            }

            // Clear the progress bar.
            StatusBar.Progress(ref cookie, 0, string.Empty, 0, 0);
            StatusBar.FreezeOutput(0);
            StatusBar.Clear();
        }
コード例 #59
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 = ProjectFileConstants.Content;
                Assert.AreEqual(nestedItemProperty.Value, ProjectFileConstants.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 = ProjectFileConstants.Content;
                Assert.AreEqual(itemProperty.Value, ProjectFileConstants.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);
                ReferenceContainerNode containerNode = (ReferenceContainerNode)project.FindChild("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");
            });
        }
コード例 #60
0
 private void OnRunStarted(DTE dTE, Dictionary <string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
 {
     // add the root project name (the name the user passed in) to the global replacement dictionary
     GlobalDictionary["$saferootprojectname$"]    = replacementsDictionary["$safeprojectname$"];
     GlobalDictionary["$saferootidentifiername$"] = replacementsDictionary["$safeprojectname$"].Replace(".", "");
 }