Labels

CSOM (1) JavaScript (1) SharePoint (1)

Sunday, May 28, 2017

CODE GEN

using System.ComponentModel;
using System.IO;
using Microsoft.CSharp;
using System.CodeDom;

public class ClassGen<T>
    {
        public static void Generate()

        {

            Type type = typeof(T);
            PropertyDescriptorCollection properties =TypeDescriptor.GetProperties(typeof(T));

            string classtemplate =
                @" class {0} {{
                        {1}
                       }}
                 }}";

            string template = @"public {0}  {1} {{get; set;}}";

            string content = "";
            using (var provider = new CSharpCodeProvider())
            {
                foreach (PropertyDescriptor prop in properties)
                {
                    var typeRef = new CodeTypeReference(prop.PropertyType);
                    string typeName = provider.GetTypeOutput(typeRef);
                    content += string.Format(template, typeName, prop.Name) + "\n";
                }
            }
            Console.WriteLine(content);
            content = string.Format(classtemplate, type.Name, content);

            File.WriteAllText("../" + type.Name + ".cs", content);

}

ClassGen<A>.Generate();

ClassGen<B>.Generate();