Exemplo n.º 1
0
        public override void Loaded(DockItem item)
        {
            base.Loaded(item);

            mPersistence = (CommandLinePersistence)ComponentManager.LoadObject("CommandLine", typeof(CommandLinePersistence), item);

            Task.Factory.StartNew(() =>
            {
                System.Threading.Thread.CurrentThread.Name = "CommandLine.Loaded";
                if (mPersistence == null)
                {
                    mPersistence = new CommandLinePersistence()
                    {
                        Script = ""
                    }
                }
                ;                                                           // TODO: set a default script here

                try
                {
                    ComponentManager.Execute(mPersistence.Script);
                }
                catch (Exception ex)
                {
                    consoleview.WriteOutput("Error: " + ex.Message);
                    consoleview.Prompt(true);
                }

                m_ScriptingInstance = new CommandScript(this, consoleview, ComponentManager);

                // output can be redirected to any object which implements method write and property softspace
                string[] phython_script_for_redirecting_stdout_and_stderr = new string[]
                {
                    "import sys",
                    "cmd=app().GetInstance(\"" + (this as ILocalizableComponent).Name + "\")",
                    "sys.stderr=cmd",
                    "sys.stdout=cmd"
                };

                ComponentManager.Execute(String.Join("\r\n", phython_script_for_redirecting_stdout_and_stderr));
            });
        }
Exemplo n.º 2
0
 void ScriptChanged(ScriptChangedEventArgs e)
 {
     if (e.Reference == this)
     {
         mPersistence.Script = e.Script;
         try
         {
             if (e.Code != null)
             {
                 ComponentManager.Execute(e.Code);
             }
         }
         catch (Exception ex)
         {
             foreach (IScript i in m_ScriptInterface)
             {
                 i.SetMessage(this, ex.Message);
             }
         }
     }
 }
Exemplo n.º 3
0
        void HandleConsoleInput(object sender, MonoDevelop.Components.ConsoleInputEventArgs e)
        {
            string input = e.Text;

            if (input == null)
            {
                consoleview.Prompt(true);
                return;
            }

            string inputL = input.Trim().ToLowerInvariant();

            if (inputL == "help" ||
                inputL == "help()" ||
                inputL.StartsWith("?"))
            {
                // treat this input specially to help the user. we do not pass this line to the python interpreter.

                consoleview.WriteOutput("Congratulations, you have found the help function :)" + "\n" +
                                        "This window is an interactive Python command line. You can input Python commands" + "\n" +
                                        "and will see their outputs directly." + "\n" +
                                        "To get more help, use the help() function, taking 1 parameter." + "\n" +
                                        "It will show help for that parameter, including for example all its methods etc." + "\n" +
                                        "To get a list of all available such parameters, you can use" + "\n" +
                                        "   print dir()" + "\n" +
                                        "That command returns a list of all available global objects. The most interesting one in there is" + "\n" +
                                        "app(), which is the invocation of a getter for the main application object." + "\n" +
                                        "To see which methods that object offers, run" + "\n" +
                                        "   help(app())" + "\n" +
                                        "Especially, this object has 4 interesting methods:" + "\n" +
                                        "   print app().ListInstances()" + "\n" +
                                        "prints a list of all currently instantiated components." + "\n" +
                                        "Each of them can be accessed by" + "\n" +
                                        "   app().GetInstance(\"xyz\")" + "\n" +
                                        ", for example" + "\n" +
                                        "   app().GetInstance(\"Map Explorer 2\")" + "\n" +
                                        "You can also instantiate new components: To get a list of the available ones, run" + "\n" +
                                        "   print app().ListComponentTypes()" + "\n" +
                                        "Creation then works like this:" + "\n" +
                                        "   print app().CreateComponent(\"xyz\")"
                                        );
                consoleview.Prompt(true);
                return;
            }

            bool ok = true;

            DisableInvokeOnAccessingConsoleView = true;
            try { ComponentManager.Execute(input); }
            catch (Exception ex)
            {
                consoleview.WriteOutput("Error: " + ex.Message);
                ok = false;
            }
            DisableInvokeOnAccessingConsoleView = false;

            if (ok)
            {
                consoleview.Prompt(false);
            }
            else
            {
                consoleview.Prompt(true);
            }
        }
Exemplo n.º 4
0
        public object Process(ProcessRequest request)
        {
            var assembly = string.Empty;
            var typeName = string.Empty;
            var methodName = string.Empty;
            var appDomainKey = string.Empty;

            MuleMessage result;
            MuleMessage muleMessage = new MuleMessage();
            IMuleInstrumentation instrumentation = new MuleInstrumentation(Instrument, request.NotifyEvents);

            if (string.IsNullOrWhiteSpace(request.AssemblyName))
            {
                throw new ArgumentNullException("assemblyName");
            }

            var split = request.AssemblyName.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            if (split.Length == 0)
            {
                throw new ArgumentException("Invalid .NET Assembly Type. The .NET Assembly Type should be: partially qualified \"Namespace.Type, AssemblyName\" or fully qualified name \"Namespace.Type, AssemblyName, [Version], [Culture], [PublicKey]\"");
            }

            typeName = split[0].Trim();

            if (split.Length == 2)
            {
                assembly = split[1].Trim();
                appDomainKey = string.Format("{0}_{1}", request.AssemblyPath, assembly);
            }
            else // remove type from assembly name
            {
                assembly = request.AssemblyName.Substring(request.AssemblyName.IndexOf(",") + 1).Trim();
                appDomainKey = assembly;
            }

            if (string.IsNullOrWhiteSpace(request.MethodName))
            {
                throw new ArgumentNullException("The method name cannot be empty.");
            }

            // add trust to key
            appDomainKey = string.Concat(appDomainKey, request.FullTrust);

            // add timestamp to assembly not in GAC
            if (request.AssemblyPath.EndsWith(".dll"))
            {
                appDomainKey = string.Concat(appDomainKey, "_", File.GetLastWriteTime(request.AssemblyPath).Ticks.ToString());
            }

            methodName = request.MethodName;

            muleMessage.Arguments = request.MethodArguments;
            muleMessage.InboundProperties = new ReadOnlyDictionary<string, object>(request.InboundProperties);
            muleMessage.SessionProperties = request.SessionProperties;
            muleMessage.InvocationProperties = request.InvocationProperties;
            muleMessage.OutboundProperties = request.OutboundProperties;
            var requestPath = muleMessage.InboundProperties.ContainsKey(MuleMessage.RequestKey) ? muleMessage.InboundProperties[MuleMessage.RequestKey] : string.Empty;
            muleMessage.Payload = muleMessage.Arguments.ContainsKey(MuleMessage.DataKey) ? muleMessage.Arguments[MuleMessage.DataKey] : requestPath;

            var queryString = muleMessage.InboundProperties.ContainsKey("http.query.string") ?
                muleMessage.InboundProperties["http.query.string"].ToString().Replace("{", "").Replace("}", "").Replace(" ", "").Replace(",", "&") :
                string.Empty;

            muleMessage.QueryStrings = string.IsNullOrWhiteSpace(queryString) ? new NameValueCollection() : HttpUtility.ParseQueryString(queryString);

            if (string.IsNullOrWhiteSpace(request.AssemblyPath))
            {
                request.AssemblyPath = componentPath;
            }

            componentManager = appDomains.GetOrAdd(appDomainKey,
                         (key) =>
                         {
                             var cm = new ComponentManager();
                             cm.AppDomainKey = appDomainKey;

                             //Bypass assemblies installed in the GAC
                             if (request.AssemblyPath.EndsWith(".dll"))
                             {
                                 // Add FileSystemWatcher to watch any updates on the requested assembly, if changes occur, unload AppDoamin and create a new one
                                 var watcher = new FileSystemWatcher();
                                 watcher.Path = Path.GetDirectoryName(request.AssemblyPath);
                                 watcher.NotifyFilter = NotifyFilters.LastWrite;
                                 watcher.Filter = "*.dll";
                                 watcher.Changed += (o, e) =>
                                 {
                                     var componentWatcher = cm;

                                     watcher.EnableRaisingEvents = false;
                                     var retry = 0;
                                     var maxRetries = 10;
                                     // wait until AppDomain is idle to unload it
                                     while (componentWatcher.State != ComponentState.Idle && retry < maxRetries)
                                     {
                                         Thread.Sleep(15000);
                                         retry++;
                                     }

                                     AppDomain.Unload(componentWatcher.LoaderDomain);
                                     appDomains.TryRemove(appDomainKey, out componentWatcher);

                                     if (retry >= maxRetries)
                                     {
                                         throw new Exception(string.Format("The AppDomain couldn't be unloaded normally after {0} attempts.", retry));
                                     }
                                 };
                                 watcher.EnableRaisingEvents = true;
                             }

                             cm.Init(componentPath, request.AssemblyPath, request.FullTrust, logger);

                             return cm;
                         });

            try
            {
                // Execute method
                string assemblyName;
                // Check if it's an assembly in the GAC or one specified by the user
                if (request.AssemblyPath.EndsWith(".dll"))
                {
                    assemblyName = AssemblyName.GetAssemblyName(request.AssemblyPath).FullName;
                }
                else
                {
                    assemblyName = assembly;
                }

                if(request.Log)
                {
                    Log(string.Format("Start execution of component: {0}.{1}", typeName, methodName));
                }

                //logger.Write(string.Format("Start execution of component: {0}.{1}", typeName, methodName), LoggerLevel.Trace);

                result = (MuleMessage)componentManager.Execute(assemblyName, typeName, methodName, muleMessage, request.IsSingleton, instrumentation);

                //logger.Write("End execution {0}.{1}", LoggerLevel.Trace, typeName, methodName);
                if(request.Log)
                {
                    Log(string.Format("End execution {0}.{1}", typeName, methodName));
                }
            }
            catch (Exception ex)
            {
                Log(string.Format("Error executing component {0}.{1} : {2}", typeName, methodName, ex.Message));
                throw;
            }

            return ToProcessRequest(result);
        }
Exemplo n.º 5
0
        public object Process(ProcessRequest request)
        {
            var assembly     = string.Empty;
            var typeName     = string.Empty;
            var methodName   = string.Empty;
            var appDomainKey = string.Empty;

            MuleMessage          result;
            MuleMessage          muleMessage     = new MuleMessage();
            IMuleInstrumentation instrumentation = new MuleInstrumentation(Instrument, request.NotifyEvents);

            if (string.IsNullOrWhiteSpace(request.AssemblyName))
            {
                throw new ArgumentNullException("assemblyName");
            }

            var split = request.AssemblyName.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            if (split.Length == 0)
            {
                throw new ArgumentException("Invalid .NET Assembly Type. The .NET Assembly Type should be: partially qualified \"Namespace.Type, AssemblyName\" or fully qualified name \"Namespace.Type, AssemblyName, [Version], [Culture], [PublicKey]\"");
            }

            typeName = split[0].Trim();

            if (split.Length == 2)
            {
                assembly     = split[1].Trim();
                appDomainKey = string.Format("{0}_{1}", request.AssemblyPath, assembly);
            }
            else // remove type from assembly name
            {
                assembly     = request.AssemblyName.Substring(request.AssemblyName.IndexOf(",") + 1).Trim();
                appDomainKey = assembly;
            }

            if (string.IsNullOrWhiteSpace(request.MethodName))
            {
                throw new ArgumentNullException("The method name cannot be empty.");
            }

            // add trust to key
            appDomainKey = string.Concat(appDomainKey, request.FullTrust);

            // add timestamp to assembly not in GAC
            if (request.AssemblyPath.EndsWith(".dll"))
            {
                appDomainKey = string.Concat(appDomainKey, "_", File.GetLastWriteTime(request.AssemblyPath).Ticks.ToString());
            }

            methodName = request.MethodName;

            muleMessage.Arguments            = request.MethodArguments;
            muleMessage.InboundProperties    = new ReadOnlyDictionary <string, object>(request.InboundProperties);
            muleMessage.SessionProperties    = request.SessionProperties;
            muleMessage.InvocationProperties = request.InvocationProperties;
            muleMessage.OutboundProperties   = request.OutboundProperties;
            var requestPath = muleMessage.InboundProperties.ContainsKey(MuleMessage.RequestKey) ? muleMessage.InboundProperties[MuleMessage.RequestKey] : string.Empty;

            muleMessage.Payload = muleMessage.Arguments.ContainsKey(MuleMessage.DataKey) ? muleMessage.Arguments[MuleMessage.DataKey] : requestPath;

            var queryString = muleMessage.InboundProperties.ContainsKey("http.query.string") ?
                              muleMessage.InboundProperties["http.query.string"].ToString().Replace("{", "").Replace("}", "").Replace(" ", "").Replace(",", "&") :
                              string.Empty;

            muleMessage.QueryStrings = string.IsNullOrWhiteSpace(queryString) ? new NameValueCollection() : HttpUtility.ParseQueryString(queryString);

            if (string.IsNullOrWhiteSpace(request.AssemblyPath))
            {
                request.AssemblyPath = componentPath;
            }

            componentManager = appDomains.GetOrAdd(appDomainKey,
                                                   (key) =>
            {
                var cm          = new ComponentManager();
                cm.AppDomainKey = appDomainKey;

                //Bypass assemblies installed in the GAC
                if (request.AssemblyPath.EndsWith(".dll"))
                {
                    // Add FileSystemWatcher to watch any updates on the requested assembly, if changes occur, unload AppDoamin and create a new one
                    var watcher          = new FileSystemWatcher();
                    watcher.Path         = Path.GetDirectoryName(request.AssemblyPath);
                    watcher.NotifyFilter = NotifyFilters.LastWrite;
                    watcher.Filter       = "*.dll";
                    watcher.Changed     += (o, e) =>
                    {
                        var componentWatcher = cm;

                        watcher.EnableRaisingEvents = false;
                        var retry      = 0;
                        var maxRetries = 10;
                        // wait until AppDomain is idle to unload it
                        while (componentWatcher.State != ComponentState.Idle && retry < maxRetries)
                        {
                            Thread.Sleep(15000);
                            retry++;
                        }

                        AppDomain.Unload(componentWatcher.LoaderDomain);
                        appDomains.TryRemove(appDomainKey, out componentWatcher);

                        if (retry >= maxRetries)
                        {
                            throw new Exception(string.Format("The AppDomain couldn't be unloaded normally after {0} attempts.", retry));
                        }
                    };
                    watcher.EnableRaisingEvents = true;
                }

                cm.Init(componentPath, request.AssemblyPath, request.FullTrust, logger);

                return(cm);
            });

            try
            {
                // Execute method
                string assemblyName;
                // Check if it's an assembly in the GAC or one specified by the user
                if (request.AssemblyPath.EndsWith(".dll"))
                {
                    assemblyName = AssemblyName.GetAssemblyName(request.AssemblyPath).FullName;
                }
                else
                {
                    assemblyName = assembly;
                }

                if (request.Log)
                {
                    Log(string.Format("Start execution of component: {0}.{1}", typeName, methodName));
                }

                //logger.Write(string.Format("Start execution of component: {0}.{1}", typeName, methodName), LoggerLevel.Trace);

                result = (MuleMessage)componentManager.Execute(assemblyName, typeName, methodName, muleMessage, request.IsSingleton, instrumentation);

                //logger.Write("End execution {0}.{1}", LoggerLevel.Trace, typeName, methodName);
                if (request.Log)
                {
                    Log(string.Format("End execution {0}.{1}", typeName, methodName));
                }
            }
            catch (Exception ex)
            {
                Log(string.Format("Error executing component {0}.{1} : {2}", typeName, methodName, ex.Message));
                throw;
            }

            return(ToProcessRequest(result));
        }