コード例 #1
0
 public static NamespaceList GetNamespaces(PluginSource pluginSource)
 {
     using (var runtime = CreateInvokeAppDomain())
     {
         return(runtime.Value.FetchNamespaceListObject(pluginSource));
     }
 }
コード例 #2
0
        public void PluginSourceContructorWithDefaultExpectedInitializesProperties()
        {
            var source = new PluginSource();

            Assert.AreEqual(Guid.Empty, source.ResourceID);
            Assert.AreEqual("PluginSource", source.ResourceType);
        }
コード例 #3
0
        public void Execute_GivenHasContructorWithInputs_ShouldReturnCorrectInputs()
        {
            //---------------Set up test pack-------------------
            var type          = typeof(Human);
            var assembly      = type.Assembly;
            var namespaceItem = new NamespaceItem()
            {
                AssemblyLocation = assembly.Location,
                AssemblyName     = assembly.FullName,
                FullName         = type.FullName,
            };
            var pluginSource = new PluginSource()
            {
                AssemblyName     = type.AssemblyQualifiedName,
                AssemblyLocation = assembly.Location,
            };

            var pluginSourceDefinition = new PluginSourceDefinition();
            var serializeToJson        = pluginSourceDefinition.SerializeToJsonStringBuilder();
            var nameSpace   = namespaceItem.SerializeToJsonStringBuilder();
            var resourceCat = new Mock <IResourceCatalog>();

            resourceCat.Setup(catalog => catalog.GetResource <PluginSource>(It.IsAny <Guid>(), It.IsAny <Guid>()))
            .Returns(pluginSource);
            var FetchPluginConstructors = new FetchPluginConstructors(resourceCat.Object);

            //---------------Assert Precondition----------------

            //---------------Execute Test ----------------------
            var mock          = new Mock <IWorkspace>();
            var stringBuilder = FetchPluginConstructors.Execute(new Dictionary <string, StringBuilder>()
            {
                { "source", serializeToJson },
                { "namespace", nameSpace },
            },
                                                                mock.Object);
            //---------------Test Result -----------------------
            var executeMessage      = stringBuilder.DeserializeToObject <ExecuteMessage>();
            var deserializeToObject = executeMessage.Message.DeserializeToObject <List <IPluginConstructor> >();

            Assert.AreEqual(3, deserializeToObject.Count);

            var pluginConstructor = deserializeToObject[1];
            var count             = pluginConstructor.Inputs.Count;

            Assert.AreEqual(1, count);
            var serviceInput  = pluginConstructor.Inputs[0];
            var name          = serviceInput.Name;
            var emptyIsNull   = serviceInput.EmptyToNull;
            var requiredField = serviceInput.IsRequired;
            var value         = serviceInput.Value;
            var typeName      = serviceInput.TypeName;

            Assert.AreEqual("name", name);
            Assert.AreEqual(false, emptyIsNull);
            Assert.AreEqual(true, requiredField);
            Assert.IsTrue(string.IsNullOrEmpty(value));
            Assert.AreEqual(typeof(string), Type.GetType(typeName));
        }
コード例 #4
0
        public void Execute_GivenHasContructorWithInputs_ShouldReturnCorrectConstructorName()
        {
            //---------------Set up test pack-------------------
            var type          = typeof(Human);
            var assembly      = type.Assembly;
            var namespaceItem = new NamespaceItem()
            {
                AssemblyLocation = assembly.Location,
                AssemblyName     = assembly.FullName,
                FullName         = type.FullName,
            };
            var pluginSource = new PluginSource()
            {
                AssemblyName     = type.AssemblyQualifiedName,
                AssemblyLocation = assembly.Location,
            };

            var pluginSourceDefinition = new PluginSourceDefinition();
            var serializeToJson        = pluginSourceDefinition.SerializeToJsonStringBuilder();
            var nameSpace   = namespaceItem.SerializeToJsonStringBuilder();
            var resourceCat = new Mock <IResourceCatalog>();

            resourceCat.Setup(catalog => catalog.GetResource <PluginSource>(It.IsAny <Guid>(), It.IsAny <Guid>()))
            .Returns(pluginSource);
            var FetchPluginConstructors = new FetchPluginConstructors(resourceCat.Object);

            //---------------Assert Precondition----------------

            //---------------Execute Test ----------------------
            var mock          = new Mock <IWorkspace>();
            var stringBuilder = FetchPluginConstructors.Execute(new Dictionary <string, StringBuilder>()
            {
                { "source", serializeToJson },
                { "namespace", nameSpace },
            },
                                                                mock.Object);
            //---------------Test Result -----------------------
            var executeMessage      = stringBuilder.DeserializeToObject <ExecuteMessage>();
            var deserializeToObject = executeMessage.Message.DeserializeToObject <List <IPluginConstructor> >();

            Assert.AreEqual(3, deserializeToObject.Count);

            var          pluginConstructor1 = deserializeToObject[1];
            var          constructorName1   = pluginConstructor1.ConstructorName;
            const string expectedName1      = ".ctor (System.String)";

            Assert.AreEqual(expectedName1, constructorName1);

            var          pluginConstructor0 = deserializeToObject[0];
            var          constructorName0   = pluginConstructor0.ConstructorName;
            const string expectedName0      = ".ctor ";

            Assert.AreEqual(expectedName0, constructorName0);
            var          pluginConstructor2 = deserializeToObject[2];
            var          constructorName2   = pluginConstructor2.ConstructorName;
            const string expectedName2      = ".ctor (System.String,System.String,TestingDotnetDllCascading.Food)";

            Assert.AreEqual(expectedName2, constructorName2);
        }
コード例 #5
0
        /// <summary>
        /// Fetches the name space list object.
        /// </summary>
        /// <param name="pluginSource">The plugin source.</param>
        /// <returns></returns>
        public NamespaceList FetchNamespaceListObject(PluginSource pluginSource)
        {
            var interrogatePlugin = ReadNamespaces(pluginSource.AssemblyLocation, pluginSource.AssemblyName);
            var namespacelist     = new NamespaceList();

            namespacelist.AddRange(interrogatePlugin);
            return(namespacelist);
        }
コード例 #6
0
        public void PluginSourceContructorWithInvalidXmlExpectedDoesNotThrowExceptionAndInitializesProperties()
        {
            var xml    = new XElement("root");
            var source = new PluginSource(xml);

            Assert.AreNotEqual(Guid.Empty, source.ResourceID);
            Assert.IsTrue(source.IsUpgraded);
            Assert.AreEqual("PluginSource", source.ResourceType);
        }
コード例 #7
0
        public IPluginSource FetchSource(Guid resourceID)
        {
            var xaml = _queryProxy.FetchResourceXaml(resourceID);
            var db   = new PluginSource(xaml.ToXElement());

            var def = new PluginSourceDefinition(db);

            return(def);
        }
コード例 #8
0
        public void Execute_GivenSourceAndNamespaceWithActionsTakingObject_ShouldObjectParameters()
        {
            var humanType = typeof(Human);
            //------------Setup for test--------------------------
            var pluginSource = new PluginSource
            {
                ResourceName     = humanType.FullName,
                ResourceID       = humanType.GUID,
                AssemblyName     = humanType.AssemblyQualifiedName,
                AssemblyLocation = humanType.Assembly.Location
            };

            var resourceCat = new Mock <IResourceCatalog>();

            resourceCat.Setup(catalog => catalog.GetResource <PluginSource>(It.IsAny <Guid>(), It.IsAny <Guid>()))
            .Returns(pluginSource);
            var fetchPluginActionsWithReturnsTypes = new FetchPluginActionsWithReturnsTypes(resourceCat.Object);

            var jsonSerializer   = new Dev2JsonSerializer();
            var sourceDefinition = new PluginSourceDefinition
            {
                Id = humanType.GUID, Name = humanType.FullName, Path = humanType.Assembly.Location
            };
            var namespaceItem = new NamespaceItem
            {
                FullName         = humanType.FullName,
                AssemblyLocation = humanType.Assembly.Location,
                AssemblyName     = humanType.Assembly.FullName
            };

            var serialezedSource    = jsonSerializer.SerializeToBuilder(sourceDefinition);
            var serialezedNamespace = jsonSerializer.SerializeToBuilder(namespaceItem);
            var values = new Dictionary <string, StringBuilder>
            {
                { "source", serialezedSource },
                { "namespace", serialezedNamespace }
            };
            var workspace = new Mock <IWorkspace>();
            var execute   = fetchPluginActionsWithReturnsTypes.Execute(values, workspace.Object);
            var results   = jsonSerializer.Deserialize <ExecuteMessage>(execute);

            //------------Assert Results-------------------------
            Assert.IsFalse(results.HasError);
            var pluginActions = jsonSerializer.Deserialize <List <IPluginAction> >(results.Message);

            Assert.IsTrue(pluginActions.Any(action => action.IsVoid));
            IEnumerable <IList <IServiceInput> > parameters = pluginActions.Select(action => action.Inputs);
            var enumerable = parameters as IList <IServiceInput>[] ?? parameters.ToArray();
            var containsObjectParameters = enumerable.Any(list => list.Any(input => input.IsObject));
            var shortTypeName            = enumerable.All(list => list.All(input => !string.IsNullOrEmpty(input.ShortTypeName)));
            var dev2ReturnType           = enumerable.All(list => list.All(input => !string.IsNullOrEmpty(input.Dev2ReturnType)));

            Assert.IsTrue(containsObjectParameters);
            Assert.IsTrue(shortTypeName);
            Assert.IsTrue(dev2ReturnType);
        }
コード例 #9
0
        static void LoadPlugin(string PluginFile, ScriptEngine Engine)
        {
            try
            {
                ScriptSource        PluginSource;
                CompiledCode        CompiledPlugin;
                ScriptErrorReporter CompileErrors = new ScriptErrorReporter();
                string ErrorMessage = "";

                fileName = PluginFile.Substring(PluginFile.LastIndexOf('\\') + 1);
                if (StartUp)
                {
                    IronUI.ShowLoadMessage("Loading Plugin - " + fileName);
                }
                if (PluginFile.EndsWith(".py", StringComparison.CurrentCultureIgnoreCase))
                {
                    Engine.Runtime.TryGetEngine("py", out Engine);
                    PluginSource = Engine.CreateScriptSourceFromFile(PluginFile);
                    string IndentError = PluginEditor.CheckPythonIndentation(PluginSource.GetCode())[1];
                    CompiledPlugin = PluginSource.Compile(CompileErrors);
                    ErrorMessage   = CompileErrors.GetErrors();
                    if (IndentError.Length > 0)
                    {
                        ErrorMessage = string.Format("{0}\r\n{1}", IndentError, ErrorMessage);
                    }
                    if (ErrorMessage.Length == 0)
                    {
                        PluginSource.ExecuteProgram();
                    }
                }
                else if (PluginFile.EndsWith(".rb", StringComparison.CurrentCultureIgnoreCase))
                {
                    Engine.Runtime.TryGetEngine("rb", out Engine);
                    PluginSource   = Engine.CreateScriptSourceFromFile(PluginFile);
                    CompiledPlugin = PluginSource.Compile(CompileErrors);
                    ErrorMessage   = CompileErrors.GetErrors();
                    if (ErrorMessage.Length == 0)
                    {
                        PluginSource.ExecuteProgram();
                    }
                }
                if (ErrorMessage.Length > 0)
                {
                    IronException.Report("Syntax error in Plugin - " + PluginFile, ErrorMessage);
                }
            }
            catch (Exception Exp)
            {
                IronException.Report("Error loading plugin - " + PluginFile, Exp.Message, Exp.StackTrace);
            }
            finally
            {
                fileName = "";
            }
        }
コード例 #10
0
        public void PluginSourceContructorWithValidXmlExpectedInitializesProperties()
        {
            var xml = XmlResource.Fetch("PluginSource");

            var source = new PluginSource(xml);

            Assert.AreEqual(Guid.Parse("00746beb-46c1-48a8-9492-e2d20817fcd5"), source.ResourceID);
            Assert.AreEqual("PluginSource", source.ResourceType);
            Assert.AreEqual(@"C:\Development\DEV2 SCRUM Project\Branches\BUG_9500_PluginNamespaces\BPM Resources\Plugins\Dev2.PluginTester.dll", source.AssemblyLocation);
            Assert.AreEqual("Dev2.PluginTester", source.AssemblyName);
        }
コード例 #11
0
        public StringBuilder Execute(Dictionary <string, StringBuilder> values, IWorkspace theWorkspace)
        {
            ExecuteMessage     msg        = new ExecuteMessage();
            Dev2JsonSerializer serializer = new Dev2JsonSerializer();

            try
            {
                Dev2Logger.Info("Save Plugin Source");
                StringBuilder resourceDefinition;

                values.TryGetValue("PluginSource", out resourceDefinition);

                var src = serializer.Deserialize <PluginSourceDefinition>(resourceDefinition);
                if (src.Path.EndsWith("\\"))
                {
                    src.Path = src.Path.Substring(0, src.Path.LastIndexOf("\\", StringComparison.Ordinal));
                }
                PluginSource res;
                var          existingSource = ResourceCatalog.Instance.GetResource(GlobalConstants.ServerWorkspaceID, src.Name);
                if (existingSource != null)
                {
                    res = existingSource as PluginSource;
                }
                else
                {
                    res = new PluginSource
                    {
                        ResourceID     = src.Id,
                        ConfigFilePath = src.ConfigFilePath,
                        ResourceName   = src.Name
                    };
                }
                Debug.Assert(res != null, "res != null");
                if (!string.IsNullOrEmpty(src.FileSystemAssemblyName))
                {
                    res.AssemblyLocation = src.FileSystemAssemblyName;
                }
                else if (!string.IsNullOrEmpty(src.GACAssemblyName))
                {
                    res.AssemblyLocation = src.GACAssemblyName;
                }
                ResourceCatalog.Instance.SaveResource(GlobalConstants.ServerWorkspaceID, res, src.Path);
                ServerExplorerRepo.UpdateItem(res);
                msg.HasError = false;
            }
            catch (Exception err)
            {
                msg.HasError = true;
                msg.Message  = new StringBuilder(err.Message);
                Dev2Logger.Error(err);
            }

            return(serializer.SerializeToBuilder(msg));
        }
コード例 #12
0
        static void RunScript(string ScriptFile, ScriptEngine Engine)
        {
            try
            {
                ScriptSource        PluginSource;
                CompiledCode        CompiledPlugin;
                ScriptErrorReporter CompileErrors = new ScriptErrorReporter();
                string ErrorMessage = "";

                if (ScriptFile.EndsWith(".py", StringComparison.CurrentCultureIgnoreCase))
                {
                    Engine.Runtime.TryGetEngine("py", out Engine);
                    PluginSource = Engine.CreateScriptSourceFromFile(ScriptFile);
                    string IndentError = PluginEditor.CheckPythonIndentation(PluginSource.GetCode())[1];
                    if (IndentError.Length > 0)
                    {
                        string UpdatedCode = PluginEditor.FixPythonIndentation(PluginSource.GetCode());
                        PluginSource = Engine.CreateScriptSourceFromString(UpdatedCode);
                        //ErrorMessage = string.Format("{0}\r\n{1}", IndentError, ErrorMessage);
                    }
                    CompiledPlugin = PluginSource.Compile(CompileErrors);
                    ErrorMessage   = CompileErrors.GetErrors();
                    if (ErrorMessage.Length > 0 && IndentError.Length > 0)
                    {
                        ErrorMessage = string.Format("{0}\r\n{1}", IndentError, ErrorMessage);
                    }
                    if (ErrorMessage.Length == 0)
                    {
                        PluginSource.ExecuteProgram();
                    }
                }
                else if (ScriptFile.EndsWith(".rb", StringComparison.CurrentCultureIgnoreCase))
                {
                    Engine.Runtime.TryGetEngine("rb", out Engine);
                    PluginSource   = Engine.CreateScriptSourceFromFile(ScriptFile);
                    CompiledPlugin = PluginSource.Compile(CompileErrors);
                    ErrorMessage   = CompileErrors.GetErrors();
                    if (ErrorMessage.Length == 0)
                    {
                        PluginSource.ExecuteProgram();
                    }
                }
                if (ErrorMessage.Length > 0)
                {
                    IronException.Report("Syntax error in API Script - " + ScriptFile, ErrorMessage);
                }
            }
            catch (Exception Exp)
            {
                IronException.Report("Error loading script - " + ScriptFile, Exp.Message, Exp.StackTrace);
            }
        }
コード例 #13
0
        /// <summary>
        /// Fetches the name space list object.
        /// </summary>
        /// <param name="pluginSource">The plugin source.</param>
        /// <returns></returns>
        public NamespaceList FetchNamespaceListObject(PluginSource pluginSource)
        {
            // BUG 9500 - 2013.05.31 - TWR : added check to avoid nulling AssemblyLocation/Name in tests
            if (string.IsNullOrEmpty(pluginSource.AssemblyLocation))
            {
                pluginSource = new PluginSources().Get(pluginSource.ResourceID.ToString(), Guid.Empty, Guid.Empty);
            }
            var interrogatePlugin = ReadNamespaces(pluginSource.AssemblyLocation, pluginSource.AssemblyName);
            var namespacelist     = new NamespaceList();

            namespacelist.AddRange(interrogatePlugin);
            return(namespacelist);
        }
コード例 #14
0
        public void Execute_GivenSourceAndNamespaceWithStringActions_ShouldReturnAStringFunction()
        {
            var humanType = typeof(Human);
            //------------Setup for test--------------------------
            var pluginSource = new PluginSource
            {
                ResourceName     = humanType.FullName,
                ResourceID       = humanType.GUID,
                AssemblyName     = humanType.AssemblyQualifiedName,
                AssemblyLocation = humanType.Assembly.Location
            };

            var resourceCat = new Mock <IResourceCatalog>();

            resourceCat.Setup(catalog => catalog.GetResource <PluginSource>(It.IsAny <Guid>(), It.IsAny <Guid>()))
            .Returns(pluginSource);
            var fetchPluginActionsWithReturnsTypes = new FetchPluginActionsWithReturnsTypes(resourceCat.Object);

            var jsonSerializer   = new Dev2JsonSerializer();
            var sourceDefinition = new PluginSourceDefinition
            {
                Id = humanType.GUID, Name = humanType.FullName, Path = humanType.Assembly.Location
            };
            var namespaceItem = new NamespaceItem
            {
                FullName         = humanType.FullName,
                AssemblyLocation = humanType.Assembly.Location,
                AssemblyName     = humanType.Assembly.FullName
            };

            var serialezedSource    = jsonSerializer.SerializeToBuilder(sourceDefinition);
            var serialezedNamespace = jsonSerializer.SerializeToBuilder(namespaceItem);
            var values = new Dictionary <string, StringBuilder>
            {
                { "source", serialezedSource },
                { "namespace", serialezedNamespace }
            };
            var workspace = new Mock <IWorkspace>();
            var execute   = fetchPluginActionsWithReturnsTypes.Execute(values, workspace.Object);
            var results   = jsonSerializer.Deserialize <ExecuteMessage>(execute);

            //------------Assert Results-------------------------
            Assert.IsFalse(results.HasError);
            var pluginActions = jsonSerializer.Deserialize <List <IPluginAction> >(results.Message);

            Assert.IsTrue(pluginActions.Any(action => action.IsVoid));
            var any = pluginActions.Any(action => action.Dev2ReturnType.Equals("return: String"));

            Assert.IsTrue(any);
        }
コード例 #15
0
        public void PluginSourceToXmlExpectedSerializesProperties()
        {
            var expected = new PluginSource
            {
                AssemblyLocation = "Plugins\\someDllIMadeUpToTest.dll",
                AssemblyName     = "dev2.test.namespacefortesting",
            };

            var xml = expected.ToXml();

            var actual = new PluginSource(xml);

            Assert.AreEqual(expected.ResourceType, actual.ResourceType);
            Assert.AreEqual(expected.AssemblyLocation, actual.AssemblyLocation);
            Assert.AreEqual(expected.AssemblyName, actual.AssemblyName);
        }
コード例 #16
0
        public void PluginSourceToXmlWithNullPropertiesExpectedSerializesPropertiesAsEmpty()
        {
            var expected = new PluginSource
            {
                AssemblyLocation = null,
                AssemblyName     = null,
            };

            var xml = expected.ToXml();

            var actual = new PluginSource(xml);

            Assert.AreEqual(expected.ResourceType, actual.ResourceType);
            Assert.AreEqual("", actual.AssemblyLocation);
            Assert.AreEqual("", actual.AssemblyName);
        }
コード例 #17
0
        // POST: Service/PluginServices/Methods
        public ServiceMethodList Methods(string args, Guid workspaceId, Guid dataListId)
        {
            var result = new ServiceMethodList();

            try
            {
                // BUG 9500 - 2013.05.31 - TWR : changed to use PluginService as args
                var service = JsonConvert.DeserializeObject <PluginService>(args);
                var pluginSourceFromCatalog = _resourceCatalog.GetResource <PluginSource>(workspaceId, service.Source.ResourceID);
                if (pluginSourceFromCatalog == null)
                {
                    try
                    {
                        var xmlStr = Resources.ReadXml(workspaceId, ResourceType.PluginSource, service.Source.ResourceID.ToString());
                        if (!string.IsNullOrEmpty(xmlStr))
                        {
                            var xml = XElement.Parse(xmlStr);
                            pluginSourceFromCatalog = new PluginSource(xml);
                        }
                    }
                    catch (Exception)
                    {
                        //ignore this
                    }
                }
                if (pluginSourceFromCatalog != null)
                {
                    service.Source = pluginSourceFromCatalog;
                }
                var broker       = new PluginBroker();
                var pluginSource = (PluginSource)service.Source;
                if (pluginSource != null)
                {
                    result = broker.GetMethods(pluginSource.AssemblyLocation, pluginSource.AssemblyName, service.Namespace);
                }
                return(result);
            }
            catch (Exception ex)
            {
                RaiseError(ex);
            }
            return(result);
        }
コード例 #18
0
        public static NamespaceList GetNamespaces(PluginSource pluginSource)
        {
            AppDomain childDomain = null;

            try
            {
                var runtime = CreateInvokeAppDomain(out childDomain);

                // start the runtime.  call will marshal into the child runtime app domain
                return(runtime.FetchNamespaceListObject(pluginSource));
            }
            finally
            {
                if (childDomain != null)
                {
                    AppDomain.Unload(childDomain);
                }
            }
        }
コード例 #19
0
        public void Execute_GivenTestInputs_ShouldReturnConstructorList()
        {
            //---------------Set up test pack-------------------
            var type          = typeof(Human);
            var assembly      = type.Assembly;
            var namespaceItem = new NamespaceItem()
            {
                AssemblyLocation = assembly.Location,
                AssemblyName     = assembly.FullName,
                FullName         = type.FullName,
            };
            var pluginSource = new PluginSource()
            {
                AssemblyName     = type.AssemblyQualifiedName,
                AssemblyLocation = assembly.Location,
            };

            var pluginSourceDefinition = new PluginSourceDefinition();
            var serializeToJson        = pluginSourceDefinition.SerializeToJsonStringBuilder();
            var nameSpace   = namespaceItem.SerializeToJsonStringBuilder();
            var resourceCat = new Mock <IResourceCatalog>();

            resourceCat.Setup(catalog => catalog.GetResource <PluginSource>(It.IsAny <Guid>(), It.IsAny <Guid>()))
            .Returns(pluginSource);
            var FetchPluginConstructors = new FetchPluginConstructors(resourceCat.Object);

            //---------------Assert Precondition----------------

            //---------------Execute Test ----------------------
            var mock          = new Mock <IWorkspace>();
            var stringBuilder = FetchPluginConstructors.Execute(new Dictionary <string, StringBuilder>()
            {
                { "source", serializeToJson },
                { "namespace", nameSpace },
            },
                                                                mock.Object);
            //---------------Test Result -----------------------
            var executeMessage      = stringBuilder.DeserializeToObject <ExecuteMessage>();
            var deserializeToObject = executeMessage.Message.DeserializeToObject <List <IPluginConstructor> >();

            Assert.AreEqual(3, deserializeToObject.Count);
        }
コード例 #20
0
 // POST: Service/PluginServices/Test
 public RecordsetList Test(string args, Guid workspaceId, Guid dataListId)
 {
     try
     {
         var service = JsonConvert.DeserializeObject <PluginService>(args, new JsonSerializerSettings
         {
             TypeNameHandling = TypeNameHandling.Objects
         });
         var pluginSourceFromCatalog = _resourceCatalog.GetResource <PluginSource>(workspaceId, service.Source.ResourceID);
         if (pluginSourceFromCatalog == null)
         {
             try
             {
                 var xmlStr = Resources.ReadXml(workspaceId, ResourceType.PluginSource, service.Source.ResourceID.ToString());
                 if (!string.IsNullOrEmpty(xmlStr))
                 {
                     var xml = XElement.Parse(xmlStr);
                     pluginSourceFromCatalog = new PluginSource(xml);
                 }
             }
             catch (Exception)
             {
                 //ignore the exception
             }
         }
         if (pluginSourceFromCatalog != null)
         {
             service.Source = pluginSourceFromCatalog;
         }
         return(FetchRecordset(service, true));
     }
     catch (Exception ex)
     {
         RaiseError(ex);
         return(new RecordsetList {
             new Recordset {
                 HasErrors = true, ErrorMessage = ex.Message
             }
         });
     }
 }
コード例 #21
0
        // POST: Service/PluginSources/Get
        public PluginSource Get(string resourceId, Guid workspaceId, Guid dataListId)
        {
            var result = new PluginSource {
                ResourceID = Guid.Empty, ResourceType = ResourceType.PluginSource
            };

            try
            {
                var xmlStr = Resources.ReadXml(workspaceId, ResourceType.PluginSource, resourceId);
                if (!string.IsNullOrEmpty(xmlStr))
                {
                    var xml = XElement.Parse(xmlStr);
                    result = new PluginSource(xml);
                }
            }
            catch (Exception ex)
            {
                RaiseError(ex);
            }
            return(result);
        }
コード例 #22
0
        // POST: Service/PluginServices/Namespaces
        public virtual NamespaceList Namespaces(PluginSource args, Guid workspaceId, Guid dataListId)
        {
            var result = new NamespaceList();

            try
            {
                if (args != null)
                {
                    var broker = new PluginBroker();
                    return(broker.GetNamespaces(args));
                }
            }
            catch (BadImageFormatException e)
            {
                RaiseError(e);
                throw;
            }
            catch (Exception ex)
            {
                RaiseError(ex);
            }
            return(result);
        }
コード例 #23
0
ファイル: PluginStore.cs プロジェクト: xuezs/IronWASP
        static void LoadPlugin(string PluginFile, ScriptEngine Engine)
        {
            try
            {
                ScriptSource PluginSource;
                CompiledCode CompiledPlugin;

                fileName = PluginFile.Substring(PluginFile.LastIndexOf('\\') + 1);
                if (StartUp)
                {
                    IronUI.ShowLoadMessage("Loading Plugin - " + fileName);
                }
                if (PluginFile.EndsWith(".py", StringComparison.CurrentCultureIgnoreCase))
                {
                    Engine.Runtime.TryGetEngine("py", out Engine);
                    PluginSource   = Engine.CreateScriptSourceFromFile(PluginFile);
                    CompiledPlugin = PluginSource.Compile();
                    PluginSource.ExecuteProgram();
                }
                else if (PluginFile.EndsWith(".rb", StringComparison.CurrentCultureIgnoreCase))
                {
                    Engine.Runtime.TryGetEngine("rb", out Engine);
                    PluginSource   = Engine.CreateScriptSourceFromFile(PluginFile);
                    CompiledPlugin = PluginSource.Compile();
                    PluginSource.ExecuteProgram();
                }
            }
            catch (Exception Exp)
            {
                IronException.Report("Error loading plugin - " + PluginFile, Exp.Message, Exp.StackTrace);
            }
            finally
            {
                fileName = "";
            }
        }
コード例 #24
0
        public void Execute_GivenNoNamespace_ShouldReturnEmpyt()
        {
            //------------Setup for test--------------------------
            var pluginSource = new PluginSource
            {
                ResourceName = "ResourceName",
                FilePath     = "ResourcePath",
                ResourceID   = Guid.Empty
            };

            var resourceCat = new Mock <IResourceCatalog>();

            resourceCat.Setup(catalog => catalog.GetResource <PluginSource>(It.IsAny <Guid>(), It.IsAny <Guid>()))
            .Returns(pluginSource);
            var fetchPluginActionsWithReturnsTypes = new FetchPluginActionsWithReturnsTypes(resourceCat.Object);

            var jsonSerializer   = new Dev2JsonSerializer();
            var sourceDefinition = new PluginSourceDefinition
            {
                Id = Guid.Empty, Name = "SourceName", Path = "SourcePath"
            };
            var serialezedSource = jsonSerializer.SerializeToBuilder(sourceDefinition);
            var values           = new Dictionary <string, StringBuilder>
            {
                { "source", serialezedSource },
                { "namespace", new StringBuilder("") }
            };
            var workspace = new Mock <IWorkspace>();
            //-------------------------Test Execution -----------------
            var execute = fetchPluginActionsWithReturnsTypes.Execute(values, workspace.Object);
            var results = jsonSerializer.Deserialize <ExecuteMessage>(execute);

            //------------Assert Results-------------------------
            Assert.IsFalse(results.HasError);
            Assert.AreEqual("[]", results.Message.ToString());
        }
コード例 #25
0
 public void PluginSourceContructorWithNullXmlExpectedThrowsArgumentNullException()
 {
     var source = new PluginSource(null);
 }
コード例 #26
0
 private void ResetPlugin()
 {
     Cleanup();
     SetRotatingFrameThresholds();
     RemoveBuggyTidalLocking();
     plugin_construction_ = DateTime.Now;
     Dictionary<String, ConfigNode> name_to_gravity_model = null;
     var gravity_model_configs =
     GameDatabase.Instance.GetConfigs(principia_gravity_model_config_name);
     var cartesian_configs =
     GameDatabase.Instance.GetConfigs(principia_initial_state_config_name);
     if (gravity_model_configs.Length == 1) {
       name_to_gravity_model =
       gravity_model_configs[0].config.GetNodes("body").
       ToDictionary(node => node.GetValue("name"));
     } else if (gravity_model_configs.Length > 1) {
       Log.Fatal("too many gravity models (" + gravity_model_configs.Length +
     ")");
     }
     if (cartesian_configs.Length > 0) {
       plugin_source_ = PluginSource.CARTESIAN_CONFIG;
       if (cartesian_configs.Length > 1) {
     Log.Fatal("too many Cartesian configs (" + cartesian_configs.Length +
       ")");
       }
       if (name_to_gravity_model == null) {
     Log.Fatal("Cartesian config without gravity models");
       }
       try {
     ConfigNode initial_states =
     GameDatabase.Instance.GetConfigs(principia_initial_state_config_name)[0].config;
     plugin_ =
     Interface.NewPlugin(initial_states.GetValue("game_epoch"),
                     initial_states.GetValue("solar_system_epoch"),
                     Planetarium.InverseRotAngle);
     var name_to_initial_state =
     initial_states.GetNodes("body").
     ToDictionary(node => node.GetValue("name"));
     BodyProcessor insert_body = body => {
       Log.Info("Inserting " + body.name + "...");
       ConfigNode gravity_model;
       if (!name_to_gravity_model.TryGetValue(body.name,
                                      out gravity_model)) {
      Log.Fatal("missing gravity model for " + body.name);
       }
       ConfigNode initial_state;
       if (!name_to_initial_state.TryGetValue(body.name,
                                      out initial_state)) {
      Log.Fatal("missing Cartesian initial state for " + body.name);
       }
       int? parent_index = body.orbit?.referenceBody.flightGlobalsIndex;
       var body_parameters = new BodyParameters{
       name = body.name,
       gravitational_parameter =
       gravity_model.GetValue("gravitational_parameter"),
       reference_instant       =
       double.Parse(gravity_model.GetValue("reference_instant")),
       mean_radius             = gravity_model.GetValue("mean_radius"),
       axis_right_ascension    =
       gravity_model.GetValue("axis_right_ascension"),
       axis_declination        =
       gravity_model.GetValue("axis_declination"),
       reference_angle         =
       gravity_model.GetValue("reference_angle"),
       angular_frequency       =
       gravity_model.GetValue("angular_frequency"),
       j2                      = gravity_model.GetValue("j2"),
       reference_radius        =
       gravity_model.GetValue("reference_radius")};
       plugin_.InsertCelestialAbsoluteCartesian(
       celestial_index         : body.flightGlobalsIndex,
       parent_index            : parent_index,
       body_parameters         : body_parameters,
       x                       : initial_state.GetValue("x"),
       y                       : initial_state.GetValue("y"),
       z                       : initial_state.GetValue("z"),
       vx                      : initial_state.GetValue("vx"),
       vy                      : initial_state.GetValue("vy"),
       vz                      : initial_state.GetValue("vz"));
     };
     insert_body(Planetarium.fetch.Sun);
     ApplyToBodyTree(insert_body);
     plugin_.EndInitialization();
     plugin_.AdvanceTime(Planetarium.GetUniversalTime(),
                 Planetarium.InverseRotAngle);
       } catch (Exception e) {
     Log.Fatal("Exception while reading initial state: " + e.ToString());
       }
     } else {
       plugin_source_ = PluginSource.ORBITAL_ELEMENTS;
       // We create the plugin at time 0, rather than
       // |Planetarium.GetUniversalTime()|, in order to get a deterministic
       // initial state.
       for(;;) {
     plugin_ = Interface.NewPlugin("0 s", "0 s",
                           Planetarium.InverseRotAngle);
     BodyProcessor insert_body = body => {
       Log.Info("Inserting " + body.name + "...");
       ConfigNode gravity_model = null;
       if (name_to_gravity_model?.TryGetValue(body.name,
                                      out gravity_model) == true) {
     Log.Info("using custom gravity model");
       }
       Orbit orbit = unmodified_orbits_.GetValueOrNull(body);
       var body_parameters = new BodyParameters{
       name = body.name,
       gravitational_parameter =
       (gravity_model?.GetValue("gravitational_parameter")).
           GetValueOrDefault(body.gravParameter + " m^3/s^2"),
       // J2000, because that's when we start non-config games.  We
       // should really parse real-life dates from strings.
       // The origin of rotation in KSP is the x of Barycentric, rather
       // than the y axis as is the case for Earth, so the right
       // ascension is -90 deg.
       reference_instant    = double.Parse(
       (gravity_model?.GetValue("reference_instant")).
           GetValueOrDefault("2451545.0")),
       mean_radius          =
       (gravity_model?.GetValue("mean_radius")).
           GetValueOrDefault(body.Radius + " m"),
       axis_right_ascension =
       (gravity_model?.GetValue("axis_right_ascension")).
           GetValueOrDefault("-90 deg"),
       axis_declination     =
       (gravity_model?.GetValue("axis_declination")).
           GetValueOrDefault("90 deg"),
       reference_angle      =
       (gravity_model?.GetValue("reference_angle")).
           GetValueOrDefault(body.initialRotation.ToString() +
                             " deg"),
       angular_frequency    =
       (gravity_model?.GetValue("angular_frequency")).
           GetValueOrDefault(body.angularV.ToString() + " rad/s"),
       j2                   = gravity_model?.GetValue("j2"),
       reference_radius     =
       gravity_model?.GetValue("reference_radius")};
       plugin_.InsertCelestialJacobiKeplerian(
       celestial_index             : body.flightGlobalsIndex,
       parent_index                :
       orbit?.referenceBody.flightGlobalsIndex,
       body_parameters             : body_parameters,
       keplerian_elements          : orbit?.Elements());
     };
     insert_body(Planetarium.fetch.Sun);
     ApplyToBodyTree(insert_body);
     plugin_.EndInitialization();
     if (plugin_.IsKspStockSystem()) {
       Interface.DeletePlugin(ref plugin_);
       Fix631();
     } else {
       break;
     }
       }
     }
     plotting_frame_selector_.reset(
     new ReferenceFrameSelector(this,
                        plugin_,
                        UpdateRenderingFrame,
                        "Plotting frame"));
     flight_planner_.reset(new FlightPlanner(this, plugin_));
     VesselProcessor insert_vessel = vessel => {
       Log.Info("Inserting " + vessel.name + "...");
       bool inserted =
       plugin_.InsertOrKeepVessel(
       vessel.id.ToString(),
       vessel.orbit.referenceBody.flightGlobalsIndex);
       if (!inserted) {
     Log.Fatal("Plugin initialization: vessel not inserted");
       } else {
     plugin_.SetVesselStateOffset(vessel.id.ToString(),
                          new QP{q = (XYZ)vessel.orbit.pos,
                                 p = (XYZ)vessel.orbit.vel});
       }
     };
     ApplyToVesselsOnRailsOrInInertialPhysicsBubbleInSpace(insert_vessel);
 }
コード例 #27
0
ファイル: PluginBroker.cs プロジェクト: Spharah/Warewolf-ESB
 /// <summary>
 /// Gets the namespaces.
 /// </summary>
 /// <param name="pluginSource">The plugin source.</param>
 /// <returns></returns>
 public NamespaceList GetNamespaces(PluginSource pluginSource)
 {
     return(PluginServiceExecutionFactory.GetNamespaces(pluginSource));
 }
コード例 #28
0
            public override void OnLoad(ConfigNode node)
            {
                base.OnLoad(node);
                if (must_record_journal_) {
                  Log.ActivateRecorder(true);
                }
                if (node.HasValue(principia_key)) {
                  Cleanup();
                  SetRotatingFrameThresholds();
                  RemoveBuggyTidalLocking();
                  Log.SetBufferedLogging(buffered_logging_);
                  Log.SetSuppressedLogging(suppressed_logging_);
                  Log.SetStderrLogging(stderr_logging_);
                  Log.SetVerboseLogging(verbose_logging_);

                  IntPtr deserializer = IntPtr.Zero;
                  String[] serializations = node.GetValues(principia_key);
                  Log.Info("Serialization has " + serializations.Length + " chunks");
                  foreach (String serialization in serializations) {
                Log.Info("serialization is " + serialization.Length +
                 " characters long");
                Interface.DeserializePlugin(serialization,
                                    serialization.Length,
                                    ref deserializer,
                                    ref plugin_);
                  }
                  Interface.DeserializePlugin("", 0, ref deserializer, ref plugin_);

                  plotting_frame_selector_.reset(
                  new ReferenceFrameSelector(this,
                                     plugin_,
                                     UpdateRenderingFrame,
                                     "Plotting frame"));
                  flight_planner_.reset(new FlightPlanner(this, plugin_));

                  plugin_construction_ = DateTime.Now;
                  plugin_source_ = PluginSource.SAVED_STATE;
                } else {
                  Log.Warning("No principia state found, creating one");
                  ResetPlugin();
                }
            }
コード例 #29
0
ファイル: ObsidianPlugin.cs プロジェクト: savioacp/Obsidian
 public ObsidianPlugin(PluginSource source, string path, ObsidianPluginClass @class) : base(source, path, @class.Info)
 {
     this.Class = @class;
 }
コード例 #30
0
 private void ResetPlugin()
 {
     Cleanup();
     SetRotatingFrameThresholds();
     RemoveBuggyTidalLocking();
     ResetRenderedTrajectory();
     plugin_construction_ = DateTime.Now;
     if (GameDatabase.Instance.GetConfigs(kPrincipiaInitialState).Length > 0) {
       plugin_source_ = PluginSource.CARTESIAN_CONFIG;
       if (GameDatabase.Instance.GetConfigs(
       kPrincipiaGravityModel).Length == 0) {
     Log.Fatal("missing gravity models");
       }
       if (GameDatabase.Instance.GetConfigs(kPrincipiaInitialState).Length > 1 ||
       GameDatabase.Instance.GetConfigs(
       kPrincipiaGravityModel).Length > 1) {
     Log.Fatal("too many configs");
       }
       try {
     ConfigNode initial_states =
     GameDatabase.Instance.GetConfigs(kPrincipiaInitialState)[0].config;
     ConfigNode gravity_models =
     GameDatabase.Instance.GetConfigs(kPrincipiaGravityModel)[0].config;
     plugin_ =
     Interface.NewPlugin(double.Parse(initial_states.GetValue("epoch")),
                     Planetarium.InverseRotAngle);
     var name_to_initial_state = new Dictionary<String, ConfigNode>();
     var name_to_gravity_model = new Dictionary<String, ConfigNode>();
     foreach (ConfigNode node in initial_states.GetNodes("body")) {
       name_to_initial_state.Add(node.GetValue("name"), node);
     }
     foreach (ConfigNode node in gravity_models.GetNodes("body")) {
       name_to_gravity_model.Add(node.GetValue("name"), node);
     }
     ConfigNode sun_gravity_model =
     name_to_gravity_model[Planetarium.fetch.Sun.name];
     ConfigNode sun_initial_state =
     name_to_initial_state[Planetarium.fetch.Sun.name];
     plugin_.InsertCelestialAbsoluteCartesian(
     celestial_index: Planetarium.fetch.Sun.flightGlobalsIndex,
     parent_index: IntPtr.Zero,
     gravitational_parameter:
     sun_gravity_model.GetValue("gravitational_parameter"),
     axis_right_ascension:
     sun_gravity_model.HasValue("axis_right_ascension") ?
     sun_gravity_model.GetValue("axis_right_ascension") : null,
     axis_declination:
     sun_gravity_model.HasValue("axis_declination") ?
     sun_gravity_model.GetValue("axis_declination") : null,
     j2: sun_gravity_model.HasValue("j2") ?
     sun_gravity_model.GetValue("j2") : null,
     reference_radius:
     sun_gravity_model.HasValue("reference_radius") ?
     sun_gravity_model.GetValue("reference_radius") : null,
     x: sun_initial_state.GetValue("x"),
     y: sun_initial_state.GetValue("y"),
     z: sun_initial_state.GetValue("z"),
     vx: sun_initial_state.GetValue("vx"),
     vy: sun_initial_state.GetValue("vy"),
     vz: sun_initial_state.GetValue("vz"));
     BodyProcessor insert_body = body => {
       Log.Info("Inserting " + body.name + "...");
       ConfigNode gravity_model = name_to_gravity_model[body.name];
       ConfigNode initial_state = name_to_initial_state[body.name];
       int parent_index = body.orbit.referenceBody.flightGlobalsIndex;
       plugin_.InsertCelestialAbsoluteCartesian(
       celestial_index: body.flightGlobalsIndex,
       parent_index: ref parent_index,
       gravitational_parameter:
       gravity_model.GetValue("gravitational_parameter"),
       axis_right_ascension:
       gravity_model.HasValue("axis_right_ascension") ?
       gravity_model.GetValue("axis_right_ascension") : null,
       axis_declination:
       gravity_model.HasValue("axis_declination") ?
       gravity_model.GetValue("axis_declination") : null,
       j2: gravity_model.HasValue("j2") ?
       gravity_model.GetValue("j2") : null,
       reference_radius:
       gravity_model.HasValue("reference_radius") ?
       gravity_model.GetValue("reference_radius") : null,
       x: initial_state.GetValue("x"),
       y: initial_state.GetValue("y"),
       z: initial_state.GetValue("z"),
       vx: initial_state.GetValue("vx"),
       vy: initial_state.GetValue("vy"),
       vz: initial_state.GetValue("vz"));
     };
     ApplyToBodyTree(insert_body);
     plugin_.EndInitialization();
     plugin_.AdvanceTime(Planetarium.GetUniversalTime(),
                 Planetarium.InverseRotAngle);
       } catch (Exception e) {
     Log.Fatal("Exception while reading initial state: " + e.ToString());
       }
     } else {
       plugin_source_ = PluginSource.ORBITAL_ELEMENTS;
       // We create the plugin at time 0, rather than
       // |Planetarium.GetUniversalTime()|, in order to get a deterministic
       // initial state.
       plugin_ = Interface.NewPlugin(0,
                         Planetarium.InverseRotAngle);
       plugin_.InsertSun(Planetarium.fetch.Sun.flightGlobalsIndex,
             Planetarium.fetch.Sun.gravParameter);
       BodyProcessor insert_body = body => {
     Log.Info("Inserting " + body.name + "...");
     Orbit orbit = unmodified_orbits_[body];
     double mean_motion = 2 * Math.PI / orbit.period;
     plugin_.InsertCelestialJacobiKeplerian(
     celestial_index             : body.flightGlobalsIndex,
     parent_index                : body.referenceBody.flightGlobalsIndex,
     gravitational_parameter     : body.gravParameter + " m^3/s^2",
     axis_right_ascension        : null,
     axis_declination            : null,
     j2                          : null,
     reference_radius            : null,
     eccentricity                : orbit.eccentricity,
     mean_motion                 : mean_motion + " rad/s",
     inclination                 : orbit.inclination + " deg",
     longitude_of_ascending_node : orbit.LAN + " deg",
     argument_of_periapsis       : orbit.argumentOfPeriapsis + " deg",
     mean_anomaly                : orbit.meanAnomalyAtEpoch -
                               orbit.epoch * mean_motion + " rad");
       };
       ApplyToBodyTree(insert_body);
       plugin_.EndInitialization();
     }
     plotting_frame_selector_.reset(
     new ReferenceFrameSelector(this,
                        plugin_,
                        UpdateRenderingFrame,
                        "Plotting frame"));
     flight_planner_.reset(new FlightPlanner(this, plugin_));
     VesselProcessor insert_vessel = vessel => {
       Log.Info("Inserting " + vessel.name + "...");
       bool inserted =
       plugin_.InsertOrKeepVessel(
       vessel.id.ToString(),
       vessel.orbit.referenceBody.flightGlobalsIndex);
       if (!inserted) {
     Log.Fatal("Plugin initialization: vessel not inserted");
       } else {
     plugin_.SetVesselStateOffset(vessel.id.ToString(),
                          new QP{q = (XYZ)vessel.orbit.pos,
                                 p = (XYZ)vessel.orbit.vel});
       }
     };
     ApplyToVesselsOnRailsOrInInertialPhysicsBubbleInSpace(insert_vessel);
 }
コード例 #31
0
            public override void OnLoad(ConfigNode node)
            {
                base.OnLoad(node);
                if (node.HasValue(kPrincipiaKey)) {
                  Cleanup();
                  SetRotatingFrameThresholds();
                  Log.SetBufferedLogging(buffered_logging_);
                  Log.SetSuppressedLogging(suppressed_logging_);
                  Log.SetStderrLogging(stderr_logging_);
                  Log.SetVerboseLogging(verbose_logging_);

                  IntPtr deserializer = IntPtr.Zero;
                  String[] serializations = node.GetValues(kPrincipiaKey);
                  Log.Info("Serialization has " + serializations.Length + " chunks");
                  foreach (String serialization in serializations) {
                Log.Info("serialization is " + serialization.Length +
                 " characters long");
                DeserializePlugin(serialization,
                          serialization.Length,
                          ref deserializer,
                          ref plugin_);
                  }
                  DeserializePlugin("", 0, ref deserializer, ref plugin_);

                  UpdateRenderingFrame();
                  plugin_construction_ = DateTime.Now;
                  plugin_source_ = PluginSource.SAVED_STATE;
                } else {
                  Log.Warning("No principia state found, creating one");
                  ResetPlugin();
                }
            }
コード例 #32
0
 private void ResetPlugin()
 {
     Cleanup();
     SetRotatingFrameThresholds();
     ResetRenderedTrajectory();
     plugin_construction_ = DateTime.Now;
     if (GameDatabase.Instance.GetConfigs(kPrincipiaInitialState).Length > 0) {
       plugin_source_ = PluginSource.CARTESIAN_CONFIG;
       if (GameDatabase.Instance.GetConfigs(
       kPrincipiaGravityModel).Length == 0) {
     Log.Fatal("missing gravity models");
       }
       if (GameDatabase.Instance.GetConfigs(kPrincipiaInitialState).Length > 1 ||
       GameDatabase.Instance.GetConfigs(
       kPrincipiaGravityModel).Length > 1) {
     Log.Fatal("too many configs");
       }
       try {
     ConfigNode initial_states =
     GameDatabase.Instance.GetConfigs(kPrincipiaInitialState)[0].config;
     ConfigNode gravity_models =
     GameDatabase.Instance.GetConfigs(kPrincipiaGravityModel)[0].config;
     plugin_ = NewPlugin(double.Parse(initial_states.GetValue("epoch")),
                 Planetarium.InverseRotAngle);
     var name_to_initial_state = new Dictionary<String, ConfigNode>();
     var name_to_gravity_model = new Dictionary<String, ConfigNode>();
     foreach (ConfigNode node in initial_states.GetNodes("body")) {
       name_to_initial_state.Add(node.GetValue("name"), node);
     }
     foreach (ConfigNode node in gravity_models.GetNodes("body")) {
       name_to_gravity_model.Add(node.GetValue("name"), node);
     }
     ConfigNode sun_gravity_model =
     name_to_gravity_model[Planetarium.fetch.Sun.name];
     ConfigNode sun_initial_state =
     name_to_initial_state[Planetarium.fetch.Sun.name];
     DirectlyInsertCelestial(
     plugin: plugin_,
     celestial_index: Planetarium.fetch.Sun.flightGlobalsIndex,
     parent_index: IntPtr.Zero,
     gravitational_parameter:
     sun_gravity_model.GetValue("gravitational_parameter"),
     axis_right_ascension:
     sun_gravity_model.HasValue("axis_right_ascension") ?
     sun_gravity_model.GetValue("axis_right_ascension") : null,
     axis_declination:
     sun_gravity_model.HasValue("axis_declination") ?
     sun_gravity_model.GetValue("axis_declination") : null,
     j2: sun_gravity_model.HasValue("j2") ?
     sun_gravity_model.GetValue("j2") : null,
     reference_radius:
     sun_gravity_model.HasValue("reference_radius") ?
     sun_gravity_model.GetValue("reference_radius") : null,
     x: sun_initial_state.GetValue("x"),
     y: sun_initial_state.GetValue("y"),
     z: sun_initial_state.GetValue("z"),
     vx: sun_initial_state.GetValue("vx"),
     vy: sun_initial_state.GetValue("vy"),
     vz: sun_initial_state.GetValue("vz"));
     BodyProcessor insert_body = body => {
       Log.Info("Inserting " + body.name + "...");
       ConfigNode gravity_model = name_to_gravity_model[body.name];
       ConfigNode initial_state = name_to_initial_state[body.name];
       int parent_index = body.orbit.referenceBody.flightGlobalsIndex;
       DirectlyInsertCelestial(
       plugin: plugin_,
       celestial_index: body.flightGlobalsIndex,
       parent_index: ref parent_index,
       gravitational_parameter:
       gravity_model.GetValue("gravitational_parameter"),
       axis_right_ascension:
       gravity_model.HasValue("axis_right_ascension") ?
       gravity_model.GetValue("axis_right_ascension") : null,
       axis_declination:
       gravity_model.HasValue("axis_declination") ?
       gravity_model.GetValue("axis_declination") : null,
       j2: gravity_model.HasValue("j2") ?
       gravity_model.GetValue("j2") : null,
       reference_radius:
       gravity_model.HasValue("reference_radius") ?
       gravity_model.GetValue("reference_radius") : null,
       x: initial_state.GetValue("x"),
       y: initial_state.GetValue("y"),
       z: initial_state.GetValue("z"),
       vx: initial_state.GetValue("vx"),
       vy: initial_state.GetValue("vy"),
       vz: initial_state.GetValue("vz"));
     };
     ApplyToBodyTree(insert_body);
     EndInitialization(plugin_);
     AdvanceTime(plugin_,
         Planetarium.GetUniversalTime(),
         Planetarium.InverseRotAngle);
       } catch (Exception e) {
     Log.Fatal("Exception while reading initial state: " + e.ToString());
       }
     } else {
       plugin_source_ = PluginSource.ORBITAL_ELEMENTS;
       plugin_ = NewPlugin(Planetarium.GetUniversalTime(),
               Planetarium.InverseRotAngle);
       InsertSun(plugin_,
     Planetarium.fetch.Sun.flightGlobalsIndex,
     Planetarium.fetch.Sun.gravParameter);
       BodyProcessor insert_body = body => {
     Log.Info("Inserting " + body.name + "...");
     InsertCelestial(plugin_,
             body.flightGlobalsIndex,
             body.gravParameter,
             body.orbit.referenceBody.flightGlobalsIndex,
             new QP{q = (XYZ)body.orbit.pos,
                    p = (XYZ)body.orbit.vel});
       };
       ApplyToBodyTree(insert_body);
       EndInitialization(plugin_);
     }
     UpdateRenderingFrame();
     VesselProcessor insert_vessel = vessel => {
       Log.Info("Inserting " + vessel.name + "...");
       bool inserted =
       InsertOrKeepVessel(plugin_,
                  vessel.id.ToString(),
                  vessel.orbit.referenceBody.flightGlobalsIndex);
       if (!inserted) {
     Log.Fatal("Plugin initialization: vessel not inserted");
       } else {
     SetVesselStateOffset(plugin_,
                  vessel.id.ToString(),
                  new QP{q = (XYZ)vessel.orbit.pos,
                         p = (XYZ)vessel.orbit.vel});
       }
     };
     ApplyToVesselsOnRailsOrInInertialPhysicsBubbleInSpace(insert_vessel);
 }