コード例 #1
0
        public static UpdateInfo Deserialize(string data)
        {
            var        yamlDeserializer = new YamlDotNet.Serialization.DeserializerBuilder().IgnoreUnmatchedProperties().WithNamingConvention(PascalCaseNamingConvention.Instance).Build();
            UpdateInfo deserialized     = yamlDeserializer.Deserialize <UpdateInfo>(data);

            return(deserialized);
        }
コード例 #2
0
        /// <summary>
        /// Validate if the contents of the GitVersion.yml file are changed correctly.
        /// </summary>
        /// <param name="originalContents">The contents of the GitVersion.yml file from the main branch.</param>
        /// <param name="updatedContents">The contents of the GitVersion.yml file from the PR.</param>
        /// <returns>Wether the changes to the GitVersion file were valid.</returns>
        public static bool IsValidGitversion(string originalContents, string updatedContents)
        {
            // If the files are empty, it's not valid.
            if (string.IsNullOrEmpty(originalContents) || string.IsNullOrEmpty(updatedContents))
            {
                return(false);
            }

            var deserializer = new YamlDotNet.Serialization.DeserializerBuilder()
                               .WithNamingConvention(HyphenatedNamingConvention.Instance)
                               .IgnoreUnmatchedProperties()
                               .Build();

            // Parse both YAML files to a POCO, so we can compare content.
            var originalYaml = deserializer.Deserialize <GitVersion>(originalContents);
            var updatedYaml  = deserializer.Deserialize <GitVersion>(updatedContents);

            // If both files have the same version, the contents aren't really updated, but rather reverted to the original state.
            if (originalYaml.NextVersion == updatedYaml.NextVersion)
            {
                return(false);
            }

            // Return wether the new YAML version is higher then the original.
            return(ParseAndValidateGitVersion(originalYaml.NextVersion, updatedYaml.NextVersion));
        }
コード例 #3
0
        public static void Test()
        {
            // SchemaPorter.YamlSpace.RootNode retVal = null;
            // SchemaPorter.foofoo.RootNode retVal = null;
            SchemaPorter.SimpleYamlSchema.RootObject retVal = null;

            YamlDotNet.Serialization.IDeserializer deserializer =
                new YamlDotNet.Serialization.DeserializerBuilder()
                .WithNamingConvention(new YamlDotNet.Serialization.NamingConventions.CamelCaseNamingConvention())
                //.IgnoreUnmatchedProperties()
                .Build();


            using (System.IO.Stream fs = System.IO.File.OpenRead(@"d:\username\Documents\Visual Studio 2017\Projects\BlueMine\BlueMine\Code\de.yml"))
            {
                //using (System.IO.TextReader r = new System.IO.StringReader(@""))
                using (System.IO.TextReader r = new System.IO.StreamReader(fs, System.Text.Encoding.UTF8))
                {
                    // retVal = deserializer.Deserialize<SchemaPorter.YamlSpace.RootNode>(r);
                    // retVal = deserializer.Deserialize<SchemaPorter.foofoo.RootNode>(r);
                    retVal = deserializer.Deserialize <SchemaPorter.SimpleYamlSchema.RootObject>(r);
                } // End using r
            }     // End Using fs

            System.Console.WriteLine(retVal);
        } // End Sub Test
コード例 #4
0
        public static async Task <HttpResponseMessage> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest request,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            //var yamlStream = new YamlStream();
            using (var reader = new StreamReader(request.Body))
            {
                string s = await reader.ReadToEndAsync();

                //    yamlStream.Load(reader);
                var deserializer = new YamlDotNet.Serialization.DeserializerBuilder().Build();
                var obj          = deserializer.Deserialize <object>(s);

                var serializer = new YamlDotNet.Serialization.SerializerBuilder().JsonCompatible().Build();

                return(new HttpResponseMessage
                {
                    Content = new PushStreamContent((stream, content, context) =>
                    {
                        using (var writer = new StreamWriter(stream))
                            serializer.Serialize(writer, obj);
                    }),
                });
            }

            //return name != null
            //    ? (ActionResult)new OkObjectResult($"Hello, {name}")
            //    : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
        }
コード例 #5
0
ファイル: MarkdownConvert.cs プロジェクト: gengle/PSRule
        private static PSObject YamlHeader(string markdown)
        {
            var stream = new MarkdownStream(markdown);

            if (stream.EOF || stream.Line > 1 || stream.Current != Dash)
            {
                return(null);
            }

            // Check if the line is just dashes indicating start of yaml header
            if (!stream.PeakLine(Dash, out int count) || count < 2)
            {
                return(null);
            }

            stream.Skip(count + 1);
            stream.SkipLineEnding();

            var yaml = stream.CaptureUntil(TripleDash, onNewLine: true).Trim();
            var d    = new YamlDotNet.Serialization.DeserializerBuilder()
                       .IgnoreUnmatchedProperties()
                       .WithTypeConverter(new PSObjectYamlTypeConverter())
                       .WithNodeTypeResolver(new PSObjectYamlTypeResolver())
                       .Build();

            return(d.Deserialize <PSObject>(yaml));
        }
コード例 #6
0
ファイル: Program.cs プロジェクト: mythz/servicestack-demos
        public static T FromYaml <T>(this string target)
        {
            var deserializer = new YamlDotNet.Serialization.DeserializerBuilder()
                               .WithNamingConvention(new YamlDotNet.Serialization.NamingConventions.CamelCaseNamingConvention())
                               .Build();

            return(deserializer.Deserialize <T>(target));
        }
コード例 #7
0
        static void Main(string[] args)
        {
            var log = LogManager.GetCurrentClassLogger();

            var conf = new YamlDotNet.Serialization.DeserializerBuilder()
                       .Build()
                       .Deserialize <Conf>(
                File.ReadAllText("Conf.yml")
                );

            if (args.Length >= 1 && args[0] == "build")
            {
                using (var writer = new StreamWriter("Files.txt", false, Encoding.UTF8, 10 * 1024 * 1024))
                {
                    foreach (var dir in conf.dirs)
                    {
                        log.Info(dir);
                        Walk(writer, dir);
                    }
                }
                log.Info("Done");
                return;
            }
            else if (args.Length >= 2 && args[0] == "find")
            {
                var rex = new Regex(string.Join("|", args.Skip(1).Select(arg => "^" + Regex.Escape(arg).Replace("\\*", ".*").Replace("\\?", ".?"))), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled);

                using (var reader = new StreamReader("Files.txt", Encoding.UTF8, true, 10 * 1024 * 1024))
                {
                    while (true)
                    {
                        var row = reader.ReadLine();
                        if (row == null)
                        {
                            break;
                        }
                        int pos = row.LastIndexOf('\\');
                        if (pos < 0)
                        {
                            pos = 0;
                        }
                        else
                        {
                            pos++;
                        }
                        var target = row.Substring(pos);
                        if (rex.IsMatch(target))
                        {
                            Console.WriteLine(row);
                        }
                    }
                }
                return;
            }

            Console.Error.WriteLine(Resources.Usage);
            Environment.ExitCode = 1;
        }
コード例 #8
0
ファイル: Program.cs プロジェクト: microsoft/Oryx
        private static T LoadFromString <T>(string content)
        {
            var deserializer = new YamlDotNet.Serialization.DeserializerBuilder()
                               .WithNamingConvention(new YamlDotNet.Serialization.NamingConventions.CamelCaseNamingConvention())
                               .Build();
            var obj = deserializer.Deserialize <T>(content);

            return(obj);
        }
コード例 #9
0
        public static BuildScenario Load(string path)
        {
            var yamlBuilder = new YamlDotNet.Serialization.DeserializerBuilder();

            foreach (var type in _GetMappingTypes())
            {
                yamlBuilder.WithTagMapping("!" + type.Name, type);
            }

            return(yamlBuilder.Build().Deserialize <BuildScenario>(File.ReadAllText(path)));
        }
コード例 #10
0
        public void ReadSimpleTypesFromYamlParser()
        {
            // The .NET SDK allows flag data to be read from a YAML file by first running it through a YAML
            // parser, which produces types like Dictionary, and then feeding that into JReader. So we'll
            // verify that a basic use case like that works, using YamlDotNet.
            var yamlContent = @"
---
flags:
  flag1:
    key: flag1
    ""on"": true
    version: 1
    fallthrough:
      variation: 2
    variations:
      - fall
      - ""off""
      - ""on""
flagValues:
  flag2: value2
segments:
  seg1:
    key: seg1
    version: 1
    include: [""user1""]
";
            var yaml        = new YamlDotNet.Serialization.DeserializerBuilder().Build();
            var dataIn      = yaml.Deserialize <object>(yamlContent);

            var r = JReader.FromAdapter(ReaderAdapters.FromSimpleTypes(dataIn));

            var dataOut = JsonStreamConvert.ConvertSimpleTypes.ReadJson(ref r);

            var jsonOut      = JsonStreamConvert.SerializeObject(dataOut, JsonStreamConvert.ConvertSimpleTypes);
            var expectedJson = @"{
""flags"": {
  ""flag1"": {
    ""key"": ""flag1"",
    ""on"": ""true"",
    ""version"": ""1"",
    ""fallthrough"": { ""variation"": ""2"" },
    ""variations"": [ ""fall"", ""off"", ""on"" ]
  }
},
""flagValues"": { ""flag2"": ""value2"" },
""segments"": {
  ""seg1"": { ""key"": ""seg1"", ""version"": ""1"", ""include"": [""user1""] }
}
}";

            // Note that YamlDotNet parses all the booleans and numbers as strings; that's why we provide a
            // type coercion option.
            TestUtil.AssertJsonEqual(expectedJson, jsonOut);
        }
コード例 #11
0
        private string ReadConfigYamlToJson(string path)
        {
            var yamlReader   = new StringReader(File.ReadAllText(path));
            var deserializer = new YamlDotNet.Serialization.DeserializerBuilder().Build();
            var yamlObject   = deserializer.Deserialize(yamlReader);
            var serializer   = new YamlDotNet.Serialization.SerializerBuilder()
                               .JsonCompatible()
                               .Build();

            return(serializer.Serialize(yamlObject));
        }
コード例 #12
0
        public static YamlConfig Parse(string filepath)
        {
            var deserializer = new YamlDotNet.Serialization.DeserializerBuilder().Build();

            using (Stream stream = File.OpenRead(filepath))
            {
                using (TextReader reader = new StreamReader(stream))
                {
                    var preparsedConfig = deserializer.Deserialize <YamlConfig>(reader);
                    return(preparsedConfig);
                }
            }
        }
コード例 #13
0
        private static int MergeToc(string mkdocsPath, string newTocPath)
        {
            var mkdocs = new YamlStream();

            using (var reader = new StreamReader(mkdocsPath))
            {
                mkdocs.Load(reader);
            }

            Toc toc = null;

            using (var reader = new StreamReader(newTocPath))
            {
                // Examine the new toc
                var deserializer = new YamlDotNet.Serialization.DeserializerBuilder().Build();
                toc = deserializer.Deserialize <Toc>(reader);
            }

            // the mkdocs format is not ammenable to object serialization unfortunately...
            var root = (YamlMappingNode)mkdocs.Documents[0].RootNode;

            // Examine the stream
            var items = (YamlSequenceNode)root.Children[new YamlScalarNode("nav")];

            var apitoc = items.Where(it => it is YamlMappingNode ym && ym.Children.Count > 0 &&
                                     ym.Children[0].Key is YamlScalarNode s && s.Value == "API documentation").FirstOrDefault() as YamlMappingNode;

            if (apitoc == null)
            {
                apitoc = new YamlMappingNode();
                items.Add(apitoc);
            }

            apitoc.Children.Clear();
            var s = new YamlSequenceNode();

            apitoc.Add(new YamlScalarNode("API documentation"), s);
            int count = AddLinks(s, toc.toc);

            // save the updated mkdocs
            using (var writer = new StreamWriter(mkdocsPath))
            {
                mkdocs.Save(writer, false);
            }

            Console.WriteLine("Added {0} api documentation links to the nav: section in {1}", count, mkdocsPath);

            return(0);
        }
コード例 #14
0
ファイル: Program.cs プロジェクト: pombredanne/EatPdb
        private static void ConfigMain(ConfigOptions options)
        {
            var deserializer = new YamlDotNet.Serialization.DeserializerBuilder()
                               .WithTagMapping("!whitelist", typeof(Config.WhitelistFilter))
                               .WithTagMapping("!blacklist", typeof(Config.BlacklistFilter))
                               .WithTypeConverter(new Config.YamlTypeConverter())
                               .Build();
            var cfg = deserializer.Deserialize <Config>(File.ReadAllText(options.ConfigFile));

            cfg.ApplyDefault();
            if (options.Debug)
            {
                Console.WriteLine("{0}", ObjectDumper.Dump(cfg));
            }
            RealMain(cfg, options.Verbose);
        }
コード例 #15
0
ファイル: Program.cs プロジェクト: codehz/DiscussPollBot
        private static void Main(string[] _)
        {
            var deserializer = new YamlDotNet.Serialization.DeserializerBuilder().Build();

            cfg       = deserializer.Deserialize <Config>(input: System.IO.File.ReadAllText("config.yaml"));
            db        = new DB(cfg.Database);
            botClient = new TelegramBotClient(token: cfg.TelegramToken);
            var me = botClient.GetMeAsync().Result;

            botname = me.Username;
            Console.WriteLine($"UserID {me.Id} NAME: {me.Username}.");
            cfg.Admins = botClient.GetChatAdministratorsAsync(cfg.MainChatId).Result.Select(x => x.User.Id);
            botClient.StartReceiving(allowedUpdates: new UpdateType[] { UpdateType.Message, UpdateType.CallbackQuery });
            botClient.OnMessage       += BotClient_OnMessage;
            botClient.OnCallbackQuery += BotClient_OnCallbackQuery;
            while (true)
            {
                Thread.Sleep(millisecondsTimeout: int.MaxValue);
            }
        }
コード例 #16
0
        public List <Config> DeserializeConfigFile(string configFile)
        {
            var fileInfo = new FileInfo(configFile);
            var isYaml   = fileInfo.Extension.EndsWith("yaml", StringComparison.OrdinalIgnoreCase) || fileInfo.Extension.EndsWith("yml", StringComparison.OrdinalIgnoreCase);

            var configs = new List <Config>();

            var text = File.ReadAllText(fileInfo.FullName);

            if (isYaml)
            {
                var s = new YamlDotNet.Serialization.DeserializerBuilder()
                        .WithNamingConvention(new CamelCaseNamingConvention())
                        .Build();
                configs = s.Deserialize <List <Config> >(text);
            }
            else
            {
                configs = Newtonsoft.Json.JsonConvert.DeserializeObject <List <Config> >(text);
            }

            return(configs);
        }
コード例 #17
0
        public SERIALIZER_TYPE Deserialize(string FilePath, bool ShowError = true)
        {
            if (!(File.Exists(FilePath)))
            {
                if (ShowError)
                {
                    throw new FileNotFoundException();
                }
                else
                {
                    return(new SERIALIZER_TYPE());
                }
            }
            SERIALIZER_TYPE DESERIALIZED_OBJECT = new SERIALIZER_TYPE();

            YamlDotNet.Serialization.IDeserializer DESERIALIZER = new YamlDotNet.Serialization.DeserializerBuilder()
                                                                  .WithNamingConvention(new CamelCaseNamingConvention())
                                                                  .Build();
            using (StringReader YAML_STREAM = new StringReader(FilePath))
            {
                DESERIALIZED_OBJECT = DESERIALIZER.Deserialize <SERIALIZER_TYPE>(YAML_STREAM);
            }
            return(DESERIALIZED_OBJECT);
        }
コード例 #18
0
ファイル: Program.cs プロジェクト: tadanokojin/OpenKh
        protected int OnExecute(CommandLineApplication app)
        {
            try
            {
                var yamlReader = new YamlDotNet.Serialization.DeserializerBuilder()
                                 .IgnoreUnmatchedProperties()
                                 .Build();

                MapBuilder   builder;
                MapGenConfig config;
                string       baseDir;
                string       outMapFile;

                if (FileExtUtil.IsExtension(InputFile, ".yml"))
                {
                    var ymlFile = Path.GetFullPath(InputFile);
                    baseDir = Path.GetDirectoryName(ymlFile);

                    logger.Debug($"ymlFile is \"{ymlFile}\"");
                    logger.Debug($"baseDir is \"{baseDir}\"");

                    config = yamlReader.Deserialize <MapGenConfig>(File.ReadAllText(ymlFile));

                    var modelFile = Path.Combine(baseDir, config.inputFile);
                    outMapFile = Path.GetFullPath(OutputMap ?? Path.Combine(baseDir, config.outputFile));

                    builder = new MapBuilder(modelFile, config, CreateImageLoader(baseDir, config, FileLoader));
                }
                else
                {
                    var modelFile = Path.GetFullPath(InputFile);
                    baseDir = Path.GetDirectoryName(modelFile);
                    var ymlFile = Path.Combine(baseDir, "mapdef.yml");
                    outMapFile = Path.GetFullPath(OutputMap ?? Path.Combine(baseDir, Path.ChangeExtension(InputFile, ".map")));

                    logger.Debug($"ymlFile is \"{ymlFile}\"");
                    logger.Debug($"baseDir is \"{baseDir}\"");

                    config = File.Exists(ymlFile)
                        ? yamlReader.Deserialize <MapGenConfig>(File.ReadAllText(ymlFile))
                        : new MapGenConfig();

                    builder = new MapBuilder(modelFile, config, CreateImageLoader(baseDir, config, FileLoader));
                }

                logger.Debug("Building map file structure.");

                var buff = new MemoryStream();

                void trySaveTo(string toFile, MemoryStream stream)
                {
                    if (!string.IsNullOrWhiteSpace(toFile))
                    {
                        toFile = Path.Combine(baseDir, toFile);

                        logger.Debug($"Writing raw data to \"{toFile}\".");

                        Directory.CreateDirectory(Path.GetDirectoryName(toFile));

                        File.WriteAllBytes(toFile, stream.ToArray());
                    }
                }

                Bar.Write(
                    buff,
                    builder.GetBarEntries(trySaveTo)
                    .Concat(LoadAdditionalBarEntries(config, CreateRawFileLoader(baseDir)))
                    .ToArray()
                    );

                logger.Debug($"Writing to \"{outMapFile}\".");

                File.WriteAllBytes(outMapFile, buff.ToArray());

                logger.Debug("Done");

                return(0);
            }
            finally
            {
                LogManager.Shutdown();
            }
        }
コード例 #19
0
        static Hash OpenYaml(string file)
        {
            var deserializer = new YamlDotNet.Serialization.DeserializerBuilder().Build();

            return(deserializer.Deserialize <Hash>(File.OpenText(file)));
        }
コード例 #20
0
        public static async Task <AwsSettings> GetAwsSettings(string profileName, string stackName)
        {
            if (string.IsNullOrEmpty(profileName))
            {
                throw new Exception($"Error: No ProfileName provided");
            }

            if (string.IsNullOrEmpty(stackName))
            {
                throw new Exception($"Error: No StackName provided");
            }

            var sharedCredentialsFile = new SharedCredentialsFile(); // AWS finds the shared credentials store for us
            CredentialProfile profile = null;

            if (!sharedCredentialsFile.TryGetProfile(profileName, out profile))
            {
                throw new Exception($"Error: Aws Profile \"{profileName}\" not found in shared credentials store.");
            }

            AWSCredentials creds = null;

            if (!AWSCredentialsFactory.TryGetAWSCredentials(profile, sharedCredentialsFile, out creds))
            {
                throw new Exception($"Error: Could not get AWS Credentials using specified profile \"{profileName}\".");
            }

            var awsSettings = new AwsSettings();

            awsSettings["StackName"] = stackName;

            // Get Original Template
            AmazonCloudFormationClient cfClient = null;
            GetTemplateRequest         getTemplateRequestOriginal = null;

            try
            {
                // Note the need to extract region from the profile!
                cfClient = new AmazonCloudFormationClient(creds, profile.Region);
                getTemplateRequestOriginal = new GetTemplateRequest()
                {
                    StackName     = stackName,
                    TemplateStage = Amazon.CloudFormation.TemplateStage.Original
                };
            }
            catch (Exception ex)
            {
                throw new Exception($"Could not create AmazonCloudFormationClient");
            }

            var templateReponse = cfClient.GetTemplateAsync(getTemplateRequestOriginal).GetAwaiter().GetResult();
            //var templateBodyIndex = templateReponse.StagesAvailable.IndexOf("Original");
            var templateBody = templateReponse.TemplateBody; // Original is in yaml form
            //var tmplYaml = new StringReader(new YamlDotNet.Serialization.SerializerBuilder().Build().Serialize(templateBody));
            var tmplYaml     = new StringReader(templateBody);
            var templYamlObj = new YamlDotNet.Serialization.DeserializerBuilder().Build().Deserialize(tmplYaml);

            templateBody = new YamlDotNet.Serialization.SerializerBuilder().JsonCompatible().Build().Serialize(templYamlObj);
            var jTemplateObjOriginal = JObject.Parse(templateBody);


            // Get Processed Template
            var getTemplateRequestProcessed = new GetTemplateRequest()
            {
                StackName     = stackName,
                TemplateStage = Amazon.CloudFormation.TemplateStage.Processed
            };

            templateReponse = cfClient.GetTemplateAsync(getTemplateRequestProcessed).GetAwaiter().GetResult();
            //var templateBodyIndex = templateReponse.StagesAvailable.IndexOf("Original");
            templateBody = templateReponse.TemplateBody;
            var jTemplateObjProcessed = JObject.Parse(templateBody);

            // Get Stack Resources - note: this call only returns the first 100 resources.
            // We are calling it to get the StackId
            var describeStackResourcesRequest = new DescribeStackResourcesRequest()
            {
                StackName = stackName
            };
            var describeStackResourcesResponse = await cfClient.DescribeStackResourcesAsync(describeStackResourcesRequest);

            if (describeStackResourcesResponse.StackResources.Count == 0)
            {
                throw new Exception($"Error: No resources found for specified stack.");
            }

            // Extract region from StackId ARN -- "arn:aws:cloudformation:us-east-1:..."
            var stackIdParts = describeStackResourcesResponse.StackResources[0].StackId.Split(':');


            var region = stackIdParts[3];

            awsSettings["Region"] = region;

            // Get all stack resources - paginated
            // The the ListStackResourcesResponse does not contain the StackId.
            string nextToken     = null;
            string apiName       = null;
            int    resourceCount = 0;
            var    apiGateways   = new Dictionary <string, AwsSettings.Api>();

            awsSettings["ApiGateways"] = apiGateways;
            do
            {
                var listStackResourcesRequest = new ListStackResourcesRequest()
                {
                    StackName = stackName, NextToken = nextToken
                };
                var listStackResourcesResponse = await cfClient.ListStackResourcesAsync(listStackResourcesRequest);

                nextToken = listStackResourcesResponse.NextToken;

                foreach (var resource in listStackResourcesResponse.StackResourceSummaries)
                {
                    resourceCount++;
                    switch (resource.ResourceType)
                    {
                    case "AWS::Cognito::UserPool":
                    case "AWS::Cognito::IdentityPool":
                    case "AWS::Cognito::UserPoolClient":
                        awsSettings[resource.LogicalResourceId] = resource.PhysicalResourceId;
                        break;

                    case "AWS::ApiGatewayV2::Api":
                        var httpApi = new AwsSettings.Api();
                        apiGateways.Add(resource.LogicalResourceId, httpApi);
                        httpApi.Id   = resource.PhysicalResourceId;
                        httpApi.Type = "HttpApi";
                        apiName      = resource.LogicalResourceId;
                        try
                        {
                            var HttpApiSecureAuthType = (string)jTemplateObjProcessed["Resources"][apiName]["Properties"]["Body"]["components"]["securitySchemes"]["OpenIdAuthorizer"]["type"];
                            if (HttpApiSecureAuthType.Equals("oauth2"))
                            {
                                httpApi.SecurityLevel = AwsSettings.SecurityLevel.JWT;
                            }
                            else
                            {
                                httpApi.SecurityLevel = AwsSettings.SecurityLevel.None;
                            }
                        }
                        catch
                        {
                            httpApi.SecurityLevel = AwsSettings.SecurityLevel.None;
                        }
                        httpApi.Stage = (string)jTemplateObjOriginal["Resources"][apiName]["Properties"]["StageName"];
                        break;

                    case "AWS::ApiGateway::RestApi":
                        var restApi = new AwsSettings.Api();
                        apiGateways.Add(resource.LogicalResourceId, restApi);
                        restApi.Id   = resource.PhysicalResourceId;
                        restApi.Type = "Api";
                        apiName      = resource.LogicalResourceId;
                        try
                        {
                            var apiAuthSecurityType = (string)jTemplateObjProcessed["Resources"][apiName]["Properties"]["Body"]["securityDefinitions"]["AWS_IAM"]["x-amazon-apigateway-authtype"];
                            if (apiAuthSecurityType.Equals("awsSigv4"))
                            {
                                restApi.SecurityLevel = AwsSettings.SecurityLevel.AwsSignatureVersion4;
                            }
                            else
                            {
                                restApi.SecurityLevel = AwsSettings.SecurityLevel.None;
                            }
                        }
                        catch
                        {
                            restApi.SecurityLevel = AwsSettings.SecurityLevel.None;
                        }
                        restApi.Stage = (string)jTemplateObjOriginal["Resources"][apiName]["Properties"]["StageName"];
                        break;
                    }
                }
            } while (nextToken != null);

            if (resourceCount == 0)
            {
                throw new Exception($"Error: No resources found for specified stack.");
            }

            return(awsSettings);
        }
コード例 #21
0
        public static async Task <string> GenerateMethodMapJsonAsync(
            string profileName,
            string stackName)
        {
            if (string.IsNullOrEmpty(profileName))
            {
                throw new Exception($"Error: No ProfileName provided");
            }

            if (string.IsNullOrEmpty(stackName))
            {
                throw new Exception($"Error: No StackName provided");
            }

            var sharedCredentialsFile = new SharedCredentialsFile(); // AWS finds the shared credentials store for us
            CredentialProfile profile = null;

            if (!sharedCredentialsFile.TryGetProfile(profileName, out profile))
            {
                throw new Exception($"Error: Aws Profile \"{profileName}\" not found in shared credentials store.");
            }

            AWSCredentials creds = null;

            if (!AWSCredentialsFactory.TryGetAWSCredentials(profile, sharedCredentialsFile, out creds))
            {
                throw new Exception($"Error: Could not get AWS Credentials using specified profile \"{profileName}\".");
            }

            var awsSettings = new AwsSettings();

            if (!awsSettings.ContainsKey("StackName"))
            {
                awsSettings.Add("StackName", stackName);
            }
            else
            {
                awsSettings["StackName"] = stackName;
            }

            // Get Original Template
            var cfClient = new AmazonCloudFormationClient(creds);
            var getTemplateRequestOriginal = new GetTemplateRequest()
            {
                StackName     = stackName,
                TemplateStage = Amazon.CloudFormation.TemplateStage.Original
            };

            var templateReponse = cfClient.GetTemplateAsync(getTemplateRequestOriginal).GetAwaiter().GetResult();
            //var templateBodyIndex = templateReponse.StagesAvailable.IndexOf("Original");
            var templateBody = templateReponse.TemplateBody; // Original is in yaml form
            //var tmplYaml = new StringReader(new YamlDotNet.Serialization.SerializerBuilder().Build().Serialize(templateBody));
            var tmplYaml     = new StringReader(templateBody);
            var templYamlObj = new YamlDotNet.Serialization.DeserializerBuilder().Build().Deserialize(tmplYaml);

            templateBody = new YamlDotNet.Serialization.SerializerBuilder().JsonCompatible().Build().Serialize(templYamlObj);
            var jTemplateObjOriginal = JObject.Parse(templateBody);

            // Get all Stack Resources
            string nextToken      = null;
            bool   foundResources = false;
            var    methodMap      = new Dictionary <string, string>();

            do
            {
                var listStackResourcesRequest = new ListStackResourcesRequest()
                {
                    StackName = stackName, NextToken = nextToken
                };
                var listStackResourcesResponse = await cfClient.ListStackResourcesAsync(listStackResourcesRequest);

                nextToken = listStackResourcesResponse.NextToken;

                foreach (var resource in listStackResourcesResponse.StackResourceSummaries)
                {
                    switch (resource.ResourceType)
                    {
                    case "AWS::Lambda::Function":
                        foundResources = true;
                        var funcName     = resource.LogicalResourceId;
                        var lambdaEvents = jTemplateObjOriginal["Resources"][funcName]["Properties"]["Events"].Children();
                        foreach (JToken le in lambdaEvents)
                        {
                            var jObject = new JObject(le);
                            var name    = jObject.First.First.Path;
                            var type    = jObject[name]["Type"].ToString();
                            var apiId   = string.Empty;

                            if (type.Equals("HttpApi"))
                            {
                                apiId = jObject[name]["Properties"]["ApiId"]["Ref"].ToString();
                            }

                            else if (type.Equals("Api"))
                            {
                                apiId = jObject[name]["Properties"]["RestApiId"]["Ref"].ToString();
                            }

                            if (!string.IsNullOrEmpty(apiId))
                            {
                                methodMap.Add(name + "Async", apiId);
                            }
                        }
                        break;
                    }
                }
            } while (nextToken != null);

            if (!foundResources)
            {
                throw new Exception($"Error: No Lambda resources found for specified stack.");
            }

            var result = $"{{\"MethodMap\": {Newtonsoft.Json.JsonConvert.SerializeObject(methodMap, Newtonsoft.Json.Formatting.Indented)}}}";

            return(result);
        }
コード例 #22
0
        public override ShortcodeResult Execute(KeyValuePair <string, string>[] args, string content, IDocument document, IExecutionContext context)
        {
            var dictionary      = args.ToDictionary(Configuration, PrependLinkRoot);
            var prependLinkRoot = dictionary.GetBool(PrependLinkRoot);
            var configuration   = dictionary.GetString(Configuration, "advanced");

            var contentBuilder = new StringBuilder();

            var deserializer = new YamlDotNet.Serialization.DeserializerBuilder()
                               .WithNamingConvention(new YamlDotNet.Serialization.NamingConventions.CamelCaseNamingConvention())
                               .Build();

            var tabGroup = deserializer.Deserialize <TabGroup>(content);


            contentBuilder.AppendLine("<div class=\"tab-wrap\">");


            var first = true;

            foreach (var tab in tabGroup.Tabs)
            {
                contentBuilder.AppendLine($"<input type=\"radio\" id=\"{tabGroup.Id}-{tab.Id}\" name=\"{tabGroup.Id}\" class=\"tab\" {(first ? "checked" : string.Empty)}><label for=\"{tabGroup.Id}-{tab.Id}\" >{tab.Name}</label>");
                first = false;
            }

            foreach (var tab in tabGroup.Tabs)
            {
                contentBuilder.AppendLine("<div class=\"tab__content\">");
                contentBuilder.AppendLine();

                using (var writer = new StringWriter())
                {
                    if (!string.IsNullOrWhiteSpace(tab.Content))
                    {
                        MarkdownHelper.RenderMarkdown(
                            context,
                            document,
                            tab.Content,
                            writer,
                            prependLinkRoot,
                            configuration,
                            null
                            );
                    }

                    document.RenderExternalDocument(
                        context,
                        writer,
                        prependLinkRoot,
                        configuration,
                        isCodeBlock: false,
                        filePath: tab.Include
                        );

                    document.RenderExternalDocument(
                        context,
                        writer,
                        prependLinkRoot,
                        configuration,
                        overrideCodeLang: tab.CodeLang,
                        isCodeBlock: true,
                        filePath: tab.Code
                        );

                    contentBuilder.AppendLine(writer.ToString());
                }

                contentBuilder.AppendLine();
                contentBuilder.AppendLine("</div>");
            }

            contentBuilder.AppendLine("</div>");

            return(new ShortcodeResult(
                       contentBuilder.ToString()
                       ));
        }
コード例 #23
0
        protected override async Task <StageResultList <Stream, string, TransformStageCache <TInCache> > > DoInternal([AllowNull] TransformStageCache <TInCache>?cache, OptionToken options)
        {
            var input = await this.input(cache?.ParentCache, options).ConfigureAwait(false);

            var task = LazyTask.Create(async() =>
            {
                var inputList = await input.Perform;

                var sidecarLookup = inputList.result.Where(x => Path.GetExtension(x.Id) == this.SidecarExtension)
                                    .ToDictionary(x => Path.Combine(Path.GetDirectoryName(x.Id) ?? string.Empty, Path.GetFileNameWithoutExtension(x.Id)));

                var files = inputList.result.Where(x => Path.GetExtension(x.Id) != this.SidecarExtension);


                var list = await Task.WhenAll(files.Select(async file =>
                {
                    if (sidecarLookup.TryGetValue(file.Id, out var sidecar) && (file.HasChanges || sidecar.HasChanges))
                    {
                        var(fileResult, fileCache)       = await file.Perform;
                        var(sidecarResult, sidecarCache) = await sidecar.Perform;



                        var deserializer = new YamlDotNet.Serialization.DeserializerBuilder()
                                           .WithNamingConvention(YamlDotNet.Serialization.NamingConventions.CamelCaseNamingConvention.Instance)
                                           .Build();

                        var oldMetadata = fileResult.Metadata;
                        MetadataContainer?newMetadata;
                        try
                        {
                            using var stream = sidecarResult.Value;
                            using var reader = new StreamReader(stream);
                            var metadata     = deserializer.Deserialize <TMetadata>(reader);

                            if (metadata != null)
                            {
                                if (this.update != null)
                                {
                                    newMetadata = oldMetadata.AddOrUpdate(metadata.GetType(), metadata, (oldValue, newValue) => this.update((TMetadata)oldValue !/*AllowNull is set, so why the warnign?*/, (TMetadata)newValue));
                                }
                                else
                                {
                                    newMetadata = oldMetadata.Add(metadata.GetType(), metadata);
                                }
                            }
                            else
                            {
                                newMetadata = null;
                            }
                        }
                        catch (YamlDotNet.Core.YamlException e) when(e.InnerException is null)  // Hope that only happens when it does not match.
                        {
                            newMetadata = null;
                        }

                        if (newMetadata != null)
                        {
                            fileResult = fileResult.With(newMetadata);
                        }

                        var hasChanges = true;
                        if (cache != null && cache.Transformed.TryGetValue(fileResult.Id, out var oldHash))
                        {
                            hasChanges = oldHash != fileResult.Hash;
                        }

                        return(result: StageResult.Create <Stream, string>(fileResult, fileResult.Hash, hasChanges, fileResult.Id), inputId: file.Id, outputHash: fileResult.Hash);
                    }
                    else if (file.HasChanges)
                    {
                        var(fileResult, fileCache) = await file.Perform;
                        var hasChanges             = true;
                        if (cache != null && cache.Transformed.TryGetValue(fileResult.Id, out var oldHash))
                        {
                            hasChanges = oldHash != fileResult.Hash;
                        }
                        System.Diagnostics.Debug.Assert(hasChanges); // if the original file had changes so must this have.

                        return(result: StageResult.Create <Stream, string>(fileResult, fileResult.Hash, hasChanges, fileResult.Id), inputId: file.Id, outputHash: fileResult.Hash);
                    }
                    else
                    {
                        if (cache == null || !cache.InputToOutputId.TryGetValue(file.Id, out var oldOutputId) || !cache.Transformed.TryGetValue(file.Id, out var oldOutputHash))
                        {
                            throw this.Context.Exception("No changes, so old value should be there.");
                        }


                        var task = LazyTask.Create(async() =>
                        {
                            var(fileResult, fileCache) = await file.Perform;

                            return(fileResult, fileResult.Hash);
                        });

                        return(result: StageResult.Create(task, false, oldOutputId), inputId: file.Id, outputHash: oldOutputHash);
                    }
                })).ConfigureAwait(false);



                var newCache = new TransformStageCache <TInCache>()
                {
                    InputToOutputId = list.ToDictionary(x => x.inputId, x => x.result.Id),
                    OutputIdOrder   = list.Select(x => x.result.Id).ToArray(),
                    ParentCache     = inputList.cache,
                    Transformed     = list.ToDictionary(x => x.result.Id, x => x.outputHash)
                };
                return(result: list.Select(x => x.result).ToImmutableList(), cache: newCache);
            });

            bool hasChanges = input.HasChanges;
            var  newCache   = cache;

            if (input.HasChanges || newCache == null)
            {
                var(list, c) = await task;
                newCache     = c;


                if (!hasChanges && list.Count != cache?.OutputIdOrder.Length)
                {
                    hasChanges = true;
                }

                if (!hasChanges && cache != null)
                {
                    for (int i = 0; i < cache.OutputIdOrder.Length && !hasChanges; i++)
                    {
                        if (list[i].Id != cache.OutputIdOrder[i])
                        {
                            hasChanges = true;
                        }
                        if (list[i].HasChanges)
                        {
                            hasChanges = true;
                        }
                    }
                }
            }

            return(StageResultList.Create(task, hasChanges, newCache.OutputIdOrder.ToImmutableList()));
        }
コード例 #24
0
        private CodeGenResult GenerateCodeCore(String inputFilePath, String inputFileContent, String fileNamespace)
        {
            String fileName, workingDirectory, baseName;

            try
            {
                var fileInfo = new FileInfo(inputFilePath);
                fileName = fileInfo.Name;

                // Base name is commonly used to generate the class name
                baseName = fileName;
                while (baseName.Contains("."))
                {
                    baseName = Path.GetFileNameWithoutExtension(baseName);
                }

                workingDirectory = fileInfo.Directory.FullName;
            }
            catch (Exception exc)
            {
                var message = $"// Unable to access input file: {inputFilePath}";
                return(new CodeGenResult(message));
            }

            String metaPath, metaContents;

            try
            {
                (metaPath, metaContents) = metaFileNameCandidates
                                           .Select(name => Path.Combine(workingDirectory, name))
                                           .Where(path => File.Exists(path))
                                           .Select(path => (path, File.ReadAllText(path)))
                                           .FirstOrDefault();
            }
            catch (Exception exc)
            {
                var message = $"// Unable to access \"{metaFileNameCandidates.First()}\" in same directory as input: {inputFilePath}";
                return(new CodeGenResult(message));
            }

            Yaml.Spec spec;
            if (metaContents == null)
            {
                spec = null;
            }
            else
            {
                var deserializer = new YamlDotNet.Serialization.DeserializerBuilder()
                                   .Build();

                try
                {
                    spec = deserializer.Deserialize <Yaml.Spec>(metaContents);
                }
                catch (YamlDotNet.Core.YamlException yamlException)
                {
                    var    start   = yamlException.Start;
                    String message = $"Unable to parse YAML from {metaPath}\nLine: {start.Line}, Column: {start.Column}\n{yamlException.Message}";
                    this.GeneratorErrorCallback(false, 0, message, start.Line, start.Column);
                    return(new CodeGenResult($"// {message}"));
                }
            }

            String  toolName;
            Boolean isGlobalTool;

            if (spec != null && spec.Files.FirstOrDefault(i => i.FileName == fileName) is Yaml.File file)
            {
                toolName     = file.Tool;
                isGlobalTool = false;

                // Set file extension from config
                if (!(file.Extension is String fileExtension))
                {
                    fileExtension = ".cs";                     // Most code is C#, right? :-D
                }
                else if (!fileExtensionRegex.IsMatch(fileExtension))
                {
                    return(new CodeGenResult($"// Invalid extension: {fileExtension}"));
                }
                else if (!fileExtension.StartsWith("."))
                {
                    fileExtension = "." + fileExtension;
                }
                this.fileExtension = fileExtension;
            }