PageRenderTime 26ms CodeModel.GetById 12ms app.highlight 10ms RepoModel.GetById 1ms app.codeStats 0ms

/src/AddIns/Misc/PackageManagement/PowerShell/Project/Src/PowerShellHost.cs

https://github.com/ajadex/SharpDevelop
C# | 198 lines | 150 code | 31 blank | 17 comment | 2 complexity | b658090e179bd03cafcce92d2cc49275 MD5 | raw file
  1// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
  2// 
  3// Permission is hereby granted, free of charge, to any person obtaining a copy of this
  4// software and associated documentation files (the "Software"), to deal in the Software
  5// without restriction, including without limitation the rights to use, copy, modify, merge,
  6// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
  7// to whom the Software is furnished to do so, subject to the following conditions:
  8// 
  9// The above copyright notice and this permission notice shall be included in all copies or
 10// substantial portions of the Software.
 11// 
 12// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
 13// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
 14// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
 15// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 16// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 17// DEALINGS IN THE SOFTWARE.
 18
 19using System;
 20using System.Collections;
 21using System.Collections.Generic;
 22using System.Globalization;
 23using System.Management.Automation;
 24using System.Management.Automation.Host;
 25using System.Management.Automation.Runspaces;
 26using System.Threading;
 27
 28using ICSharpCode.Scripting;
 29
 30namespace ICSharpCode.PackageManagement.Scripting
 31{
 32	public class PowerShellHost : PSHost, IPowerShellHost
 33	{
 34		public static readonly string EnvironmentPathVariableName = "env:path";
 35		
 36		IScriptingConsole scriptingConsole;
 37		CultureInfo currentUICulture = Thread.CurrentThread.CurrentUICulture;
 38		CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
 39		Guid instanceId = Guid.NewGuid();
 40		Runspace runspace;
 41		PowerShellHostUserInterface userInterface;
 42		List<string> modulesToImport = new List<string>();
 43		PSObject privateData;
 44		object dte;
 45		Version version;
 46		
 47		public PowerShellHost(
 48			IScriptingConsole scriptingConsole,
 49			Version version,
 50			object privateData,
 51			object dte)
 52		{
 53			this.scriptingConsole = scriptingConsole;
 54			this.version = version;
 55			this.privateData = new PSObject(privateData);
 56			this.dte = dte;
 57			userInterface = new PowerShellHostUserInterface(scriptingConsole);
 58		}
 59		
 60		public override PSObject PrivateData {
 61			get { return privateData; }
 62		}
 63		
 64		public IList<string> ModulesToImport {
 65			get { return modulesToImport; }
 66		}
 67		
 68		public void SetRemoteSignedExecutionPolicy()
 69		{
 70			ExecuteCommand("Set-ExecutionPolicy RemoteSigned -Scope 0 -Force");	
 71		}
 72		
 73		public void UpdateFormatting(IEnumerable<string> formattingFiles)
 74		{
 75			foreach (string file in formattingFiles) {
 76				string command = String.Format("Update-FormatData '{0}'", file);
 77				ExecuteCommand(command);
 78			}
 79		}
 80		
 81		public void ExecuteCommand(string command)
 82		{
 83			try {
 84				CreateRunspace();
 85				
 86				using (Pipeline pipeline = CreatePipeline(command)) {
 87					pipeline.Invoke();
 88				}
 89				
 90			} catch (Exception ex) {
 91				scriptingConsole.WriteLine(ex.Message, ScriptingStyle.Error);
 92			}
 93		}
 94		
 95		Pipeline CreatePipeline(string command)
 96		{
 97			Pipeline pipeline = runspace.CreatePipeline();
 98			pipeline.Commands.AddScript(command);
 99			pipeline.Commands.Add("out-default");
100			pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
101			return pipeline;
102		}
103		
104		void CreateRunspace()
105		{
106			if (runspace == null) {
107				InitialSessionState initialSessionState = CreateInitialSessionState();
108				runspace = RunspaceFactory.CreateRunspace(this, initialSessionState);
109				runspace.Open();
110			}
111		}
112		
113		InitialSessionState CreateInitialSessionState()
114		{
115			var initialSessionState = InitialSessionState.CreateDefault();
116			initialSessionState.ImportPSModule(modulesToImport.ToArray());
117			SessionStateVariableEntry variable = CreateDTESessionVariable();
118			initialSessionState.Variables.Add(variable);
119			return initialSessionState;
120		}
121		
122		SessionStateVariableEntry CreateDTESessionVariable()
123		{
124			var options = ScopedItemOptions.AllScope | ScopedItemOptions.Constant;
125			return new SessionStateVariableEntry("DTE", dte, "SharpDevelop DTE object", options);
126		}
127		
128		public override Version Version {
129			get { return version; }
130		}
131		
132		public override PSHostUserInterface UI {
133			get { return userInterface; }
134		}
135		
136		public override void SetShouldExit(int exitCode)
137		{
138		}
139		
140		public override void NotifyEndApplication()
141		{
142		}
143		
144		public override void NotifyBeginApplication()
145		{
146		}
147		
148		public override string Name {
149			get { return "Package Manager Host"; }
150		}
151		
152		public override Guid InstanceId {
153			get { return instanceId; }
154		}
155		
156		public override void ExitNestedPrompt()
157		{
158			throw new NotImplementedException();
159		}
160		
161		public override void EnterNestedPrompt()
162		{
163			throw new NotImplementedException();
164		}
165		
166		public override CultureInfo CurrentUICulture {
167			get { return currentUICulture; }
168		}
169		
170		public override CultureInfo CurrentCulture {
171			get { return currentCulture; }
172		}
173		
174		public void RunScript(string fileName, IEnumerable<object> input)
175		{
176			try {
177				CreateRunspace();
178				
179				string command = 
180					"$__args = @(); " +
181					"$input | ForEach-Object {$__args += $_}; " +
182					"& '" + fileName + "' $__args[0] $__args[1] $__args[2] $__args[3]" +
183					"Remove-Variable __args -Scope 0";
184				using (Pipeline pipeline = CreatePipeline(command)) {
185					pipeline.Invoke(input);
186				}
187				
188			} catch (Exception ex) {
189				scriptingConsole.WriteLine(ex.Message, ScriptingStyle.Error);
190			}
191		}
192		
193		public void SetDefaultRunspace()
194		{
195			Runspace.DefaultRunspace = runspace;
196		}
197	}
198}