<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>[Freeswitch-trunk][14366] </title>
</head>
<body>

<style type="text/css"><!--
#msg dl.meta { border: 1px #006 solid; background: #369; padding: 6px; color: #fff; }
#msg dl.meta dt { float: left; width: 6em; font-weight: bold; }
#msg dt:after { content:':';}
#msg dl, #msg dt, #msg ul, #msg li, #header, #footer, #logmsg { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt;  }
#msg dl a { font-weight: bold}
#msg dl a:link    { color:#fc3; }
#msg dl a:active  { color:#ff0; }
#msg dl a:visited { color:#cc6; }
h3 { font-family: verdana,arial,helvetica,sans-serif; font-size: 10pt; font-weight: bold; }
#msg pre { overflow: auto; background: #ffc; border: 1px #fa0 solid; padding: 6px; }
#logmsg { background: #ffc; border: 1px #fa0 solid; padding: 1em 1em 0 1em; }
#logmsg p, #logmsg pre, #logmsg blockquote { margin: 0 0 1em 0; }
#logmsg p, #logmsg li, #logmsg dt, #logmsg dd { line-height: 14pt; }
#logmsg h1, #logmsg h2, #logmsg h3, #logmsg h4, #logmsg h5, #logmsg h6 { margin: .5em 0; }
#logmsg h1:first-child, #logmsg h2:first-child, #logmsg h3:first-child, #logmsg h4:first-child, #logmsg h5:first-child, #logmsg h6:first-child { margin-top: 0; }
#logmsg ul, #logmsg ol { padding: 0; list-style-position: inside; margin: 0 0 0 1em; }
#logmsg ul { text-indent: -1em; padding-left: 1em; }#logmsg ol { text-indent: -1.5em; padding-left: 1.5em; }
#logmsg > ul, #logmsg > ol { margin: 0 0 1em 0; }
#logmsg pre { background: #eee; padding: 1em; }
#logmsg blockquote { border: 1px solid #fa0; border-left-width: 10px; padding: 1em 1em 0 1em; background: white;}
#logmsg dl { margin: 0; }
#logmsg dt { font-weight: bold; }
#logmsg dd { margin: 0; padding: 0 0 0.5em 0; }
#logmsg dd:before { content:'\00bb';}
#logmsg table { border-spacing: 0px; border-collapse: collapse; border-top: 4px solid #fa0; border-bottom: 1px solid #fa0; background: #fff; }
#logmsg table th { text-align: left; font-weight: normal; padding: 0.2em 0.5em; border-top: 1px dotted #fa0; }
#logmsg table td { text-align: right; border-top: 1px dotted #fa0; padding: 0.2em 0.5em; }
#logmsg table thead th { text-align: center; border-bottom: 1px solid #fa0; }
#logmsg table th.Corner { text-align: left; }
#logmsg hr { border: none 0; border-top: 2px dashed #fa0; height: 1px; }
#header, #footer { color: #fff; background: #636; border: 1px #300 solid; padding: 6px; }
#patch { width: 100%; }
#patch h4 {font-family: verdana,arial,helvetica,sans-serif;font-size:10pt;padding:8px;background:#369;color:#fff;margin:0;}
#patch .propset h4, #patch .binary h4 {margin:0;}
#patch pre {padding:0;line-height:1.2em;margin:0;}
#patch .diff {width:100%;background:#eee;padding: 0 0 10px 0;overflow:auto;}
#patch .propset .diff, #patch .binary .diff  {padding:10px 0;}
#patch span {display:block;padding:0 10px;}
#patch .modfile, #patch .addfile, #patch .delfile, #patch .propset, #patch .binary, #patch .copfile {border:1px solid #ccc;margin:10px 0;}
#patch ins {background:#dfd;text-decoration:none;display:block;padding:0 10px;}
#patch del {background:#fdd;text-decoration:none;display:block;padding:0 10px;}
#patch .lines, .info {color:#888;background:#fff;}
--></style>
<div id="msg">
<div id="header">FreeSWITCH Subversion</div>
<dl class="meta">
<dt>Revision</dt> <dd><a href="http://fisheye.freeswitch.org/changelog/FreeSWITCH?cs=14366">14366</a></dd>
<dt>Author</dt> <dd>michaelgg</dd>
<dt>Date</dt> <dd>2009-07-26 11:31:03 -0500 (Sun, 26 Jul 2009)</dd>
</dl>

<h3>Log Message</h3>
<pre>Oops. Here's the actual new mod_managed files</pre>

<h3>Added Paths</h3>
<ul>
<li><a href="#freeswitchtrunksrcmodlanguagesmod_managedmanagedPluginInterfacescs">freeswitch/trunk/src/mod/languages/mod_managed/managed/PluginInterfaces.cs</a></li>
<li><a href="#freeswitchtrunksrcmodlanguagesmod_managedmanagedPluginManagercs">freeswitch/trunk/src/mod/languages/mod_managed/managed/PluginManager.cs</a></li>
<li><a href="#freeswitchtrunksrcmodlanguagesmod_managedmanagedScriptPluginManagercs">freeswitch/trunk/src/mod/languages/mod_managed/managed/ScriptPluginManager.cs</a></li>
</ul>

</div>
<div id="patch">
<h3>Diff</h3>
<a id="freeswitchtrunksrcmodlanguagesmod_managedmanagedPluginInterfacescs"></a>
<div class="addfile"><h4>Added: freeswitch/trunk/src/mod/languages/mod_managed/managed/PluginInterfaces.cs (0 => 14366)</h4>
<pre class="diff"><span>
<span class="info">--- freeswitch/trunk/src/mod/languages/mod_managed/managed/PluginInterfaces.cs                                (rev 0)
+++ freeswitch/trunk/src/mod/languages/mod_managed/managed/PluginInterfaces.cs        2009-07-26 16:31:03 UTC (rev 14366)
</span><span class="lines">@@ -0,0 +1,91 @@
</span><ins>+/* 
+ * FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application - mod_managed
+ * Copyright (C) 2008, Michael Giagnocavo &lt;mgg@giagnocavo.net&gt;
+ *
+ * Version: MPL 1.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the &quot;License&quot;); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an &quot;AS IS&quot; basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application - mod_managed
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Giagnocavo &lt;mgg@giagnocavo.net&gt;
+ * Portions created by the Initial Developer are Copyright (C)
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ * 
+ * Michael Giagnocavo &lt;mgg@giagnocavo.net&gt;
+ * Jeff Lenk &lt;jeff@jefflenk.com&gt;
+ * 
+ * PluginInterfaces.cs -- Public interfaces for plugins
+ *
+ */
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+
+namespace FreeSWITCH {
+
+    public class AppContext {
+        readonly string arguments;
+        readonly Native.ManagedSession session;
+
+        public AppContext(string arguments, Native.ManagedSession session) {
+            this.arguments = arguments;
+            this.session = session;
+        }
+
+        public string Arguments { get { return arguments; } }
+        public Native.ManagedSession Session { get { return session; } }
+    }
+
+    public class ApiContext {
+        readonly string arguments;
+        readonly Native.Stream stream;
+        readonly Native.Event evt;
+
+        public ApiContext(string arguments, Native.Stream stream, Native.Event evt) {
+            this.arguments = arguments;
+            this.stream = stream;
+            this.evt = evt;
+        }
+
+        public string Arguments { get { return arguments; } }
+        public Native.Stream Stream { get { return stream; } }
+        public Native.Event Event { get { return evt; } }
+    }
+
+    public class ApiBackgroundContext {
+        readonly string arguments;
+
+        public ApiBackgroundContext(string arguments) {
+            this.arguments = arguments;
+        }
+
+        public string Arguments { get { return arguments; } }
+    }
+
+    public interface IApiPlugin {
+        void Execute(ApiContext context);
+        void ExecuteBackground(ApiBackgroundContext context);
+    }
+
+    public interface IAppPlugin {
+        void Run(AppContext context);
+    }
+
+    public interface ILoadNotificationPlugin {
+        bool Load();
+    }
+
+}
</ins></span></pre></div>
<a id="freeswitchtrunksrcmodlanguagesmod_managedmanagedPluginManagercs"></a>
<div class="addfile"><h4>Added: freeswitch/trunk/src/mod/languages/mod_managed/managed/PluginManager.cs (0 => 14366)</h4>
<pre class="diff"><span>
<span class="info">--- freeswitch/trunk/src/mod/languages/mod_managed/managed/PluginManager.cs                                (rev 0)
+++ freeswitch/trunk/src/mod/languages/mod_managed/managed/PluginManager.cs        2009-07-26 16:31:03 UTC (rev 14366)
</span><span class="lines">@@ -0,0 +1,291 @@
</span><ins>+/* 
+ * FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application - mod_managed
+ * Copyright (C) 2008, Michael Giagnocavo &lt;mgg@giagnocavo.net&gt;
+ *
+ * Version: MPL 1.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the &quot;License&quot;); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an &quot;AS IS&quot; basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application - mod_managed
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Giagnocavo &lt;mgg@giagnocavo.net&gt;
+ * Portions created by the Initial Developer are Copyright (C)
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ * 
+ * Michael Giagnocavo &lt;mgg@giagnocavo.net&gt;
+ * Jeff Lenk &lt;jeff@jefflenk.com&gt;
+ * 
+ * PluginManager.cs -- Plugin execution code
+ *
+ */
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Reflection;
+using System.Reflection.Emit;
+
+namespace FreeSWITCH {
+
+    internal abstract class PluginExecutor : MarshalByRefObject {
+        public override object InitializeLifetimeService() {
+            return null;
+        }
+
+        /// &lt;summary&gt;Names by which this plugin may be executed.&lt;/summary&gt;
+        public List&lt;string&gt; Aliases { get { return aliases; } }
+        readonly List&lt;string&gt; aliases = new List&lt;string&gt;();
+        
+        /// &lt;summary&gt;The canonical name to identify this plugin (informative).&lt;/summary&gt;
+        public string Name { get { return name; } }
+        readonly string name;
+
+        protected PluginExecutor(string name, List&lt;string&gt; aliases) {
+            if (string.IsNullOrEmpty(name)) throw new ArgumentException(&quot;No name provided.&quot;);
+            if (aliases == null || aliases.Count == 0) throw new ArgumentException(&quot;No aliases provided.&quot;);
+            this.name = name;
+            this.aliases = aliases.Distinct().ToList();
+        }
+
+        int useCount = 0;
+        protected void IncreaseUse() {
+            System.Threading.Interlocked.Increment(ref useCount);
+        }
+        protected void DecreaseUse() {
+            var count = System.Threading.Interlocked.Decrement(ref useCount);
+            if (count == 0 &amp;&amp; onZeroUse != null) {
+                onZeroUse();
+            }
+        }
+
+        Action onZeroUse;
+        public void SetZeroUseNotification(Action onZeroUse) {
+            this.onZeroUse = onZeroUse;
+            if (useCount == 0) onZeroUse();
+        }
+
+        protected static void LogException(string action, string moduleName, Exception ex) {
+            Log.WriteLine(LogLevel.Error, &quot;{0} exception in {1}: {2}&quot;, action, moduleName, ex.Message);
+            Log.WriteLine(LogLevel.Debug, &quot;{0} exception: {1}&quot;, moduleName, ex.ToString());
+        }
+    }
+
+    internal sealed class AppPluginExecutor : PluginExecutor {
+
+        readonly Func&lt;IAppPlugin&gt; createPlugin;
+
+        public AppPluginExecutor(string name, List&lt;string&gt; aliases, Func&lt;IAppPlugin&gt; creator)
+            : base(name, aliases) {
+            if (creator == null) throw new ArgumentNullException(&quot;Creator cannot be null.&quot;);
+            this.createPlugin = creator;
+        }
+
+        public bool Execute(string args, IntPtr sessionHandle) {
+            IncreaseUse();
+            try {
+                using (var session = new Native.ManagedSession(new Native.SWIGTYPE_p_switch_core_session(sessionHandle, false))) {
+                    session.Initialize();
+                    session.SetAutoHangup(false);
+                    try {
+                        var plugin = createPlugin();
+                        var context = new AppContext(args, session);;
+                        plugin.Run(context);
+                        return true;
+                    } catch (Exception ex) {
+                        LogException(&quot;Run&quot;, Name, ex);
+                        return false;
+                    }
+                }
+            } finally {
+                DecreaseUse();
+            }
+        }
+    }
+
+    internal sealed class ApiPluginExecutor : PluginExecutor {
+
+        readonly Func&lt;IApiPlugin&gt; createPlugin;
+
+        public ApiPluginExecutor(string name, List&lt;string&gt; aliases, Func&lt;IApiPlugin&gt; creator)
+            : base(name, aliases) {
+            if (creator == null) throw new ArgumentNullException(&quot;Creator cannot be null.&quot;);
+            this.createPlugin = creator;
+        }
+
+        public bool ExecuteApi(string args, IntPtr streamHandle, IntPtr eventHandle) {
+            IncreaseUse();
+            try {
+                using (var stream = new Native.Stream(new Native.switch_stream_handle(streamHandle, false)))
+                using (var evt = eventHandle == IntPtr.Zero ? null : new Native.Event(new Native.switch_event(eventHandle, false), 0)) {
+                    try {
+                        var context = new ApiContext(args, stream, evt);
+                        var plugin = createPlugin();
+                        plugin.Execute(context);
+                        return true;
+                    } catch (Exception ex) {
+                        LogException(&quot;Execute&quot;, Name, ex);
+                        return false;
+                    }
+                }
+            } finally {
+                DecreaseUse();
+            }
+        }
+
+        public bool ExecuteApiBackground(string args) {
+            // Background doesn't affect use count
+            new System.Threading.Thread(() =&gt; {
+                try {
+                    var context = new ApiBackgroundContext(args);
+                    var plugin = createPlugin();
+                    plugin.ExecuteBackground(context);
+                    Log.WriteLine(LogLevel.Debug, &quot;ExecuteBackground in {0} completed.&quot;, Name);
+                } catch (Exception ex) {
+                    LogException(&quot;ExecuteBackground&quot;, Name, ex);
+                }
+            }).Start();
+            return true;
+        }
+    }
+
+    internal abstract class PluginManager : MarshalByRefObject {
+        public override object InitializeLifetimeService() {
+            return null;
+        }
+
+        public List&lt;ApiPluginExecutor&gt; ApiExecutors { get { return _apiExecutors; } }
+        readonly List&lt;ApiPluginExecutor&gt; _apiExecutors = new List&lt;ApiPluginExecutor&gt;();
+
+        public List&lt;AppPluginExecutor&gt; AppExecutors { get { return _appExecutors; }  }
+
+        readonly List&lt;AppPluginExecutor&gt; _appExecutors = new List&lt;AppPluginExecutor&gt;();
+
+        bool isLoaded = false;
+
+        public bool Load(string file) {
+            Console.WriteLine(&quot;Loading {0} from domain {1}&quot;, file, AppDomain.CurrentDomain.FriendlyName);
+            if (isLoaded) throw new InvalidOperationException(&quot;PluginManager has already been loaded.&quot;);
+            if (string.IsNullOrEmpty(file)) throw new ArgumentNullException(&quot;file cannot be null or empty.&quot;);
+            if (AppDomain.CurrentDomain.IsDefaultAppDomain()) throw new InvalidOperationException(&quot;PluginManager must load in its own AppDomain.&quot;);
+            var res = LoadInternal(file);
+            isLoaded = true;
+
+            res = res &amp;&amp; AppExecutors.Count &gt; 0 &amp;&amp; ApiExecutors.Count &gt; 0;
+            return res;
+        }
+
+        protected abstract bool LoadInternal(string fileName);
+
+        protected bool RunLoadNotify(Type[] allTypes) {
+            // Run Load on all the load plugins
+            var ty = typeof(ILoadNotificationPlugin);
+            var pluginTypes = allTypes.Where(x =&gt; ty.IsAssignableFrom(x) &amp;&amp; !x.IsAbstract).ToList();
+            if (pluginTypes.Count == 0) return true;
+            foreach (var pt in pluginTypes) {
+                var load = ((ILoadNotificationPlugin)Activator.CreateInstance(pt, false));
+                if (!load.Load()) {
+                    Log.WriteLine(LogLevel.Notice, &quot;Type {0} requested no loading. Assembly will not be loaded.&quot;, pt.FullName);
+                    return false;
+                }
+            }
+            return true;
+        }
+
+        protected void AddApiPlugins(Type[] allTypes) {
+            var iApiTy = typeof(IApiPlugin);
+            foreach (var ty in allTypes.Where(x =&gt; iApiTy.IsAssignableFrom(x) &amp;&amp; !x.IsAbstract)) {
+                var del = CreateConstructorDelegate&lt;IApiPlugin&gt;(ty);
+                var exec = new ApiPluginExecutor(ty.FullName, new List&lt;string&gt; { ty.FullName, ty.Name }, del);
+                this.ApiExecutors.Add(exec);
+            }
+        }
+
+        protected void AddAppPlugins(Type[] allTypes) {
+            var iAppTy = typeof(IAppPlugin);
+            foreach (var ty in allTypes.Where(x =&gt; iAppTy.IsAssignableFrom(x) &amp;&amp; !x.IsAbstract)) {
+                var del = CreateConstructorDelegate&lt;IAppPlugin&gt;(ty);
+                var exec = new AppPluginExecutor(ty.FullName, new List&lt;string&gt; { ty.FullName, ty.Name }, del);
+                this.AppExecutors.Add(exec);
+            }
+        }
+
+        #region Unload
+
+        bool isUnloading = false;
+        int unloadCount;
+        System.Threading.ManualResetEvent unloadSignal = new System.Threading.ManualResetEvent(false);
+        void decreaseUnloadCount() {
+            if (System.Threading.Interlocked.Decrement(ref unloadCount) == 0) {
+                unloadSignal.Set();
+            }
+        }
+
+        public void BlockUntilUnloadIsSafe() {
+            if (isUnloading) throw new InvalidOperationException(&quot;PluginManager is already unloading.&quot;);
+            isUnloading = true;
+            unloadCount = ApiExecutors.Count + AppExecutors.Count;
+            ApiExecutors.ForEach(x =&gt; x.SetZeroUseNotification(decreaseUnloadCount));
+            AppExecutors.ForEach(x =&gt; x.SetZeroUseNotification(decreaseUnloadCount));
+            unloadSignal.WaitOne();
+        }
+
+        #endregion
+
+        public static Func&lt;T&gt; CreateConstructorDelegate&lt;T&gt;(Type ty) {
+            var destTy = typeof(T);
+            if (!destTy.IsAssignableFrom(ty)) throw new ArgumentException(string.Format(&quot;Type {0} is not assignable from {1}.&quot;, destTy.FullName, ty.FullName));
+            var con = ty.GetConstructor(Type.EmptyTypes);
+            if (con == null) throw new ArgumentException(string.Format(&quot;Type {0} doesn't have an accessible parameterless constructor.&quot;, ty.FullName));
+
+            var rand = Guid.NewGuid().ToString().Replace(&quot;-&quot;, &quot;&quot;);
+            var dm = new DynamicMethod(&quot;CREATE_&quot; + ty.FullName.Replace('.', '_') + rand, ty, null, true);
+            var il = dm.GetILGenerator();
+            il.Emit(OpCodes.Newobj, ty.GetConstructor(Type.EmptyTypes));
+            il.Emit(OpCodes.Ret);
+
+            return (Func&lt;T&gt;)dm.CreateDelegate(typeof(Func&lt;T&gt;));
+        }
+    }
+
+    internal class AsmPluginManager : PluginManager {
+
+        protected override bool LoadInternal(string fileName) {
+            Assembly asm;
+            try {
+                asm = Assembly.LoadFrom(fileName);
+            } catch (Exception ex) {
+                Log.WriteLine(LogLevel.Info, &quot;Couldn't load {0}: {1}&quot;, fileName, ex.Message);
+                return false;
+            }
+
+            // Ensure it's a plugin assembly
+            var ourName = Assembly.GetExecutingAssembly().GetName().Name;
+            if (!asm.GetReferencedAssemblies().Any(n =&gt; n.Name == ourName)) {
+                Log.WriteLine(LogLevel.Debug, &quot;Assembly {0} doesn't reference FreeSWITCH.Managed, not loading.&quot;);
+                return false; 
+            }
+
+            // See if it wants to be loaded
+            var allTypes = asm.GetExportedTypes();
+            if (!RunLoadNotify(allTypes)) return false;
+
+            AddApiPlugins(allTypes);
+            AddAppPlugins(allTypes);
+
+            return true;
+        }
+
+    }
+
+}
</ins></span></pre></div>
<a id="freeswitchtrunksrcmodlanguagesmod_managedmanagedScriptPluginManagercs"></a>
<div class="addfile"><h4>Added: freeswitch/trunk/src/mod/languages/mod_managed/managed/ScriptPluginManager.cs (0 => 14366)</h4>
<pre class="diff"><span>
<span class="info">--- freeswitch/trunk/src/mod/languages/mod_managed/managed/ScriptPluginManager.cs                                (rev 0)
+++ freeswitch/trunk/src/mod/languages/mod_managed/managed/ScriptPluginManager.cs        2009-07-26 16:31:03 UTC (rev 14366)
</span><span class="lines">@@ -0,0 +1,242 @@
</span><ins>+/* 
+ * FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application - mod_managed
+ * Copyright (C) 2008, Michael Giagnocavo &lt;mgg@giagnocavo.net&gt;
+ *
+ * Version: MPL 1.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the &quot;License&quot;); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an &quot;AS IS&quot; basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is FreeSWITCH Modular Media Switching Software Library / Soft-Switch Application - mod_managed
+ *
+ * The Initial Developer of the Original Code is
+ * Michael Giagnocavo &lt;mgg@giagnocavo.net&gt;
+ * Portions created by the Initial Developer are Copyright (C)
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ * 
+ * Michael Giagnocavo &lt;mgg@giagnocavo.net&gt;
+ * 
+ * ScriptPluginManager.cs -- Dynamic compilation and script execution
+ *
+ */
+
+using System;
+using System.Collections.Generic;
+using System.Linq;
+using System.Text;
+using System.CodeDom;
+using System.CodeDom.Compiler;
+using System.IO;
+using System.Reflection;
+using System.Reflection.Emit;
+
+
+namespace FreeSWITCH {
+
+    public enum ScriptContextType {
+        App,
+        Api,
+        ApiBackground,
+    }
+
+    public static class Script {
+
+        [ThreadStatic]
+        internal static ScriptContextType contextType;
+        [ThreadStatic]
+        internal static object context;
+
+        public static ScriptContextType ContextType { get { return contextType; } }
+
+        public static ApiContext GetApiContext() {
+            return getContext&lt;ApiContext&gt;(ScriptContextType.Api);
+        }
+        public static ApiBackgroundContext GetApiBackgroundContext() {
+            return getContext&lt;ApiBackgroundContext&gt;(ScriptContextType.ApiBackground);
+        }
+        public static AppContext GetAppContext() {
+            return getContext&lt;AppContext&gt;(ScriptContextType.App);
+        }
+
+        public static T getContext&lt;T&gt;(ScriptContextType sct) {
+            var ctx = context;
+            if (ctx == null) throw new InvalidOperationException(&quot;Current context is null.&quot;);
+            if (contextType != sct) throw new InvalidOperationException(&quot;Current ScriptContextType is not &quot; + sct.ToString() + &quot;.&quot;);
+            return (T)ctx;
+        }
+
+    }
+
+    internal class ScriptPluginManager : PluginManager {
+
+        protected override bool LoadInternal(string fileName) {
+            Assembly asm;
+            if (Path.GetExtension(fileName).ToLowerInvariant() == &quot;.exe&quot;) {
+                asm = Assembly.LoadFrom(fileName);
+            } else {
+                asm = compileAssembly(fileName);
+            }
+            if (asm == null) return false;
+
+            return processAssembly(fileName, asm);
+        }
+
+        Assembly compileAssembly(string fileName) {
+            var comp = new CompilerParameters();
+            var mainRefs = new List&lt;string&gt; { 
+                Path.Combine(Native.freeswitch.SWITCH_GLOBAL_dirs.mod_dir, &quot;FreeSWITCH.Managed.dll&quot;),
+                &quot;System.dll&quot;, &quot;System.Xml.dll&quot;, &quot;System.Data.dll&quot; 
+            };
+            var extraRefs = new List&lt;string&gt; {
+                &quot;System.Core.dll&quot;, 
+                &quot;System.Xml.Linq.dll&quot;,
+            };
+            comp.ReferencedAssemblies.AddRange(mainRefs.ToArray());
+            comp.ReferencedAssemblies.AddRange(extraRefs.ToArray());
+            CodeDomProvider cdp;
+            var ext = Path.GetExtension(fileName).ToLowerInvariant();
+            switch (ext) {
+                case &quot;.fsx&quot;:
+                    cdp = CodeDomProvider.CreateProvider(&quot;f#&quot;);
+                    break;
+                case &quot;.csx&quot;:
+                    cdp = new Microsoft.CSharp.CSharpCodeProvider(new Dictionary&lt;string, string&gt; { { &quot;CompilerVersion&quot;, &quot;v3.5&quot; } });
+                    break;
+                case &quot;.vbx&quot;:
+                    cdp = new Microsoft.VisualBasic.VBCodeProvider(new Dictionary&lt;string, string&gt; { { &quot;CompilerVersion&quot;, &quot;v3.5&quot; } });
+                    break;
+                case &quot;.jsx&quot;:
+                    // Have to figure out better JS support
+                    cdp = CodeDomProvider.CreateProvider(&quot;js&quot;);
+                    extraRefs.ForEach(comp.ReferencedAssemblies.Remove);
+                    break;
+                default:
+                    if (CodeDomProvider.IsDefinedExtension(ext)) {
+                        cdp = CodeDomProvider.CreateProvider(CodeDomProvider.GetLanguageFromExtension(ext));
+                    } else {
+                        return null;
+                    }
+                    break;
+            }
+
+            comp.GenerateInMemory = true;
+            comp.GenerateExecutable = true;
+
+            Log.WriteLine(LogLevel.Info, &quot;Compiling {0}&quot;, fileName);
+            var res = cdp.CompileAssemblyFromFile(comp, fileName);
+
+            var errors = res.Errors.Cast&lt;CompilerError&gt;().Where(x =&gt; !x.IsWarning).ToList();
+            if (errors.Count &gt; 0) {
+                Log.WriteLine(LogLevel.Error, &quot;There were {0} errors compiling {1}.&quot;, errors.Count, fileName);
+                foreach (var err in errors) {
+                    if (string.IsNullOrEmpty(err.FileName)) {
+                        Log.WriteLine(LogLevel.Error, &quot;{0}: {1}&quot;, err.ErrorNumber, err.ErrorText);
+                    } else {
+                        Log.WriteLine(LogLevel.Error, &quot;{0}: {1}:{2}:{3} {4}&quot;, err.ErrorNumber, err.FileName, err.Line, err.Column, err.ErrorText);
+                    }
+                }
+                return null;
+            }
+            Log.WriteLine(LogLevel.Info, &quot;File {0} compiled successfully.&quot;, fileName);
+            return res.CompiledAssembly;
+        }
+
+        bool processAssembly(string fileName, Assembly asm) {
+            var allTypes = asm.GetExportedTypes();
+            if (!RunLoadNotify(allTypes)) return false;
+
+            // Scripts can specify classes too
+            AddApiPlugins(allTypes);
+            AddAppPlugins(allTypes);
+
+            // Add the script executors
+            var entryPoint = getEntryDelegate(asm.EntryPoint);
+            var name = Path.GetFileName(fileName);
+            var aliases = new List&lt;string&gt; { name };
+            this.ApiExecutors.Add(new ApiPluginExecutor(name, aliases, () =&gt; new ScriptApiWrapper(entryPoint)));
+            this.AppExecutors.Add(new AppPluginExecutor(name, aliases, () =&gt; new ScriptAppWrapper(entryPoint)));
+
+            return true;
+        }
+
+        class ScriptApiWrapper : IApiPlugin {
+
+            readonly Action entryPoint;
+            public ScriptApiWrapper(Action entryPoint) {
+                this.entryPoint = entryPoint;
+            }
+
+            public void Execute(ApiContext context) {
+                Script.contextType = ScriptContextType.Api;
+                Script.context = context;
+                try {
+                    entryPoint();
+                } finally {
+                    Script.context = null;
+                }
+            }
+
+            public void ExecuteBackground(ApiBackgroundContext context) {
+                Script.contextType = ScriptContextType.ApiBackground;
+                Script.context = context;
+                try {
+                    entryPoint();
+                } finally {
+                    Script.context = null;
+                }
+            }
+
+        }
+
+        class ScriptAppWrapper : IAppPlugin {
+            
+            readonly Action entryPoint;
+            public ScriptAppWrapper(Action entryPoint) {
+                this.entryPoint = entryPoint;
+            }
+
+            public void Run(AppContext context) {
+                Script.contextType = ScriptContextType.App;
+                Script.context = context;
+                try {
+                    entryPoint();
+                } finally {
+                    Script.context = null;
+                }
+            }
+
+        }
+
+        static Action getEntryDelegate(MethodInfo entryPoint) {
+            if (!entryPoint.IsPublic || !entryPoint.DeclaringType.IsPublic) {
+                Log.WriteLine(LogLevel.Error, &quot;Entry point: {0}.{1} is not public. This may cause errors with Mono.&quot;,
+                    entryPoint.DeclaringType.FullName, entryPoint.Name);
+            }
+            var dm = new DynamicMethod(entryPoint.DeclaringType.Assembly.GetName().Name + &quot;_entrypoint_&quot; + entryPoint.DeclaringType.FullName + entryPoint.Name, null, null, true);
+            var il = dm.GetILGenerator();
+            var args = entryPoint.GetParameters();
+            if (args.Length &gt; 1) throw new ArgumentException(&quot;Cannot handle entry points with more than 1 parameter.&quot;);
+            if (args.Length == 1) {
+                if (args[0].ParameterType != typeof(string[])) throw new ArgumentException(&quot;Entry point paramter must be a string array.&quot;);
+                il.Emit(OpCodes.Ldc_I4_0);
+                il.Emit(OpCodes.Newarr, typeof(string));
+            }
+            il.EmitCall(OpCodes.Call, entryPoint, null);
+            if (entryPoint.ReturnType != typeof(void)) {
+                il.Emit(OpCodes.Pop);
+            }
+            il.Emit(OpCodes.Ret);
+            return (Action)dm.CreateDelegate(typeof(Action));
+        }
+
+    }
+}
</ins></span></pre>
</div>
</div>
<div id="footer">See you at ClueCon</div>

</body>
</html>