Skip to content
Browse files

Rewrote IronConsole using .NET4 async features

  • Loading branch information...
1 parent 2380e96 commit ee9b4928cc95dfedd5dd12eae130aa203bb16928 @kmees kmees committed Mar 20, 2013
Showing with 958 additions and 582 deletions.
  1. +25 −0 src/IronSharePoint.Framework/Console/Hooks/HookBase.cs
  2. +12 −0 src/IronSharePoint.Framework/Console/Hooks/IHook.cs
  3. +21 −0 src/IronSharePoint.Framework/Console/Hooks/RubyHook.cs
  4. +8 −5 src/IronSharePoint.Framework/{IronConsole/IronConsoleResult.cs → Console/ScriptResult.cs}
  5. +153 −0 src/IronSharePoint.Framework/IronConsole.cs
  6. +0 −12 src/IronSharePoint.Framework/IronConsole/Hooks/IIronConsoleHook.cs
  7. +0 −25 src/IronSharePoint.Framework/IronConsole/Hooks/IronConsoleHookBase.cs
  8. +0 −38 src/IronSharePoint.Framework/IronConsole/Hooks/RubyConsoleHook.cs
  9. +0 −92 src/IronSharePoint.Framework/IronConsole/IronConsole.cs
  10. +0 −88 src/IronSharePoint.Framework/IronConsole/IronConsoleTask.cs
  11. +1 −1 src/IronSharePoint.Framework/IronConstant.cs
  12. +22 −14 src/IronSharePoint.Framework/IronJob.cs
  13. +45 −0 src/IronSharePoint.Framework/Util/ScriptEngineExtensions.cs
  14. +1 −1 src/IronSharePoint/IronConsole/IronConsole.webpart
  15. +1 −1 src/IronSharePoint/IronConsole/IronConsoleUserControl.ascx.designer.cs
  16. +1 −1 src/IronSharePoint/IronConsole/IronConsoleWebPart.cs
  17. +46 −1 src/IronSharePoint/IronSharePoint.csproj
  18. +10 −5 src/IronSharePoint/Layouts/IronSP/IronConsole.coffee
  19. +269 −249 src/IronSharePoint/Layouts/IronSP/IronConsole.js
  20. +20 −23 src/IronSharePoint/Layouts/IronSP/IronConsoleService.ashx.cs
  21. +1 −25 src/IronSharePoint/TEMPLATE/Features/IronSP_Root/iron_sharepoint/console/utils.rb
  22. +47 −0 test/IronSharePoint.Framework.Test/Console/Hooks/RubyHook_Fixture.cs
  23. +26 −0 test/IronSharePoint.Framework.Test/Console/ScriptResult_Fixture.cs
  24. +83 −0 test/IronSharePoint.Framework.Test/IOCapture_Fixture.cs
  25. +58 −0 test/IronSharePoint.Framework.Test/IronConsole_Fixture.cs
  26. +42 −0 test/IronSharePoint.Framework.Test/IronSharePoint.Framework.Test.csproj
  27. +22 −0 test/IronSharePoint.Framework.Test/TestHelper.cs
  28. +3 −1 test/IronSharePoint.Framework.Test/Util/EnumerableExtensions_Fixture.cs
  29. +41 −0 test/IronSharePoint.Framework.Test/Util/ScriptEngineExtensions_Fixture.cs
View
25 src/IronSharePoint.Framework/Console/Hooks/HookBase.cs
@@ -0,0 +1,25 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using Microsoft.Scripting.Hosting;
+
+namespace IronSharePoint.Console.Hooks
+{
+ abstract class HookBase : IHook
+ {
+ #region IHook Members
+
+ public bool SupportsLanguage(string languageName)
+ {
+ return SupportedLanguages().Contains(languageName, StringComparer.InvariantCultureIgnoreCase);
+ }
+
+ public virtual void BeforeExecute(ScriptEngine scriptEngine, ScriptScope scope, ScriptResult result) {}
+
+ public virtual void AfterExecute(ScriptEngine scriptEngine, ScriptScope scope, ScriptResult result) {}
+
+ #endregion
+
+ protected abstract IEnumerable<string> SupportedLanguages();
+ }
+}
View
12 src/IronSharePoint.Framework/Console/Hooks/IHook.cs
@@ -0,0 +1,12 @@
+using Microsoft.Scripting.Hosting;
+
+namespace IronSharePoint.Console.Hooks
+{
+ interface IHook
+ {
+ bool SupportsLanguage(string languageName);
+
+ void BeforeExecute(ScriptEngine scriptEngine, ScriptScope scope, ScriptResult result);
+ void AfterExecute(ScriptEngine scriptEngine, ScriptScope scope, ScriptResult result);
+ }
+}
View
21 src/IronSharePoint.Framework/Console/Hooks/RubyHook.cs
@@ -0,0 +1,21 @@
+using System;
+using System.Collections.Generic;
+using Microsoft.Scripting.Hosting;
+
+namespace IronSharePoint.Console.Hooks
+{
+ class RubyHook : HookBase
+ {
+ public override void AfterExecute(ScriptEngine scriptEngine, ScriptScope scope, ScriptResult result)
+ {
+ base.AfterExecute(scriptEngine, scope, result);
+ var inspected = scriptEngine.Execute("_.inspect", scope);
+ result.ReturnString = Convert.ToString(inspected ?? "nil");
+ }
+
+ protected override IEnumerable<string> SupportedLanguages()
+ {
+ return new[] {IronConstant.RubyLanguageName};
+ }
+ }
+}
View
13 ...ramework/IronConsole/IronConsoleResult.cs → ...rePoint.Framework/Console/ScriptResult.cs
@@ -1,14 +1,17 @@
using System;
using Newtonsoft.Json;
-namespace IronSharePoint.IronConsole
+namespace IronSharePoint.Console
{
- public class IronConsoleResult
+ public class ScriptResult
{
public string Output { get; set; }
- public string Result { get; set; }
+ [JsonIgnore]
+ public dynamic ReturnValue { get; set; }
+ public string ReturnString { get; set; }
public string Error { get; set; }
public string StackTrace { get; set; }
+ public long ExecutionTime { get; set; }
public bool HasError
{
@@ -25,9 +28,9 @@ public void LoadJson(string json)
JsonConvert.PopulateObject(json, this);
}
- public static IronConsoleResult FromJson(string json)
+ public static ScriptResult FromJson(string json)
{
- return JsonConvert.DeserializeObject<IronConsoleResult>(json);
+ return JsonConvert.DeserializeObject<ScriptResult>(json);
}
}
}
View
153 src/IronSharePoint.Framework/IronConsole.cs
@@ -0,0 +1,153 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading;
+using System.Threading.Tasks;
+using IronSharePoint.Console;
+using IronSharePoint.Console.Hooks;
+using IronSharePoint.Util;
+using Microsoft.Scripting.Hosting;
+
+namespace IronSharePoint
+{
+ public class IronConsole
+ {
+ private readonly ScriptRuntime _runtime;
+ private readonly IHook[] _hooks;
+
+ internal IronConsole(ScriptRuntime scriptRuntime)
+ {
+ _runtime = scriptRuntime;
+ _hooks = new IHook[]
+ {
+ new RubyHook()
+ };
+ }
+
+ public ScriptRuntime Runtime
+ {
+ get { return _runtime; }
+ }
+
+ public bool IsDisposed { get; private set; }
+
+ public async Task<ScriptResult> Execute(string script, string languageName)
+ {
+ return await Task.Run(() => RunScript(script, languageName));
+ }
+
+ private ScriptResult RunScript(string script, string languageName)
+ {
+ var result = new ScriptResult();
+ var sw = new Stopwatch();
+ sw.Start();
+ try
+ {
+ var engine = Runtime.GetEngine(languageName);
+ var scope = engine.CreateScope();
+
+ ExecuteBeforeHooks(engine, result, scope);
+
+ using (var io = new IOCapture(Runtime))
+ {
+ script = string.Format("_ = ({0})", script);
+ result.ReturnValue = engine.Execute(script, scope);
+ io.Read();
+ result.Output = io.Out;
+ result.Error = io.Error;
+ }
+
+ ExecuteAfterHooks(engine, result, scope);
+
+
+ }
+ catch (Exception ex)
+ {
+ result.Error = ex.Message;
+ result.StackTrace = ex.StackTrace;
+ }
+ sw.Stop();
+ result.ExecutionTime = sw.ElapsedMilliseconds;
+
+ return result;
+ }
+
+ private void ExecuteBeforeHooks(ScriptEngine engine, ScriptResult result, ScriptScope scope)
+ {
+ var languageName = engine.Setup.DisplayName;
+
+ foreach (var hook in _hooks.Where(x => x.SupportsLanguage(languageName)))
+ {
+ hook.BeforeExecute(engine, scope, result);
+ }
+ }
+
+ private void ExecuteAfterHooks(ScriptEngine engine, ScriptResult result, ScriptScope scope)
+ {
+ var languageName = engine.Setup.DisplayName;
+
+ foreach (var hook in _hooks.Where(x => x.SupportsLanguage(languageName)))
+ {
+ hook.AfterExecute(engine, scope, result);
+ }
+ }
+ }
+
+ internal class IOCapture : IDisposable
+ {
+ public IOCapture(ScriptRuntime runtime)
+ {
+ _runtime = runtime;
+ _outBackup = runtime.IO.OutputStream;
+ _outEncoding = runtime.IO.OutputEncoding;
+ _errBackup = runtime.IO.ErrorStream;
+ _errEncoding = runtime.IO.ErrorEncoding;
+
+ _out = new MemoryStream();
+ _err = new MemoryStream();
+
+ _runtime.IO.SetOutput(_out, _outEncoding);
+ _runtime.IO.SetErrorOutput(_err, _errEncoding);
+ }
+
+ private readonly Encoding _errEncoding;
+ private readonly Stream _errBackup;
+ private readonly Encoding _outEncoding;
+ private readonly Stream _outBackup;
+
+ private readonly MemoryStream _out;
+ private readonly MemoryStream _err;
+ private readonly ScriptRuntime _runtime;
+
+ public void Read()
+ {
+ _runtime.IO.OutputWriter.Flush();
+ _runtime.IO.ErrorWriter.Flush();
+ _out.Position = 0;
+ _err.Position = 0;
+ using (var sr = new StreamReader(_out))
+ {
+ Out = sr.ReadToEnd();
+ }
+ using (var sr = new StreamReader(_err))
+ {
+ Error = sr.ReadToEnd();
+ }
+ }
+
+ public string Out { get; private set; }
+ public string Error { get; private set; }
+
+ public void Dispose()
+ {
+ _runtime.IO.SetOutput(_outBackup, _outEncoding);
+ _runtime.IO.SetErrorOutput(_errBackup, _errEncoding);
+
+ _out.Dispose();
+ _err.Dispose();
+ }
+ }
+}
View
12 src/IronSharePoint.Framework/IronConsole/Hooks/IIronConsoleHook.cs
@@ -1,12 +0,0 @@
-using Microsoft.Scripting.Hosting;
-
-namespace IronSharePoint.IronConsole.Hooks
-{
- interface IIronConsoleHook
- {
- bool SupportsExtension(string extension);
-
- void BeforeExecute(ScriptEngine scriptEngine, IronConsoleResult result);
- void AfterExecute(ScriptEngine scriptEngine, IronConsoleResult result);
- }
-}
View
25 src/IronSharePoint.Framework/IronConsole/Hooks/IronConsoleHookBase.cs
@@ -1,25 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Linq;
-using Microsoft.Scripting.Hosting;
-
-namespace IronSharePoint.IronConsole.Hooks
-{
- abstract class IronConsoleHookBase : IIronConsoleHook
- {
- #region IIronConsoleHook Members
-
- public bool SupportsExtension(string extension)
- {
- return SupportedExtensions().Contains(extension, StringComparer.InvariantCultureIgnoreCase);
- }
-
- public virtual void BeforeExecute(ScriptEngine scriptEngine, IronConsoleResult result) {}
-
- public virtual void AfterExecute(ScriptEngine scriptEngine, IronConsoleResult result) {}
-
- #endregion
-
- protected abstract IEnumerable<string> SupportedExtensions();
- }
-}
View
38 src/IronSharePoint.Framework/IronConsole/Hooks/RubyConsoleHook.cs
@@ -1,38 +0,0 @@
-using System;
-using System.Collections.Generic;
-using Microsoft.Scripting.Hosting;
-
-namespace IronSharePoint.IronConsole.Hooks
-{
- class RubyConsoleHook : IronConsoleHookBase
- {
- public override void BeforeExecute(ScriptEngine scriptEngine, IronConsoleResult result)
- {
- base.BeforeExecute(scriptEngine, result);
- /*
- scriptEngine.Execute(
- @"
- unless respond_to? :out
- begin
- include IronSharePoint::Console::Utils
- rescue
-#raise 'Could not load console utils'
- end
- end");
- */
- }
-
- public override void AfterExecute(ScriptEngine scriptEngine, IronConsoleResult result)
- {
- base.AfterExecute(scriptEngine, result);
- var consoleOut = scriptEngine.Execute(String.Format("out '{0}' if respond_to? :out", Environment.NewLine));
- result.Output = Convert.ToString(consoleOut);
- result.Result = result.Result ?? "nil";
- }
-
- protected override IEnumerable<string> SupportedExtensions()
- {
- return new[] {".rb", ".ruby"};
- }
- }
-}
View
92 src/IronSharePoint.Framework/IronConsole/IronConsole.cs
@@ -1,92 +0,0 @@
-using System;
-using System.Collections.Generic;
-using System.Threading;
-using IronSharePoint.Util;
-
-namespace IronSharePoint.IronConsole
-{
- public class IronConsole : IDisposable
- {
- // HiveId -> IIronConsole
- static readonly IDictionary<Guid, IronConsole> _hiveConsoles = new Dictionary<Guid, IronConsole>();
-
- readonly IBlockingQueue<IronConsoleTask> _queue;
- readonly Thread _queueWorker;
- readonly IronRuntime _runtime;
-
- static IronConsole()
- {
- _hiveConsoles = new Dictionary<Guid, IronConsole>();
- }
-
- protected IronConsole(IronRuntime runtime, params string[] supportedExtensions)
- {
- _runtime = runtime;
- _queue = new BlockingQueue<IronConsoleTask>();
- _queueWorker = new Thread(ProcessTaskQueue)
- {
- Name = string.Format("IronConsole Worker for {0}",
- string.Join(", ", supportedExtensions)),
- IsBackground = true
- };
- _queueWorker.Start();
- }
-
- public IronRuntime Runtime
- {
- get { return _runtime; }
- }
-
- public bool IsDisposed { get; private set; }
-
- #region IDisposable Members
-
- public void Dispose()
- {
- if (!IsDisposed)
- {
- IsDisposed = true;
- _queue.Stop();
- _queueWorker.Join(5000);
- }
- }
-
- #endregion
-
- public static IronConsole GetConsoleForRuntime(IronRuntime runtime)
- {
- var hiveId = runtime.Id;
- IronConsole console;
- if (!_hiveConsoles.TryGetValue(hiveId, out console) || console.IsDisposed)
- {
- console = new IronConsole(runtime);
- _hiveConsoles[hiveId] = console;
- }
-
- return console;
- }
-
- void ProcessTaskQueue()
- {
- IronConsoleTask task;
- while ((task = _queue.Dequeue()) != null)
- {
- task.Execute();
- }
- }
-
- public IronConsoleResult Execute(string expression, string extension)
- {
- return Execute(expression, extension, true);
- }
-
- public IronConsoleResult Execute(string expression, string extension, bool wait)
- {
- var task = new IronConsoleTask(Runtime, expression, extension);
- _queue.Enqueue(task);
- if (wait) task.WaitFor(5000);
-
- return task.IronConsoleResult;
- }
- }
-}
View
88 src/IronSharePoint.Framework/IronConsole/IronConsoleTask.cs
@@ -1,88 +0,0 @@
-using System;
-using System.Threading;
-using IronSharePoint.IronConsole.Hooks;
-using Microsoft.Scripting.Hosting;
-
-namespace IronSharePoint.IronConsole
-{
- class IronConsoleTask
- {
- static readonly IIronConsoleHook[] _hooks = new IIronConsoleHook[]
- {
- new RubyConsoleHook()
- };
-
- readonly string _expression;
- readonly string _extension;
- readonly IronRuntime _runtime;
- readonly AutoResetEvent _waitHandle;
- private IronEngine _engine;
-
- public IronConsoleTask(IronRuntime runtime, string expression, string extension)
- {
- _runtime = runtime;
- _expression = expression;
- _extension = extension;
- _waitHandle = new AutoResetEvent(false);
- }
-
- public IronConsoleResult IronConsoleResult { get; private set; }
-
- public void Execute()
- {
- IronConsoleResult = new IronConsoleResult();
- try
- {
- _engine = _runtime.GetEngineByExtension(_extension);
- var scriptEngine = _engine.ScriptEngine;
-
- ExecuteBeforeHooks(scriptEngine, IronConsoleResult);
-
- var expressionResult = scriptEngine.Execute(_expression, _runtime.ScriptRuntime.Globals);
- IronConsoleResult.Result = expressionResult != null ? expressionResult.ToString() : null;
-
- ExecuteAfterHooks(scriptEngine, IronConsoleResult);
- }
- catch (Exception ex)
- {
- IronConsoleResult.Error = ex.Message;
- IronConsoleResult.StackTrace = ex.StackTrace;
-
- if (_engine != null)
- {
- try
- {
- var eo = _engine.ScriptEngine.GetService<ExceptionOperations>();
- IronConsoleResult.StackTrace = eo.FormatException(ex);
- }
- catch { }
- }
- }
- finally
- {
- _waitHandle.Set();
- }
- }
-
- void ExecuteBeforeHooks(ScriptEngine scriptEngine, IronConsoleResult ironConsoleResult)
- {
- foreach (var hook in _hooks)
- {
- hook.BeforeExecute(scriptEngine, ironConsoleResult);
- }
- }
-
- void ExecuteAfterHooks(ScriptEngine scriptEngine, IronConsoleResult ironConsoleResult)
- {
- foreach (var hook in _hooks)
- {
- hook.AfterExecute(scriptEngine, ironConsoleResult);
- }
- }
-
- public void WaitFor(int timeout)
- {
- _waitHandle.WaitOne(5000);
- }
- }
-}
View
2 src/IronSharePoint.Framework/IronConstant.cs
@@ -18,7 +18,7 @@ public static class IronConstant
public const string IronPrefix = "IronSP_";
- public const string IronRubyLanguageName = "IronRuby";
+ public const string RubyLanguageName = "ruby";
public const string IronRuntimeKey = IronPrefix + "Runtime";
public static string IronSPRootDirectory =
View
36 src/IronSharePoint.Framework/IronJob.cs
@@ -10,51 +10,59 @@ namespace IronSharePoint
public class IronJob : SPJobDefinition
{
[Persisted]
- private string script;
+ private string _script;
public string Script
{
- get { return script; }
- set { script = value; }
+ get { return _script; }
+ set { _script = value; }
}
[Persisted]
- private Guid hiveId;
+ private Guid _siteId;
- public Guid HiveId
+ public Guid SiteId
{
- get { return hiveId; }
- set { hiveId = value; }
+ get { return _siteId; }
+ set { _siteId = value; }
}
[Persisted]
- private string data;
+ private string _data;
public string Data
{
- get { return data; }
- set { data = value; }
+ get { return _data; }
+ set { _data = value; }
}
+ [Persisted]
+ private string _languageName;
+
+ public string LanguageName
+ {
+ get { return _languageName; }
+ set { _languageName = value; }
+ }
public IronJob() : base(){}
- public IronJob(string jobName, SPWebApplication webApplication, SPServer server, SPJobLockType lockType, Guid hiveId) : base(jobName, webApplication, SPServer.Local, lockType)
+ public IronJob(string jobName, SPWebApplication webApplication, SPServer server, SPJobLockType lockType, Guid siteId) : base(jobName, webApplication, SPServer.Local, lockType)
{
this.Title = jobName;
- this.HiveId = hiveId;
+ this.SiteId = siteId;
this.Script = String.Empty;
}
public override void Execute(Guid targetInstanceId)
{
- using(SPSite site = new SPSite(HiveId))
+ using(SPSite site = new SPSite(SiteId))
{
var runtime = IronRuntime.GetDefaultIronRuntime(site);
if (String.IsNullOrEmpty(Script))
{
- runtime.IronConsole.Execute(Script, ".rb", true);
+ runtime.Console.Execute(Script, LanguageName).Wait();
}
}
}
View
45 src/IronSharePoint.Framework/Util/ScriptEngineExtensions.cs
@@ -0,0 +1,45 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics.Contracts;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+using Microsoft.Scripting;
+using Microsoft.Scripting.Hosting;
+using Microsoft.SharePoint;
+
+namespace IronSharePoint.Util
+{
+ public static class ScriptEngineExtensions
+ {
+ public static dynamic ExecuteSPFile(this ScriptEngine scriptEngine, SPFile file)
+ {
+ Contract.Requires<FileNotFoundException>(file.Exists);
+
+ var script = file.Web.GetFileAsString(file.Url);
+ var source = scriptEngine.CreateScriptSourceFromString(script, SourceCodeKind.File);
+ return source.Execute(scriptEngine.Runtime.Globals);
+ }
+
+ public static dynamic CreateInstance(this ScriptEngine scriptEngine, string typeName, params object[] parameters)
+ {
+ Contract.Requires<ArgumentNullException>(!String.IsNullOrWhiteSpace(typeName));
+
+ if (scriptEngine.Setup.DisplayName == IronConstant.RubyLanguageName)
+ {
+ // TODO better way?
+ try
+ {
+ var type = scriptEngine.Execute(typeName);
+ return scriptEngine.Operations.CreateInstance(type, parameters);
+ }
+ catch (Exception ex)
+ {
+ throw new ArgumentException(string.Format("{0} not found", typeName), "typeName", ex);
+ }
+ }
+ return null;
+ }
+ }
+}
View
2 src/IronSharePoint/IronConsole/IronConsole.webpart
@@ -2,7 +2,7 @@
<webParts>
<webPart xmlns="http://schemas.microsoft.com/WebPart/v3">
<metaData>
- <type name="IronSharePoint.IronConsole.IronConsoleWebPart, $SharePoint.Project.AssemblyFullName$" />
+ <type name="IronSharePoint.IronConsoleWebPart, $SharePoint.Project.AssemblyFullName$" />
<importErrorMessage>$Resources:core,ImportErrorMessage;</importErrorMessage>
</metaData>
<data>
View
2 src/IronSharePoint/IronConsole/IronConsoleUserControl.ascx.designer.cs
@@ -7,7 +7,7 @@
// </auto-generated>
//------------------------------------------------------------------------------
-namespace IronSharePoint.IronConsole {
+namespace IronSharePoint {
public partial class IronConsoleUserControl {
View
2 src/IronSharePoint/IronConsole/IronConsoleWebPart.cs
@@ -2,7 +2,7 @@
using System.Web.UI;
using System.Web.UI.WebControls.WebParts;
-namespace IronSharePoint.IronConsole
+namespace IronSharePoint
{
[ToolboxItem(false)]
public class IronConsoleWebPart : WebPart
View
47 src/IronSharePoint/IronSharePoint.csproj
@@ -45,6 +45,7 @@
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
<ProjectMode>SharePointCustomization</ProjectMode>
+ <CodeContractsAssemblyMode>1</CodeContractsAssemblyMode>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@@ -55,6 +56,41 @@
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<UseVSHostingProcess>false</UseVSHostingProcess>
+ <CodeContractsEnableRuntimeChecking>True</CodeContractsEnableRuntimeChecking>
+ <CodeContractsRuntimeOnlyPublicSurface>False</CodeContractsRuntimeOnlyPublicSurface>
+ <CodeContractsRuntimeThrowOnFailure>True</CodeContractsRuntimeThrowOnFailure>
+ <CodeContractsRuntimeCallSiteRequires>False</CodeContractsRuntimeCallSiteRequires>
+ <CodeContractsRuntimeSkipQuantifiers>False</CodeContractsRuntimeSkipQuantifiers>
+ <CodeContractsRunCodeAnalysis>False</CodeContractsRunCodeAnalysis>
+ <CodeContractsNonNullObligations>True</CodeContractsNonNullObligations>
+ <CodeContractsBoundsObligations>True</CodeContractsBoundsObligations>
+ <CodeContractsArithmeticObligations>False</CodeContractsArithmeticObligations>
+ <CodeContractsEnumObligations>False</CodeContractsEnumObligations>
+ <CodeContractsRedundantAssumptions>False</CodeContractsRedundantAssumptions>
+ <CodeContractsMissingPublicRequiresAsWarnings>True</CodeContractsMissingPublicRequiresAsWarnings>
+ <CodeContractsInferRequires>True</CodeContractsInferRequires>
+ <CodeContractsInferEnsures>False</CodeContractsInferEnsures>
+ <CodeContractsInferObjectInvariants>False</CodeContractsInferObjectInvariants>
+ <CodeContractsSuggestAssumptions>False</CodeContractsSuggestAssumptions>
+ <CodeContractsSuggestRequires>True</CodeContractsSuggestRequires>
+ <CodeContractsSuggestEnsures>False</CodeContractsSuggestEnsures>
+ <CodeContractsSuggestObjectInvariants>False</CodeContractsSuggestObjectInvariants>
+ <CodeContractsRunInBackground>True</CodeContractsRunInBackground>
+ <CodeContractsShowSquigglies>True</CodeContractsShowSquigglies>
+ <CodeContractsUseBaseLine>False</CodeContractsUseBaseLine>
+ <CodeContractsEmitXMLDocs>False</CodeContractsEmitXMLDocs>
+ <CodeContractsCustomRewriterAssembly />
+ <CodeContractsCustomRewriterClass />
+ <CodeContractsLibPaths />
+ <CodeContractsExtraRewriteOptions />
+ <CodeContractsExtraAnalysisOptions />
+ <CodeContractsSQLServerOption />
+ <CodeContractsBaseLineFile />
+ <CodeContractsCacheAnalysisResults>True</CodeContractsCacheAnalysisResults>
+ <CodeContractsFailBuildOnWarnings>False</CodeContractsFailBuildOnWarnings>
+ <CodeContractsRuntimeCheckingLevel>Full</CodeContractsRuntimeCheckingLevel>
+ <CodeContractsReferenceAssembly>%28none%29</CodeContractsReferenceAssembly>
+ <CodeContractsAnalysisWarningLevel>0</CodeContractsAnalysisWarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
@@ -190,12 +226,19 @@
<DependentUpon>Package.package</DependentUpon>
</None>
<None Include="TEMPLATE\Features\IronSP_Root\iron_sharepoint.rb" />
+ <None Include="TEMPLATE\Features\IronSP_Root\iron_sharepoint\application.rb" />
<None Include="TEMPLATE\Features\IronSP_Root\iron_sharepoint\console\utils.rb" />
<None Include="TEMPLATE\Features\IronSP_Root\iron_sharepoint\ext\kernel.rb" />
+ <None Include="TEMPLATE\Features\IronSP_Root\iron_sharepoint\ext\log4r.rb" />
<None Include="TEMPLATE\Features\IronSP_Root\iron_sharepoint\ext\log4r\outputter\iron_logs_outputter.rb" />
<None Include="TEMPLATE\Features\IronSP_Root\iron_sharepoint\ext\log4r\outputter\iron_memory_outputter.rb" />
+ <None Include="TEMPLATE\Features\IronSP_Root\iron_sharepoint\ext\rack.rb" />
+ <None Include="TEMPLATE\Features\IronSP_Root\iron_sharepoint\ext\rack\handlers\iis.rb" />
<None Include="TEMPLATE\Features\IronSP_Root\iron_sharepoint\file_stat.rb" />
+ <None Include="TEMPLATE\Features\IronSP_Root\iron_sharepoint\hives\directory_hive.rb" />
+ <None Include="TEMPLATE\Features\IronSP_Root\iron_sharepoint\hives\hive_composite.rb" />
<None Include="TEMPLATE\Features\IronSP_Root\iron_sharepoint\hives\sp_document_hive.rb" />
+ <None Include="TEMPLATE\Features\IronSP_Root\iron_sharepoint\hives\system_hive.rb" />
<None Include="TEMPLATE\Features\IronSP_Root\iron_sharepoint\iron_composite_control.rb" />
<None Include="TEMPLATE\Features\IronSP_Root\iron_sharepoint\iron_control.rb" />
<None Include="TEMPLATE\Features\IronSP_Root\iron_sharepoint\iron_view.rb" />
@@ -267,7 +310,9 @@
<SubType>Designer</SubType>
</Content>
<Content Include="Layouts\IronSP\503.html" />
- <Content Include="Layouts\IronSP\IronConsole.js" />
+ <Content Include="Layouts\IronSP\IronConsole.js">
+ <DependentUpon>IronConsole.coffee</DependentUpon>
+ </Content>
<Content Include="Layouts\IronSP\jquery.js" />
<Content Include="Layouts\IronSP\mustache.js" />
<Content Include="Lists\IronHive\EditDlg.htm" />
View
15 src/IronSharePoint/Layouts/IronSP/IronConsole.coffee
@@ -5,6 +5,7 @@ class IronConsole
@successCallbacks = []
@errorCallbacks = []
+
execute: (expression) ->
@addToHistory expression
wrapped = @wrapExpression(expression)
@@ -13,11 +14,11 @@ class IronConsole
$.ajax
type: 'POST'
dataType: 'text'
- data: { expression: wrapped }
+ data: { script: wrapped }
url: @serviceUrl + url_params
success: (json) =>
result = $.parseJSON(json)
- unless result["Error"]?
+ unless result["HasError"]
cb(result) for cb in @successCallbacks
else
cb(result["Error"], result["StackTrace"]) for cb in @errorCallbacks
@@ -39,7 +40,7 @@ class IronConsole
wrapExpression : (expression) =>
if @lastResultVariable?
- "#{@lastResultVariable} = (#{expression});#{@lastResultVariable}.inspect"
+ expression
else
expression
@@ -65,8 +66,8 @@ class IronConsoleView
registerEventHandlers: =>
@console.onExecuteSuccess (response) =>
- @append "output", @outputPrefix, response["Output"] if response["Output"]?
- @append "result", @resultPrefix, response["Result"]
+ @append "output", @outputPrefix, response["Output"] if response["Output"]
+ @append "result", @resultPrefix, "[" + response["ExecutionTime"] + "ms] " + response["ReturnString"]
@showExecuting false
@console.onExecuteError (error, stackTrace) =>
@append "error", '', error
@@ -146,3 +147,7 @@ class IronConsoleView
@$input.addClass 'ironSP-console-executing'
else
@$input.removeClass 'ironSP-console-executing'
+
+
+window.IronConsole = IronConsole
+window.IronConsoleView = IronConsoleView
View
518 src/IronSharePoint/Layouts/IronSP/IronConsole.js
@@ -1,277 +1,297 @@
-// Generated by CoffeeScript 1.3.3
-var IronConsole, IronConsoleView,
- __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
- __slice = [].slice;
-
-IronConsole = (function() {
- var mod;
-
- function IronConsole(serviceUrl, options) {
- this.serviceUrl = serviceUrl;
- if (options == null) {
- options = {};
+(function() {
+ var IronConsole, IronConsoleView,
+ _this = this,
+ __slice = [].slice;
+
+ IronConsole = (function() {
+ var mod;
+
+ function IronConsole(serviceUrl, options) {
+ var _this = this;
+ this.serviceUrl = serviceUrl;
+ if (options == null) {
+ options = {};
+ }
+ this.wrapExpression = function(expression) {
+ return IronConsole.prototype.wrapExpression.apply(_this, arguments);
+ };
+ this.addToHistory = function(expression) {
+ return IronConsole.prototype.addToHistory.apply(_this, arguments);
+ };
+ this.lastResultVariable = options['lastResultVariable'] || '_';
+ this.history = [];
+ this.successCallbacks = [];
+ this.errorCallbacks = [];
}
- this.wrapExpression = __bind(this.wrapExpression, this);
-
- this.addToHistory = __bind(this.addToHistory, this);
- this.lastResultVariable = options['lastResultVariable'] || '_';
- this.history = [];
- this.successCallbacks = [];
- this.errorCallbacks = [];
- }
-
- IronConsole.prototype.execute = function(expression) {
- var url_params, wrapped,
- _this = this;
- this.addToHistory(expression);
- wrapped = this.wrapExpression(expression);
- url_params = location.search.substring(1);
- if (url_params) {
- url_params = "&" + url_params;
- }
- return $.ajax({
- type: 'POST',
- dataType: 'text',
- data: {
- expression: wrapped
- },
- url: this.serviceUrl + url_params,
- success: function(json) {
- var cb, result, _i, _j, _len, _len1, _ref, _ref1, _results, _results1;
- result = $.parseJSON(json);
- if (result["Error"] == null) {
- _ref = _this.successCallbacks;
+ IronConsole.prototype.execute = function(expression) {
+ var url_params, wrapped,
+ _this = this;
+ this.addToHistory(expression);
+ wrapped = this.wrapExpression(expression);
+ url_params = location.search.substring(1);
+ if (url_params) {
+ url_params = "&" + url_params;
+ }
+ return $.ajax({
+ type: 'POST',
+ dataType: 'text',
+ data: {
+ script: wrapped
+ },
+ url: this.serviceUrl + url_params,
+ success: function(json) {
+ var cb, result, _i, _j, _len, _len1, _ref, _ref1, _results, _results1;
+ result = $.parseJSON(json);
+ if (!result["HasError"]) {
+ _ref = _this.successCallbacks;
+ _results = [];
+ for (_i = 0, _len = _ref.length; _i < _len; _i++) {
+ cb = _ref[_i];
+ _results.push(cb(result));
+ }
+ return _results;
+ } else {
+ _ref1 = _this.errorCallbacks;
+ _results1 = [];
+ for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
+ cb = _ref1[_j];
+ _results1.push(cb(result["Error"], result["StackTrace"]));
+ }
+ return _results1;
+ }
+ },
+ error: function() {
+ var args, cb, _i, _len, _ref, _results;
+ args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
+ _ref = _this.errorCallbacks;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
cb = _ref[_i];
- _results.push(cb(result));
+ _results.push(cb.apply(null, args));
}
return _results;
- } else {
- _ref1 = _this.errorCallbacks;
- _results1 = [];
- for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
- cb = _ref1[_j];
- _results1.push(cb(result["Error"], result["StackTrace"]));
- }
- return _results1;
- }
- },
- error: function() {
- var args, cb, _i, _len, _ref, _results;
- args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
- _ref = _this.errorCallbacks;
- _results = [];
- for (_i = 0, _len = _ref.length; _i < _len; _i++) {
- cb = _ref[_i];
- _results.push(cb.apply(null, args));
}
- return _results;
- }
- });
- };
-
- IronConsole.prototype.getExpressionFromHistory = function(index) {
- if (this.history.length === 0) {
- return '';
- }
- return this.history[this.history.length - 1 - mod(index, this.history.length)];
- };
-
- IronConsole.prototype.onExecuteSuccess = function(callback) {
- return this.successCallbacks.push(callback);
- };
-
- IronConsole.prototype.onExecuteError = function(callback) {
- return this.errorCallbacks.push(callback);
- };
-
- IronConsole.prototype.addToHistory = function(expression) {
- var escaped;
- escaped = expression.replace(/\\n$/, '');
- return this.history.push(escaped);
- };
+ });
+ };
- IronConsole.prototype.wrapExpression = function(expression) {
- if (this.lastResultVariable != null) {
- return "" + this.lastResultVariable + " = (" + expression + ");" + this.lastResultVariable + ".inspect";
- } else {
- return expression;
- }
- };
+ IronConsole.prototype.getExpressionFromHistory = function(index) {
+ if (this.history.length === 0) {
+ return '';
+ }
+ return this.history[this.history.length - 1 - mod(index, this.history.length)];
+ };
+
+ IronConsole.prototype.onExecuteSuccess = function(callback) {
+ return this.successCallbacks.push(callback);
+ };
+
+ IronConsole.prototype.onExecuteError = function(callback) {
+ return this.errorCallbacks.push(callback);
+ };
+
+ IronConsole.prototype.addToHistory = function(expression) {
+ var escaped;
+ escaped = expression.replace(/\\n$/, '');
+ return this.history.push(escaped);
+ };
+
+ IronConsole.prototype.wrapExpression = function(expression) {
+ if (this.lastResultVariable != null) {
+ return expression;
+ } else {
+ return expression;
+ }
+ };
- mod = function(n, base) {
- return ((n % base) + base) % base;
- };
+ mod = function(n, base) {
+ return ((n % base) + base) % base;
+ };
- return IronConsole;
+ return IronConsole;
-})();
+ })();
-IronConsoleView = (function() {
+ IronConsoleView = (function() {
- function IronConsoleView(console, options) {
- this.console = console != null ? console : new IronConsole;
- if (options == null) {
- options = {};
+ function IronConsoleView(console, options) {
+ var _this = this;
+ this.console = console != null ? console : new IronConsole;
+ if (options == null) {
+ options = {};
+ }
+ this.showExecuting = function(b) {
+ if (b == null) {
+ b = true;
+ }
+ return IronConsoleView.prototype.showExecuting.apply(_this, arguments);
+ };
+ this.toggleEditMode = function() {
+ return IronConsoleView.prototype.toggleEditMode.apply(_this, arguments);
+ };
+ this.scrollToPrompt = function() {
+ return IronConsoleView.prototype.scrollToPrompt.apply(_this, arguments);
+ };
+ this.append = function(type, prefix, text) {
+ return IronConsoleView.prototype.append.apply(_this, arguments);
+ };
+ this.insertTab = function() {
+ return IronConsoleView.prototype.insertTab.apply(_this, arguments);
+ };
+ this.registerEventHandlers = function() {
+ return IronConsoleView.prototype.registerEventHandlers.apply(_this, arguments);
+ };
+ this.render = function() {
+ return IronConsoleView.prototype.render.apply(_this, arguments);
+ };
+ this.resultPrefix = options["resultPrefix"] || '=>';
+ this.inputPrefix = options["inputPrefix"] || '>>';
+ this.outputPrefix = options["outputPrefix"] || '';
+ this.$container = $(options["containerSelector"] || '#ironSP-console-container');
+ this.consoleTemplate = $(options["consoleTemplateSelector"] || '#ironSP-console-template').html();
+ this.consoleLineTemplate = $(options["consoleLineTemplateSelector"] || '#ironSP-console-line-template').html();
+ this.historyIndex = 0;
+ this.editMode = false;
+ this.render();
+ this.registerEventHandlers();
}
- this.showExecuting = __bind(this.showExecuting, this);
- this.toggleEditMode = __bind(this.toggleEditMode, this);
-
- this.scrollToPrompt = __bind(this.scrollToPrompt, this);
-
- this.append = __bind(this.append, this);
-
- this.insertTab = __bind(this.insertTab, this);
-
- this.registerEventHandlers = __bind(this.registerEventHandlers, this);
-
- this.render = __bind(this.render, this);
-
- this.resultPrefix = options["resultPrefix"] || '=>';
- this.inputPrefix = options["inputPrefix"] || '>>';
- this.outputPrefix = options["outputPrefix"] || '';
- this.$container = $(options["containerSelector"] || '#ironSP-console-container');
- this.consoleTemplate = $(options["consoleTemplateSelector"] || '#ironSP-console-template').html();
- this.consoleLineTemplate = $(options["consoleLineTemplateSelector"] || '#ironSP-console-line-template').html();
- this.historyIndex = 0;
- this.editMode = false;
- this.render();
- this.registerEventHandlers();
- }
-
- IronConsoleView.prototype.render = function() {
- this.$console = $(Mustache.render(this.consoleTemplate, {
- prompt: this.inputPrefix
- }));
- return this.$container.empty().append(this.$console);
- };
-
- IronConsoleView.prototype.registerEventHandlers = function() {
- var _this = this;
- this.console.onExecuteSuccess(function(response) {
- if (response["Output"] != null) {
- _this.append("output", _this.outputPrefix, response["Output"]);
- }
- _this.append("result", _this.resultPrefix, response["Result"]);
- return _this.showExecuting(false);
- });
- this.console.onExecuteError(function(error, stackTrace) {
- _this.append("error", '', error);
- _this.append("stackTrace", '', stackTrace);
- return _this.showExecuting(false);
- });
- this.$input || (this.$input = $("#ironSP-console-input"));
- return this.$input.keydown(function(e) {
- var expression, handled, _ref;
- expression = (_ref = _this.$input.val()) != null ? _ref.trim() : void 0;
- handled = true;
- if (!_this.editMode) {
- switch (e.keyCode) {
- case 13:
- if (expression === 'clear') {
- _this.clearConsole();
- } else if (expression !== '') {
- _this.append("input", _this.inputPrefix, expression);
- _this.historyIndex = 0;
- _this.clearInput();
- _this.showExecuting();
- _this.console.execute(expression);
- }
- break;
- case 9:
- _this.insertTab();
- break;
- case 38:
- _this.$input.val(_this.console.getExpressionFromHistory(_this.historyIndex));
- _this.historyIndex += 1;
- break;
- case 40:
- _this.historyIndex -= 1;
- _this.$input.val(_this.console.getExpressionFromHistory(_this.historyIndex));
- break;
- case 45:
- case 126:
- _this.toggleEditMode();
- break;
- default:
- handled = false;
+ IronConsoleView.prototype.render = function() {
+ this.$console = $(Mustache.render(this.consoleTemplate, {
+ prompt: this.inputPrefix
+ }));
+ return this.$container.empty().append(this.$console);
+ };
+
+ IronConsoleView.prototype.registerEventHandlers = function() {
+ var _this = this;
+ this.console.onExecuteSuccess(function(response) {
+ if (response["Output"]) {
+ _this.append("output", _this.outputPrefix, response["Output"]);
}
- } else {
- switch (e.keyCode) {
- case 9:
- _this.insertTab();
- break;
- case 45:
- case 126:
- _this.toggleEditMode();
- break;
- default:
- handled = false;
+ _this.append("result", _this.resultPrefix, "[" + response["ExecutionTime"] + "ms] " + response["ReturnString"]);
+ return _this.showExecuting(false);
+ });
+ this.console.onExecuteError(function(error, stackTrace) {
+ _this.append("error", '', error);
+ _this.append("stackTrace", '', stackTrace);
+ return _this.showExecuting(false);
+ });
+ this.$input || (this.$input = $("#ironSP-console-input"));
+ return this.$input.keydown(function(e) {
+ var expression, handled, _ref;
+ expression = (_ref = _this.$input.val()) != null ? _ref.trim() : void 0;
+ handled = true;
+ if (!_this.editMode) {
+ switch (e.keyCode) {
+ case 13:
+ if (expression === 'clear') {
+ _this.clearConsole();
+ } else if (expression !== '') {
+ _this.append("input", _this.inputPrefix, expression);
+ _this.historyIndex = 0;
+ _this.clearInput();
+ _this.showExecuting();
+ _this.console.execute(expression);
+ }
+ break;
+ case 9:
+ _this.insertTab();
+ break;
+ case 38:
+ _this.$input.val(_this.console.getExpressionFromHistory(_this.historyIndex));
+ _this.historyIndex += 1;
+ break;
+ case 40:
+ _this.historyIndex -= 1;
+ _this.$input.val(_this.console.getExpressionFromHistory(_this.historyIndex));
+ break;
+ case 45:
+ case 126:
+ _this.toggleEditMode();
+ break;
+ default:
+ handled = false;
+ }
+ } else {
+ switch (e.keyCode) {
+ case 9:
+ _this.insertTab();
+ break;
+ case 45:
+ case 126:
+ _this.toggleEditMode();
+ break;
+ default:
+ handled = false;
+ }
+ }
+ return !handled;
+ });
+ };
+
+ IronConsoleView.prototype.insertTab = function() {
+ return this.$input.replaceSelection(" ");
+ };
+
+ IronConsoleView.prototype.clearInput = function() {
+ return this.$input.val('');
+ };
+
+ IronConsoleView.prototype.clearConsole = function() {
+ this.clearInput();
+ return this.$console.find(".ironSP-console-line").remove();
+ };
+
+ IronConsoleView.prototype.append = function(type, prefix, text) {
+ var $line, i, line, linePrefix, _i, _len, _ref;
+ text || (text = '');
+ _ref = text.replace(/\r/gm, '\n').split('\n');
+ for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
+ line = _ref[i];
+ if ((line != null ? line.trim() : void 0) !== '') {
+ linePrefix = i === 0 ? prefix : '';
+ $line = $(Mustache.render(this.consoleLineTemplate, {
+ text: line,
+ type: type,
+ prefix: linePrefix
+ }));
+ $(".ironSP-console-prompt").before($line);
}
}
- return !handled;
- });
- };
+ return this.scrollToPrompt();
+ };
- IronConsoleView.prototype.insertTab = function() {
- return this.$input.replaceSelection(" ");
- };
+ IronConsoleView.prototype.scrollToPrompt = function() {
+ return this.$container.scrollTop(this.$container[0].scrollHeight);
+ };
- IronConsoleView.prototype.clearInput = function() {
- return this.$input.val('');
- };
-
- IronConsoleView.prototype.clearConsole = function() {
- this.clearInput();
- return this.$console.find(".ironSP-console-line").remove();
- };
+ IronConsoleView.prototype.toggleEditMode = function() {
+ this.editMode = !this.editMode;
+ if (this.editMode) {
+ return this.$input.addClass('ironSP-console-edit');
+ } else {
+ return this.$input.removeClass('ironSP-console-edit');
+ }
+ };
- IronConsoleView.prototype.append = function(type, prefix, text) {
- var $line, i, line, linePrefix, _i, _len, _ref;
- text || (text = '');
- _ref = text.replace(/\r/gm, '\n').split('\n');
- for (i = _i = 0, _len = _ref.length; _i < _len; i = ++_i) {
- line = _ref[i];
- if ((line != null ? line.trim() : void 0) !== '') {
- linePrefix = i === 0 ? prefix : '';
- $line = $(Mustache.render(this.consoleLineTemplate, {
- text: line,
- type: type,
- prefix: linePrefix
- }));
- $(".ironSP-console-prompt").before($line);
+ IronConsoleView.prototype.showExecuting = function(b) {
+ if (b == null) {
+ b = true;
}
- }
- return this.scrollToPrompt();
- };
+ if (b) {
+ return this.$input.addClass('ironSP-console-executing');
+ } else {
+ return this.$input.removeClass('ironSP-console-executing');
+ }
+ };
- IronConsoleView.prototype.scrollToPrompt = function() {
- return this.$container.scrollTop(this.$container[0].scrollHeight);
- };
+ return IronConsoleView;
- IronConsoleView.prototype.toggleEditMode = function() {
- this.editMode = !this.editMode;
- if (this.editMode) {
- return this.$input.addClass('ironSP-console-edit');
- } else {
- return this.$input.removeClass('ironSP-console-edit');
- }
- };
+ })();
- IronConsoleView.prototype.showExecuting = function(b) {
- if (b == null) {
- b = true;
- }
- if (b) {
- return this.$input.addClass('ironSP-console-executing');
- } else {
- return this.$input.removeClass('ironSP-console-executing');
- }
- };
+ window.IronConsole = IronConsole;
- return IronConsoleView;
+ window.IronConsoleView = IronConsoleView;
-})();
+}).call(this);
View
43 src/IronSharePoint/Layouts/IronSP/IronConsoleService.ashx.cs
@@ -2,7 +2,7 @@
using System.Collections.Generic;
using System.Web.Script.Serialization;
using IronSharePoint.Administration;
-using IronSharePoint.IronConsole;
+using IronSharePoint.Console;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web;
@@ -19,56 +19,53 @@ public bool IsReusable
public void ProcessRequest(HttpContext context)
{
- var response = new IronConsoleResult();
- var jsonResponse = string.Empty;
+ var result = new ScriptResult();
+ string jsonResponse;
try
{
var site = SPContext.Current.Site;
var web = SPContext.Current.Web;
+
if (!web.CurrentUser.IsSiteAdmin)
{
- context.Response.Write("Only Site Admins are allowed to use the Console");
- return;
+ result.Error = "Only Site Admins are allowed to use the Console";
}
+ else
+ {
- //HiveRegistry.Local.IsTrusted(site.ID);
-
- //var ironRuntime = IronRuntime.GetIronRuntime(site, site.ID);
+ }
var ironRuntime = IronRuntime.GetDefaultIronRuntime(site);
- var extension = HttpContext.Current.Request["ext"];
- var expression = HttpContext.Current.Request["expression"];
+ var languageName = HttpContext.Current.Request["lang"];
+ var script = HttpContext.Current.Request["script"];
- if (expression == "_ = (kill);_.inspect")
+ if (script == "kill")
{
ironRuntime.Dispose();
- response.Output = "Runtime disposed.";
- }
- else if(expression == "_ = (sp_status);_.inspect")
- {
-
+ result.Output = "Runtime disposed.";
}
else
{
- response = ironRuntime.IronConsole.Execute(expression, extension);
+ result = ironRuntime.Console.Execute(script, languageName).Result;
}
}
catch (Exception ex)
{
- response.Error = ex.Message;
- response.StackTrace = ex.StackTrace;
+ result.Error = ex.Message;
+ result.StackTrace = ex.StackTrace;
}
finally
{
- if (response == null)
+ if (result == null)
{
- response = new IronConsoleResult();
- response.Error = "Request timed out";
+ result = new ScriptResult {Error = "Request timed out"};
}
- jsonResponse = response.ToJson();
+ jsonResponse = result.ToJson();
}
+ context.Response.StatusCode = 200;
+ context.Response.ContentType = "application/json";
context.Response.Write(jsonResponse);
}
}
View
26 src/IronSharePoint/TEMPLATE/Features/IronSP_Root/iron_sharepoint/console/utils.rb
@@ -1,23 +1,6 @@
module IronSharePoint
module Console
module Utils
- def puts obj
- out_buffer << obj.to_s
- return nil
- end
-
- def p obj
- inspected = obj.inspect
- puts inspected
- inspected
- end
-
- def out seperator = '\n', clear = true
- response = out_buffer.join seperator
- out_buffer.clear
- response
- end
-
def pm obj, *options
methods = obj.methods
methods -= Object.methods unless options.include? :more
@@ -53,15 +36,8 @@ def pm obj, *options
def print_log n = 10
Log4r::Outputter["iron_default"].print_log n
end
-
- private
-
- def out_buffer
- $out_buffer ||= []
- end
end
end
end
-include IronSharePoint::Console::Utils
-puts self
+include IronSharePoint::Console::Utils
View
47 test/IronSharePoint.Framework.Test/Console/Hooks/RubyHook_Fixture.cs
@@ -0,0 +1,47 @@
+using FluentAssertions;
+using IronSharePoint.Console;
+using IronSharePoint.Console.Hooks;
+using Microsoft.Scripting.Hosting;
+using NUnit.Framework;
+
+namespace IronSharePoint.Framework.Test.Console.Hooks
+{
+ [TestFixture]
+ public class RubyHook_Fixture
+ {
+ internal RubyHook Sut;
+ public ScriptRuntime ScriptRuntime;
+ public ScriptEngine ScriptEngine;
+
+ [TestFixtureSetUp]
+ public void FixtureSetUp()
+ {
+ ScriptRuntime = TestHelper.CreateRubyRuntime();
+ ScriptEngine = ScriptRuntime.GetEngine(IronConstant.RubyLanguageName);
+ }
+
+ [SetUp]
+ public void SetUp()
+ {
+ Sut = new RubyHook();
+ }
+
+ [Test]
+ public void AfterExecute_InspectsReturnValueAndSetsReturnString()
+ {
+ var scope = ScriptEngine.CreateScope();
+ var returnValue = ScriptEngine.Execute("_ = Object.new", scope);
+ var scriptResult = new ScriptResult {ReturnValue = returnValue};
+
+ Sut.AfterExecute(ScriptEngine, scope, scriptResult);
+
+ scriptResult.ReturnString.Should().Match("#<Object:0x*>");
+ }
+
+ [Test]
+ public void SupportsRuby()
+ {
+ Sut.SupportsLanguage(IronConstant.RubyLanguageName).Should().BeTrue();
+ }
+ }
+}
View
26 test/IronSharePoint.Framework.Test/Console/ScriptResult_Fixture.cs
@@ -0,0 +1,26 @@
+using FluentAssertions;
+using IronSharePoint.Console;
+using NUnit.Framework;
+
+namespace IronSharePoint.Framework.Test.Console
+{
+ [TestFixture]
+ public class ScriptResult_Fixture
+ {
+ public ScriptResult Sut;
+
+ [Test]
+ public void ToJson_IgnoresReturnValue()
+ {
+ Sut = new ScriptResult
+ {
+ Output = "foo",
+ ReturnValue = "ReturnValue"
+ };
+
+ System.Console.WriteLine(Sut.ToJson());
+ Sut.ToJson().Should().NotContain("ReturnValue");
+ }
+
+ }
+}
View
83 test/IronSharePoint.Framework.Test/IOCapture_Fixture.cs
@@ -0,0 +1,83 @@
+using FluentAssertions;
+using Microsoft.Scripting.Hosting;
+using NUnit.Framework;
+
+namespace IronSharePoint.Framework.Test
+{
+ [TestFixture]
+ public class IOCapture_Fixture
+ {
+ internal IOCapture Sut;
+ public ScriptRuntime ScriptRuntime;
+
+ [SetUp]
+ public void SetUp()
+ {
+ ScriptRuntime = TestHelper.CreateRubyRuntime();
+ }
+
+ [Test]
+ public void ReplacesOutputStreamInScope()
+ {
+ var originalOut = ScriptRuntime.IO.OutputStream;
+
+ using (Sut = new IOCapture(ScriptRuntime))
+ {
+ ScriptRuntime.IO.OutputStream.Should().NotBeSameAs(originalOut);
+ }
+ }
+
+ [Test]
+ public void ReplacesErrorStreamInScope()
+ {
+ var originalOut = ScriptRuntime.IO.ErrorStream;
+
+ using (Sut = new IOCapture(ScriptRuntime))
+ {
+ ScriptRuntime.IO.ErrorStream.Should().NotBeSameAs(originalOut);
+ }
+ }
+
+ [Test]
+ public void Dispose_SetsOutputStreamBackToOriginal()
+ {
+ var originalOut = ScriptRuntime.IO.OutputStream;
+
+ using (Sut = new IOCapture(ScriptRuntime)) {}
+
+ ScriptRuntime.IO.OutputStream.Should().BeSameAs(originalOut);
+ }
+
+ [Test]
+ public void Dispose_SetsErrorStreamBackToOriginal()
+ {
+ var originalOut = ScriptRuntime.IO.ErrorStream;
+
+ using (Sut = new IOCapture(ScriptRuntime)) { }
+
+ ScriptRuntime.IO.ErrorStream.Should().BeSameAs(originalOut);
+ }
+
+ [Test]
+ public void Read_WritesCapturedOutputToProperty()
+ {
+ using (Sut = new IOCapture(ScriptRuntime))
+ {
+ ScriptRuntime.IO.OutputWriter.Write("foo");
+ Sut.Read();
+ Sut.Out.Should().Be("foo");
+ }
+ }
+
+ [Test]
+ public void Read_WritesCapturedErrorToProperty()
+ {
+ using (Sut = new IOCapture(ScriptRuntime))
+ {
+ ScriptRuntime.IO.ErrorWriter.Write("foo");
+ Sut.Read();
+ Sut.Error.Should().Be("foo");
+ }
+ }
+ }
+}
View
58 test/IronSharePoint.Framework.Test/IronConsole_Fixture.cs
@@ -0,0 +1,58 @@
+using System;
+using System.Threading;
+using FluentAssertions;
+using Microsoft.Scripting.Hosting;
+using NUnit.Framework;
+
+namespace IronSharePoint.Framework.Test
+{
+ [TestFixture]
+ public class IronConsole_Fixture
+ {
+ public IronConsole Sut;
+ public ScriptRuntime ScriptRuntime;
+
+ [TestFixtureSetUp]
+ public void FixtureSetUp()
+ {
+ ScriptRuntime = TestHelper.CreateRubyRuntime();
+ }
+
+ [SetUp]
+ public void SetUp()
+ {
+ Sut = new IronConsole(ScriptRuntime);
+ }
+
+ [Test]
+ public void Execute_SetsOutputOnResult()
+ {
+ var result = Sut.Execute("puts 'foo'", IronConstant.RubyLanguageName).Result;
+
+ result.Output.Should().Be("foo\r\n");
+ }
+
+ [Test]
+ public void Execute_SetsErrorOnResult()
+ {
+ var result = Sut.Execute("$stderr.puts 'foo'", IronConstant.RubyLanguageName).Result;
+
+ result.Error.Should().Be("foo\r\n");
+ }
+
+ [Test]
+ public void Execute_SetsReturnValueOnResult()
+ {
+ var result = Sut.Execute("1", IronConstant.RubyLanguageName).Result;
+
+ Assert.AreEqual(result.ReturnValue, 1); // Cannot use Should() on dynamic types
+ }
+
+ [Test]
+ public void Execute_SetsExecutionTimeOnResult()
+ {
+ var result = Sut.Execute("sleep 0.01 # 10 ms", IronConstant.RubyLanguageName).Result;
+ result.ExecutionTime.Should().BeGreaterOrEqualTo(10);
+ }
+ }
+}
View
42 test/IronSharePoint.Framework.Test/IronSharePoint.Framework.Test.csproj
@@ -11,6 +11,7 @@
<AssemblyName>IronSharePoint.Framework.Test</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
+ <CodeContractsAssemblyMode>1</CodeContractsAssemblyMode>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
@@ -20,6 +21,41 @@
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
+ <CodeContractsEnableRuntimeChecking>True</CodeContractsEnableRuntimeChecking>
+ <CodeContractsRuntimeOnlyPublicSurface>False</CodeContractsRuntimeOnlyPublicSurface>
+ <CodeContractsRuntimeThrowOnFailure>True</CodeContractsRuntimeThrowOnFailure>
+ <CodeContractsRuntimeCallSiteRequires>False</CodeContractsRuntimeCallSiteRequires>
+ <CodeContractsRuntimeSkipQuantifiers>False</CodeContractsRuntimeSkipQuantifiers>
+ <CodeContractsRunCodeAnalysis>False</CodeContractsRunCodeAnalysis>
+ <CodeContractsNonNullObligations>True</CodeContractsNonNullObligations>
+ <CodeContractsBoundsObligations>True</CodeContractsBoundsObligations>
+ <CodeContractsArithmeticObligations>False</CodeContractsArithmeticObligations>
+ <CodeContractsEnumObligations>False</CodeContractsEnumObligations>
+ <CodeContractsRedundantAssumptions>False</CodeContractsRedundantAssumptions>
+ <CodeContractsMissingPublicRequiresAsWarnings>True</CodeContractsMissingPublicRequiresAsWarnings>
+ <CodeContractsInferRequires>True</CodeContractsInferRequires>
+ <CodeContractsInferEnsures>False</CodeContractsInferEnsures>
+ <CodeContractsInferObjectInvariants>False</CodeContractsInferObjectInvariants>
+ <CodeContractsSuggestAssumptions>False</CodeContractsSuggestAssumptions>
+ <CodeContractsSuggestRequires>True</CodeContractsSuggestRequires>
+ <CodeContractsSuggestEnsures>False</CodeContractsSuggestEnsures>
+ <CodeContractsSuggestObjectInvariants>False</CodeContractsSuggestObjectInvariants>
+ <CodeContractsRunInBackground>True</CodeContractsRunInBackground>
+ <CodeContractsShowSquigglies>True</CodeContractsShowSquigglies>
+ <CodeContractsUseBaseLine>False</CodeContractsUseBaseLine>
+ <CodeContractsEmitXMLDocs>False</CodeContractsEmitXMLDocs>
+ <CodeContractsCustomRewriterAssembly />
+ <CodeContractsCustomRewriterClass />
+ <CodeContractsLibPaths />
+ <CodeContractsExtraRewriteOptions />
+ <CodeContractsExtraAnalysisOptions />
+ <CodeContractsSQLServerOption />
+ <CodeContractsBaseLineFile />
+ <CodeContractsCacheAnalysisResults>True</CodeContractsCacheAnalysisResults>
+ <CodeContractsFailBuildOnWarnings>False</CodeContractsFailBuildOnWarnings>
+ <CodeContractsRuntimeCheckingLevel>Full</CodeContractsRuntimeCheckingLevel>
+ <CodeContractsReferenceAssembly>%28none%29</CodeContractsReferenceAssembly>
+ <CodeContractsAnalysisWarningLevel>0</CodeContractsAnalysisWarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
@@ -66,13 +102,19 @@
<Compile Include="Administration\HiveSetupCollection_Fixture.cs" />
<Compile Include="Administration\HiveSetup_Fixture.cs" />
<Compile Include="Administration\HiveRegistry_Fixture.cs" />
+ <Compile Include="Console\Hooks\RubyHook_Fixture.cs" />
<Compile Include="Hive\HiveComposite_Fixture.cs" />
<Compile Include="Hive\DirectoryHive_Fixture.cs" />
<Compile Include="Hive\SPDocumentHive_Fixture.cs" />
+ <Compile Include="IOCapture_Fixture.cs" />
+ <Compile Include="IronConsole_Fixture.cs" />
<Compile Include="IronPlatformAdaptionLayer_Fixture.cs" />
<Compile Include="IronScriptHost_Fixture.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
+ <Compile Include="Console\ScriptResult_Fixture.cs" />
+ <Compile Include="TestHelper.cs" />
<Compile Include="Util\EnumerableExtensions_Fixture.cs" />
+ <Compile Include="Util\ScriptEngineExtensions_Fixture.cs" />
<Compile Include="Util\StringExtensions_Fixture.cs" />
</ItemGroup>
<ItemGroup>
View
22 test/IronSharePoint.Framework.Test/TestHelper.cs
@@ -0,0 +1,22 @@
+using Microsoft.Scripting.Hosting;
+
+namespace IronSharePoint.Framework.Test
+{
+ public static class TestHelper
+ {
+ public static ScriptRuntime CreateRubyRuntime()
+ {
+ var setup = new ScriptRuntimeSetup();
+ var languageSetup = new LanguageSetup(
+ "IronRuby.Runtime.RubyContext, IronRuby, Version=1.1.3.0, Culture=neutral, PublicKeyToken=7f709c5b713576e1",
+ IronConstant.RubyLanguageName,
+ new[] { "IronRuby", "Ruby", "rb" },
+ new[] { ".rb" });
+ setup.LanguageSetups.Add(languageSetup);
+ setup.HostType = typeof(ScriptHost);
+ setup.DebugMode = true;
+
+ return new ScriptRuntime(setup);
+ }
+ }
+}
View
4 test/IronSharePoint.Framework.Test/Util/EnumerableExtensions_Fixture.cs
@@ -1,4 +1,6 @@
-using FluentAssertions;
+using System.IO;
+using System.Text;
+using FluentAssertions;
using IronSharePoint.Util;
using NUnit.Framework;
View
41 test/IronSharePoint.Framework.Test/Util/ScriptEngineExtensions_Fixture.cs
@@ -0,0 +1,41 @@
+using System;
+using IronSharePoint.Util;
+using Microsoft.Scripting.Hosting;
+using NUnit.Framework;
+
+namespace IronSharePoint.Framework.Test.Util
+{
+ [TestFixture]
+ public class ScriptEngineExtensions_Fixture
+ {
+ public ScriptRuntime ScriptRuntime;
+ public ScriptEngine Sut;
+
+ [TestFixtureSetUp]
+ public void FixtureSetUp()
+ {
+ ScriptRuntime = TestHelper.CreateRubyRuntime();
+ Sut = ScriptRuntime.GetEngine(IronConstant.RubyLanguageName);
+ }
+
+ [Test]
+ public void CreateInstance_WithExistingType_ReturnsInstance()
+ {
+ var instance = Sut.CreateInstance("System::String", "foo");
+
+ Assert.AreEqual(instance, "foo");
+ }
+
+ [Test, ExpectedException(typeof (ArgumentException))]
+ public void CreateInstance_WithUnknownType_ThrowsArgumentException()
+ {
+ Sut.CreateInstance("FOO", "foo");
+ }
+
+ [Test, ExpectedException(typeof(ArgumentNullException))]
+ public void CreateInstance_ThrowsArgumentNullException()
+ {
+ Sut.CreateInstance(null);
+ }
+ }
+}

0 comments on commit ee9b492

Please sign in to comment.
Something went wrong with that request. Please try again.