Exemplo n.º 1
0
        public static string CreatePublicApiForAssembly(Assembly assembly)
        {
            var publicApiBuilder = new StringBuilder();
            var cgo = new CodeGeneratorOptions
            {
                BracingStyle = "C",
                BlankLinesBetweenMembers = false
            };

            using (var provider = new CSharpCodeProvider())
            {
                var publicTypes = assembly.GetTypes()
                    .Where(t => t.IsPublic && t.Name != "GeneratedInternalTypeHelper") //GeneratedInternalTypeHelper seems to be a r# runner side effect
                    .OrderBy(t => t.FullName);
                foreach (var publicType in publicTypes)
                {
                    var writer = new StringWriter();
                    var genClass = CreateClassDeclaration(publicType);
                    foreach (var memberInfo in publicType.GetMembers().Where(m => !IsDotNetTypeMember(m)).OrderBy(m => m.Name))
                    {
                        AddMemberToClassDefinition(genClass, memberInfo);
                    }
                    provider.GenerateCodeFromType(genClass, writer, cgo);
                    var gennedClass = GenerateClassCode(writer);
                    publicApiBuilder.AppendLine(gennedClass);
                }
            }
            var publicApi = publicApiBuilder.ToString();
            return publicApi.Trim();
        }
Exemplo n.º 2
0
        static void Main(string[] args)
        {
            CodeTypeDeclaration MyClass = Class("MyClass");
            MyClass.Add(Method("StrLen", Type(typeof(int))));
            TheMethod.Add(Parameter(typeof(string), "str"));
            TheMethod.Return(Expression("str.Length"));

            CSharpCodeProvider Provider = new CSharpCodeProvider();
            Provider.GenerateCodeFromType(MyClass, Console.Out, new System.CodeDom.Compiler.CodeGeneratorOptions());
            Console.ReadKey();
        }
 // Litee: This method is used for additional sorting of custom attributes when multiple values are allowed
 private static object ConvertAttrbuteToCode(Func<CodeTypeReference, CodeTypeReference> codeTypeModifier, CustomAttribute customAttribute)
 {
     using (var provider = new CSharpCodeProvider())
     {
         var cgo = new CodeGeneratorOptions
         {
             BracingStyle = "C",
             BlankLinesBetweenMembers = false,
             VerbatimOrder = false
         };
         var attribute = GenerateCodeAttributeDeclaration(codeTypeModifier, customAttribute);
         var declaration = new CodeTypeDeclaration("DummyClass")
         {
             CustomAttributes = new CodeAttributeDeclarationCollection(new[] { attribute }),
         };
         using (var writer = new StringWriter())
         {
             provider.GenerateCodeFromType(declaration, writer, cgo);
             return writer.ToString();
         }
     }
 }
Exemplo n.º 4
0
 /// <summary>
 /// Generates CSharp text from a type declaration and writes it to a text writer with the given options.
 /// </summary>
 /// <param name="typeDeclaration">The type declaration to generate text from.</param>
 /// <param name="writer">The text writer to write to.</param>
 /// <param name="options">The generation options.</param>
 public static void GenerateCSharpTo(this CodeTypeDeclaration typeDeclaration, TextWriter writer, CodeGeneratorOptions options)
 {
     using (var provider = new CSharpCodeProvider())
     {
         provider.GenerateCodeFromType(typeDeclaration, writer, options);
     }
 }
Exemplo n.º 5
0
        private static string DeclToString(CodeTypeDeclaration decl)
        {
            var provider = new CSharpCodeProvider();
            var opts = new CodeGeneratorOptions { IndentString = "    ", BracingStyle = "C" };

            var writer = new StringWriter();
            provider.GenerateCodeFromType(decl, writer, opts);
            return writer.GetStringBuilder().ToString();
        }
Exemplo n.º 6
0
  public static string GetClassWrapperText(Type type, string dynMethodBody)
  {
   string name = type.Name;
   if(name.Contains("`"))
    name = name.Substring(0, type.Name.IndexOf('`'));
   CodeTypeDeclaration ctd = new CodeTypeDeclaration(name);
   if(type.BaseType != typeof(object) && type.BaseType != typeof(ValueType))
    ctd.BaseTypes.Add(type.BaseType);
   foreach(Type t in type.GetInterfaces())
    ctd.BaseTypes.Add(t);
   ctd.IsClass = type.IsClass;
   ctd.IsEnum = type.IsEnum;
   ctd.IsInterface = type.IsInterface;
   ctd.TypeAttributes = type.Attributes;
   foreach(Type t in type.GetGenericArguments())
    ctd.TypeParameters.Add(t.Name);

   BindingFlags bf = BindingFlags.Instance | BindingFlags.Static|
                     BindingFlags.NonPublic | BindingFlags.Public |
                     BindingFlags.DeclaredOnly;

   foreach(MemberInfo mi in type.GetMembers(bf))
    switch(mi.MemberType)
    {
     case MemberTypes.Field:
     {
      if(((FieldInfo)mi).Name.Contains("<"))
       break;
      CodeMemberField ctm = new CodeMemberField();
      if(((FieldInfo)mi).IsPrivate)
       ctm.Attributes = (ctm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Private;
      if(((FieldInfo)mi).IsPublic)
       ctm.Attributes = (ctm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
      if(((FieldInfo)mi).IsStatic)
       ctm.Attributes |= MemberAttributes.Static;

      ctm.Type = new CodeTypeReference(((FieldInfo)mi).FieldType);
      ctm.InitExpression = new CodeDefaultValueExpression(ctm.Type);
      ctm.Name = mi.Name;
      ctd.Members.Add(ctm);
     }
     break;
     case MemberTypes.Constructor:
     {
      CodeConstructor cc = new CodeConstructor();
      if(((ConstructorInfo)mi).IsPrivate)
       cc.Attributes = (cc.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Private;
      if(((ConstructorInfo)mi).IsPublic)
       cc.Attributes = (cc.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
      if(((ConstructorInfo)mi).IsStatic)
       cc.Attributes |= MemberAttributes.Static;

      cc.Name = ((ConstructorInfo)mi).Name;
      foreach(ParameterInfo i in ((ConstructorInfo)mi).GetParameters())
       cc.Parameters.Add(new CodeParameterDeclarationExpression(i.ParameterType, i.Name));
      ctd.Members.Add(cc);
     }
     break;
     case MemberTypes.Method:
     {
      if(((MethodInfo)mi).IsSpecialName)
       break;
      CodeMemberMethod cc = new CodeMemberMethod();
      if(((MethodInfo)mi).Name.Contains("."))
       cc.Attributes = (cc.Attributes & ~MemberAttributes.AccessMask);
      else if(((MethodInfo)mi).IsPrivate)
       cc.Attributes = (cc.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Private;
      else if(((MethodInfo)mi).IsPublic)
       cc.Attributes = (cc.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
      if(((MethodInfo)mi).IsStatic)
       cc.Attributes |= MemberAttributes.Static;
      cc.Name = ((MethodInfo)mi).Name;
      foreach(ParameterInfo i in ((MethodInfo)mi).GetParameters())
      {
       CodeParameterDeclarationExpression par = new CodeParameterDeclarationExpression(i.ParameterType, i.Name);
       if(i.IsOut)
        par.Direction = FieldDirection.Out;
       if(i.IsRetval)
        par.Direction = FieldDirection.Ref;
       if(i.IsIn)
        par.Direction = FieldDirection.In;
       if(i.ParameterType.IsByRef)
       {
        par.Type = new CodeTypeReference(i.ParameterType.FullName.Replace("&", ""));
        cc.Statements.Add(new CodeSnippetExpression(
         String.Format("{0} = default({1})", i.Name, par.Type.BaseType)));
       }
       cc.Parameters.Add(par);
      }
      foreach(Type p in ((MethodInfo)mi).GetGenericArguments())
       cc.TypeParameters.Add(p.Name);
      cc.ReturnType = new CodeTypeReference(((MethodInfo)mi).ReturnType);
      if(((MethodInfo)mi).ReturnType != typeof(void))
       cc.Statements.Add(new CodeMethodReturnStatement(new CodeDefaultValueExpression(cc.ReturnType)));
      ctd.Members.Add(cc);
     }
     break;
     case MemberTypes.Property:
     {
      #region ...
      CodeMemberProperty cc = new CodeMemberProperty();
      cc.Name = ((PropertyInfo)mi).Name;
      foreach(ParameterInfo i in ((PropertyInfo)mi).GetIndexParameters())
       cc.Parameters.Add(new CodeParameterDeclarationExpression(i.ParameterType, i.Name));
      cc.Type = new CodeTypeReference(((PropertyInfo)mi).PropertyType);
      cc.HasGet = ((PropertyInfo)mi).CanRead;
      cc.HasSet = ((PropertyInfo)mi).CanWrite;
      cc.GetStatements.Add(new CodeMethodReturnStatement(new CodeDefaultValueExpression(cc.Type)));

      MethodInfo[] mis = ((PropertyInfo)mi).GetAccessors();
      if(((PropertyInfo)mi).Name.Contains("."))
       cc.Attributes = (cc.Attributes & ~MemberAttributes.AccessMask);
      else if(mis.Length > 0)
       cc.Attributes = (cc.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Public;
      else
       cc.Attributes = (cc.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Private;
      ctd.Members.Add(cc);
      #endregion ...
     }
     break;

    }

   CodeMemberMethod dm = new CodeMemberMethod();
   dm.Attributes = (dm.Attributes & ~MemberAttributes.AccessMask) | MemberAttributes.Private;
   dm.Name = "DynamicMethod";
   dm.ReturnType = new CodeTypeReference(typeof(object));
   if(String.IsNullOrWhiteSpace(dynMethodBody))
    dm.Statements.Add(new CodeSnippetStatement("\r\n  //Dynamic Method Body\r\n\r\n\r\n   return null;"));
   dm.Statements.Add(new CodeSnippetStatement(dynMethodBody));
   ctd.Members.Add(dm);

   string s;
   using(CSharpCodeProvider cp = new CSharpCodeProvider())
    using(System.IO.TextWriter tw = new System.IO.StringWriter())
    {
     CodeGeneratorOptions cgo = new CodeGeneratorOptions();
     cgo.BracingStyle = "C";
     cgo.IndentString = " ";
     cgo.BlankLinesBetweenMembers = false;
     cp.GenerateCodeFromType(ctd, tw, cgo);
     s = tw.ToString();
    }
   s = s.Insert(0, "using System;\r\nusing System.Collections;\r\nusing System.Collections.Generic;\r\n" +
                   "\r\nusing Pulsar;\r\nusing Pulsar.Shared;\r\n");
   s = s.Replace(" {\r\n", " { ");
   s = s.Replace("\r\n {", " {");
   s = s.Replace("\r\n  {", " {");
   s = s.Replace("\r\n   {", " {");
   s = s.Replace("\r\n }", " }");
   s = s.Replace("\r\n  }", " }");
   s = s.Replace("\r\n   }", " }");
   s = s.Replace("  ", " ");
   s = s.Replace("  ", " ");
   s = s.Replace("DynamicMethod() {", "DynamicMethod()\r\n {");
   s = s.Replace("\r\n set {", "set {");
   s = s.Replace("\r\n return ", " return ");
   return s;
  }
Exemplo n.º 7
0
        public void Test()
        {
            string[] Names = Enum.GetNames(typeof(Voldemort.AdminRequestType));

            CodeTypeDeclaration implementation = new CodeTypeDeclaration("VoldemortAdminClient");
            implementation.IsClass = true;
            implementation.Attributes = MemberAttributes.Public;
            CodeTypeDeclaration interfaceType = new CodeTypeDeclaration("IVoldemortAdminClient");
            interfaceType.IsInterface = true;
            interfaceType.Attributes = MemberAttributes.Public;

            foreach (string Name in Names)
            {
                string[] parts = Name.Split(new string[] { "_" }, StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < parts.Length; i++)
                    parts[i] = System.Globalization.CultureInfo.CurrentUICulture.TextInfo.ToTitleCase(parts[i].ToLower());
                CodeMemberMethod method = new CodeMemberMethod();
                method.Name = string.Concat(parts);
                interfaceType.Members.Add(method);

                string typeName = string.Format("Voldemort.{0}Request, Voldemort", method.Name);


                Type type = Type.GetType(typeName);

                if (null == type)
                    continue;

                PropertyInfo[] properties = type.GetProperties();

                foreach (PropertyInfo property in properties)
                {
                    CodeParameterDeclarationExpression methodParameter = new CodeParameterDeclarationExpression(property.PropertyType, property.Name);
                    method.Parameters.Add(methodParameter);
                }
            }

            CodeGeneratorOptions options = new CodeGeneratorOptions();
            options.BracingStyle = "C";
            options.BlankLinesBetweenMembers = false;

            CSharpCodeProvider csp = new CSharpCodeProvider();
            csp.GenerateCodeFromType(interfaceType, Console.Out, options);
        }