Click here to Skip to main content
15,881,757 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
I have code that extracts the Namespace, Classes, Methods and parameters from the user defined dll file.

I need a code that can serialize Namespace, Classes, Methods and Parameters in JSON.

=================== C# Code
C#
public static void Main(string[] args)
      {

          string filePath = @"C:\Users\admin\source\repos\TestHarness\UtilityFunctions\bin\Debug\netstandard2.0\UtilityFunctions.dll";

          if (File.Exists(filePath))
          {
              Assembly SampleAssembly = Assembly.LoadFrom(filePath);


              // Obtain a class name

              Type[] types = SampleAssembly.GetTypes();

              foreach (var type in types)
              {

                  string tChoice = type.ToString();

                  Console.WriteLine(tChoice);

                  MethodInfo[] methods = type.GetMethods();

                  foreach (var method in methods)
                  {

                      Console.WriteLine("Class: " +type.Name+"\n"+ "Method: "+method.Name);

                      ParameterInfo[] parameters = method.GetParameters();

                      foreach (var param in parameters)
                      {
                          Console.WriteLine("Parameter:"+param.Name+":"+param.ParameterType);
                      }

                      var countP = parameters.Count();
                      Console.WriteLine("         -- Total Parameters:" + countP);

                  }


                  // Second Option starts

                  var countC = types.Count();

                  string testString = "BasicMathFunctions";

                  for (int i = 0; i < countC; i++)
                  {

                      if (testString == types[i].Name)
                      {
                          Type typeChoice = types[i];

                          //string methodChoice = "Substract";

                          string methodChoice = "MultiplyOperation";

                          dynamic dObj = Activator.CreateInstance(typeChoice);

                          var methodInfo = typeChoice.GetMethod(methodChoice);

                          object[] parametersArray = new object[] { 15, 10 };

                          //object[] parametersArray = new object[] { 15 };

                          var result = methodInfo.Invoke(dObj, parametersArray);

                          Console.WriteLine("Result: " + result);

                          Console.ReadKey();


                         // break;
                      }

                  }

=== Expected JSON format
C#
[{
        "namespace": "namespace1",
        "classes": {
            "classname": "math1",
            "methods": {
                "methodname": "m1",
                "params": {
                    "seq": "1",
                    "paramname": "",
                    "paramtype": ""
                }
            },
            "classname": "math2",
            "methods": {
                "methodname": "m1",
                "params": {
                    "seq": "1",
                    "paramname": "",
                    "paramtype": ""
                }
            }
        },
		
    }, {
        "namespace": "alternatenamespace1",
        "classes": {
            "classname": "math1",
            "methods": {
                "methodname": "m1",
                "params": {
                    "seq": "1",
                    "paramname": "",
                    "paramtype": ""
                }
            },
            "classname": "math2",
            "methods": {
                "methodname": "m1",
                "params": {
                    "seq": "1",
                    "paramname": "",
                    "paramtype": ""
                }
            }
        },
		
    }
]


What I have tried:

I was able to get json format for the list:
C#
var opt = new JsonSerializerOptions() { WriteIndented = true };

string strJson = JsonSerializer.Serialize<Department>(dept, opt);


However I am still not able to apply this code to my above code.

Can anyone please help?
Posted
Updated 13-May-22 15:00pm
v3

1 solution

You need to create an object in C# to represent the data you want to serialize.

For example:
C#
Assembly asm = Assembly.ReflectionOnlyLoadFrom(filePath);

var result = asm.GetExportedTypes().GroupBy(t => t.Namespace, (ns, types) => new
{
    @namespace = ns,
    classes = types.Select(t => new
    {
        classname = t.Name,
        methods = t.GetMethods().Select(m => new
        {
            methodname = m.Name,
            @params = m.GetParameters().Select(p => new
            {
                seq = p.Position + 1,
                paramname = p.Name,
                paramtype = p.ParameterType,
            }),
        }),
    }),
});

string strJson = JsonSerializer.Serialize(result, opt);
 
Share this answer
 
Comments
Keyur Raval 2022 15-May-22 12:04pm    
Thank you for your reply. I tried this but still i am getting error when i run your code. How can i integrate this code with my code? Can you please paste the whole code?
Richard Deeming 16-May-22 3:33am    
If you want someone to help you fix an error, then you need to provide proper details of the error. Just saying "I am getting error" tells us precisely nothing.
Keyur Raval 2022 16-May-22 6:43am    
Sorry for not mentioning details about the error. Here is the details about code which I run and then I have described the error which I am getting. Thank you!!

Code I run ==========================
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using RunDLLsDynamically;
using System.Text.Json;
using System.Collections;

namespace Run_DLL_Application
{
class Program
{
public static void Main(string[] args)
{
var opt = new JsonSerializerOptions() { WriteIndented = true };

string filePath = @"C:\Users\admin\source\repos\TestHarness\UtilityFunctions\bin\Debug\netstandard2.0\UtilityFunctions.dll";

Assembly asm = Assembly.ReflectionOnlyLoadFrom(filePath);

var result = asm.GetExportedTypes().GroupBy(t => t.Namespace, (ns, types) => new
{
@namespace = ns,
classes = types.Select(t => new
{
classname = t.Name,
methods = t.GetMethods().Select(m => new
{
methodname = m.Name,
@params = m.GetParameters().Select(p => new
{
seq = p.Position + 1,
paramname = p.Name,
paramtype = p.ParameterType,
}),
}),
}),
});

string strJson = JsonSerializer.Serialize(result, opt);

Console.WriteLine(strJson);

}
}

}
==================================================
Error:
Unhandled Exception: System.IO.FileLoadException: Cannot resolve dependency to assembly 'netstandard, Version=2.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' because it has not been preloaded. When using the ReflectionOnly APIs, dependent assemblies must be pre-loaded or loaded on demand through the ReflectionOnlyAssemblyResolve event.
at System.Reflection.RuntimeAssembly.GetExportedTypes(RuntimeAssembly assembly, ObjectHandleOnStack retTypes)
at System.Reflection.RuntimeAssembly.GetExportedTypes()
at Run_DLL_Application.Program.Main(String[] args) in C:\Users\admin\source\repos\Run_DLL_Application\Run_DLL_Application\Program.cs:line 23
Press any key to continue . . .
========================================

Even I tried with :

Assembly asm = Assembly.LoadFile(filePath);

for which I am getting below error:

Unhandled Exception: System.NotSupportedException: Serialization and deserialization of 'System.Type' instances are not supported. Path: $.classes.methods.params.paramtype. ---> System.NotSupportedException: Serialization and deserialization of 'System.Type' instances are not supported.
at System.Text.Json.Serialization.Converters.UnsupportedTypeConverter`1.Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)

==============================================
Let me know if you require any more details from my end.

Thank you so much for your assistance.
Richard Deeming 16-May-22 9:03am    
Use Assembly.LoadFromFile to avoid the netstandard reference error, and change the parameter type to:
paramtype = p.ParameterType.FullName
Keyur Raval 2022 16-May-22 11:55am    
This is working perfect!! Thank you so much!! Next time I would like to handle this kind of stuff by my own. If you have any reference youtube videos or any website can you please suggest.
Thank you so much....

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900