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)); }
public Type GetTypeFromString(string type) { IServiceProvider serviceProvider = new ServiceProvider(_dte2 as Microsoft.VisualStudio.OLE.Interop.IServiceProvider); DynamicTypeService typeService = serviceProvider.GetService(typeof(DynamicTypeService)) as DynamicTypeService; IVsSolution sln = serviceProvider.GetService(typeof(IVsSolution)) as IVsSolution; IVsHierarchy hier; sln.GetProjectOfUniqueName(_dte2.ActiveDocument.ProjectItem.ContainingProject.UniqueName, out hier); return typeService.GetTypeResolutionService(hier).GetType(type, true); }
/// <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 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 IVsTextManager GetTextManager(DTE2 application) { using (ServiceProvider wrapperSP = new ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider)application)) { return (IVsTextManager)wrapperSP.GetService(typeof(SVsTextManager)); } }
/// <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); }
/// <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)); } }
// 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); } } } }
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(); } }
/// <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); }
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); }
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); } }
public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams) { var requiredReferences = GetRequiredReferences(replacementsDictionary); using (var serviceProvider = new ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider)automationObject)) { var componentModel = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel)); var installerServices = componentModel.GetService<IVsPackageInstaller>(); //installerServices.InstallPackage() //installerServices.InstallPackage("http://packages.nuget.org", project, "Microsoft.AspNet.SignalR.JS", "1.0.0-alpha2", false); var dte = (EnvDTE.DTE)serviceProvider.GetService(typeof(EnvDTE.DTE)); var missingReferences = FindMissingReferences(requiredReferences, installerServices, dte).ToList(); if (missingReferences.Count > 0) { var packages = string.Join(", ", missingReferences.Select(r => r.Reference.Package)); var msg = string.Format("This template requires these references. Do you want to add them using nuget?\n\n{0}", packages); var result = MessageBox.Show(Helpers.MainWindow, msg, "Missing packages", MessageBoxButtons.OKCancel, MessageBoxType.Information, MessageBoxDefaultButton.OK); if (result == DialogResult.Cancel) throw new WizardCancelledException(); foreach (var missingRef in missingReferences) { var reference = missingRef.Reference; if (!string.IsNullOrEmpty(reference.ExtensionId)) { installerServices.InstallPackagesFromVSExtensionRepository(reference.ExtensionId, false, false, false, missingRef.Project, new Dictionary<string, string> { { reference.Package, reference.Version } }); } else { installerServices.InstallPackage("https://packages.nuget.org", missingRef.Project, reference.Package, reference.Version, false); } } } } }
public VsOutputWindow(DTE2 dte2) { using ( var sp = new ServiceProvider( (IServiceProvider) dte2)) { _output = (IVsOutputWindow) sp.GetService(typeof (SVsOutputWindow)); } }
protected SelectionListener(ServiceProvider serviceProvider) { this.serviceProvider = serviceProvider; this.monSel = serviceProvider.GetService(typeof(SVsShellMonitorSelection)) as IVsMonitorSelection; if(this.monSel == null) { throw new InvalidOperationException(); } }
public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams) { requiredReferences = GetRequiredReferences(replacementsDictionary).ToList(); if (runKind == WizardRunKind.AsNewItem) { using (var serviceProvider = new ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider)automationObject)) { var componentModel = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel)); var installerServices = componentModel.GetService<IVsPackageInstaller>(); var dte = (EnvDTE.DTE)serviceProvider.GetService(typeof(EnvDTE.DTE)); var missingReferences = FindMissingReferences(installerServices, dte).ToList(); InstallReferences(installerServices, missingReferences); } } else this.automationObject = automationObject; }
/// <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); } }
protected DocumentProperties(CodeWindowManager mgr) { this.mgr = mgr; this.visible = true; if (mgr != null) { IOleServiceProvider sp = mgr.CodeWindow as IOleServiceProvider; if (sp != null) { ServiceProvider site = new ServiceProvider(sp); this.tracker = site.GetService(typeof(SVsTrackSelectionEx)) as IVsTrackSelectionEx; } } }
private void Initialize(object automationObject) { using (var serviceProvider = new ServiceProvider((IServiceProvider)automationObject)) { var componentModel = (IComponentModel)serviceProvider.GetService(typeof(SComponentModel)); using (var container = new CompositionContainer(componentModel.DefaultExportProvider)) { container.ComposeParts(this); } } }
/// <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); } }
/*protected, but public for FSharp.Project.dll*/ public SelectionListener(ServiceProvider serviceProvider) { this.serviceProvider = serviceProvider; this.monSel = serviceProvider.GetService(typeof(SVsShellMonitorSelection)) as IVsMonitorSelection; Debug.Assert(this.monSel != null, "Could not get the IVsMonitorSelection object from the services exposed by this project"); if (this.monSel == null) { throw new InvalidOperationException(); } }
public static IVsHierarchy AsHierarchy(this Project project) { using (var serviceProvider = new ServiceProvider((IServiceProvider)project.DTE)) { var solution = (IVsSolution)serviceProvider.GetService(typeof(SVsSolution)); IVsHierarchy hierarchy; ErrorHandler.ThrowOnFailure(solution.GetProjectOfUniqueName(project.UniqueName, out hierarchy)); return hierarchy; } }
protected ProjectDocumentsListener(ServiceProvider serviceProvider) { this.serviceProvider = serviceProvider; this.projectDocTracker = serviceProvider.GetService(typeof(SVsTrackProjectDocuments)) as IVsTrackProjectDocuments2; Debug.Assert(this.projectDocTracker != null, "Could not get the IVsTrackProjectDocuments2 object from the services exposed by this project"); if(this.projectDocTracker == null) { throw new InvalidOperationException(); } }
internal static ISharePointProjectService GetSharePointProjectService(DTE dte) { EnvDTE80.DTE2 dte2 = (EnvDTE80.DTE2)dte; ServiceProvider serviceProvider = new ServiceProvider(dte2 as Microsoft.VisualStudio.OLE.Interop.IServiceProvider); Microsoft.VisualStudio.SharePoint.ISharePointProjectService projectService = serviceProvider.GetService(typeof(Microsoft.VisualStudio.SharePoint.ISharePointProjectService)) as Microsoft.VisualStudio.SharePoint.ISharePointProjectService; if (projectService == null) { projectService = Package.GetGlobalService(typeof(Microsoft.VisualStudio.SharePoint.ISharePointProjectService)) as Microsoft.VisualStudio.SharePoint.ISharePointProjectService; } return projectService; }
protected SelectionListener(ServiceProvider serviceProviderParameter) { if (serviceProviderParameter == null) { throw new ArgumentNullException("serviceProviderParameter"); } ServiceProvider = serviceProviderParameter; SelectionMonitor = ServiceProvider.GetService(typeof (SVsShellMonitorSelection)) as IVsMonitorSelection; if (SelectionMonitor == null) { throw new InvalidOperationException(); } }
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); }
/// <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; } } }
/// <summary> /// Attach to a process. /// </summary> /// <param name="sProcessName"></param> public 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; } } }
private void Initialize(object automationObject) { using (var provider = new ServiceProvider((IServiceProvider)automationObject)) { var service = (IComponentModel)provider.GetService(typeof(SComponentModel)); using (var container = new CompositionContainer(service.DefaultExportProvider)) { container.ComposeParts(this); } } if (Wizard == null) { MessageBox.Show("NuGet Package Manager not available."); throw new WizardBackoutException("NuGet Package Manager not available."); } }
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 oleProvider = automationObject as Microsoft.VisualStudio.OLE.Interop.IServiceProvider; if (oleProvider == null) { MessageBox.Show("Unable to start wizard: no automation object available.", "Python Tools for Visual Studio"); throw new WizardBackoutException(); } using (var serviceProvider = new ServiceProvider(oleProvider)) { int hr = EnsurePackageLoaded(serviceProvider); if (ErrorHandler.Failed(hr)) { MessageBox.Show(string.Format("Unable to start wizard: failed to load Python Tools Package (0x{0:X08})", hr), "Python Tools for Visual Studio"); throw new WizardBackoutException(); } var uiShell = (IVsUIShell)serviceProvider.GetService(typeof(SVsUIShell)); string projName = replacementsDictionary["$projectname$"]; string solnName; replacementsDictionary.TryGetValue("$specifiedsolutionname$", out solnName); 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$"])); } object inObj = projName + "|" + directory; var guid = GuidList.guidPythonToolsCmdSet; hr = uiShell.PostExecCommand(ref guid, PkgCmdIDList.cmdidImportWizard, 0, ref inObj); if (ErrorHandler.Failed(hr)) { MessageBox.Show(string.Format("Unable to start wizard: Unexpected error 0x{0:X08}", hr), "Python Tools for Visual Studio"); } } throw new WizardCancelledException(); }
public override void ProjectFinishedGenerating(Project project) { base.ProjectFinishedGenerating(project); var vs = project.DTE; if (vs != null) { using (var serviceProvider = new ServiceProvider((Microsoft.VisualStudio.OLE.Interop.IServiceProvider)vs)) { TraceSourceExtensions.ShieldUI(tracer, (Action)(() => { var solution = serviceProvider.GetService<ISolution>(); var projectAdded = solution.Find<IProject>(p => p.As<Project>().UniqueName == project.UniqueName).FirstOrDefault(); var items = projectAdded.Find<IItem>(item => item.As<ProjectItem>() != null); foreach (var item in items) { if (!string.IsNullOrEmpty(item.Data.CustomTool)) { var runCustomToolOnUnfold = item.Data.RunCustomToolOnUnfold; if (!string.IsNullOrEmpty(runCustomToolOnUnfold)) { bool runTool = false; Boolean.TryParse(runCustomToolOnUnfold, out runTool); if (!runTool) { continue; } } var projectItem = item.As<ProjectItem>().Object as VSProjectItem; if (projectItem != null) { tracer.Info(Resources.CustomToolRunnerTemplateWizard_RunningCustomTool, ((object)item.Data.CustomTool).ToString(), item.GetLogicalPath()); projectItem.RunCustomTool(); } } } }), Resources.CustomToolRunnerTemplateWizard_FailedToRunCustomTools); } } }
internal async Task AttachDebugger(string ipAddress) { string path = GetStartupAssemblyPath(); string targetExe = Path.GetFileName(path); string outputDirectory = Path.GetDirectoryName(path); Project startup = GetStartupProject(); bool isWeb = ((object[]) startup.ExtenderNames).Any(x => x.ToString() == "WebApplication"); ApplicationType appType = isWeb ? ApplicationType.Webapplication : ApplicationType.Desktopapplication; if (appType == ApplicationType.Webapplication) outputDirectory += @"\..\..\"; var client = new DebugClient(appType, targetExe, outputDirectory); DebugSession session = await client.ConnectToServerAsync(ipAddress); await session.TransferFilesAsync(); await session.WaitForAnswerAsync(); IntPtr pInfo = GetDebugInfo(ipAddress, targetExe, outputDirectory); var sp = new ServiceProvider((IServiceProvider) _dte); try { var dbg = (IVsDebugger) sp.GetService(typeof (SVsShellDebugger)); int hr = dbg.LaunchDebugTargets(1, pInfo); Marshal.ThrowExceptionForHR(hr); DebuggedMonoProcess.Instance.AssociateDebugSession(session); } catch(Exception ex) { logger.Error(ex); string msg; var sh = (IVsUIShell) sp.GetService(typeof (SVsUIShell)); sh.GetErrorInfo(out msg); if (!string.IsNullOrWhiteSpace(msg)) { logger.Error(msg); } throw; } finally { if (pInfo != IntPtr.Zero) Marshal.FreeCoTaskMem(pInfo); } }
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); }
public void ProjectFinishedGenerating(Project project) { if (winRTCertificateWizard != null) winRTCertificateWizard.ProjectFinishedGenerating(project); try { var services = new ServiceProvider(dte as Microsoft.VisualStudio.OLE.Interop.IServiceProvider); var componentModel = (IComponentModel)services.GetService(typeof(SComponentModel)); var packageManager = componentModel.GetService<IVsPackageInstaller>(); packageManager.InstallPackage(null, project, "SharpDX.Toolkit.Game", (string)null, false); packageManager.InstallPackage(null, project, "SharpDX.Toolkit.Input", (string)null, false); } catch (Exception) { MessageBox.Show("Unable to install nuget SharpDX.Toolkit.Game package. Please install it manually", "Error installing SharpDX nuget package", MessageBoxButtons.OK); } }
protected ProjectDocumentsListener(ServiceProvider serviceProviderParameter) { if (serviceProviderParameter == null) { throw new ArgumentNullException("serviceProviderParameter"); } ServiceProvider = serviceProviderParameter; ProjectDocumentTracker2 = ServiceProvider.GetService(typeof (SVsTrackProjectDocuments)) as IVsTrackProjectDocuments2; Debug.Assert(ProjectDocumentTracker2 != null, "Could not get the IVsTrackProjectDocuments2 object from the services exposed by this project"); if (ProjectDocumentTracker2 == null) { throw new InvalidOperationException(); } }
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; }
/// <summary> /// Reloads the project. /// </summary> /// <param name="project">The project.</param> public static void ReloadProject(this Project project) { Guard.NotNull(() => project, project); var dte = project.DTE; if (dte != null) { using (var serviceProvider = new ServiceProvider((Ole.IServiceProvider)project.DTE)) { if (serviceProvider != null) { var solution = serviceProvider.GetService(typeof(SVsSolution)) as IVsSolution; if (solution != null) { IVsHierarchy hierarchy; if (Microsoft.VisualStudio.ErrorHandler.Succeeded(solution.GetProjectOfUniqueName(project.FullName, out hierarchy)) && hierarchy != null) { object hier = null; if (Microsoft.VisualStudio.ErrorHandler.Succeeded(hierarchy.GetProperty(Microsoft.VisualStudio.VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ParentHierarchy, out hier)) && hier != null) { object itemId = null; if (Microsoft.VisualStudio.ErrorHandler.Succeeded(hierarchy.GetProperty(Microsoft.VisualStudio.VSConstants.VSITEMID_ROOT, (int)__VSHPROPID.VSHPROPID_ParentHierarchyItemid, out itemId)) && itemId != null) { var persistHierarchy = hier as IVsPersistHierarchyItem2; if (persistHierarchy != null) { Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(persistHierarchy.ReloadItem((uint)(int)itemId, 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(); } }
/// <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; } } }
/// <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); } } }
/// <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); } } }
/// <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>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); } }
/// <include file='doc\WindowPane.uex' path='docs/doc[@for="WindowPane.GetService"]' /> /// <devdoc> /// Maps to IServiceProvider for service routing. /// </devdoc> protected virtual object GetService(Type serviceType) { if (_zombie) { Debug.Fail("GetService called after WindowPane was zombied"); return(null); } if (serviceType == null) { throw new ArgumentNullException("serviceType"); } // We provide IMenuCommandService, so we will // demand create it. MenuCommandService also // implements IOleCommandTarget, but unless // someone requested IMenuCommandService no commands // will exist, so we don't demand create for // IOleCommandTarget // if (serviceType.IsEquivalentTo(typeof(IMenuCommandService))) { EnsureCommandService(); return(_commandService); } else if (serviceType.IsEquivalentTo(typeof(IOleCommandTarget))) { return(_commandService); } else if (serviceType.IsEquivalentTo(typeof(IHelpService))) { if (_helpService == null) { _helpService = new HelpService(this); } return(_helpService); } if (_provider != null) { object service = _provider.GetService(serviceType); if (service != null) { return(service); } } // We should never attempt to resite the parent // if _provider is not null it will have already succeeded above. if (serviceType.IsEquivalentTo(typeof(IObjectWithSite))) { return(null); } if (_parentProvider != null) { return(_parentProvider.GetService(serviceType)); } return(null); }
/// <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; } }
/// <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 }