Gatsby Starter Blog

มาสร้าง Automation Script แบบง่ายๆ กันด้วย Scripty

August 02, 2016

Scripty An alternative to T4 for compile-time code generation using the power of Roslyn scripting http://daveaglick.com/posts/announcing-scripty

using Microsoft.CodeAnalysis;
using System.Collections.Generic;

string className = "SchemaData";
string variableType = "string";

Dictionary obj = new Dictionary();
obj.Add("DomainID", "Schema.ObjectId");
obj.Add("ComponentID", "Schema.ObjectId");
obj.Add("imgType", "Number");

Output.WriteLine($@"class {className}
{{");
foreach (var entry in obj)
{
    Output.Write("\t");
    switch (entry.Value)
    {
        case "Schema.ObjectId":
            variableType = "string";
            break;
        case "Number":
            variableType = "int";
            break;
        default: variableType = "string";
            break;
    }
    Output.WriteLine($@"public {variableType} {entry.Key} {{ get; set; }}");
}
Output.WriteLine("}");

// Java Script Schema Generator

Output[className + ".js"].WriteLine($@"var {className}Schema = new Schema({{");
foreach (var entry in obj)
{
    Output[className + ".js"].Write("\t");
    Output[className + ".js"].Write($@"{entry.Key} : {entry.Value}");
    if (entry.Key != "imgType")
    {
        Output[className + ".js"].WriteLine(",");
    }
    else
    {
        Output[className + ".js"].WriteLine("");
    }

}
Output[className + ".js"].WriteLine($@"}});");


Auto generate Schema Mongoose

var SchemaDataSchema = new Schema({
	DomainID : Schema.ObjectId,
	ComponentID : Schema.ObjectId,
	imgType : Number
});

Auto generate C# Class

class SchemaData
{
	public string DomainID { get; set; }
	public string ComponentID { get; set; }
	public int imgType { get; set; }
}