コード例 #1
0
        public void ProcessOperationFromJsonFull()
        {
            MockRunspaceManager runspace = new MockRunspaceManager();
            GeneratedModule     module   = new GeneratedModule(runspace);

            module.Operations["thing_get"] = new OperationData("Thing_Get", "Get-Thing")
            {
                Parameters = new Dictionary <string, ParameterData>()
                {
                    { "parameter", new ParameterData()
                      {
                          Name = "Parameter", Type = new RuntimeTypeData(typeof(GeneratedModuleTestsObject))
                      } }
                }
            };

            string json = "{\"method\":\"Things.Thing_Get\",\"params\":{\"__reserved\":{\"credentials\":[{\"x-ps-credtype\":\"commandBased\",\"tenantId\":\"testTenantId\",\"clientId\":\"testClientId\",\"secret\":\"testSecret\"},{\"x-ps-credtype\":\"parameterBased\",\"tenantId\":\"testTenantId\",\"clientId\":\"testClientId\",\"secret\":\"testSecret\"}]},\"parameter\":{\"string\":\"testValue\",\"number\":500,\"object\":{\"decimal\":1.2,\"boolean\":true}}}}";
            LiveTestRequestConverter converter = new LiveTestRequestConverter(module);

            Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings();
            converter.RegisterSelf(settings);

            MockTestCredentialFactory credentialsFactory = new MockTestCredentialFactory();

            credentialsFactory.RegisterProvider("commandbased", new CommandBasedCredentialProvider());
            credentialsFactory.RegisterProvider("parameterbased", new ParameterBasedCredentialProvider());

            LiveTestRequest        request = Newtonsoft.Json.JsonConvert.DeserializeObject <LiveTestRequest>(json, settings);
            CommandExecutionResult result  = module.ProcessRequest(request, credentialsFactory);

            Assert.Equal("Login-Account [parameter {[String testValue] [Number 500] [Object [Decimal 1.2] [Boolean True]]}]", (string)runspace.InvokeHistory[0]);
            Assert.Equal("Login-Account [parameter {[String testValue] [Number 500] [Object [Decimal 1.2] [Boolean True]]}] [CredentialKey testCredentials]", (string)runspace.InvokeHistory[1]);
        }
コード例 #2
0
        public void RegistersAllSubConverters()
        {
            GeneratedModule module = new GeneratedModule(null);
            OperationData   test   = new OperationData("testoperationid", "Get-Test");

            module.Operations["testoperationid"] = test;
            RuntimeTypeData jsonParmData = new RuntimeTypeData()
            {
                Type = typeof(LiveTestRequestConverterTestsObject)
            };

            jsonParmData.Properties["property"] = new ParameterData()
            {
                Name     = "property",
                JsonName = "prop",
                Type     = new RuntimeTypeData()
                {
                    Type = typeof(string)
                }
            };
            test.Parameters["jsonparm"] = new ParameterData()
            {
                Name = "jsonParm",
                Type = jsonParmData
            };

            LiveTestRequestConverter converter = new LiveTestRequestConverter(module);
            JsonSerializerSettings   settings  = new JsonSerializerSettings();

            converter.RegisterSelf(settings);

            // 1. LiveTestRequestConverter
            // 2. DynamicTypedObjectConverter for LiveTestRequestConverterTestsObject
            Assert.Equal(2, settings.Converters.Count);
        }
コード例 #3
0
        public void ReservedParameterStaysJObject()
        {
            GeneratedModule module = new GeneratedModule(null);
            OperationData   test   = new OperationData("testoperationid", "Get-Test");

            module.Operations["testoperationid"] = test;
            test.Parameters["__reserved"]        = new ParameterData()
            {
                Name = "__reserved",
                Type = new RuntimeTypeData()
                {
                    Type = typeof(string)
                }
            };

            LiveTestRequestConverter converter = new LiveTestRequestConverter(module);
            JsonSerializerSettings   settings  = new JsonSerializerSettings();

            settings.Converters.Add(converter);

            string          json    = "{\"method\":\"A.testOperationId\",\"jsonrpc\":\"2.0\",\"id\":\"0\",\"params\":{\"__reserved\":{}}}";
            LiveTestRequest request = JsonConvert.DeserializeObject <LiveTestRequest>(json, settings);

            Assert.NotNull(request);
            Assert.Equal("0", request.Id);
            Assert.Equal("2.0", request.JsonRpc);
            Assert.Equal("A.testOperationId", request.Method);
            Assert.Equal("testoperationid", request.OperationId);
            Assert.True(request.Params.ContainsKey("__reserved"));
            Assert.Equal(typeof(JObject), request.Params["__reserved"].GetType());
        }
コード例 #4
0
        public void GetModuleInfoByName()
        {
            string             modulePath = "PowerShellGet";
            PowerShellRunspace psRunspace = new PowerShellRunspace(this.logger);
            GeneratedModule    module     = psRunspace.GetModuleInfo(modulePath);

            Assert.Equal(12, module.Operations.Count);
        }
コード例 #5
0
        public void ProcessOperationWithCredentials()
        {
            MockRunspaceManager runspace = new MockRunspaceManager();
            GeneratedModule     module   = new GeneratedModule(runspace);

            module.Operations["thing_get"] = new OperationData("Thing_Get", "Get-Thing");

            MockTestCredentialFactory credentialsFactory = new MockTestCredentialFactory();

            credentialsFactory.RegisterProvider("commandbased", new CommandBasedCredentialProvider());
            credentialsFactory.RegisterProvider("parameterbased", new ParameterBasedCredentialProvider());
            LiveTestRequest request = new LiveTestRequest();

            request.Method      = "Things.Thing_Get";
            request.OperationId = "Thing_Get";
            request.Params      = new Dictionary <string, object>()
            {
                { "__reserved", new Dictionary <string, object>()
                  {
                      { "credentials", new LiveTestCredentials[] { new LiveTestCredentials()
                                                                   {
                                                                       Type       = "commandBased",
                                                                       Properties = new Dictionary <string, object>()
                                                                       {
                                                                           { "tenantId", "testTenantId" },
                                                                           { "clientId", "testClientId" },
                                                                           { "secret", "testSecret" }
                                                                       }
                                                                   }, new LiveTestCredentials()
                                                                   {
                                                                       Type       = "parameterBased",
                                                                       Properties = new Dictionary <string, object>()
                                                                       {
                                                                           { "tenantId", "testTenantId" },
                                                                           { "clientId", "testClientId" },
                                                                           { "secret", "testSecret" }
                                                                       }
                                                                   } } }
                  } }
            };
            request.Params["parameter"] = new GeneratedModuleTestsObject()
            {
                String = "testValue",
                Number = 500,
                Object = new GeneratedModuleTestsSubObject()
                {
                    Decimal = 1.2,
                    Boolean = true
                }
            };

            CommandExecutionResult result = module.ProcessRequest(request, credentialsFactory);

            Assert.Equal(2, runspace.InvokeHistory.Count);
            Assert.Equal("Login-Account", (string)runspace.InvokeHistory[0]);
            Assert.Equal("Login-Account [CredentialKey testCredentials]", (string)runspace.InvokeHistory[1]);
        }
コード例 #6
0
        private void GetLoadMetadataFromSpecificationTestData(out GeneratedModule expectedModule, out GeneratedModule testModule)
        {
            MockRunspaceManager runspace = new MockRunspaceManager();

            expectedModule = new GeneratedModule(runspace);
            expectedModule.Operations["operationid"] = new OperationData("operationid", "command")
            {
                Parameters = new Dictionary <string, ParameterData>()
                {
                    { "psparametername", new ParameterData()
                      {
                          Name     = "psparametername",
                          JsonName = "namefromspec"
                      } }
                },
                ResponseType = new ResponseTypeData()
                {
                    ModuleData = new RuntimeTypeData()
                    {
                        Type = typeof(GeneratedModuleTestsSubObject)
                    }
                }
            };
            expectedModule.Operations["operationid"].ResponseType.SpecificationData.Add(new RuntimeTypeData()
            {
                Properties = new Dictionary <string, ParameterData>()
                {
                    { "pspropertyname", new ParameterData()
                      {
                          Name     = "pspropertyname",
                          JsonName = "propertynamefromspec"
                      } }
                }
            });
            expectedModule.Operations["operationid"].ResponseType.Complete();

            testModule = new GeneratedModule(runspace);
            testModule.Operations["operationid"] = new OperationData("operationid", "command")
            {
                Parameters = new Dictionary <string, ParameterData>()
                {
                    { "psparametername", new ParameterData()
                      {
                          Name = "psparametername"
                      } }
                },
                ResponseType = new ResponseTypeData()
                {
                    ModuleData = new RuntimeTypeData()
                    {
                        Type = typeof(GeneratedModuleTestsSubObject)
                    }
                }
            };
        }
コード例 #7
0
        public void LoadWithName()
        {
            MockRunspaceManager runspace = new MockRunspaceManager();
            GeneratedModule     module   = new GeneratedModule(runspace);

            module.ModulePath = "PackageManagement";
            module.Load();

            Assert.Equal("Import-Module", runspace.CommandBuilders[0].Command);
            Assert.True(runspace.CommandBuilders[0].Parameters.ContainsKey("Name"));
            Assert.Equal("PackageManagement", runspace.CommandBuilders[0].Parameters["Name"]);
        }
コード例 #8
0
        public void BasicLoadTest()
        {
            MockRunspaceManager runspace = new MockRunspaceManager();
            GeneratedModule     module   = new GeneratedModule(runspace);

            module.ModulePath = "test.psd1";
            module.Load();

            Assert.Equal("Import-Module", runspace.CommandBuilders[0].Command);
            Assert.True(runspace.CommandBuilders[0].Parameters.ContainsKey("Name"));
            Assert.Equal("test.psd1", runspace.CommandBuilders[0].Parameters["Name"]);
        }
コード例 #9
0
        public void LoadWithRequiredModules()
        {
            MockRunspaceManager runspace       = new MockRunspaceManager();
            GeneratedModule     module         = new GeneratedModule(runspace);
            GeneratedModule     requiredModule = new GeneratedModule(runspace);

            requiredModule.ModulePath = "PowerShellGet";
            module.ModulePath         = "PackageManagement";
            module.RequiredModules.Add(requiredModule);
            module.Load();

            Assert.Equal("import-module [name powershellget false]", runspace.Builder.InvokeHistory[0].ToLowerInvariant());
            Assert.Equal("import-module [name packagemanagement false]", runspace.Builder.InvokeHistory[1].ToLowerInvariant());
        }
コード例 #10
0
 private void AssertModulesArEqual(GeneratedModule expectedModule, GeneratedModule actualModule)
 {
     Assert.Equal(expectedModule.Operations.Count, actualModule.Operations.Count);
     foreach (string key in expectedModule.Operations.Keys)
     {
         Assert.True(actualModule.Operations.ContainsKey(key));
         foreach (string pkey in expectedModule.Operations[key].Parameters.Keys)
         {
             Assert.True(actualModule.Operations[key].Parameters.ContainsKey(pkey));
             Assert.Equal(expectedModule.Operations[key].Parameters[pkey].Name, actualModule.Operations[key].Parameters[pkey].Name);
             Assert.Equal(expectedModule.Operations[key].Parameters[pkey].JsonName, actualModule.Operations[key].Parameters[pkey].JsonName);
         }
     }
 }
コード例 #11
0
        public void BasicHappyPathTest()
        {
            string             modulePath = GetRootedPath(System.IO.Path.Combine("data", "Modules", "BasicHappyPath", "BasicHappyPath.psd1"));
            PowerShellRunspace psRunspace = new PowerShellRunspace(this.logger);
            GeneratedModule    result     = psRunspace.GetModuleInfo(modulePath);

            Assert.Equal(0, this.error.Errors.Count);
            Assert.NotNull(result);
            Assert.Equal(modulePath, result.ModulePath);
            Assert.Equal(4, result.Operations.Count);
            AssertModuleContainsOperation(result, new OperationData("Guitar_Create", "New-Guitar")
            {
                Parameters =
                {
                    { "id", new ParameterData()
                        {
                            Name = "id",
                            Type = new RuntimeTypeData(typeof(string))
                        } }
                }
            });
            AssertModuleContainsOperation(result, new OperationData("Guitar_CreateByName", "New-Guitar")
            {
                Parameters =
                {
                    { "name", new ParameterData()
                        {
                            Name = "name",
                            Type = new RuntimeTypeData(typeof(string))
                        } }
                }
            });
            AssertModuleContainsOperation(result, new OperationData("Guitar_GetById", "Get-Guitar")
            {
                Parameters =
                {
                    { "id", new ParameterData()
                        {
                            Name = "id",
                            Type = new RuntimeTypeData(typeof(string))
                        } }
                },
                ResponseType = new ResponseTypeData()
                {
                    ModuleData = new RuntimeTypeData(typeof(string))
                }
            });
        }
コード例 #12
0
        public void ConvertsMappedPropertyOfParameter()
        {
            GeneratedModule module = new GeneratedModule(null);
            OperationData   test   = new OperationData("testoperationid", "Get-Test");

            module.Operations["testoperationid"] = test;
            RuntimeTypeData jsonParmData = new RuntimeTypeData()
            {
                Type = typeof(LiveTestRequestConverterTestsObject)
            };

            jsonParmData.Properties["property"] = new ParameterData()
            {
                Name     = "property",
                JsonName = "prop",
                Type     = new RuntimeTypeData()
                {
                    Type = typeof(string)
                }
            };
            test.Parameters["jsonparm"] = new ParameterData()
            {
                Name = "jsonParm",
                Type = jsonParmData
            };

            LiveTestRequestConverter converter = new LiveTestRequestConverter(module);
            JsonSerializerSettings   settings  = new JsonSerializerSettings();

            settings.Converters.Add(converter);
            settings.Converters.Add(new DynamicTypedObjectConverter(jsonParmData));

            string          json    = "{\"method\":\"A.testOperationId\",\"jsonrpc\":\"2.0\",\"id\":\"0\",\"params\":{\"jsonparm\":{\"prop\":\"testValue\"}}}";
            LiveTestRequest request = JsonConvert.DeserializeObject <LiveTestRequest>(json, settings);

            Assert.NotNull(request);
            Assert.Equal("0", request.Id);
            Assert.Equal("2.0", request.JsonRpc);
            Assert.Equal("A.testOperationId", request.Method);
            Assert.Equal("testoperationid", request.OperationId);
            Assert.True(request.Params.ContainsKey("jsonparm"));
            Assert.Equal(typeof(LiveTestRequestConverterTestsObject), request.Params["jsonparm"].GetType());
            Assert.Equal("testValue", ((LiveTestRequestConverterTestsObject)request.Params["jsonparm"]).Property);

            string reserialized = JsonConvert.SerializeObject(request, settings);

            Assert.Equal(json, reserialized);
        }
コード例 #13
0
        public void ForceLoadTest()
        {
            MockRunspaceManager runspace = new MockRunspaceManager();
            GeneratedModule     module   = new GeneratedModule(runspace);

            module.ModulePath = "test.psd1";
            module.Load(force: true);

            Assert.Equal("Import-Module", runspace.Builder.Command);
            Assert.True(runspace.Builder.Parameters.ContainsKey("Name"));
            Assert.Equal("test.psd1", runspace.Builder.Parameters["Name"].Item1);
            Assert.False(runspace.Builder.Parameters["Name"].Item2);
            Assert.True(runspace.Builder.Parameters.ContainsKey("Force"));
            Assert.True((bool)runspace.Builder.Parameters["Force"].Item1);
            Assert.True(runspace.Builder.Parameters["Force"].Item2);
        }
コード例 #14
0
        public void ForceIsPropogatedToAllModules()
        {
            MockRunspaceManager runspace          = new MockRunspaceManager();
            GeneratedModule     module            = new GeneratedModule(runspace);
            GeneratedModule     requiredModule    = new GeneratedModule(runspace);
            GeneratedModule     requiredModuleSub = new GeneratedModule(runspace);

            requiredModuleSub.ModulePath = "psreadline";
            requiredModule.ModulePath    = "PowerShellGet";
            requiredModule.RequiredModules.Add(requiredModuleSub);
            module.ModulePath = "PackageManagement";
            module.RequiredModules.Add(requiredModule);
            module.Load(force: true);

            Assert.Equal("import-module [name psreadline false] [force true true]", runspace.Builder.InvokeHistory[0].ToLowerInvariant());
            Assert.Equal("import-module [name powershellget false] [force true true]", runspace.Builder.InvokeHistory[1].ToLowerInvariant());
            Assert.Equal("import-module [name packagemanagement false] [force true true]", runspace.Builder.InvokeHistory[2].ToLowerInvariant());
        }
コード例 #15
0
        /// <summary>
        /// Verify <paramref name="result"/> contains the expected operation exactly.
        /// </summary>
        /// <param name="result">Resulting GeneratedModule object.</param>
        /// <param name="expectedOperation">Expected operation info.</param>
        private void AssertModuleContainsOperation(GeneratedModule result, OperationData expectedOperation)
        {
            // Ignore these 11 parameters:

            /* Verbose
             * Debug
             * ErrorAction
             * WarningAction
             * InformationAction
             * ErrorVariable
             * WarningVariable
             * InformationVariable
             * OutVariable
             * OutBuffer
             * PipelineVariable */
            Assert.True(result.Operations.ContainsKey(expectedOperation.OperationId.ToLowerInvariant()));
            Assert.Equal(expectedOperation.Parameters.Count, result.Operations[expectedOperation.OperationId.ToLowerInvariant()].Parameters.Count - 11);
            OperationData actualOperation = result.Operations[expectedOperation.OperationId.ToLowerInvariant()];

            foreach (string parmName in expectedOperation.Parameters.Keys)
            {
                Assert.True(actualOperation.Parameters.ContainsKey(parmName), parmName);
                Assert.NotNull(actualOperation.Parameters[parmName].Type);
                Assert.Equal(expectedOperation.Parameters[parmName].Type.Type, actualOperation.Parameters[parmName].Type.Type);
                Assert.Equal(expectedOperation.Parameters[parmName].Type.Properties.Count, actualOperation.Parameters[parmName].Type.Properties.Count);
                foreach (string propertyName in expectedOperation.Parameters[parmName].Type.Properties.Keys)
                {
                    Assert.Equal(expectedOperation.Parameters[parmName].Type.Properties[propertyName].Type, actualOperation.Parameters[parmName].Type.Properties[propertyName].Type);
                    Assert.Equal(expectedOperation.Parameters[parmName].Type.Properties[propertyName].Name, actualOperation.Parameters[parmName].Type.Properties[propertyName].Name);
                    Assert.Equal(expectedOperation.Parameters[parmName].Type.Properties[propertyName].JsonName, actualOperation.Parameters[parmName].Type.Properties[propertyName].JsonName);
                }
            }

            if (expectedOperation.ResponseType != null)
            {
                Assert.NotNull(actualOperation.ResponseType);
                Assert.NotNull(actualOperation.ResponseType.ModuleData);
                Assert.Equal(expectedOperation.ResponseType.ModuleData.Type, actualOperation.ResponseType.ModuleData.Type);
            }
            else
            {
                Assert.Null(actualOperation.ResponseType);
            }
        }
コード例 #16
0
        public void ProcessOperationSimpleParameters()
        {
            MockRunspaceManager runspace = new MockRunspaceManager();
            GeneratedModule     module   = new GeneratedModule(runspace);

            module.Operations["thing_get"] = new OperationData("Thing_Get", "Get-Thing")
            {
                Parameters = new Dictionary <string, ParameterData>()
                {
                    { "Integer", new ParameterData()
                      {
                          Name = "Integer", Type = new RuntimeTypeData(typeof(int))
                      } },
                    { "Boolean", new ParameterData()
                      {
                          Name = "Boolean", Type = new RuntimeTypeData(typeof(bool))
                      } },
                    { "Decimal", new ParameterData()
                      {
                          Name = "Decimal", Type = new RuntimeTypeData(typeof(double))
                      } },
                    { "String", new ParameterData()
                      {
                          Name = "String", Type = new RuntimeTypeData(typeof(string))
                      } }
                }
            };

            MockTestCredentialFactory credentialsFactory = new MockTestCredentialFactory();
            LiveTestRequest           request            = new LiveTestRequest();

            request.Method            = "Things.Thing_Get";
            request.OperationId       = "Thing_Get";
            request.Params            = new Dictionary <string, object>();
            request.Params["integer"] = 5;
            request.Params["boolean"] = true;
            request.Params["decimal"] = 1.2;
            request.Params["string"]  = "testValue";

            CommandExecutionResult result = module.ProcessRequest(request, credentialsFactory);

            Assert.Equal(1, runspace.InvokeHistory.Count);
            Assert.Equal("Get-Thing [Integer 5] [Boolean True] [Decimal 1.2] [String testValue]", ((string)runspace.InvokeHistory[0]));
        }
コード例 #17
0
        public void ProcessOperationComplexParameters()
        {
            MockRunspaceManager runspace = new MockRunspaceManager();
            GeneratedModule     module   = new GeneratedModule(runspace);

            module.Operations["thing_get"] = new OperationData("Thing_Get", "Get-Thing")
            {
                Parameters = new Dictionary <string, ParameterData>()
                {
                    { "Parameter", new ParameterData()
                      {
                          Name = "Parameter", Type = new RuntimeTypeData(typeof(GeneratedModuleTestsObject))
                      } }
                }
            };

            MockTestCredentialFactory credentialsFactory = new MockTestCredentialFactory();
            LiveTestRequest           request            = new LiveTestRequest();

            request.Method              = "Things.Thing_Get";
            request.OperationId         = "Thing_Get";
            request.Params              = new Dictionary <string, object>();
            request.Params["parameter"] = new GeneratedModuleTestsObject()
            {
                String = "testValue",
                Number = 500,
                Object = new GeneratedModuleTestsSubObject()
                {
                    Decimal = 1.2,
                    Boolean = true
                }
            };

            CommandExecutionResult result = module.ProcessRequest(request, credentialsFactory);

            Assert.Equal(1, runspace.InvokeHistory.Count);
            Assert.Equal("Get-Thing [Parameter {[String testValue] [Number 500] [Object [Decimal 1.2] [Boolean True]]}]", (string)runspace.InvokeHistory[0]);
        }
コード例 #18
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="module">Module containing all operations and data this converter should handle.</param>
 public LiveTestRequestConverter(GeneratedModule module)
 {
     this.module = module;
 }
コード例 #19
0
        public void ConvertsPrimitiveParameters()
        {
            GeneratedModule module = new GeneratedModule(null);
            OperationData   test   = new OperationData("testoperationid", "Get-Test");

            module.Operations["testoperationid"] = test;
            test.Parameters["string"]            = new ParameterData()
            {
                Name     = "string",
                JsonName = "stringparm",
                Type     = new RuntimeTypeData()
                {
                    Type = typeof(string)
                }
            };
            test.Parameters["bool"] = new ParameterData()
            {
                Name     = "bool",
                JsonName = "boolparm",
                Type     = new RuntimeTypeData()
                {
                    Type = typeof(bool)
                }
            };
            test.Parameters["array"] = new ParameterData()
            {
                Name     = "array",
                JsonName = "arrayparm",
                Type     = new RuntimeTypeData()
                {
                    Type = typeof(bool[])
                }
            };

            LiveTestRequestConverter converter = new LiveTestRequestConverter(module);
            JsonSerializerSettings   settings  = new JsonSerializerSettings();

            converter.RegisterSelf(settings);

            string          json    = "{\"method\":\"A.testOperationId\",\"jsonrpc\":\"2.0\",\"id\":\"0\",\"params\":{\"stringparm\":\"testValue\",\"boolparm\":true,\"arrayparm\":[true,false]}}";
            LiveTestRequest request = JsonConvert.DeserializeObject <LiveTestRequest>(json, settings);

            Assert.NotNull(request);
            Assert.Equal("0", request.Id);
            Assert.Equal("2.0", request.JsonRpc);
            Assert.Equal("A.testOperationId", request.Method);
            Assert.Equal("testoperationid", request.OperationId);
            Assert.True(request.Params.ContainsKey("string"));
            Assert.Equal(typeof(string), request.Params["string"].GetType());
            Assert.Equal("testValue", (string)request.Params["string"]);
            Assert.True(request.Params.ContainsKey("bool"));
            Assert.Equal(typeof(bool), request.Params["bool"].GetType());
            Assert.True((bool)request.Params["bool"]);
            Assert.True(request.Params.ContainsKey("array"));
            Assert.Equal(typeof(bool[]), request.Params["array"].GetType());
            Assert.Equal(2, ((bool[])request.Params["array"]).Length);
            Assert.True(((bool[])request.Params["array"])[0]);
            Assert.False(((bool[])request.Params["array"])[1]);

            string reserialized = JsonConvert.SerializeObject(request, settings);

            Assert.Equal(json, reserialized);
        }
コード例 #20
0
        static void Main(string[] args)
        {
            ServerArgs serverArgs = new ServerArgs().Parse(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "config.json")).Parse(args).Validate();

            EventLogOutputPipe eventLogOutputPipe = new EventLogOutputPipe();
            CompositeLogger    logger             = new CompositeLogger();

            if (serverArgs.EnableEventLog)
            {
                logger.AddLogger(new Logger(eventLogOutputPipe, eventLogOutputPipe));
            }

            if (serverArgs.EnablePipeLog)
            {
                try
                {
                    NamedPipeServer namedPipe       = new NamedPipeServer(serverArgs.LogPipeName);
                    Logger          namedPipeLogger = new Logger(namedPipe, namedPipe);
                    logger.AddLogger(namedPipeLogger);
                }
                catch (Exception e)
                {
                    logger.LogError("Failed to initialize named pipe logger: " + e.Message);
                }
            }

            if (serverArgs.Errors.Count > 0)
            {
                logger.LogError("Server arguments had errors.");
                foreach (string error in serverArgs.Errors)
                {
                    logger.LogError(error);
                }
                return;
            }

            // Load external modules
            PowerShellRunspace runspace = new PowerShellRunspace(logger);

            foreach (string externalModule in serverArgs.ExternalModules)
            {
                GeneratedModule module = new GeneratedModule(runspace);
                module.ModulePath = externalModule;
                CommandExecutionResult result = module.Load();
                if (result != null && result.HadErrors)
                {
                    logger.LogError(String.Format(CultureInfo.CurrentCulture, "Failed to load extra module: {0}", externalModule));
                    result.LogErrors(logger);
                    return;
                }
            }

            // Start test server
            JsonRpcPipe    jsonRpcPipe = new JsonRpcPipe(new StandardInputPipe(), new StandardOutputPipe());
            LiveTestServer server      = new LiveTestServer(new LiveTestServerStartParams()
            {
                Logger             = logger,
                Input              = jsonRpcPipe,
                Output             = jsonRpcPipe,
                CredentialFactory  = new LiveTestCredentialFactory(),
                RunspaceManager    = runspace,
                ModulePath         = serverArgs.ModulePath,
                TracingManager     = new ServiceTracingManager(),
                SpecificationPaths = serverArgs.SpecificationPaths,
                ObjectTransforms   = serverArgs.GetTransforms()
            });

            try
            {
                server.RunAsync().Wait();
            } catch (Exception ex)
            {
                logger.LogError("Failed to start server: " + ex.ToString());
            }

            // Wait until server exits (usually means the server ran into an internal error)
            while (server.IsRunning)
            {
                Thread.Sleep(2);
            }
        }
コード例 #21
0
        public GeneratedModule GetModuleInfo(string modulePath)
        {
            if (this.logger != null)
            {
                this.logger.LogAsync(String.Format(CultureInfo.CurrentCulture, "Parsing module: {0}", modulePath));
            }
            string          moduleName = String.Empty;
            GeneratedModule module     = new GeneratedModule(this);

            module.ModulePath = modulePath;
            if (File.Exists(modulePath) || Directory.Exists(modulePath))
            {
                // First we have to run Test-ModuleManifest to get RequiredModules
                if (!Path.IsPathRooted(modulePath))
                {
                    throw new ModulePathNotRootedException(modulePath);
                }

                ICommandBuilder testModuleManifest = this.CreateCommand();
                testModuleManifest.Command = "Test-ModuleManifest";
                testModuleManifest.AddParameter("Path", modulePath);
                // Note that this returns errors, but RequiredModules is still filled out.
                CommandExecutionResult result = testModuleManifest.Invoke();

                PSModuleInfo testResult = result.Results.FirstOrDefault() as PSModuleInfo;
                if (testResult == null)
                {
                    if (this.logger != null)
                    {
                        this.logger.LogError("No module object was returned by Test-ModuleManifest.");
                    }
                    throw new CommandFailedException(testModuleManifest, result, "Can't get module information for an invalid module.");
                }

                moduleName = testResult.Name;
                foreach (PSModuleInfo requiredModule in testResult.RequiredModules)
                {
                    GeneratedModule requiredModuleInfo = new GeneratedModule(this);
                    requiredModuleInfo.ModulePath = requiredModule.Name;
                    module.RequiredModules.Add(requiredModuleInfo);
                }
            }
            else
            {
                // Otherwise assume the input is a module name instead of a path and attempt a direct load
                moduleName = modulePath;
            }

            if (this.logger != null)
            {
                this.logger.LogAsync(String.Format(CultureInfo.CurrentCulture, "Loading module: {0}", moduleName));
            }
            CommandExecutionResult loadResult = module.Load();

            if (loadResult.HadErrors)
            {
                loadResult.LogErrors(this.logger);
                throw new CommandFailedException(null, loadResult, "Failed to load module.");
            }

            ICommandBuilder getModule = this.CreateCommand();

            getModule.Command = "Get-Module";
            getModule.AddParameter("Name", moduleName);
            CommandExecutionResult getModuleResult = getModule.Invoke();

            if (getModuleResult.HadErrors)
            {
                getModuleResult.LogErrors(this.logger);
                throw new CommandFailedException(getModule, getModuleResult, "Failed to get module after loading.");
            }

            PSModuleInfo moduleInfo = getModuleResult.Results.First() as PSModuleInfo;

            foreach (string entry in moduleInfo.ExportedFunctions.Keys)
            {
                FunctionInfo commandInfo    = moduleInfo.ExportedFunctions[entry] as FunctionInfo;
                PSTypeName   outputTypeName = null;
                if (commandInfo.OutputType != null && commandInfo.OutputType.Count > 0)
                {
                    // For now PSSwagger only takes the first response
                    outputTypeName = commandInfo.OutputType.First();
                }

                if (this.logger != null)
                {
                    this.logger.LogAsync("Parsing command: " + entry);
                }

                if (commandInfo != null)
                {
                    foreach (CommandParameterSetInfo parameterSet in commandInfo.ParameterSets)
                    {
                        OperationData operationData = new OperationData(parameterSet.Name, entry);
                        if (this.logger != null)
                        {
                            this.logger.LogAsync("Found operation: " + parameterSet.Name);
                        }
                        foreach (CommandParameterInfo commandParameterInfo in parameterSet.Parameters)
                        {
                            ParameterData parameterData = new ParameterData();
                            parameterData.Name = commandParameterInfo.Name.ToLowerInvariant();
                            parameterData.Type = new RuntimeTypeData(commandParameterInfo.ParameterType);
                            operationData.Parameters.Add(parameterData.Name.ToLowerInvariant(), parameterData);
                        }

                        if (outputTypeName != null)
                        {
                            operationData.ResponseType = new ResponseTypeData()
                            {
                                ModuleData = new RuntimeTypeData(outputTypeName.Type)
                            };
                        }

                        module.Operations[operationData.OperationId.ToLowerInvariant()] = operationData;
                    }
                }
            }

            return(module);
        }