Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Better exception handling/logging

  • Loading branch information...
commit 2f61f73f3bbefb792e7297ab606b59a26e6fb1bc 1 parent b79ce24
@kmees kmees authored
Showing with 400 additions and 346 deletions.
  1. +0 −1  src/IronSharePoint.Framework/Console/ScriptResult.cs
  2. +14 −0 src/IronSharePoint.Framework/Diagnostics/IronCategoryDiagnosticsId.cs
  3. +75 −9 src/IronSharePoint.Framework/Diagnostics/IronDiagnosticService.cs
  4. +62 −0 src/IronSharePoint.Framework/Exceptions.cs
  5. +14 −0 src/IronSharePoint.Framework/IWrapperControl.cs
  6. +0 −1  src/IronSharePoint.Framework/IronConsole.cs
  7. +15 −25 src/IronSharePoint.Framework/IronHttpModule.cs
  8. +23 −49 src/IronSharePoint.Framework/IronRuntime.cs
  9. +4 −0 src/IronSharePoint.Framework/IronSharePoint.Framework.csproj
  10. +30 −50 src/IronSharePoint.Framework/IronWrapperControl.cs
  11. +45 −87 src/IronSharePoint.Framework/IronWrapperUserControl.cs
  12. +7 −0 src/IronSharePoint.Framework/Util/EnumerableExtensions.cs
  13. +6 −1 src/IronSharePoint.Framework/Util/ScriptEngineExtensions.cs
  14. +34 −0 src/IronSharePoint.Framework/Util/WrapperControlExtensions.cs
  15. +53 −90 src/IronSharePoint/IronPart/IronPart.cs
  16. +2 −1  src/IronSharePoint/IronSharePoint.csproj
  17. +1 −2  src/IronSharePoint/Layouts/IronSP/IronConsole.coffee
  18. +1 −2  src/IronSharePoint/Layouts/IronSP/IronConsole.js
  19. +3 −4 src/IronSharePoint/Layouts/IronSP/IronConsoleService.ashx.cs
  20. +0 −5 src/IronSharePoint/TEMPLATE/Features/IronSP_Root/iron_sharepoint/iron_composite_control.rb
  21. +0 −5 src/IronSharePoint/TEMPLATE/Features/IronSP_Root/iron_sharepoint/iron_control.rb
  22. +0 −2  src/IronSharePoint/TEMPLATE/Features/IronSP_Root/iron_sharepoint/main_http_handler.rb
  23. +0 −9 src/IronSharePoint/TEMPLATE/Features/IronSP_Root/iron_sharepoint/mixins/type_registration.rb
  24. +7 −0 src/IronSharePoint/TEMPLATE/Features/IronSP_Root/iron_sharepoint/patches/system/date_time.rb
  25. +0 −1  test/IronSharePoint.Framework.Test/Console/ScriptResult_Fixture.cs
  26. +3 −1 test/IronSharePoint.Framework.Test/Util/ScriptEngineExtensions_Fixture.cs
  27. +1 −1  test/IronSharePoint.Framework.Test/_assets/script_result.json
View
1  src/IronSharePoint.Framework/Console/ScriptResult.cs
@@ -8,7 +8,6 @@ public class ScriptResult
public string Output { get; set; }
public string ReturnValue { get; set; }
public string Error { get; set; }
- public string StackTrace { get; set; }
public long ExecutionTime { get; set; }
public bool HasError
View
14 src/IronSharePoint.Framework/Diagnostics/IronCategoryDiagnosticsId.cs
@@ -0,0 +1,14 @@
+namespace IronSharePoint.Diagnostics
+{
+ public enum IronCategoryDiagnosticsId
+ {
+ None = 0,
+ Core = 100,
+ Controls = 200,
+ WebParts = 300,
+ EventReceivers = 400,
+ Jobs = 900,
+ Services = 1000,
+ Unknown = 9999
+ }
+}
View
84 src/IronSharePoint.Framework/Diagnostics/IronDiagnosticService.cs
@@ -2,21 +2,87 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;
+using Microsoft.Scripting.Hosting;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint;
namespace IronSharePoint.Diagnostics
{
- public enum IronCategoryDiagnosticsId
+ public class IronULSLogger
{
- None = 0,
- Core = 100,
- Controls = 200,
- WebParts = 300,
- EventReceivers = 400,
- Jobs = 900,
- Services = 1000,
- Unknown = 9999
+ private readonly IronDiagnosticsService _service;
+
+ const string ErrorFormat = "Exception '{0}' - {1} at {2}";
+
+ public IronULSLogger(IronDiagnosticsService service)
+ {
+ _service = service;
+ }
+
+ public IronULSLogger() : this(IronDiagnosticsService.Local)
+ {
+ }
+
+ static readonly Lazy<IronULSLogger> _local = new Lazy<IronULSLogger>(() => new IronULSLogger(), true);
+
+ public static IronULSLogger Local
+ {
+ get { return _local.Value; }
+ }
+
+ public void Verbose(string message, IronCategoryDiagnosticsId categoryId)
+ {
+ IronDiagnosticsService.Local.WriteTrace(1, IronDiagnosticsService.Local[categoryId],
+ TraceSeverity.Verbose, message);
+ }
+
+ public void Error(string message, IronCategoryDiagnosticsId categoryId = IronCategoryDiagnosticsId.None)
+ {
+ _service.WriteTrace(1, IronDiagnosticsService.Local[categoryId], TraceSeverity.Unexpected, message);
+ }
+
+ public string Error(string message, Exception ex, IronCategoryDiagnosticsId categoryId = IronCategoryDiagnosticsId.None)
+ {
+ string output;
+ if (!IsRubyException(ex) || !TryFormatRubyException(ex, out output))
+ {
+ output = String.Format(ErrorFormat,
+ ex.GetType().Name,
+ ex.Message,
+ ex.StackTrace);
+ }
+ if (!String.IsNullOrWhiteSpace(message)) output = message + " - " + output;
+ _service.WriteTrace(1, IronDiagnosticsService.Local[categoryId], TraceSeverity.Unexpected, output);
+
+ return output;
+ }
+
+ bool IsRubyException(Exception ex)
+ {
+ return ex.TargetSite != null
+ && ex.TargetSite.DeclaringType.FullName.StartsWith("Microsoft.Scripting.Interpreter");
+ }
+
+ bool TryFormatRubyException(Exception ex, out string output)
+ {
+ output = string.Empty;
+ if (SPContext.Current != null)
+ {
+ try
+ {
+ var runtime = IronRuntime.GetDefaultIronRuntime(SPContext.Current.Site);
+ var expcetionOperations = runtime.RubyEngine.GetService<ExceptionOperations>();
+
+ output = expcetionOperations.FormatException(ex);
+ return true;
+ }
+ catch
+ {
+ return false;
+ }
+ }
+ return false;
+ }
}
[System.Runtime.InteropServices.GuidAttribute("8D5F89BA-0DE0-4D46-811C-E631B6FAC228")]
View
62 src/IronSharePoint.Framework/Exceptions.cs
@@ -0,0 +1,62 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Runtime.Serialization;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace IronSharePoint.Exceptions
+{
+ [Serializable]
+ public class IronRuntimeAccesssException : Exception
+ {
+ public Guid SiteId { get; set; }
+
+ public IronRuntimeAccesssException() {}
+
+ public IronRuntimeAccesssException(string message)
+ : base(message) {}
+
+ public IronRuntimeAccesssException(string message, Exception inner)
+ : base(message, inner) {}
+
+ protected IronRuntimeAccesssException(
+ SerializationInfo info,
+ StreamingContext context)
+ : base(info, context) {}
+ }
+
+ [Serializable]
+ public class RubyFrameworkInitializationException : Exception
+ {
+ public RubyFrameworkInitializationException() {}
+
+ public RubyFrameworkInitializationException(string message)
+ : base(message) {}
+
+ public RubyFrameworkInitializationException(string message, Exception inner)
+ : base(message, inner) {}
+
+ protected RubyFrameworkInitializationException(
+ SerializationInfo info,
+ StreamingContext context)
+ : base(info, context) {}
+ }
+
+ [Serializable]
+ public class DynamicInstanceInitializationException : Exception
+ {
+ public DynamicInstanceInitializationException() {}
+
+ public DynamicInstanceInitializationException(string message)
+ : base(message) {}
+
+ public DynamicInstanceInitializationException(string message, Exception inner)
+ : base(message, inner) {}
+
+ protected DynamicInstanceInitializationException(
+ SerializationInfo info,
+ StreamingContext context)
+ : base(info, context) {}
+ }
+}
View
14 src/IronSharePoint.Framework/IWrapperControl.cs
@@ -0,0 +1,14 @@
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace IronSharePoint
+{
+ interface IWrapperControl
+ {
+ string ControlName { get; set; }
+ Exception InstantiationException { get; set; }
+ }
+}
View
1  src/IronSharePoint.Framework/IronConsole.cs
@@ -54,7 +54,6 @@ private ScriptResult RunScript(string script)
catch (Exception ex)
{
result.Error = ex.Message;
- result.StackTrace = ex.StackTrace;
}
sw.Stop();
result.ExecutionTime = sw.ElapsedMilliseconds;
View
40 src/IronSharePoint.Framework/IronHttpModule.cs
@@ -1,50 +1,42 @@
using System;
using System.Collections.Generic;
using System.Linq;
-using System.Text;
using System.Web;
-using Microsoft.SharePoint;
-using Microsoft.Scripting.Hosting;
+using IronSharePoint.Diagnostics;
namespace IronSharePoint
{
- public class IronHttpModule:IHttpModule
+ public class IronHttpModule : IHttpModule
{
public void Init(HttpApplication application)
{
- application.EndRequest += new EventHandler(EndRequest);
- application.Error += new EventHandler(Error);
+ application.EndRequest += EndRequest;
+ application.Error += Error;
}
- void Error(object sender, EventArgs e)
+ public void Dispose()
{
- var application = sender as HttpApplication;
-
- if (SPContext.Current != null)
- {
- var runtime = IronRuntime.GetDefaultIronRuntime(SPContext.Current.Site);
- var engine = runtime.RubyEngine;
- var exception = application.Server.GetLastError();
+ }
- var eo = engine.GetService<ExceptionOperations>();
- string error = eo.FormatException(exception);
+ private void Error(object sender, EventArgs e)
+ {
+ var application = sender as HttpApplication;
- IronRuntime.LogError(error, exception);
- }
+ IronULSLogger.Local.Error("Error in HttpModule", application.Server.GetLastError(), IronCategoryDiagnosticsId.Core);
}
-
- void EndRequest(object sender, EventArgs e)
+
+ private void EndRequest(object sender, EventArgs e)
{
var application = sender as HttpApplication;
- CleanUp(application);
+ CleanUp(application);
}
private static void CleanUp(HttpApplication application)
{
var ironObjectsToDispose = new List<IDisposable>();
- foreach (var key in application.Context.Items.Keys.OfType<String>())
+ foreach (string key in application.Context.Items.Keys.OfType<String>())
{
if (key.StartsWith(IronConstant.IronPrefix))
{
@@ -58,7 +50,5 @@ private static void CleanUp(HttpApplication application)
ironObjectsToDispose.ForEach(o => o.Dispose());
}
-
- public void Dispose() { }
}
-}
+}
View
72 src/IronSharePoint.Framework/IronRuntime.cs
@@ -3,6 +3,7 @@
using System.IO;
using System.Web;
using IronSharePoint.Diagnostics;
+using IronSharePoint.Exceptions;
using Microsoft.Scripting.Hosting;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
@@ -24,13 +25,13 @@ public class IronRuntime : IDisposable
private readonly Guid _siteId;
private readonly Guid _id;
+ public IronULSLogger ULSLogger { get; private set; }
+
private IronRuntime(Guid siteId)
{
_siteId = siteId;
_id = Guid.NewGuid();
-
- DynamicTypeRegistry = new Dictionary<string, Object>();
- DynamicFunctionRegistry = new Dictionary<string, Object>();
+ ULSLogger = new IronULSLogger();
CreateScriptRuntime();
Console = new IronConsole(ScriptRuntime);
@@ -64,10 +65,6 @@ public IHive Hive
get { return ScripHost.Hive; }
}
- public Dictionary<string, Object> DynamicTypeRegistry { get; private set; }
- public Dictionary<string, Object> DynamicFunctionRegistry { get; private set; }
-
- public string HttpHandlerClass { get; set; }
public bool IsDisposed { get; private set; }
public Guid SiteId
@@ -80,31 +77,6 @@ public Guid Id
get { return _id; }
}
- public SPSite Site
- {
- get
- {
- var key = IronConstant.GetPrefixed("Site_" + Id);
- var httpContext = HttpContext.Current;
- SPSite site;
-
- if (httpContext != null)
- {
- if (!httpContext.Items.Contains(key))
- {
- httpContext.Items[key] = new SPSite(Id, SPUserToken.SystemAccount);
- }
- site = httpContext.Items[key] as SPSite;
- }
- else
- {
- site = new SPSite(Id, SPUserToken.SystemAccount);
- }
-
- return site;
- }
- }
-
#region IDisposable Members
public void Dispose()
@@ -158,7 +130,6 @@ private void InitializeScriptEngines()
ScriptScope scope = RubyEngine.CreateScope();
scope.SetVariable("iron_runtime", this);
RubyEngine.Execute("$RUNTIME = iron_runtime", scope);
- RubyEngine.Execute(@"require 'rubygems'; #require 'application'", ScriptRuntime.Globals);
}
}
@@ -176,6 +147,18 @@ private void PrivilegedInitialize()
Directory.SetCurrentDirectory(IronConstant.IronRubyRootDirectory);
}
+ private void LoadRubyFramework()
+ {
+ try
+ {
+ RubyEngine.Execute(@"require 'rubygems'; require 'iron_sharepoint'; require 'application'", ScriptRuntime.Globals);
+ }
+ catch (Exception ex)
+ {
+ throw new RubyFrameworkInitializationException("Error loading ruby framework", ex);
+ }
+ }
+
public static IronRuntime GetDefaultIronRuntime(SPSite targetSite)
{
using (new SPMonitoredScope("Retrieving IronRuntime"))
@@ -190,11 +173,16 @@ public static IronRuntime GetDefaultIronRuntime(SPSite targetSite)
{
runtime = new IronRuntime(targetId);
LivingRuntimes[targetId] = runtime;
+ runtime.LoadRubyFramework();
+ }
+ catch (RubyFrameworkInitializationException ex)
+ {
+ IronULSLogger.Local.Error(string.Format("Could not initialize ruby framework for SPSite '{0}'", targetId), ex, IronCategoryDiagnosticsId.Core);
}
catch (Exception ex)
{
- LogError("Error creating IronRuntime", ex);
- throw;
+ IronULSLogger.Local.Error(string.Format("Could not create IronRuntime for SPSite '{0}'", targetId), ex, IronCategoryDiagnosticsId.Core);
+ throw new IronRuntimeAccesssException("Cannot access IronRuntime", ex){SiteId = targetId};
}
}
}
@@ -218,19 +206,5 @@ private static bool TryGetExistingRuntime(Guid targetId, out IronRuntime runtime
}
return runtime != null;
}
-
- public static void LogError(string msg, Exception ex)
- {
- IronDiagnosticsService.Local.WriteTrace(1, IronDiagnosticsService.Local[IronCategoryDiagnosticsId.Core],
- TraceSeverity.Unexpected,
- String.Format("{0}\nError:{1}\nStack:{2}", msg, ex.Message,
- ex.StackTrace));
- }
-
- public static void LogVerbose(string msg)
- {
- IronDiagnosticsService.Local.WriteTrace(1, IronDiagnosticsService.Local[IronCategoryDiagnosticsId.Core],
- TraceSeverity.Verbose, String.Format("{0}.", msg));
- }
}
}
View
4 src/IronSharePoint.Framework/IronSharePoint.Framework.csproj
@@ -98,11 +98,14 @@
<Compile Include="Administration\HiveSetup.cs" />
<Compile Include="Administration\HiveRegistry.cs" />
<Compile Include="Administration\HiveSetupCollection.cs" />
+ <Compile Include="Diagnostics\IronCategoryDiagnosticsId.cs" />
<Compile Include="Diagnostics\IronDiagnosticService.cs" />
+ <Compile Include="Exceptions.cs" />
<Compile Include="Hives\SystemHive.cs" />
<Compile Include="Hives\HiveComposite.cs" />
<Compile Include="Hives\DirectoryHive.cs" />
<Compile Include="Hives\SPDocumentHive.cs" />
+ <Compile Include="IWrapperControl.cs" />
<Compile Include="IHive.cs" />
<Compile Include="IIronControl.cs" />
<Compile Include="IIronDataStore.cs" />
@@ -127,6 +130,7 @@
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="RackHttpHandler.cs" />
<Compile Include="Util\BlockingQueue.cs" />
+ <Compile Include="Util\WrapperControlExtensions.cs" />
<Compile Include="Util\EnumerableExtensions.cs" />
<Compile Include="Util\IBlockingQueue.cs" />
<Compile Include="Util\ScriptEngineExtensions.cs" />
View
80 src/IronSharePoint.Framework/IronWrapperControl.cs
@@ -1,49 +1,27 @@
using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
+using System.Diagnostics.Contracts;
using System.Web.UI;
-using Microsoft.Scripting.Hosting;
-using Microsoft.SharePoint;
-using System.IO;
using System.Web.UI.WebControls;
-using Microsoft.Scripting.Hosting.Providers;
using IronSharePoint.Diagnostics;
-using Microsoft.SharePoint.Administration;
-using System.Web.Caching;
-using System.Web;
-using System.ComponentModel;
+using IronSharePoint.Util;
+using Microsoft.Scripting.Hosting;
+using Microsoft.SharePoint;
namespace IronSharePoint
{
- public class IronWrapperControl : CompositeControl
+ public class IronWrapperControl : CompositeControl, IWrapperControl
{
- public string ControlName { get; set; }
- private ScriptEngine _engine;
private Control _control;
- private Exception Exception { get; set; }
+ public string ControlName { get; set; }
+ public Exception InstantiationException { get; set; }
protected override void OnInit(EventArgs e)
{
- if (String.IsNullOrWhiteSpace(ControlName))
- {
- Exception = new InvalidOperationException("ControlName not set");
- return;
- }
+ Contract.Requires<InvalidOperationException>(!String.IsNullOrWhiteSpace(ControlName), "ControlName not set");
- try
+ if (this.TryCreateDynamicControl(out _control))
{
- IronRuntime ironRuntime = IronRuntime.GetDefaultIronRuntime(SPContext.Current.Site);
- _engine = ironRuntime.RubyEngine;
- var scope = _engine.CreateScope();
- var controlClass = scope.GetVariable("ControlName");
- _control = controlClass.@new();
-
- this.Controls.Add(_control);
- }
- catch (Exception ex)
- {
- Exception = ex;
+ Controls.Add(_control);
}
base.OnInit(e);
@@ -51,33 +29,35 @@ protected override void OnInit(EventArgs e)
protected override void Render(HtmlTextWriter writer)
{
- // Todo better error handling
- if (Exception != null)
+ if (InstantiationException != null)
+ {
+ HandleException(InstantiationException, writer);
+ }
+ else
{
- string errorMessage = null;
- if (SPContext.Current.Web.UserIsSiteAdmin)
+ try
{
- var eo = _engine.GetService<ExceptionOperations>();
- errorMessage = eo.FormatException(Exception);
- IronRuntime.LogError(String.Format("Error creating control: {0}", ControlName), Exception);
+ _control.RenderControl(writer);
}
- else
+ catch (Exception ex)
{
- errorMessage = "An Error occured.";
+ HandleException(ex, writer);
}
- writer.Write(errorMessage);
- return;
}
+ }
- try
+ private void HandleException(Exception ex, HtmlTextWriter writer)
+ {
+ string output = IronULSLogger.Local.Error("Error in IronWrapperControl", ex,
+ IronCategoryDiagnosticsId.Controls);
+ if (!SPContext.Current.Web.UserIsSiteAdmin)
{
- _control.RenderControl(writer);
+ writer.Write("An error occured.");
}
- catch (Exception ex)
+ else
{
- writer.Write(ex.Message);
- IronRuntime.LogError("Error while rendering " + GetType().AssemblyQualifiedName, ex);
+ writer.Write(output);
}
- }
+ }
}
-}
+}
View
132 src/IronSharePoint.Framework/IronWrapperUserControl.cs
@@ -1,92 +1,52 @@
using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
+using System.Diagnostics.Contracts;
using System.Web.UI;
using IronSharePoint.Diagnostics;
-using Microsoft.SharePoint.Administration;
+using IronSharePoint.Util;
using Microsoft.SharePoint;
-using System.ComponentModel;
-using System.IO;
-using Microsoft.Scripting.Hosting;
namespace IronSharePoint
{
- public class IronWrapperUserControl : UserControl
+ public class IronWrapperUserControl : UserControl, IWrapperControl
{
- [TemplateContainer(typeof(IronWrapperControl))]
+ protected Control _control;
+
+ [TemplateContainer(typeof (IronWrapperControl))]
[PersistenceMode(PersistenceMode.InnerDefaultProperty)]
public ITemplate Template { get; set; }
public string TemplatePath { get; set; }
-
- public string ScriptName { get; set; }
- public string ScriptClass { get; set; }
- public string ScriptHiveId { get; set; }
-
public string Config { get; set; }
-
- private Exception _exception;
- private ScriptEngine _scriptEngine;
- protected Control _ctrl;
+ public string ControlName { get; set; }
+ public Exception InstantiationException { get; set; }
protected override void OnInit(EventArgs e)
{
- try
- {
+ Contract.Requires<InvalidOperationException>(!String.IsNullOrWhiteSpace(ControlName),
+ "ControlName not set");
- if (String.IsNullOrEmpty(ScriptName))
+ if (this.TryCreateDynamicControl(out _control))
+ {
+ if (_control is IIronControl)
{
- _exception = new InvalidEnumArgumentException("Property ScripName is empty!");
+ var ironControl = _control as IIronControl;
+ ironControl.WebPart = null;
+ ironControl.DataStore = null;
}
- else if (String.IsNullOrEmpty(ScriptClass))
+ if (Template != null)
{
- _exception = new InvalidEnumArgumentException("Property ScripClass is empty!");
+ Template.InstantiateIn(_control);
}
-
- if (_exception != null)
- return;
-
- Guid hiveId = String.IsNullOrEmpty(ScriptHiveId) ? Guid.Empty : new Guid(ScriptHiveId);
-
- //IronRuntime ironRuntime = IronRuntime.GetIronRuntime(SPContext.Current.Site, hiveId);
- IronRuntime ironRuntime = IronRuntime.GetDefaultIronRuntime(SPContext.Current.Site);
- _scriptEngine = ironRuntime.ScriptRuntime.GetEngineByFileExtension(Path.GetExtension(ScriptName));
-
- if (_scriptEngine != null)
+ else if (!String.IsNullOrEmpty(TemplatePath))
{
- _ctrl = null;// TODO _scriptEngine.CreateDynamicInstance(ScriptClass, ScriptName) as Control;
-
- var dynamicControl = _ctrl as IIronControl;
- if (dynamicControl != null)
- {
- dynamicControl.WebPart = null;
- dynamicControl.DataStore = null;
- }
-
- if (Template != null)
- {
- Template.InstantiateIn(_ctrl);
- }
- else
- {
- if (!String.IsNullOrEmpty(TemplatePath))
- {
- var path = TemplatePath.Replace("~site", SPContext.Current.Site.ServerRelativeUrl)
- .Replace("~web", SPContext.Current.Web.ServerRelativeUrl);
+ string path = TemplatePath.Replace("~site", SPContext.Current.Site.ServerRelativeUrl)
+ .Replace("~web", SPContext.Current.Web.ServerRelativeUrl);
- Template = this.LoadTemplate(path);
- Template.InstantiateIn(_ctrl);
- }
- }
-
- this.Controls.Add(_ctrl);
+ Template = LoadTemplate(path);
+ Template.InstantiateIn(_control);
}
- }
- catch (Exception ex)
- {
- IronDiagnosticsService.Local.WriteTrace(1, IronDiagnosticsService.Local[IronCategoryDiagnosticsId.Controls], TraceSeverity.Unexpected, String.Format("Error: {0}; Stack: {1}", ex.Message, ex.StackTrace));
- _exception = ex;
+
+ Controls.Add(_control);
}
base.OnInit(e);
@@ -94,37 +54,35 @@ protected override void OnInit(EventArgs e)
protected override void Render(HtmlTextWriter writer)
{
- // TODO better error handling
- if (_exception!=null)
+ if (InstantiationException != null)
+ {
+ HandleException(InstantiationException, writer);
+ }
+ else
{
- if (SPContext.Current.Web.UserIsSiteAdmin)
+ try
{
- var eo = _scriptEngine.GetService<ExceptionOperations>();
- string error = eo.FormatException(_exception);
-
- IronRuntime.LogError(String.Format("Error executing script {0}: {1}", ScriptName, error), _exception);
-
- //if (engine != null)
- //{
- // new IronLogger(engine.IronRuntime).Log(String.Format("Ruby Error: {0} at {1}", _exception.Message, error));
- //}
-
- writer.Write(error);
+ _control.RenderControl(writer);
}
- else
+ catch (Exception ex)
{
- writer.Write("Error occured.");
+ HandleException(ex, writer);
}
}
- try
+ }
+
+ private void HandleException(Exception ex, HtmlTextWriter writer)
+ {
+ string output = IronULSLogger.Local.Error("Error in IronWrapperControl", ex,
+ IronCategoryDiagnosticsId.Controls);
+ if (!SPContext.Current.Web.UserIsSiteAdmin)
{
- _ctrl.RenderControl(writer);
+ writer.Write("An error occured.");
}
- catch (Exception ex)
+ else
{
- IronDiagnosticsService.Local.WriteTrace(1, IronDiagnosticsService.Local[IronCategoryDiagnosticsId.Controls], TraceSeverity.Unexpected, String.Format("Error: {0}; Stack: {1}", ex.Message, ex.StackTrace));
- writer.Write(ex.Message);
+ writer.Write(output);
}
}
}
-}
+}
View
7 src/IronSharePoint.Framework/Util/EnumerableExtensions.cs
@@ -25,6 +25,13 @@ public static IEnumerable<T> Compact<T>(this IEnumerable<T> enumerable)
return enumerable.Where(x => !Equals(x, default(T)));
}
+ /// <summary>
+ /// Calls ToString() on all items in the <paramref name="enumerable"/> and joins the strings with the given <paramref name="seperator"/>
+ /// </summary>
+ /// <typeparam name="T"></typeparam>
+ /// <param name="enumerable"></param>
+ /// <param name="seperator"></param>
+ /// <returns></returns>
public static string StringJoin<T>(this IEnumerable<T> enumerable, string seperator = ", ")
{
var values = enumerable.Select(x => x == null ? "null" : x.ToString());
View
7 src/IronSharePoint.Framework/Util/ScriptEngineExtensions.cs
@@ -5,6 +5,7 @@
using System.Linq;
using System.Text;
using System.Threading.Tasks;
+using IronSharePoint.Exceptions;
using Microsoft.Scripting;
using Microsoft.Scripting.Hosting;
using Microsoft.SharePoint;
@@ -32,9 +33,13 @@ public static dynamic CreateInstance(this ScriptEngine scriptEngine, string type
var type = scriptEngine.Execute(typeName);
return scriptEngine.Operations.CreateInstance(type, parameters);
}
+ catch (MemberAccessException ex)
+ {
+ throw new DynamicInstanceInitializationException(string.Format("Type '{0}' not found", typeName), ex);
+ }
catch (Exception ex)
{
- throw new ArgumentException(string.Format("{0} not found", typeName), "typeName", ex);
+ throw new DynamicInstanceInitializationException(string.Format("Could not create instance of type '{0}'", typeName), ex);
}
}
}
View
34 src/IronSharePoint.Framework/Util/WrapperControlExtensions.cs
@@ -0,0 +1,34 @@
+using System;
+using System.Web.UI;
+using IronSharePoint.Diagnostics;
+using Microsoft.Scripting.Hosting;
+using Microsoft.SharePoint;
+
+namespace IronSharePoint.Util
+{
+ internal static class WrapperControlExtensions
+ {
+ public static Control CreateDynamicControl(this IWrapperControl control)
+ {
+ IronRuntime runtime = IronRuntime.GetDefaultIronRuntime(SPContext.Current.Site);
+ ScriptEngine engine = runtime.RubyEngine;
+ dynamic controlClass = engine.Execute(control.ControlName, runtime.ScriptRuntime.Globals);
+ return (Control) engine.Operations.CreateInstance(controlClass);
+ }
+
+ public static bool TryCreateDynamicControl(this IWrapperControl control, out Control dynamicControl)
+ {
+ try
+ {
+ dynamicControl = CreateDynamicControl(control);
+ return true;
+ }
+ catch (Exception ex)
+ {
+ control.InstantiationException = ex;
+ dynamicControl = null;
+ return false;
+ }
+ }
+ }
+}
View
143 src/IronSharePoint/IronPart/IronPart.cs
@@ -1,142 +1,105 @@
using System;
using System.ComponentModel;
-using System.Web;
+using System.Diagnostics.Contracts;
using System.Web.UI;
-using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
-using Microsoft.SharePoint;
-using Microsoft.SharePoint.WebControls;
-using System.Collections.Generic;
-using Microsoft.Scripting.Hosting;
-using System.IO;
+using IronSharePoint.Diagnostics;
using IronSharePoint.Util;
+using Microsoft.SharePoint;
namespace IronSharePoint.IronPart
{
- // TODO fix
- [ToolboxItemAttribute(false)]
- public class IronPart : WebPart, IIronDataStore
+ [ToolboxItem(false)]
+ public class IronPart : WebPart, IIronDataStore, IWrapperControl
{
- [WebBrowsable(true)]
- [Category("IronPart")]
- [Personalizable(PersonalizationScope.Shared)]
- public string ScriptName { get; set; }
+ protected Exception Exception;
+ protected Control InnerControl;
- [WebBrowsable(true)]
- [Category("IronPart")]
[Personalizable(PersonalizationScope.Shared)]
- public string ScriptClass { get; set; }
+ public string Data { get; set; }
- [WebBrowsable(false)]
- [Category("IronPart")]
- [Personalizable(PersonalizationScope.Shared)]
- public String ScriptHiveId { get; set; }
+ public void SaveData(string data)
+ {
+ Data = data;
+ SetPersonalizationDirty();
+ }
+ public string GetData()
+ {
+ return Data;
+ }
+
+ [WebBrowsable(true)]
+ [Category("IronPart")]
[Personalizable(PersonalizationScope.Shared)]
- public string Data { get; set; }
+ public string ControlName { get; set; }
- protected Exception Exception {get; set;}
- protected IIronControl DynamicControl{get; private set;}
- private IronRuntime ironRuntime;
+ public Exception InstantiationException { get; set; }
protected override void OnInit(EventArgs e)
{
- ironRuntime = IronRuntime.GetDefaultIronRuntime(SPContext.Current.Site);
+ Contract.Requires<InvalidOperationException>(!String.IsNullOrWhiteSpace(ControlName), "ControlName not set");
- if (String.IsNullOrEmpty(ScriptClass))
+ if (!this.TryCreateDynamicControl(out InnerControl))
{
- Exception = new InvalidEnumArgumentException("Property ScriptClass is empty!");
- }
-
- if (Exception != null)
- return;
-
- try
- {
-
- Control ctrl = null;
- if (!String.IsNullOrEmpty(ScriptName))
- {
- var engine = ironRuntime.ScriptRuntime.GetEngineByFileExtension(Path.GetExtension(ScriptName));
- ctrl = engine.CreateInstance(ScriptClass) as Control;
- }
-
- DynamicControl = ctrl as IIronControl;
- if (DynamicControl != null)
+ if (InnerControl is IIronControl)
{
- DynamicControl.WebPart = this;
- DynamicControl.DataStore = this;
+ var ironControl = InnerControl as IIronControl;
+ ironControl.WebPart = this;
+ ironControl.DataStore = this;
}
-
-
- this.Controls.Add(ctrl);
-
- base.OnInit(e);
- }
- catch (Exception ex)
- {
- Exception = ex;
- IronRuntime.LogError("IronWebPart Error", Exception);
}
+ Controls.Add(InnerControl);
+ base.OnInit(e);
}
- public new void SetPersonalizationDirty(){
+ public new void SetPersonalizationDirty()
+ {
base.SetPersonalizationDirty();
}
protected override void Render(HtmlTextWriter writer)
{
- if (Exception != null)
+ if (InstantiationException != null)
{
- if (SPContext.Current.Web.UserIsSiteAdmin)
- {
- IronRuntime.LogError(String.Format("Script: {0}, Error: {1}", ScriptName, Exception.Message),
- Exception);
-
- writer.Write(Exception.Message);
- }
- else
- {
- writer.Write("Error occured.");
- }
+ HandleException(InstantiationException, writer);
}
else
{
try
{
- base.Render(writer);
+ InnerControl.RenderControl(writer);
}
catch (Exception ex)
{
- writer.Write(ex.Message);
- IronRuntime.LogError("Error", ex);
+ HandleException(ex, writer);
}
}
}
-
- public override EditorPartCollection CreateEditorParts()
+ private void HandleException(Exception ex, HtmlTextWriter writer)
{
- if (DynamicControl != null)
+ string output = IronULSLogger.Local.Error("Error in IronWrapperControl", ex,
+ IronCategoryDiagnosticsId.WebParts);
+ if (!SPContext.Current.Web.UserIsSiteAdmin)
{
- return new EditorPartCollection(base.CreateEditorParts(),DynamicControl.CreateEditorParts());
+ writer.Write("An error occured.");
+ }
+ else
+ {
+ writer.Write(output);
}
-
- return base.CreateEditorParts();
}
-
- public void SaveData(string data)
+ public override EditorPartCollection CreateEditorParts()
{
- Data = data;
- SetPersonalizationDirty();
- }
+ if (InnerControl is IIronControl)
+ {
+ var ironControl = InnerControl as IIronControl;
+ return new EditorPartCollection(base.CreateEditorParts(), ironControl.CreateEditorParts());
+ }
- public string GetData()
- {
- return Data;
+ return base.CreateEditorParts();
}
-
- public string PathScriptName { get; set; }
}
-}
+}
View
3  src/IronSharePoint/IronSharePoint.csproj
@@ -245,13 +245,14 @@
<None Include="TEMPLATE\Features\IronSP_Root\iron_sharepoint\mixins\parent_attributes.rb" />
<None Include="TEMPLATE\Features\IronSP_Root\iron_sharepoint\mixins\short_term_memory.rb" />
<None Include="TEMPLATE\Features\IronSP_Root\iron_sharepoint\mixins\sp_context_accessors.rb" />
- <None Include="TEMPLATE\Features\IronSP_Root\iron_sharepoint\mixins\type_registration.rb" />
<None Include="TEMPLATE\Features\IronSP_Root\iron_sharepoint\mixins\view_helpers.rb" />
<None Include="TEMPLATE\Features\IronSP_Root\iron_sharepoint\patches\core\object.rb" />
<None Include="TEMPLATE\Features\IronSP_Root\iron_sharepoint\patches\core\regexp.rb" />
<None Include="TEMPLATE\Features\IronSP_Root\iron_sharepoint\patches\core\string.rb" />
<None Include="TEMPLATE\Features\IronSP_Root\iron_sharepoint\patches\digest\md5.rb" />
+ <None Include="TEMPLATE\Features\IronSP_Root\iron_sharepoint\patches\hike\index.rb" />
<None Include="TEMPLATE\Features\IronSP_Root\iron_sharepoint\patches\log4r\logger.rb" />
+ <None Include="TEMPLATE\Features\IronSP_Root\iron_sharepoint\patches\system\date_time.rb" />
<None Include="TEMPLATE\Features\IronSP_Root\iron_sharepoint\rescues\template_error.haml" />
<None Include="TEMPLATE\Features\IronSP_Root\iron_sharepoint\rescues\template_not_found.haml" />
<None Include="TEMPLATE\Features\IronSP_Root\iron_sharepoint\variation.rb" />
View
3  src/IronSharePoint/Layouts/IronSP/IronConsole.coffee
@@ -21,7 +21,7 @@ class IronConsole
unless result["HasError"]
cb(result) for cb in @successCallbacks
else
- cb(result["Error"], result["StackTrace"]) for cb in @errorCallbacks
+ cb(result["Error"]) for cb in @errorCallbacks
error: (args...) => cb(args...) for cb in @errorCallbacks
getExpressionFromHistory: (index) ->
@@ -71,7 +71,6 @@ class IronConsoleView
@showExecuting false
@console.onExecuteError (error, stackTrace) =>
@append "error", '', error
- @append "stackTrace", '', stackTrace
@showExecuting false
@$input ||= $("#ironSP-console-input")
View
3  src/IronSharePoint/Layouts/IronSP/IronConsole.js
@@ -56,7 +56,7 @@
_results1 = [];
for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) {
cb = _ref1[_j];
- _results1.push(cb(result["Error"], result["StackTrace"]));
+ _results1.push(cb(result["Error"]));
}
return _results1;
}
@@ -174,7 +174,6 @@
});
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"));
View
7 src/IronSharePoint/Layouts/IronSP/IronConsoleService.ashx.cs
@@ -19,8 +19,8 @@ public void ProcessRequest(HttpContext context)
try
{
- SPSite site = SPContext.Current.Site;
- SPWeb web = SPContext.Current.Web;
+ var site = SPContext.Current.Site;
+ var web = SPContext.Current.Web;
if (!web.CurrentUser.IsSiteAdmin)
{
@@ -44,8 +44,7 @@ public void ProcessRequest(HttpContext context)
}
catch (Exception ex)
{
- result.Error = ex.Message;
- result.StackTrace = ex.StackTrace;
+ result.Error = ex.ToString();
}
finally
{
View
5 src/IronSharePoint/TEMPLATE/Features/IronSP_Root/iron_sharepoint/iron_composite_control.rb
@@ -1,5 +1,4 @@
require 'iron_sharepoint/mixins/logging'
-require 'iron_sharepoint/mixins/type_registration'
require 'iron_sharepoint/mixins/control_view'
require 'iron_sharepoint/mixins/parent_attributes'
require 'iron_sharepoint/mixins/short_term_memory'
@@ -11,10 +10,6 @@ class IronCompositeControl
include Mixins::ParentAttributes
extend Mixins::ShortTermMemory
- def self.inherited child
- child.send :include, Mixins::TypeRegistration
- end
-
def CreateChildControls
monitor "Render #{self.class.name}" do
begin
View
5 src/IronSharePoint/TEMPLATE/Features/IronSP_Root/iron_sharepoint/iron_control.rb
@@ -1,5 +1,4 @@
require 'iron_sharepoint/mixins/logging'
-require 'iron_sharepoint/mixins/type_registration'
require 'iron_sharepoint/mixins/control_view'
require 'iron_sharepoint/mixins/parent_attributes'
require 'iron_sharepoint/mixins/short_term_memory'
@@ -11,10 +10,6 @@ class IronControl
include Mixins::ParentAttributes
extend Mixins::ShortTermMemory
- def self.inherited child
- child.send :include, Mixins::TypeRegistration
- end
-
def Render(writer)
monitor "Render #{self.class.name}" do
self.view.context = view_context
View
2  src/IronSharePoint/TEMPLATE/Features/IronSP_Root/iron_sharepoint/main_http_handler.rb
@@ -1,5 +1,4 @@
require 'iron_sharepoint/mixins/logging'
-require 'iron_sharepoint/mixins/type_registration'
module IronSharePoint::HttpHandlers
def self.routes
@@ -9,7 +8,6 @@ def self.routes
class MainHttpHandler
include System::Web::IHttpHandler
include IronSharePoint::Mixins::Logging
- include IronSharePoint::Mixins::TypeRegistration
def IsReusable
false
View
9 src/IronSharePoint/TEMPLATE/Features/IronSP_Root/iron_sharepoint/mixins/type_registration.rb
@@ -1,9 +0,0 @@
-module IronSharePoint::Mixins
- module TypeRegistration
- def self.included klass
- dot_net_type = klass.name.gsub("::",".")
- $RUNTIME.register_dynamic_type(dot_net_type, klass)
- IRON_DEFAULT_LOGGER.debug "Registered #{klass} as #{dot_net_type}"
- end
- end
-end
View
7 src/IronSharePoint/TEMPLATE/Features/IronSP_Root/iron_sharepoint/patches/system/date_time.rb
@@ -0,0 +1,7 @@
+module System
+ class DateTime
+ def httpdate
+ self.to_universal_time.to_string("r")
+ end
+ end
+end
View
1  test/IronSharePoint.Framework.Test/Console/ScriptResult_Fixture.cs
@@ -19,7 +19,6 @@ public void ToJson()
Output = "Output",
ReturnValue = "ReturnValue",
ExecutionTime = 1,
- StackTrace = "StackTrace"
};
System.Console.WriteLine(Sut.ToJson());
View
4 test/IronSharePoint.Framework.Test/Util/ScriptEngineExtensions_Fixture.cs
@@ -1,4 +1,6 @@
using System;
+using System.Linq;
+using IronSharePoint.Exceptions;
using IronSharePoint.Util;
using Microsoft.Scripting.Hosting;
using Moq;
@@ -25,7 +27,7 @@ public void CreateInstance_WithExistingType_ReturnsInstance()
Assert.AreEqual(instance, "foo");
}
- [Test, ExpectedException(typeof (ArgumentException))]
+ [Test, ExpectedException(typeof (DynamicInstanceInitializationException))]
public void CreateInstance_WithUnknownType_ThrowsArgumentException()
{
Sut.CreateInstance("FOO", "foo");
View
2  test/IronSharePoint.Framework.Test/_assets/script_result.json
@@ -1 +1 @@
-{"Output":"Output","ReturnValue":"ReturnValue","Error":"Error","StackTrace":"StackTrace","ExecutionTime":1,"HasError":true}
+{"Output":"Output","ReturnValue":"ReturnValue","Error":"Error","ExecutionTime":1,"HasError":true}
Please sign in to comment.
Something went wrong with that request. Please try again.