I saw this piece of code in another post, however it was posted 9 years ago so I've made a new post. I am getting the error quoted below when I try and serialize a parameter during runtime. There were a few things I wasn't confident I understood and would like help getting this to work, starting with the error message. A small repro project will reproduce the error each time.
"A circular reference was detected while serializing an object of type 'System.Reflection.RuntimeModule'."
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Web;
using System.Web.Script.Serialization;
using System.Windows.Input;
using System.Reflection;
namespace FunctionParamTesting1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private string parameterExposer (string identity, string emailAddress)
{
string returnValue = "null";
MethodBase functionMethodBase = MethodBase.GetCurrentMethod();
string functionDeclaringTypeFullName = functionMethodBase.DeclaringType.FullName;
ParameterInfo[] functionMethodBaseParams = functionMethodBase.GetParameters();
Tracer.Parameters(functionMethodBase.GetParameters());
return returnValue;
}
private void btnTest_Click(object sender, EventArgs e)
{
parameterExposer("TestId", "TestEmail");
}
}
public static class Tracer
{
private static string stop;
public static void Parameters(params object[] parameters)
{
// https://stackoverflow.com/questions/2405230/can-i-get-parameter-names-values-procedurally-from-the-currently-executing-funct
var jss = new System.Web.Script.Serialization.JavaScriptSerializer(); // add reference System.Web.Extensions and 'using System.Web.Script.Serialization;'
//var jss = new System.Web.Script.Serialization.JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore };
var stackTrace = new System.Diagnostics.StackTrace();
var paramInfos = stackTrace.GetFrame(1).GetMethod().GetParameters();
var callingMethod = stackTrace.GetFrame(1).GetMethod();
//Debug.WriteLine(string.Format("[Func: {0}", callingMethod.DeclaringType.FullName + "." + callingMethod.Name + "]"));
for (int i = 0; i < paramInfos.Count(); i++)
{
var currentParameterInfo = paramInfos[i];
var currentParameter = parameters[i];
var name = currentParameterInfo.Name;
var value = jss.Serialize(currentParameter);
//Debug.WriteLine(string.Format(" Parameter: {0}", currentParameterInfo.Name));
//Debug.WriteLine(string.Format(" Value: {0}", jss.Serialize(currentParameter)));
}
//Debug.WriteLine("[End Func]");
}
}
}