C# API generator - c#

I have a few dll files and I want to export all public classes with methods separated by namespaces (export to html / text file or anything else I can ctrl+c/v in Windows :) ).
I don't want to create documentation or merge my dlls with xml file. I just need a list of all public methods and properties.
What's the best way to accomplish that?
TIA for any answers

Very rough around the edges, but try this for size:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
namespace GetMethodsFromPublicTypes
{
class Program
{
static void Main(string[] args)
{
var assemblyName = #"FullPathAndFilenameOfAssembly";
var assembly = Assembly.ReflectionOnlyLoadFrom(assemblyName);
AppDomain.CurrentDomain.ReflectionOnlyAssemblyResolve += new ResolveEventHandler(CurrentDomain_ReflectionOnlyAssemblyResolve);
var methodsForType = from type in assembly.GetTypes()
where type.IsPublic
select new
{
Type = type,
Methods = type.GetMethods().Where(m => m.IsPublic)
};
foreach (var type in methodsForType)
{
Console.WriteLine(type.Type.FullName);
foreach (var method in type.Methods)
{
Console.WriteLine(" ==> {0}", method.Name);
}
}
}
static Assembly CurrentDomain_ReflectionOnlyAssemblyResolve(object sender, ResolveEventArgs args)
{
var a = Assembly.ReflectionOnlyLoad(args.Name);
return a;
}
}
}
Note: This needs refinement to exclude property getters/setters and inherited methods, but it's a decent starting place

Have you had a look at .NET Reflector from RedGate software. It has an export function.

You can start here with Assembly.GetExportedTypes()
http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getexportedtypes.aspx

Related

How do I solve: The type or namespace Windows does not exist in namespace Microsoft?

How do I solve this missing dependency? Googling around for this problem, it seems rare. I see similar ones like The type or namespace name 'Windows' does not exist in the namespace 'System' but nowhere do I see someone explain this particular message.
Log files naturally recorded by windows at locations such as C:\Windows\System32\WDI\LogFiles\BootPerfDiagLogger.etl record useful forensic security info, such as every process that ran persistently at boot.
My goal is to parse these files into some intermediary structure like XML or JSON so I can import the data to Python.
I wanted to parse Windows ETL files in Python for forensic / security data science. I thought this would be easy since there's a Python library for it but upon running that library, it doesn't work and is probably no longer maintained.
Luckily I found a Microsoft dev blog on parsing ETL files with the same classes Windows exposes to allow Windows Performance Analyzer to do it.
The example code shown was like:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.Windows.EventTracing;
using Microsoft.Windows.EventTracing.Disk;
using Microsoft.Windows.EventTracing.Processes;
class FileOperation
{
public IProcess IssuingProcess;
public string Operation;
public string Path;
public long Size;
public decimal Duration;
}
class Program
{
public static void Main(string[] args)
{
var etlFileName = args[0];
var diskTrace = Path.GetFileNameWithoutExtension(etlFileName) + "-disk.csv";
var fileTrace = Path.GetFileNameWithoutExtension(etlFileName) + "-file.csv";
using (ITraceProcessor trace = TraceProcessor.Create(etlFileName))
{
var pendingDisk = trace.UseDiskIOData();
var pendingFile = trace.UseFileIOData();
trace.Process();
ProcessDisk(pendingDisk.Result, diskTrace);
ProcessFile(pendingFile.Result, fileTrace);
}
}
I won't include the ProcessDisk and ProcessFile classes here because those seem to be geared toward whatever debugging purpose the writer had. Rather, I'm interested in trace. Based on the methods I see called: UseDiskIOData, UseFileIOData, presumably there is a longer list of methods like that I could use to access all available data for each trace.
My immediate goal with this question is just to view what methods exist on the trace object.
So I did some research on how you look at all properties on an object in C#, and there are plenty of answers, that's probably not a problem:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using Microsoft.Windows.EventTracing;
using Microsoft.Windows.EventTracing.Disk;
using Microsoft.Windows.EventTracing.Processes;
class Program
{
public static void Main(string[] args)
{
var etlFileName = args[0];
#var diskTrace = Path.GetFileNameWithoutExtension(etlFileName) + "-disk.csv";
#var fileTrace = Path.GetFileNameWithoutExtension(etlFileName) + "-file.csv";
using (ITraceProcessor trace = TraceProcessor.Create(etlFileName))
{
Type myType = trace.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());
foreach (PropertyInfo prop in props)
{
object propValue = prop.GetValue(trace, null);
// Do something with propValue
Console.WriteLine(propValue);
}
#var pendingDisk = trace.UseDiskIOData();
#var pendingFile = trace.UseFileIOData();
#trace.Process();
#ProcessDisk(pendingDisk.Result, diskTrace);
#ProcessFile(pendingFile.Result, fileTrace);
}
}
But what I did have a problem with is this:
The type or namespace Windows does not exist in namespace Microsoft
As I said, I looked around for solutions to this and found nothing.

c# read/edit accdb macro

I am trying to access the macros inside of an Access database (accdb).
I tried using:
using Microsoft.Office.Interop.Access.Dao;
...
DBEngine dbe = new DBEngine();
Database ac = dbe.OpenDatabase(fileName);
I found a container["Scripts"] that had a document["Macro1"] which is my target. I am struggling to access the contents of the document. I also question if the Microsoft.Office.Interop.Access.Dao is the best reference for what I am trying to achieve.
What is the best way to view the content of the macros and modules?
You can skip the DAO part, it's not needed in this case. Macros are project specific, so in order to get them all, you would need to loop through your projects. In my example, i just have one project.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Access;
namespace Sandbox48
{
public class Program
{
public static void Main(string[] args)
{
Microsoft.Office.Interop.Access.Application oAccess = null;
string savePath = #"C:\macros\";
oAccess = new Microsoft.Office.Interop.Access.Application();
// Open a database in exclusive mode:
oAccess.OpenCurrentDatabase(
#"", //filepath
true //Exclusive
);
var allMacros = oAccess.CurrentProject.AllMacros;
foreach(var macro in allMacros)
{
var fullMacro = (AccessObject)macro;
Console.WriteLine(fullMacro.Name);
oAccess.SaveAsText(AcObjectType.acMacro, fullMacro.FullName, $"{savePath}{ fullMacro.Name}.txt");
}
Console.Read();
}
}
}

Load dynamic delegate function from text file? [duplicate]

I have a WPF C# application that contains a button.
The code of the button click is written in separate text file which will be placed in the applications runtime directory.
I want to execute that code placed in the text file on the click of the button.
Any idea how to do this?
Code sample for executing compiled on fly class method:
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Net;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string source =
#"
namespace Foo
{
public class Bar
{
public void SayHello()
{
System.Console.WriteLine(""Hello World"");
}
}
}
";
Dictionary<string, string> providerOptions = new Dictionary<string, string>
{
{"CompilerVersion", "v3.5"}
};
CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions);
CompilerParameters compilerParams = new CompilerParameters
{GenerateInMemory = true,
GenerateExecutable = false};
CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, source);
if (results.Errors.Count != 0)
throw new Exception("Mission failed!");
object o = results.CompiledAssembly.CreateInstance("Foo.Bar");
MethodInfo mi = o.GetType().GetMethod("SayHello");
mi.Invoke(o, null);
}
}
}
You can use Microsoft.CSharp.CSharpCodeProvider to compile code on-the-fly. In particular, see CompileAssemblyFromFile.
I recommend having a look at Microsoft Roslyn, and specifically its ScriptEngine class.
Here are a few good examples to start with:
Introduction to the Roslyn Scripting API
Using Roslyn ScriptEngine for a ValueConverter to process user input.
Usage example:
var session = Session.Create();
var engine = new ScriptEngine();
engine.Execute("using System;", session);
engine.Execute("double Sin(double d) { return Math.Sin(d); }", session);
engine.Execute("MessageBox.Show(Sin(1.0));", session);
Looks like someone created a library for this called C# Eval.
EDIT: Updated link to point to Archive.org as it seems like the original site is dead.
What you need is a CSharpCodeProvider Class
There are several samples to understand how does it work.
1 http://www.codeproject.com/Articles/12499/Run-Time-Code-Generation-I-Compile-C-Code-using-Mi
The important point of this example that you can do all things on flay in fact.
myCompilerParameters.GenerateExecutable = false;
myCompilerParameters.GenerateInMemory = false;
2 http://www.codeproject.com/Articles/10324/Compiling-code-during-runtime
This example is good coz you can create dll file and so it can be shared between other applications.
Basically you can search for http://www.codeproject.com/search.aspx?q=csharpcodeprovider&x=0&y=0&sbo=kw&pgnum=6 and get more useful links.

execute c# code at runtime from code file

I have a WPF C# application that contains a button.
The code of the button click is written in separate text file which will be placed in the applications runtime directory.
I want to execute that code placed in the text file on the click of the button.
Any idea how to do this?
Code sample for executing compiled on fly class method:
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Net;
using Microsoft.CSharp;
using System.CodeDom.Compiler;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
string source =
#"
namespace Foo
{
public class Bar
{
public void SayHello()
{
System.Console.WriteLine(""Hello World"");
}
}
}
";
Dictionary<string, string> providerOptions = new Dictionary<string, string>
{
{"CompilerVersion", "v3.5"}
};
CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions);
CompilerParameters compilerParams = new CompilerParameters
{GenerateInMemory = true,
GenerateExecutable = false};
CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, source);
if (results.Errors.Count != 0)
throw new Exception("Mission failed!");
object o = results.CompiledAssembly.CreateInstance("Foo.Bar");
MethodInfo mi = o.GetType().GetMethod("SayHello");
mi.Invoke(o, null);
}
}
}
You can use Microsoft.CSharp.CSharpCodeProvider to compile code on-the-fly. In particular, see CompileAssemblyFromFile.
I recommend having a look at Microsoft Roslyn, and specifically its ScriptEngine class.
Here are a few good examples to start with:
Introduction to the Roslyn Scripting API
Using Roslyn ScriptEngine for a ValueConverter to process user input.
Usage example:
var session = Session.Create();
var engine = new ScriptEngine();
engine.Execute("using System;", session);
engine.Execute("double Sin(double d) { return Math.Sin(d); }", session);
engine.Execute("MessageBox.Show(Sin(1.0));", session);
Looks like someone created a library for this called C# Eval.
EDIT: Updated link to point to Archive.org as it seems like the original site is dead.
What you need is a CSharpCodeProvider Class
There are several samples to understand how does it work.
1 http://www.codeproject.com/Articles/12499/Run-Time-Code-Generation-I-Compile-C-Code-using-Mi
The important point of this example that you can do all things on flay in fact.
myCompilerParameters.GenerateExecutable = false;
myCompilerParameters.GenerateInMemory = false;
2 http://www.codeproject.com/Articles/10324/Compiling-code-during-runtime
This example is good coz you can create dll file and so it can be shared between other applications.
Basically you can search for http://www.codeproject.com/search.aspx?q=csharpcodeprovider&x=0&y=0&sbo=kw&pgnum=6 and get more useful links.

C#: execute a function stored in a string variable

Is it possible to write a simple and fast function in C# that will execute arbitrary methods from a string? For example, if I set MyString="MessageBox.Show("Some Message")" and then call ExecuteString(MyString), a message box would pop up with "Some Message" in it.
(I've probably made some sort of error in the above code. I don't yet know C#; I'm trying to evaluate whether it would be appropriate for a specific project.)
You should be able to use this and wrap the code required to run a string into a function.
Essentially what you're doing is wrapping the small bit of C# code in a Program.Mainstyle function, referencing some assemblies for basic functionality (maybe including your own assembly) then run the compiled program in memory.
It's likely a bit of more overhead than you need to simply run one or two lines of code mind you.
http://support.microsoft.com/kb/304655
what you appear to be looking for is CS-Script
Alas, C# is not a dynamic language in that way. You can't really do this easily, and if it's really something you need to do, consider using a .Net language more in line with your needs, like IronPython or IronRuby.
Your best available alternative is to use the CodeDom namespace, as this truly convoluted and heinous example from this forum thread shows:
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Text;
using System.Windows.Forms;
namespace TestApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SampleLib.SampleType test = new SampleLib.SampleType();
private void button1_Click(object sender, EventArgs e)
{
// Dynamically build and call the method
label1.Text = test.MyText;
}
private void button2_Click(object sender, EventArgs e)
{
StringBuilder DynamicCode = new StringBuilder();
DynamicCode.Append("namespace TestDynamic");
DynamicCode.Append("{");
DynamicCode.Append("public class DynamicCode");
DynamicCode.Append("{");
DynamicCode.Append("public static void EditText(SampleLib.SampleType t)");
DynamicCode.Append("{");
DynamicCode.Append("t.MyText = \"Goodbye!\";");
DynamicCode.Append("}");
DynamicCode.Append("}");
DynamicCode.Append("}");
string CodeString = DynamicCode.ToString();
System.IO.FileInfo fi = new System.IO.FileInfo(Application.ExecutablePath);
CodeDomProvider provider = CodeDomProvider.CreateProvider("C#");
CompilerParameters CompileParams = new CompilerParameters(new string[] { fi.DirectoryName + "\\SampleLib.dll" },
fi.DirectoryName + "\\Dynamic.dll");
CompileParams.MainClass = "DynamicCode";
CompileParams.GenerateExecutable = false;
//CompileParams.GenerateInMemory = true;
CompilerResults r = provider.CompileAssemblyFromSource(CompileParams, new string[] {CodeString});
foreach (CompilerError er in r.Errors)
{
Console.WriteLine(er.ErrorText);
}
}
private void button3_Click(object sender, EventArgs e)
{
// Dynamically call assembly
System.IO.FileInfo fi = new System.IO.FileInfo(Application.ExecutablePath);
Assembly dynAsm = Assembly.LoadFile(fi.DirectoryName + "\\Dynamic.dll");
if (dynAsm != null)
{
object o = dynAsm.CreateInstance("TestDynamic.DynamicCode", true);
Type t = dynAsm.GetType("TestDynamic.DynamicCode");
t.GetMethod("EditText").Invoke(o, new object[]{test});
}
}
}
}

Categories