Esempio n. 1
0
        public static IVsWindowFrame OpenDocument(string filePath, Action<IVsWindowFrame> creationCallback)
        {
            if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
                return null;

            var dte2 = (EnvDTE80.DTE2)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(EnvDTE.DTE)) as EnvDTE80.DTE2;
            Microsoft.VisualStudio.OLE.Interop.IServiceProvider sp = (Microsoft.VisualStudio.OLE.Interop.IServiceProvider)dte2;
            Microsoft.VisualStudio.Shell.ServiceProvider serviceProvider = new Microsoft.VisualStudio.Shell.ServiceProvider(sp);

            IVsUIHierarchy hierarchy;
            uint itemId;
            IVsWindowFrame frame = null;
            if (!VsShellUtilities.IsDocumentOpen(serviceProvider, filePath,
                    VSConstants.LOGVIEWID_Primary, out hierarchy, out itemId, out frame))
            {
                VsShellUtilities.OpenDocument(serviceProvider, filePath,
                    VSConstants.LOGVIEWID_Primary, out hierarchy, out itemId, out frame);

                if (creationCallback != null)
                    creationCallback(frame);
            }

            if (frame != null)
                frame.Show();

            return frame;
        }
        internal static ErrorTask CreateErrorTask(
            string document, string errorMessage, TextSpan textSpan, TaskErrorCategory taskErrorCategory, IVsHierarchy hierarchy,
            uint itemID, MARKERTYPE markerType)
        {
            ErrorTask errorTask = null;

            IOleServiceProvider oleSp = null;
            hierarchy.GetSite(out oleSp);
            IServiceProvider sp = new ServiceProvider(oleSp);

            // see if Document is open
            IVsTextLines buffer = null;
            var docData = VSHelpers.GetDocData(sp, document);
            if (docData != null)
            {
                buffer = VSHelpers.GetVsTextLinesFromDocData(docData);
            }

            if (buffer != null)
            {
                errorTask = new EFModelDocumentTask(sp, buffer, markerType, textSpan, document, itemID, errorMessage, hierarchy);
                errorTask.ErrorCategory = taskErrorCategory;
            }
            else
            {
                errorTask = new EFModelErrorTask(
                    document, errorMessage, textSpan.iStartLine, textSpan.iEndLine, taskErrorCategory, hierarchy, itemID);
            }

            return errorTask;
        }
        /////////////////////////////////////////////////////////////////////////////
        // Overridden Package Implementation
        #region Package Members

        /// <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()
        {
            Debug.WriteLine (string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString()));
            base.Initialize();

            // Add our command handlers for menu (commands must exist in the .vsct file)
            OleMenuCommandService mcs = GetService(typeof(IMenuCommandService)) as OleMenuCommandService;
            if ( null != mcs )
            {
                DTE dte = (DTE)GetService(typeof(DTE));

                migrator = new Migrator(dte);
                var serviceProvider = new ServiceProvider((IServiceProvider)dte);
                solutionLoadEvents = new SolutionLoadEvents(serviceProvider);
                synchronizationContext = SynchronizationContext.Current;

                solutionLoadEvents.BeforeSolutionLoaded += () =>
                {
                    synchronizationContext.Post(_ => migrator.OnBeforeSolutionLoaded(), null);
                };
                
                solutionLoadEvents.AfterSolutionLoaded += () =>
                {
                    synchronizationContext.Post(_ => migrator.OnAfterSolutionLoaded(), null);
                };


                // Create the command for the menu item.
                CommandID menuCommandID = new CommandID(GuidList.guidTargetFrameworkMigratorCmdSet, (int)PkgCmdIDList.cmdidTargetFrameworkMigrator);
                MenuCommand menuItem = new MenuCommand(MenuItemCallback, menuCommandID );
                mcs.AddCommand( menuItem );
            }
        }
        /// <summary>
        /// Get the hierarchy corresponding to a Project
        /// </summary>
        /// <param name="project"></param>
        /// <returns></returns>
        public static IVsHierarchy ToHierarchy(EnvDTE.Project project)
        {
            if (project == null) throw new ArgumentNullException("project");

            string projectGuid = null;

            // DTE does not expose the project GUID that exists at in the msbuild project file.
            // Cannot use MSBuild object model because it uses a static instance of the Engine, 
            // and using the Project will cause it to be unloaded from the engine when the 
            // GC collects the variable that we declare.
            using (XmlReader projectReader = XmlReader.Create(project.FileName))
            {
                projectReader.MoveToContent();
                object nodeName = projectReader.NameTable.Add("ProjectGuid");
                while (projectReader.Read())
                {
                    if (Object.Equals(projectReader.LocalName, nodeName))
                    {
                        //   projectGuid = projectReader.ReadContentAsString();
                        projectGuid = projectReader.ReadElementContentAsString();
                        break;
                    }
                }
            }

            Debug.Assert(!String.IsNullOrEmpty(projectGuid));

            System.IServiceProvider serviceProvider = new ServiceProvider(project.DTE as
                Microsoft.VisualStudio.OLE.Interop.IServiceProvider);

            return VsShellUtilities.GetHierarchy(serviceProvider, new Guid(projectGuid));
        }
        private string Transform(string fileName, string source)
        {
            var sp = new ServiceProvider(_site as Microsoft.VisualStudio.OLE.Interop.IServiceProvider);
            var vsproj = ((EnvDTE.ProjectItem)(sp.GetService(typeof(EnvDTE.ProjectItem)))).ContainingProject;
            var cm = (IComponentModel)(Package.GetGlobalService(typeof(SComponentModel)));

            var workspace = cm.GetService<VisualStudioWorkspace>();

            var solution = workspace.CurrentSolution;
            var project = solution.Projects.FirstOrDefault(p => p.FilePath == vsproj.FileName);

            var syntaxTrees = Enumerable.Empty<SyntaxTree>();

            if (project != null)
            {
                var c = project.GetCompilationAsync().Result;
                syntaxTrees = c.SyntaxTrees;
            }

            var syntaxTree = CSharpSyntaxTree.ParseText(source);
            var compilation = CSharpCompilation.Create("temp", syntaxTrees.Concat(new[] { syntaxTree }));

            var rewriter = new NotifyPropertyChangedRewriter(fileName, compilation.GetSemanticModel(syntaxTree, true));

            var result = rewriter.Visit(syntaxTree.GetRoot());

            return result.ToFullString();
        }
        private void CommandInvoke(object sender, EventArgs e)
        {
            OleMenuCmdEventArgs oOleMenuCmdEventArgs = (OleMenuCmdEventArgs)e;

            DTE2 Application = (DTE2)GetService(typeof(DTE));
            ProjectItem oProjectItem = Application.SelectedItems.Item(1).ProjectItem;
            IServiceProvider oServiceProvider = new ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider)Application);
            Microsoft.Build.Evaluation.Project oBuildProject = Microsoft.Build.Evaluation.ProjectCollection.GlobalProjectCollection.GetLoadedProjects(oProjectItem.ContainingProject.FullName).SingleOrDefault();
            Microsoft.Build.Evaluation.ProjectProperty oGUID = oBuildProject.AllEvaluatedProperties.SingleOrDefault(oProperty => oProperty.Name == "ProjectGuid");
            Microsoft.VisualStudio.Shell.Interop.IVsHierarchy oVsHierarchy = VsShellUtilities.GetHierarchy(oServiceProvider, new Guid(oGUID.EvaluatedValue));
            Microsoft.VisualStudio.Shell.Interop.IVsBuildPropertyStorage oVsBuildPropertyStorage = (Microsoft.VisualStudio.Shell.Interop.IVsBuildPropertyStorage)oVsHierarchy;

            string szItemPath = (string)oProjectItem.Properties.Item("FullPath").Value;
            uint nItemId;

            oVsHierarchy.ParseCanonicalName(szItemPath, out nItemId);

            if (oOleMenuCmdEventArgs.OutValue != IntPtr.Zero)
            {
                string szOut;

                oVsBuildPropertyStorage.GetItemAttribute(nItemId, "ItemColor", out szOut);

                Marshal.GetNativeVariantForObject(szOut, oOleMenuCmdEventArgs.OutValue);
            }
            else if (oOleMenuCmdEventArgs.InValue != null)
            {
                oVsBuildPropertyStorage.SetItemAttribute(nItemId, "ItemColor", Convert.ToString(oOleMenuCmdEventArgs.InValue));
            }
        }
        /// <summary>
        /// Executes when the wizard starts.
        /// </summary>
        public override void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, Microsoft.VisualStudio.TemplateWizard.WizardRunKind runKind, object[] customParams)
        {
            base.RunStarted(automationObject, replacementsDictionary, runKind, customParams);

            var wizardData = this.TemplateSchema.WizardData.FirstOrDefault();
            if (wizardData != null)
            {
                LoadWizards(wizardData);

                using (var services = new ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider)automationObject))
                {
                    var components = services.GetService<SComponentModel, IComponentModel>();

                    foreach (var wizard in wizards)
                    {
                        TryOrDispose(() => AttributedModelServices.SatisfyImportsOnce(components.DefaultCompositionService, wizard));
                    }
                }
            }

            foreach (var wizard in wizards)
            {
                TryOrDispose(() => wizard.RunStarted(automationObject, replacementsDictionary, runKind, customParams));
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Returns an IVsTextView for the given file path, if the given file is open in Visual Studio.
        /// </summary>
        /// <param name="serviceProvider">The package Service Provider.</param>
        /// <param name="filePath">Full Path of the file you are looking for.</param>
        /// <returns>
        /// The IVsTextView for this file, if it is open, null otherwise.
        /// </returns>
        internal static async Task <IWpfTextView> GetWpfTextViewByFilePathAsync(this Shell.IAsyncServiceProvider serviceProvider, string filePath)
        {
            if (filePath.IsNullOrWhiteSpace() || serviceProvider == null)
            {
                return(null);
            }

            if (!Shell.ThreadHelper.CheckAccess())
            {
                await Shell.ThreadHelper.JoinableTaskFactory.SwitchToMainThreadAsync();
            }

            DTE2 dte2 = await serviceProvider.GetServiceAsync <Shell.Interop.SDTE, DTE2>();

            var oleServiceProvider = dte2 as Microsoft.VisualStudio.OLE.Interop.IServiceProvider;

            if (dte2 == null || oleServiceProvider == null)
            {
                return(null);
            }

            Shell.ServiceProvider shellServiceProvider = new Shell.ServiceProvider(oleServiceProvider);

            if (Shell.VsShellUtilities.IsDocumentOpen(shellServiceProvider, filePath, Guid.Empty, out var uiHierarchy, out var itemID, out var windowFrame))
            {
                IVsTextView textView = Shell.VsShellUtilities.GetTextView(windowFrame);                   // Get the IVsTextView from the windowFrame
                return(await serviceProvider.GetWpfTextViewFromTextViewAsync(textView));
            }

            return(null);
        }
 public Context(object automationObject, IDictionary<string, string> values)
 {
     _replacementValues = values;
     _environment = (DTE)automationObject;
     ServiceProvider = new ServiceProvider(_environment as Microsoft.VisualStudio.OLE.Interop.IServiceProvider);
     TemplateService = new TemplateService(this);
 }
Esempio n. 10
0
 private static void CleanupFields()
 {
     if (container != null)
     {
         container.Dispose();
         container = null;
     }
     if (serviceProvider != null)
     {
         serviceProvider.Dispose();
         serviceProvider = null;
     }
     if (composition != null)
     {
         composition.Dispose();
         composition = null;
     }
     if (globalCatalog != null)
     {
         globalCatalog.Dispose();
         globalCatalog = null;
     }
     componentHost       = null;
     catalogProvider     = null;
     localComponentModel = null;
 }
Esempio n. 11
0
        /// <summary>
        /// Initializes VisualStudioHelper class.
        /// </summary>
        /// <param name="objDTE">DTE object.</param>
        public static void Initialize(DTE2 objDTE)
        {
            if (VisualStudioHelper._initialized == false)
            {
                VisualStudioHelper._initialized = true;

                // Set DTE reference
                VisualStudioHelper._DTE = objDTE;

                // Set event handlers
                VisualStudioHelper._DTE.Events.SolutionEvents.BeforeClosing  += VisualStudioHelper.SolutionEvents_BeforeClosing;
                VisualStudioHelper._DTE.Events.SolutionEvents.ProjectRemoved += VisualStudioHelper.SolutionEvents_ProjectRemoved;

                // Get ServiceProvider
                Microsoft.VisualStudio.Shell.ServiceProvider sp =
                    new Microsoft.VisualStudio.Shell.ServiceProvider(
                        (Microsoft.VisualStudio.OLE.Interop.IServiceProvider)objDTE);

                // Get the Solution service from the ServiceProvider
                VisualStudioHelper._solutionService = (sp.GetService(typeof(IVsSolution)) as IVsSolution);

                // Get the ErrorList provider
                VisualStudioHelper._errorListProvider = new Microsoft.VisualStudio.Shell.ErrorListProvider(sp);
                VisualStudioHelper._errorListProvider.ProviderName = Resources.ErrorList_ProviderName;
                VisualStudioHelper._errorListProvider.ProviderGuid = new Guid(Resources.ErrorList_ProviderGUID);
            }
        }
 private void CreateErrorListProvider()
 {
     IServiceProvider serviceProvider = new ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider)mApplication);
       mErrorListProvider = new ErrorListProvider(serviceProvider);
       mErrorListProvider.ProviderName = "CppCheck Errors";
       mErrorListProvider.ProviderGuid = new Guid("5A10E43F-8D1D-4026-98C0-E6B502058901");
 }
        /// <summary>
        /// The process record.
        /// </summary>
        /// <exception cref="PSInvalidOperationException">
        /// An error occured
        /// </exception>
        protected override void ProcessRecord()
        {
            var project = this.Project as VSProject;

            if (project == null)
            {
                throw new PSInvalidOperationException("Cannot cast the Project object to a VSProject");
            }

            var sp = new ServiceProvider((IOleServiceProvider)project.DTE);

            // Get the toolbox
            var svsToolbox = sp.GetService(typeof(SVsToolbox));

            if (svsToolbox == null)
            {
                throw new PSInvalidOperationException("Cannot get global Toolbox Service (SVsToolbox)");
            }

            var toolbox = svsToolbox as IVsToolbox;

            if (toolbox == null)
            {
                throw new PSInvalidOperationException("Cannot cast Toolbox Service to IVsToolbox");
            }

            toolbox.RemoveTab(this.Category);
        }
        public PropertiesEditorLauncher(ServiceProvider serviceProvider)
        {
            if(serviceProvider == null)
                throw new ArgumentNullException("serviceProvider");

            this.serviceProvider = serviceProvider;
        }
Esempio n. 15
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();
            }
        }
Esempio n. 16
0
 private IVsTextManager GetTextManager(DTE2 application)
 {
     using (ServiceProvider wrapperSP = new ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider)application))
     {
         return (IVsTextManager)wrapperSP.GetService(typeof(SVsTextManager));
     }
 }
        /// <summary>
        /// Creates a plugin instance when a new text editor is opened
        /// </summary>
        public void VsTextViewCreated(IVsTextView adapter)
        {
            IWpfTextView view = adapterFactory.GetWpfTextView(adapter);
            if (view == null)
                return;

            ITextDocument document;
            if (!docFactory.TryGetTextDocument(view.TextDataModel.DocumentBuffer, out document))
                return;

            IObjectWithSite iows = adapter as IObjectWithSite;
            if (iows == null)
                return;

            System.IntPtr p;
            iows.GetSite(typeof(IServiceProvider).GUID, out p);
            if (p == System.IntPtr.Zero)
                return;

            IServiceProvider isp = Marshal.GetObjectForIUnknown(p) as IServiceProvider;
            if (isp == null)
                return;

            ServiceProvider sp = new ServiceProvider(isp);
            DTE dte = sp.GetService(typeof(DTE)) as DTE;
            sp.Dispose();

            new Plugin(view, document, dte);
        }
Esempio n. 18
0
 internal SqlEditor(ServiceProvider sp, SqlEditorPane pane )
   : this()
 {
   Pane = pane;
   serviceProvider = sp;
   codeEditor.Init(sp, this);
 }
 public SqlEditorPane(ServiceProvider sp, SqlEditorFactory factory)
   : base(sp)
 {
   Factory = factory;
   DocumentPath = factory.LastDocumentPath;
   editor = new SqlEditor(sp, this);
 }
Esempio n. 20
0
 // Add Silverlight app to the Web project and create test web pages
 public void RunFinished()
 {
     Project silverlightProject = GetSilverlightProject();
     Project webProject = GetWebProject();
     if (webProject != null)
     {
         _dte2.Solution.SolutionBuild.StartupProjects = webProject.UniqueName;
         Properties properties = webProject.Properties;
         ProjectItem aspxTestPage = this.GetAspxTestPage(webProject);
         if (aspxTestPage != null)
         {
             properties.Item("WebApplication.StartPageUrl").Value = aspxTestPage.Name;
             properties.Item("WebApplication.DebugStartAction").Value = 1;
         }
         if (silverlightProject != null)
         {
             IVsHierarchy hierarchy;
             IVsHierarchy hierarchy2;
             silverlightProject.Properties.Item("SilverlightProject.LinkedServerProject").Value = webProject.FullName;
             var sp = _dte2 as Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
             IVsSolution service = null;
             using (var provider2 = new ServiceProvider(sp))
             {
                 service = provider2.GetService(typeof(IVsSolution)) as IVsSolution;
             }
             if (((service.GetProjectOfUniqueName(webProject.UniqueName, out hierarchy) == 0) && (hierarchy != null)) && (service.GetProjectOfUniqueName(silverlightProject.UniqueName, out hierarchy2) == 0))
             {
                 ((IVsSilverlightProjectConsumer)hierarchy).LinkToSilverlightProject("ClientBin", true, false, hierarchy2 as IVsSilverlightProject);
             }
         }
     }
 }
Esempio n. 21
0
        public void RunStarted(object automationObject, Dictionary <string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
        {
            Replacements = replacementsDictionary;

            string projName;

            if (replacementsDictionary.TryGetValue("$safeprojectname$", out projName))
            {
                ProjectName = projName;
            }

            string tname;

            if (replacementsDictionary.TryGetValue("TemplateName", out tname))
            {
                TemplateName = tname;
            }

            string tsource;

            if (replacementsDictionary.TryGetValue("TemplateSource", out tsource))
            {
                TemplateSource = tsource;
            }

            string tbranch;

            if (replacementsDictionary.TryGetValue("TemplateSourceBranch", out tbranch))
            {
                TemplateSourceBranch = tbranch;
            }

            string slndir;

            if (replacementsDictionary.TryGetValue("$destinationdirectory$", out slndir))
            {
                SolutionDirectory = slndir;
            }

            string extensionId;

            if (replacementsDictionary.TryGetValue("ExtensionId", out extensionId))
            {
                ExtensionId = extensionId;
            }

            Dte = automationObject as DTE2;

            var _oleServiceProvider = automationObject as Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
            var _serviceProvider    = new Microsoft.VisualStudio.Shell.ServiceProvider(_oleServiceProvider);
            var extManager          = (IVsExtensionManager)_serviceProvider.GetService(typeof(SVsExtensionManager));

            ExtensionInstallDir = GetExtensionInstallDir(ExtensionId, extManager);
            string pwModsFolder = Path.Combine(ExtensionInstallDir, "PwModules");

            EnsurePecanWaffleExtracted(pwModsFolder, ExtensionInstallDir);

            PowerShellInvoker.Instance.EnsureInstallPwScriptInvoked(ExtensionInstallDir);
        }
Esempio n. 22
0
 public static IWpfTextView GetWpfTextView(EnvDTE.DTE dte, IVsTextView viewAdapter)
 {
     using (ServiceProvider sp = new ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider)dte))
     {
         var svc = (IVsEditorAdaptersFactoryService)sp.GetService(typeof(IVsEditorAdaptersFactoryService));
         return svc.GetWpfTextView(viewAdapter);
     }
 }
        protected ProjectDocumentsListener(ServiceProvider serviceProviderParameter) {
            Utilities.ArgumentNotNull("serviceProviderParameter", serviceProviderParameter);

            this.serviceProvider = serviceProviderParameter;
            this.projectDocTracker = this.serviceProvider.GetService(typeof(SVsTrackProjectDocuments)) as IVsTrackProjectDocuments2;

            Utilities.CheckNotNull(this.projectDocTracker, "Could not get the IVsTrackProjectDocuments2 object from the services exposed by this project");
        }
Esempio n. 24
0
 public ErrorListHelper(object dte2)
 {
     _serviceProvider = new ServiceProvider(dte2 as Microsoft.VisualStudio.OLE.Interop.IServiceProvider);
     _errorProvider = new ErrorListProvider(_serviceProvider);//this implementing IServiceProvider
     _errorProvider.ProviderName = "JS Lint";
     _errorProvider.ProviderGuid = new Guid(); // should be package guid
     _errorProvider.Show();
 }
Esempio n. 25
0
 /// <summary>
 /// Constructor that calls the Microsoft.VisualStudio.Shell.WindowPane constructor then
 /// our initialization functions.
 /// </summary>
 /// <param name="package">Our Package instance.</param>
 public EditorPane(ServiceProvider service, VSNDK_PackagePackage package, string fileName, IVsTextLines textBuffer)
     : base(null)
 {
     _thisPackage = package;
     _fileName = fileName;
     _textBuffer = textBuffer;
     _service = service;
 }
 /// <summary>
 /// Overloaded Constructor
 /// </summary>
 /// <param name="viewModel"></param>
 public VsDesignerControl(ServiceProvider serviceProvider, IViewModel viewModel)
 {
     _serviceProvider = serviceProvider;
     DataContext = viewModel;
     InitializeComponent();
     // wait until we're initialized to handle events
     viewModel.ViewModelChanged += new EventHandler(ViewModelChanged);
 }
        /// <summary>
        /// Initializes a new instance of the <see cref="OutliningSynchronizationManager" /> class.
        /// </summary>
        /// <param name="package">The hosting package.</param>
        public OutliningSynchronizationManager(CodeMaidPackage package)
        {
            _package = package;

            // Retrieve services needed for outlining from the package.
            _editorAdaptersFactoryService = _package.ComponentModel.GetService<IVsEditorAdaptersFactoryService>();
            _outliningManagerService = _package.ComponentModel.GetService<IOutliningManagerService>();
            _serviceProvider = new ServiceProvider((IServiceProvider)_package.IDE);
        }
Esempio n. 28
0
        public void SetSite(object pUnkSite)
        {
            // Save away the site object for later use
            _site = pUnkSite;

            // These are initialized on demand via our private CodeProvider and SiteServiceProvider properties
            _codeDomProvider = null;
            _serviceProvider = null;
        }
 public VsOutputWindow(DTE2 dte2)
 {
     using (
         var sp =
             new ServiceProvider(
                 (IServiceProvider) dte2)) {
         _output = (IVsOutputWindow) sp.GetService(typeof (SVsOutputWindow));
     }
 }
		///-------------------------------------------------------------------------------------------------------------
		/// <summary>
		///	 Initializes the generator state.
		/// </summary>
		///-------------------------------------------------------------------------------------------------------------
		void IVsCodeBehindCodeGenerator.Initialize(IVsHierarchy hierarchy)
		{
			IOleServiceProvider serviceProvider = null;
			_hierarchy = hierarchy;
			_hierarchy.GetSite(out serviceProvider);
			_serviceProvider = new ServiceProvider(serviceProvider);
			_codeGeneratorOptions = new CodeGeneratorOptions();
			_codeGeneratorOptions.BlankLinesBetweenMembers = false;
		}
        public VisualStudioAutomation(DTE dte)
        {
            this.dteInternal = dte;

            ServiceProvider serviceProvider = new ServiceProvider(dte as Microsoft.VisualStudio.OLE.Interop.IServiceProvider);

            this.solutionEventsListener = new SolutionEventsListener(serviceProvider);

            this.QuitVisualStudioOnDispose = true;
        }
Esempio n. 32
0
        protected SelectionListener(ServiceProvider serviceProvider)
        {
            this.serviceProvider = serviceProvider;
            this.monSel = serviceProvider.GetService(typeof(SVsShellMonitorSelection)) as IVsMonitorSelection;

            if(this.monSel == null)
            {
                throw new InvalidOperationException();
            }
        }
Esempio n. 33
0
        public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams) {
            try {
                Directory.Delete(replacementsDictionary["$destinationdirectory$"]);
                Directory.Delete(replacementsDictionary["$solutiondirectory$"]);
            } catch {
                // If it fails (doesn't exist/contains files/read-only), let the directory stay.
            }

            var dte = automationObject as DTE;
            if (dte == null) {
                var provider = automationObject as Microsoft.VisualStudio.OLE.Interop.IServiceProvider;
                if (provider != null) {
                    dte = new ServiceProvider(provider).GetService(typeof(DTE)) as DTE;
                }
            }

            bool addingNewProject = false;
            if (dte == null) {
                MessageBox.Show("Unable to start wizard: no automation object available.", "Node.js Tools for Visual Studio");
            } else {
                // https://nodejstools.codeplex.com/workitem/462
                // we need to make sure our package is loaded before invoking our command
                Guid packageGuid = new Guid(Guids.NodejsPackageString);
                IVsPackage package;
                ((IVsShell)Package.GetGlobalService(typeof(SVsShell))).LoadPackage(
                    ref packageGuid,
                    out package
                );

                System.Threading.Tasks.Task.Factory.StartNew(() => {
                    string projName = replacementsDictionary["$projectname$"];
                    string solnName = replacementsDictionary["$specifiedsolutionname$"];
                    string directory;
                    if (String.IsNullOrWhiteSpace(solnName)) {
                        // Create directory is unchecked, destinationdirectory is the
                        // directory name the user entered plus the project name, we want
                        // to remove the project name.
                        directory = Path.GetDirectoryName(replacementsDictionary["$destinationdirectory$"]);
                    } else {
                        // Create directory is checked, the destinationdirectory is the
                        // directory the user entered plus the project name plus the
                        // solution name - we want to remove both extra folders
                        directory = Path.GetDirectoryName(Path.GetDirectoryName(replacementsDictionary["$destinationdirectory$"]));
                    }

                    var context = addingNewProject ? 
                        (int)VSConstants.VSStd97CmdID.AddExistingProject : 
                        (int)VSConstants.VSStd97CmdID.OpenProject;
                    object inObj = projName + "|" + directory + "|" + context, outObj = null;
                    dte.Commands.Raise(Guids.NodejsCmdSet.ToString("B"), (int)PkgCmdId.cmdidImportWizard, ref inObj, ref outObj);
                });
            }
            addingNewProject = IsAddNewProjectCmd;
            throw new WizardCancelledException();
        }
        public FileSystemNavigateToTarget(string fileName, int line, int column, ServiceProvider serviceProvider)
        {
            Contract.Requires<ArgumentNullException>(fileName != null, "fileName");
            Contract.Requires<ArgumentNullException>(serviceProvider != null, "serviceProvider");
            Contract.Requires<ArgumentException>(!string.IsNullOrEmpty(fileName));

            FileName = fileName;
            Line = line;
            Column = column;
            ServiceProvider = serviceProvider;
        }
Esempio n. 35
0
    /// <summary>
    /// Retrieves the <see cref="IServiceLocator"/> for the given project.
    /// </summary>
    /// <exception cref="ArgumentNullException">The <paramref name="project"/> parameter was null.</exception>
    /// <exception cref="InvalidOperationException">The required <see cref="IComponentModel"/> service was not found.</exception>
    public static IServiceLocator GetServiceLocator(this Project project)
    {
        Guard.NotNull(nameof(project), project);

        var components = new Microsoft.VisualStudio.Shell.ServiceProvider((Ole.IServiceProvider)project.DTE).GetService <SComponentModel, IComponentModel>();

        try {
            return(components.GetService <IServiceLocatorProvider> ().GetServiceLocator(project));
        } catch (ImportCardinalityMismatchException ex) {
            throw new MissingDependencyException(Strings.ServiceLocator.MissingDependency(typeof(IServiceLocatorProvider)), ex);
        }
    }
Esempio n. 36
0
        private ITypeResolutionService GetResolutionService(EnvDTE.Project project, Microsoft.VisualStudio.Shell.ServiceProvider provider)
        {
            var typeService = ( DynamicTypeService )provider.GetService(typeof(DynamicTypeService));


            IVsSolution  sln = provider.GetService(typeof(IVsSolution)) as IVsSolution;
            IVsHierarchy hier;

            sln.GetProjectOfUniqueName(project.UniqueName, out hier);

            return(typeService.GetTypeResolutionService(hier));
        }
Esempio n. 37
0
        private void Dispose(bool dispose)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            if (dispose)
            {
                if (_serviceProvider != null)
                {
                    _serviceProvider.Dispose();
                    _serviceProvider = null;
                }
            }
        }
Esempio n. 38
0
    public static HelpContext2 GetHelpContext(DTE2 dte)
    {
        // Get a reference to the current active window (presumably a code editor).
        Window activeWindow = dte.ActiveWindow;

        // make a few gnarly COM-interop calls in order to get Help Context
        Microsoft.VisualStudio.OLE.Interop.IServiceProvider sp = (Microsoft.VisualStudio.OLE.Interop.IServiceProvider)activeWindow.DTE;
        Microsoft.VisualStudio.Shell.ServiceProvider        serviceProvider = new Microsoft.VisualStudio.Shell.ServiceProvider(sp);
        IVsMonitorUserContext contextMonitor = (IVsMonitorUserContext)serviceProvider.GetService(typeof(IVsMonitorUserContext));
        IVsUserContext        userContext;
        int          hresult = contextMonitor.get_ApplicationContext(out userContext);
        HelpContext2 attrs   = new HelpContext2(userContext);

        return(attrs);
    }
Esempio n. 39
0
        /// <summary>
        /// Attach to a process.
        /// </summary>
        /// <param name="sProcessName"></param>
        private void AttachDebugTarget(string sProcessName)
        {
            Microsoft.VisualStudio.Shell.ServiceProvider sp =
                new Microsoft.VisualStudio.Shell.ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider)_applicationObject);
            IVsDebugger dbg = (IVsDebugger)sp.GetService(typeof(SVsShellDebugger));

            foreach (Process lLocalProcess in _applicationObject.Debugger.LocalProcesses)
            {
                if (lLocalProcess.Name.IndexOf(sProcessName) >= 0)
                {
                    (lLocalProcess as Process2).Attach2("NPL Debug Engine");
                    break;
                }
            }
        }
Esempio n. 40
0
        public override bool Execute()
        {
            System.Diagnostics.Debugger.Launch();
            //CoInitializeEx(NULL, COINIT_MULTITHREADED);
            //enum comEnum = {COINIT_MULTITHREADED=0};
            //CoInitializeEx((IntPtr)null, (uint)0);

            _applicationObject = (EnvDTE80.DTE2)System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.10.0");

            Microsoft.VisualStudio.Shell.ServiceProvider sp =
                new Microsoft.VisualStudio.Shell.ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider)_applicationObject);

            IVsDebugger dbg = (IVsDebugger)sp.GetService(typeof(SVsShellDebugger));

            VsDebugTargetInfo info = new VsDebugTargetInfo();

            info.cbSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(info);
            info.dlo    = Microsoft.VisualStudio.Shell.Interop.DEBUG_LAUNCH_OPERATION.DLO_CreateProcess;

            info.bstrExe                   = _filePath;
            info.bstrCurDir                = System.IO.Path.GetDirectoryName(info.bstrExe);
            info.bstrArg                   = null;                                               // no command line parameters
            info.bstrRemoteMachine         = null;                                               // debug locally
            info.fSendStdoutToOutputWindow = 0;                                                  // Let stdout stay with the application.
            info.clsidCustom               = new Guid("{D951924A-4999-42a0-9217-1EB5233D1D5A}"); // Set the launching engine the sample engine guid
            info.grfLaunch                 = 0;

            IntPtr pInfo = System.Runtime.InteropServices.Marshal.AllocCoTaskMem((int)info.cbSize);

            System.Runtime.InteropServices.Marshal.StructureToPtr(info, pInfo, false);

            try
            {
                dbg.LaunchDebugTargets(1, pInfo);
            }
            finally
            {
                if (pInfo != IntPtr.Zero)
                {
                    System.Runtime.InteropServices.Marshal.FreeCoTaskMem(pInfo);
                }
            }

            return(true);
        }
Esempio n. 41
0
        public static IVsTextView GetVsTextViewFrompPath(string filePath)
        {
            var dte2            = (EnvDTE80.DTE2)Package.GetGlobalService(typeof(SDTE));
            var sp              = (Microsoft.VisualStudio.OLE.Interop.IServiceProvider)dte2;
            var serviceProvider = new Microsoft.VisualStudio.Shell.ServiceProvider(sp);

            IVsUIHierarchy uiHierarchy;
            uint           itemID;
            IVsWindowFrame windowFrame;

            if (VsShellUtilities.IsDocumentOpen(serviceProvider, filePath, Guid.Empty,
                                                out uiHierarchy, out itemID, out windowFrame))
            {
                // Get the IVsTextView from the windowFrame.
                return(VsShellUtilities.GetTextView(windowFrame));
            }
            return(null);
        }
Esempio n. 42
0
        public IServiceLocator GetServiceLocator(IVsHierarchy hierarchy)
        {
            Guard.NotNull(nameof(hierarchy), hierarchy);

            IServiceProvider services;

            Ole.IServiceProvider site;
            if (ErrorHandler.Failed(hierarchy.GetSite(out site)))
            {
                services = Microsoft.VisualStudio.Shell.ServiceProvider.GlobalProvider;
            }
            else
            {
                services = new Microsoft.VisualStudio.Shell.ServiceProvider(site);
            }

            return(new ServiceLocatorImpl(services));
        }
        //http://stackoverflow.com/a/2427368/4574
        internal static Microsoft.VisualStudio.TextManager.Interop.IVsTextView GetIVsTextView(string filePath)
        {
            var dte2 = (EnvDTE80.DTE2)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(Microsoft.VisualStudio.Shell.Interop.SDTE));

            Microsoft.VisualStudio.OLE.Interop.IServiceProvider sp = (Microsoft.VisualStudio.OLE.Interop.IServiceProvider)dte2;
            Microsoft.VisualStudio.Shell.ServiceProvider        serviceProvider = new Microsoft.VisualStudio.Shell.ServiceProvider(sp);

            Microsoft.VisualStudio.Shell.Interop.IVsUIHierarchy uiHierarchy;
            uint itemID;

            Microsoft.VisualStudio.Shell.Interop.IVsWindowFrame windowFrame;
            //Microsoft.VisualStudio.Text.Editor.IWpfTextView wpfTextView = null;
            if (Microsoft.VisualStudio.Shell.VsShellUtilities.IsDocumentOpen(serviceProvider, filePath, Guid.Empty,
                                                                             out uiHierarchy, out itemID, out windowFrame))
            {
                // Get the IVsTextView from the windowFrame.
                return(Microsoft.VisualStudio.Shell.VsShellUtilities.GetTextView(windowFrame));
            }

            return(null);
        }
Esempio n. 44
0
        public void SpotClient_OnTrackChange(object sender, SpotifyAPI.Local.TrackChangeEventArgs e)
        {
            if (!UserPreferences.Default.showTrackArtistOnChange)
            {
                Console.WriteLine("ShowTrackArtist is disabled in user preferences.");
                return;
            }

            if (e.NewTrack == null || e.NewTrack.TrackResource == null ||
                e.NewTrack.TrackResource.Name == null || e.NewTrack.AlbumResource.Name == null)
            {
                return;
            }
            string trackName  = e.NewTrack.TrackResource.Name;
            string artistName = e.NewTrack.ArtistResource.Name;

            Console.WriteLine("Show New track name: " + trackName);
            myOleCommand.Text = String.Format("{0} - {1}", trackName, artistName);
            Microsoft.VisualStudio.Shell.ServiceProvider serviceProvider = new Microsoft.VisualStudio.Shell.ServiceProvider(((EnvDTE.DTE)Microsoft.VisualStudio.Shell.ServiceProvider.GlobalProvider.GetService(typeof(EnvDTE.DTE))) as Microsoft.VisualStudio.OLE.Interop.IServiceProvider);
            IVsUIShell uiShell = serviceProvider.GetService(typeof(SVsUIShell)) as IVsUIShell;

            uiShell.UpdateCommandUI(0);
            if (timer != null)
            {
                timer.Stop();
                timer.Start();
            }
            else
            {
                timer = new System.Timers.Timer()
                {
                    Interval = kSHOW_TRACK_INTERVAL
                };
                //timer.AutoReset = false;
                timer.Elapsed += TrackChangeTimerTick;
                timer.Start();
            }
        }
Esempio n. 45
0
        public static IVsWindowFrame IsDocumentOpened(string filePath)
        {
            if (string.IsNullOrEmpty(filePath) || !File.Exists(filePath))
            {
                return(null);
            }

            var dte2 = (EnvDTE80.DTE2)Microsoft.VisualStudio.Shell.Package.GetGlobalService(typeof(EnvDTE.DTE)) as EnvDTE80.DTE2;

            Microsoft.VisualStudio.OLE.Interop.IServiceProvider sp = (Microsoft.VisualStudio.OLE.Interop.IServiceProvider)dte2;
            Microsoft.VisualStudio.Shell.ServiceProvider        serviceProvider = new Microsoft.VisualStudio.Shell.ServiceProvider(sp);

            IVsUIHierarchy hierarchy;
            uint           itemId;
            IVsWindowFrame frame = null;

            if (VsShellUtilities.IsDocumentOpen(serviceProvider, filePath,
                                                VSConstants.LOGVIEWID_Primary, out hierarchy, out itemId, out frame))
            {
                return(frame);
            }
            return(null);
        }
Esempio n. 46
0
        /// <summary>
        /// Attach to a process.
        /// </summary>
        /// <param name="sProcessName"></param>
        public void AttachDebugTarget(int nProcessID)
        {
            Microsoft.VisualStudio.Shell.ServiceProvider sp =
                new Microsoft.VisualStudio.Shell.ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider)_applicationObject);
            IVsDebugger dbg = (IVsDebugger)sp.GetService(typeof(SVsShellDebugger));

            foreach (Process lLocalProcess in _applicationObject.Debugger.LocalProcesses)
            {
                if (lLocalProcess.ProcessID == nProcessID)
                {
                    try
                    {
                        if (true)
                        {
                            var myThread = new System.Threading.Thread(() =>
                            {
                                (lLocalProcess as Process2).Attach2("NPLDebugEngineV2");
                                Console.Write("NPLDebugEngineV2 attached");
                            });
                            myThread.Start();
                        }
                        else
                        {
                            //strange: this function hangs
                            // In VS,  TOOLS -> Options... -> Debugging -> General and checked Use Managed Compatibility Mode option:
                            (lLocalProcess as Process2).Attach2("NPLDebugEngineV2");
                        }
                    }
                    catch (Exception err)
                    {
                        Console.Write(err.ToString());
                        MessageBox.Show(String.Format("failed to attach to process {0}. because {1}. You many need to register the debug engine.", nProcessID, err.ToString()));
                    }
                    break;
                }
            }
        }
Esempio n. 47
0
    /// <summary>
    /// Retrieves the <see cref="IServiceLocator"/> for the given hierarchy.
    /// </summary>
    /// <exception cref="ArgumentNullException">The <paramref name="hierarchy"/> parameter was null.</exception>
    /// <exception cref="InvalidOperationException">The required <see cref="IComponentModel"/> service was not found.</exception>
    public static IServiceLocator GetServiceLocator(this IVsHierarchy hierarchy)
    {
        Guard.NotNull(nameof(hierarchy), hierarchy);

        IServiceProvider services;

        Ole.IServiceProvider site;
        if (ErrorHandler.Failed(hierarchy.GetSite(out site)))
        {
            services = Microsoft.VisualStudio.Shell.ServiceProvider.GlobalProvider;
        }
        else
        {
            services = new Microsoft.VisualStudio.Shell.ServiceProvider(site);
        }

        var components = services.GetService <SComponentModel, IComponentModel>();

        try {
            return(components.GetService <IServiceLocatorProvider> ().GetServiceLocator(hierarchy));
        } catch (ImportCardinalityMismatchException ex) {
            throw new MissingDependencyException(Strings.ServiceLocator.MissingDependency(typeof(IServiceLocatorProvider)), ex);
        }
    }
Esempio n. 48
0
        /// <summary>
        /// Launch an executable using the sample debug engine.
        /// </summary>
        public void LaunchDebugTarget(string command, string arguments, string workingDir)
        {
            Microsoft.VisualStudio.Shell.ServiceProvider sp =
                new Microsoft.VisualStudio.Shell.ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider)_applicationObject);

            IVsDebugger dbg = (IVsDebugger)sp.GetService(typeof(SVsShellDebugger));

            VsDebugTargetInfo info = new VsDebugTargetInfo();

            info.cbSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(info);
            info.dlo    = Microsoft.VisualStudio.Shell.Interop.DEBUG_LAUNCH_OPERATION.DLO_CreateProcess;

            info.bstrExe                   = command;
            info.bstrCurDir                = String.IsNullOrEmpty(workingDir) ? System.IO.Path.GetDirectoryName(info.bstrExe) : workingDir;
            info.bstrArg                   = arguments;                                          // command line parameters
            info.bstrRemoteMachine         = null;                                               // debug locally
            info.fSendStdoutToOutputWindow = 0;                                                  // Let stdout stay with the application.
            info.clsidCustom               = new Guid("{0B18F022-A5F5-41EA-8532-4CF3B894A7C6}"); // Set the launching engine the sample engine guid
            info.grfLaunch                 = 0;

            IntPtr pInfo = System.Runtime.InteropServices.Marshal.AllocCoTaskMem((int)info.cbSize);

            System.Runtime.InteropServices.Marshal.StructureToPtr(info, pInfo, false);

            try
            {
                dbg.LaunchDebugTargets(1, pInfo);
            }
            finally
            {
                if (pInfo != IntPtr.Zero)
                {
                    System.Runtime.InteropServices.Marshal.FreeCoTaskMem(pInfo);
                }
            }
        }
Esempio n. 49
0
        /// <summary>
        /// Launch an executible using the sample debug engine.
        /// </summary>
        private void LaunchDebugTarget(string filePath, Guid engineGuid)
        {
            Microsoft.VisualStudio.Shell.ServiceProvider sp =
                new Microsoft.VisualStudio.Shell.ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider)_applicationObject);

            IVsDebugger dbg = (IVsDebugger)sp.GetService(typeof(SVsShellDebugger));

            VsDebugTargetInfo info = new VsDebugTargetInfo();

            info.cbSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(info);
            info.dlo    = Microsoft.VisualStudio.Shell.Interop.DEBUG_LAUNCH_OPERATION.DLO_CreateProcess;

            info.bstrExe                   = filePath;
            info.bstrCurDir                = System.IO.Path.GetDirectoryName(info.bstrExe);
            info.bstrArg                   = null; // no command line parameters
            info.bstrRemoteMachine         = null; // debug locally
            info.fSendStdoutToOutputWindow = 0;    // Let stdout stay with the application.
            info.clsidCustom               = engineGuid;
            info.grfLaunch                 = 0;

            IntPtr pInfo = IntPtr.Zero;

            try
            {
                pInfo = System.Runtime.InteropServices.Marshal.AllocCoTaskMem((int)info.cbSize);
                System.Runtime.InteropServices.Marshal.StructureToPtr(info, pInfo, false);
                dbg.LaunchDebugTargets(1, pInfo);
            }
            finally
            {
                if (pInfo != IntPtr.Zero)
                {
                    System.Runtime.InteropServices.Marshal.FreeCoTaskMem(pInfo);
                }
            }
        }
Esempio n. 50
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Command4"/> class.
        /// Adds our command handlers for menu (commands must exist in the command table file)
        /// </summary>
        /// <param name="package">Owner package, not null.</param>
        private Command4(Package package)
        {
            if (package == null)
            {
                throw new ArgumentNullException("package");
            }

            this.package = package;

            OleMenuCommandService commandService = this.ServiceProvider.GetService(typeof(IMenuCommandService)) as OleMenuCommandService;

            if (commandService != null)
            {
                var menuCommandID = new CommandID(CommandSet, CommandId);

                // var menuItem = new MenuCommand(this.MenuItemCallback, menuCommandID);

                myOleCommand = new OleMenuCommand(this.MenuItemCallback, menuCommandID);

                //if (null != myOleCommand)
                //{
                //    myOleCommand.Text = "New Text";
                //
                //}
                if (IsSpotifyProcessRunning())
                {
                    if (Command1Package.SpotifyCommandShouldShowText())
                    {
                        myOleCommand.Text = kSpotifyOpenString;
                    }
                    else
                    {
                        myOleCommand.Text = " ";
                    }
                }
                else
                {
                    if (UserPreferences.Default.HideButtonTextOnInactive)
                    {
                        myOleCommand.Text = " ";
                    }
                    else
                    {
                        myOleCommand.Text = kSpotifyStartString;
                    }
                }

                Microsoft.VisualStudio.Shell.ServiceProvider serviceProvider = new Microsoft.VisualStudio.Shell.ServiceProvider(((EnvDTE.DTE)Microsoft.VisualStudio.Shell.ServiceProvider.GlobalProvider.GetService(typeof(EnvDTE.DTE))) as Microsoft.VisualStudio.OLE.Interop.IServiceProvider);
                IVsUIShell uiShell = serviceProvider.GetService(typeof(SVsUIShell)) as IVsUIShell;
                uiShell.UpdateCommandUI(0);

                if (IsSpotifyProcessRunning())
                {
                    SpotClientRegisterTrackChange();
                }

                commandService.AddCommand(myOleCommand);

                gCommand4Instance = this;
            }
        }
Esempio n. 51
0
        /// <summary>
        /// Launch an executable using the VSNDK debug engine.
        /// </summary>
        /// <param name="pidString"> Process ID in string format. </param>
        /// <returns> TRUE if successful, False if not. </returns>
        private bool LaunchDebugTarget(string pidString)
        {
            Microsoft.VisualStudio.Shell.ServiceProvider sp =
                new Microsoft.VisualStudio.Shell.ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider)_dte);

            IVsDebugger dbg = (IVsDebugger)sp.GetService(typeof(SVsShellDebugger));

            VsDebugTargetInfo info = new VsDebugTargetInfo();

            info.cbSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(info);
            info.dlo    = Microsoft.VisualStudio.Shell.Interop.DEBUG_LAUNCH_OPERATION.DLO_CreateProcess;

            // Read debugger args from a file (it is set when the Deploy task is run)
            System.IO.StreamReader argsFile = null;
            try
            {
                string localAppData = Environment.GetEnvironmentVariable("AppData");
                argsFile = new System.IO.StreamReader(localAppData + @"\BlackBerry\vsndk-args-file.txt");
            }
            catch (Exception e)
            {
                Debug.Fail("Unexpected exception in LaunchDebugTarget");
            }

            // Store all debugger arguments in a string
            var nvc = new NameValueCollection();

            nvc.Add("pid", pidString);
            nvc.Add("targetIP", argsFile.ReadLine()); // The device (IP address)
            info.bstrExe = argsFile.ReadLine();       // The executable path
            nvc.Add("isSimulator", argsFile.ReadLine());
            nvc.Add("ToolsPath", argsFile.ReadLine());
            nvc.Add("PublicKeyPath", argsFile.ReadLine());

            // Decrypt stored password.
            byte[] data = Convert.FromBase64String(argsFile.ReadLine());
            if (data.Length > 0)
            {
                byte[] decrypted = ProtectedData.Unprotect(data, null, DataProtectionScope.LocalMachine);
                nvc.Add("Password", Encoding.Unicode.GetString(decrypted));
            }

            info.bstrArg = NameValueCollectionHelper.DumpToString(nvc);
            argsFile.Close();

            info.bstrRemoteMachine         = null;                                 // debug locally
            info.fSendStdoutToOutputWindow = 0;                                    // Let stdout stay with the application.
            info.clsidCustom = new Guid("{E5A37609-2F43-4830-AA85-D94CFA035DD2}"); // Set the launching engine the VSNDK engine guid
            info.grfLaunch   = 0;

            IntPtr pInfo = System.Runtime.InteropServices.Marshal.AllocCoTaskMem((int)info.cbSize);

            System.Runtime.InteropServices.Marshal.StructureToPtr(info, pInfo, false);

            try
            {
                int result = dbg.LaunchDebugTargets(1, pInfo);

                if (result != VSConstants.S_OK)
                {
                    string     msg;
                    IVsUIShell sh = (IVsUIShell)sp.GetService(typeof(SVsUIShell));
                    sh.GetErrorInfo(out msg);
                    Debug.WriteLine("LaunchDebugTargets: " + msg);

                    return(true);
                }
            }
            finally
            {
                if (pInfo != IntPtr.Zero)
                {
                    System.Runtime.InteropServices.Marshal.FreeCoTaskMem(pInfo);
                }
            }

            return(false);
        }
        /// <summary>
        /// Creates the MVC item and add it to the MVC project.
        /// </summary>
        /// <param name="vsProj">The Visual Studio project.</param>
        private void GenerateMVCItems(VSProject vsProj)
        {
            if (string.IsNullOrEmpty(_connectionString))
            {
                return;
            }

            if (_selectedTables == null || _selectedTables.Count == 0)
            {
                return;
            }

#if CLR4 || NET_40_OR_GREATER
            IServiceProvider serviceProvider = new Microsoft.VisualStudio.Shell.ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider)dte);
            Microsoft.VisualStudio.TextTemplating.VSHost.ITextTemplating t4 = serviceProvider.GetService(typeof(STextTemplating)) as ITextTemplating;
            ITextTemplatingSessionHost sessionHost = t4 as ITextTemplatingSessionHost;
            var     controllerClassPath            = string.Empty;
            var     IndexFilePath  = string.Empty;
            var     fileExtension  = string.Empty;
            Version productVersion = Assembly.GetExecutingAssembly().GetName().Version;
            var     version        = String.Format("{0}.{1}.{2}", productVersion.Major, productVersion.Minor, productVersion.Build);
            double  visualStudioVersion;
            double.TryParse(ItemTemplateUtilities.GetVisualStudioVersion(dte), out visualStudioVersion);
            if (_language == LanguageGenerator.CSharp)
            {
                controllerClassPath = Path.GetFullPath(string.Format("{0}{1}{2}", T4Templates_Path, version, cSharpControllerClass_FileName));
                IndexFilePath       = Path.GetFullPath(string.Format("{0}{1}{2}", T4Templates_Path, version, cSharpIndexFile_FileName));
                fileExtension       = "cs";
            }
            else
            {
                controllerClassPath = Path.GetFullPath(string.Format("{0}{1}{2}", T4Templates_Path, version, vbControllerClass_FileName));
                IndexFilePath       = Path.GetFullPath(string.Format("{0}{1}{2}", T4Templates_Path, version, vbIndexFile_FileName));
                fileExtension       = "vb";
            }

            StringBuilder catalogs = new StringBuilder();
            catalogs = new StringBuilder("<h3> Catalog list</h3>");
            catalogs.AppendLine();

            foreach (var table in TablesIncludedInModel)
            {
                catalogs.AppendLine(string.Format(@"<div> @Html.ActionLink(""{0}"",""Index"", ""{0}"")</div>",
                                                  table.Key[0].ToString().ToUpperInvariant() + table.Key.Substring(1)));
            }

            try
            {
                foreach (var table in TablesIncludedInModel)
                {
                    // creating controller file
                    sessionHost.Session = sessionHost.CreateSession();
                    sessionHost.Session["namespaceParameter"]            = string.Format("{0}.Controllers", _projectNamespace);
                    sessionHost.Session["applicationNamespaceParameter"] = string.Format("{0}.Models", _projectNamespace);
                    sessionHost.Session["controllerClassParameter"]      = string.Format("{0}Controller", table.Key[0].ToString().ToUpperInvariant() + table.Key.Substring(1));
                    if ((_dataAccessTechnology == DataAccessTechnology.EntityFramework6 && _language == LanguageGenerator.VBNET) ||
                        _language == LanguageGenerator.CSharp)
                    {
                        sessionHost.Session["modelNameParameter"] = _connectionName;
                    }
                    else if (_dataAccessTechnology == DataAccessTechnology.EntityFramework5 && _language == LanguageGenerator.VBNET)
                    {
                        sessionHost.Session["modelNameParameter"] = string.Format("{1}.{0}", _connectionName, _projectNamespace);
                    }

                    sessionHost.Session["classNameParameter"]       = table.Key;
                    sessionHost.Session["entityNameParameter"]      = table.Key[0].ToString().ToUpperInvariant() + table.Key.Substring(1);
                    sessionHost.Session["entityClassNameParameter"] = table.Key;
                    if ((visualStudioVersion < 12.0 && _language == LanguageGenerator.VBNET) ||
                        _language == LanguageGenerator.CSharp)
                    {
                        sessionHost.Session["entityClassNameParameterWithNamespace"] = string.Format("{0}.{1}", _projectNamespace, table.Key);
                    }
                    else if (_language == LanguageGenerator.VBNET && visualStudioVersion >= 12.0)
                    {
                        if (_dataAccessTechnology == DataAccessTechnology.EntityFramework5)
                        {
                            sessionHost.Session["entityClassNameParameterWithNamespace"] = string.Format("{0}.{0}.{1}", _projectNamespace, table.Key);
                        }
                        else if (_dataAccessTechnology == DataAccessTechnology.EntityFramework6)
                        {
                            sessionHost.Session["entityClassNameParameterWithNamespace"] = string.Format("{0}.{1}", _projectNamespace, table.Key);
                        }
                    }

                    T4Callback    cb = new T4Callback();
                    StringBuilder resultControllerFile = new StringBuilder(t4.ProcessTemplate(controllerClassPath, File.ReadAllText(controllerClassPath), cb));
                    string        controllerFilePath   = string.Format(@"{0}\Controllers\{1}Controller.{2}", _projectPath,
                                                                       table.Key[0].ToString().ToUpperInvariant() + table.Key.Substring(1), fileExtension);
                    File.WriteAllText(controllerFilePath, resultControllerFile.ToString());
                    if (cb.errorMessages.Count > 0)
                    {
                        File.AppendAllLines(controllerFilePath, cb.errorMessages);
                    }

                    vsProj.Project.ProjectItems.AddFromFile(controllerFilePath);
                    var viewPath = Path.GetFullPath(_projectPath + string.Format(@"\Views\{0}", table.Key[0].ToString().ToUpperInvariant() + table.Key.Substring(1)));
                    Directory.CreateDirectory(viewPath);
                    string resultViewFile = t4.ProcessTemplate(IndexFilePath, File.ReadAllText(IndexFilePath), cb);
                    File.WriteAllText(string.Format(viewPath + @"\Index.{0}html", fileExtension), resultViewFile);
                    if (cb.errorMessages.Count > 0)
                    {
                        File.AppendAllLines(controllerFilePath, cb.errorMessages);
                    }

                    vsProj.Project.ProjectItems.AddFromFile(string.Format(viewPath + @"\Index.{0}html", fileExtension));
                }
            }
            catch (Exception ex)
            {
                SendToGeneralOutputWindow(string.Format("An error occurred: {0}\n\n {1}", ex.Message, ex.StackTrace));
                InfoDialog.ShowDialog(InfoDialogProperties.GetErrorDialogProperties(Resources.ErrorTitle, Resources.ItemTemplatesBaseWebWizard_GenerateMvcItemsError));
            }
#endif
        }
Esempio n. 53
0
 public virtual int SetSite(IOleServiceProvider psp)
 {
     _serviceProvider = new ServiceProvider(psp);
     return(VSConstants.S_OK);
 }
Esempio n. 54
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;


            try
            {
                // ctlProgID - the ProgID for your user control. asmPath - the path to your user control DLL. guidStr - a unique GUID for the user control.
                string ctlProgID, asmPath, guidStr;
                // Variables for the new tool window that will hold
                // your user control.
                EnvDTE80.Windows2 toolWins;
                EnvDTE.Window     toolWin;
                object            objTemp = null;

                _applicationObject = (DTE2)application;
                _addInInstance     = (AddIn)addInInst;
                ctlProgID          = "Hobbisoft.Slam.Tools.Analyzers.VisualizerHost";
                // Replace the <Path to VS Project> with the path to
                // the folder where you created the WindowsCotrolLibrary.
                // Remove the line returns from the path before
                // running the add-in.
                asmPath = @"D:\inetpub\Core\Core\Hobbisoft.Slam.Tools.Analyzers\bin\Debug\Hobbisoft.Slam.Tools.Analyzers.exe";
                guidStr = "{9ED54F84-A89D-4fcd-A854-44251E922109}";

                toolWins = (Windows2)_applicationObject.Windows;
                // Create the new tool window, adding your user control.
                toolWin = toolWins.CreateToolWindow2(_addInInstance,
                                                     asmPath, ctlProgID, "Salesforce Analyzers", guidStr,
                                                     ref objTemp);


                // The tool window must be visible before you do anything
                // with it, or you will get an error.
                if (toolWin != null)
                {
                    toolWin.Visible = true;
                }

                toolWin.Height = 500;
                toolWin.Width  = 400;


                // Get the service provider on the object
                Microsoft.VisualStudio.Shell.ServiceProvider serviceProvider = new Microsoft.VisualStudio.Shell.ServiceProvider(this._applicationObject as Microsoft.VisualStudio.OLE.Interop.IServiceProvider);

                // Get the shell service
                var  vsUIShell = (IVsUIShell)serviceProvider.GetService(typeof(SVsUIShell));
                Guid slotGuid  = new Guid("63ed935d-eac2-4b8f-9208-f28f48d49f6b");

                // Find the associated window frame on this toolwindow
                IVsWindowFrame wndFrame;
                vsUIShell.FindToolWindow((uint)__VSFINDTOOLWIN.FTW_fFrameOnly, ref slotGuid, out wndFrame);

                // Set the text on the window tab name
                wndFrame.SetProperty((int)__VSFPROPID.VSFPROPID_Caption, "Salesforce");
            }
            catch (Exception ex)
            {
                //System.Windows.Forms.MessageBox.Show("Exception: "
                //  + ex.Message);
            }
        }
Esempio n. 55
0
        /// <summary>
        /// Implements <see cref="IWizard.RunStarted"/>
        /// </summary>
        protected void RunStarted(object automationObject, Dictionary <string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
        {
            IOleServiceProvider oleServiceProvider = automationObject as IOleServiceProvider;
            ServiceProvider     serviceProvider    = (oleServiceProvider != null) ? new ServiceProvider(oleServiceProvider) : null;

            DataConnectionDialogFactory dialogFactory = GetService <DataConnectionDialogFactory>(serviceProvider);

            Debug.Assert(dialogFactory != null, "Can't get DataConnectionDialogFactory!");

            System.Data.IDbConnection dbConn;
            DataConnectionDialog      dialog = dialogFactory.CreateConnectionDialog();

            dialog.AddAllSources();
            DataConnection dataConn = dialog.ShowDialog(false);

            if (dataConn != null)
            {
                if ((dbConn = dataConn.ConnectionSupport.ProviderObject as System.Data.IDbConnection) == null)
                {
                    // show error
                    return;
                }

                DataProviderManager manager = GetService <DataProviderManager>(serviceProvider);
                if (manager != null)
                {
                    DataProvider provider      = manager.GetDataProvider(dataConn.Provider);
                    string       invariantName = provider.GetProperty("InvariantName") as string;

                    IList <string> schemaList     = DcilSchema.GetAvailableSchemaNames(dbConn, invariantName);
                    string         selectedSchema = null;
                    switch (schemaList.Count)
                    {
                    case 1:
                        selectedSchema = schemaList[0];
                        break;

                    default:
                        // Allow this for an empty list
                        selectedSchema = SchemaSelector.SelectSchema(serviceProvider, schemaList);
                        break;
                    }

                    if (!string.IsNullOrEmpty(selectedSchema))
                    {
                        DcilSchema schema = DcilSchema.FromSchemaName(selectedSchema, dbConn, invariantName);

                        StringBuilder stringBuilder     = new StringBuilder();
                        string        replacementString = null;
                        using (MemoryStream ms = new MemoryStream())
                        {
                            DcilSchema.Serialize(schema, ms);
                            ms.Seek(0, SeekOrigin.Begin);
                            StreamReader sr = new StreamReader(ms);
                            replacementString = sr.ReadToEnd();
                        }


                        replacementsDictionary.Add("$DcilFile$", replacementString);
                        myAddToProject = true;
                    }
                }
            }
        }