Dynamically Replace the Contents of a C# Method

How do I replace a method implementation at runtime?

Using the traditional .Net APIs there is no way to achieve this. Method bodies are fixed at compile time and cannot be changed.

I say traditional though because with the profiler and ENC APIs it's technically possible to change method bodies. But these APIs operate in constrained circumstances and are not considered to be general purpose APIs.

How to dynamically change the content of a textBlock inside another method?

You need to run your query asynchronously. WPF won't update UI until method is exited.
You can mark you handler as async and use Task.Run to make sql query:

private async void searchButton_Click(object sender, RoutedEventArgs e)
{
this.status.Text="running...";

// make connection

string mySQLquery= "Do a lot of things here...";



// show the result in a datagrid
SqlCommand my_cmd = new SqlCommand(mySQLquery, conn);

DataTable mydt = new DataTable();

await Task.Run(() => {
using (SqlDataAdapter a = new SqlDataAdapter(my_cmd))
{
a.Fill(mydt);
}
});

this.status.Text="done";

await Task.Delay(2000);

this.status.Text = "idle";

}

Replace Method Name Dynamically

If I understand your question right you would need something like this:

public class ProgChoice
{
public static void ProgSelection()
{
Assembly assembly = Assembly.GetExecutingAssembly();

Type t = assembly.GetType("ProgChoice.ProgSelection", false, true);

string lcProgStr = "Prog";
int liProgNumb = 4;

// Concatenate the 2 strings
lcProgStr = lcProgStr + liProgNumb.ToString();

MethodInfo method = t.GetMethod(lcProgStr);
method.Invoke(null, null);

Console.ReadKey();
}
}

How to replace string with dynamic value in c#?

You can use the Regex class and provide a delegate that will be called once for each match. It needs to return the string to replace the matched text with.

You simply have to declare a variable holding your counter:

string a = "**MustbeReplaced**asdgasfsff**MustbeReplaced**asdfafasfsa";
int replacementIndex = 0;
string b = Regex.Replace(a, "MustbeReplaced", match =>
{
replacementIndex++;
return $"Replaced{replacementIndex}";
});

After running this, b will contain this:

**Replaced1**asdgasfsff**Replaced2**asdfafasfsa

Caution: Since you're now using the Regex class, be aware of all the special characters that Regex will use to augment the pattern away from simple character-by-character matching. If you're replacing text containing symbols like asterixes, question marks, parenthesis, etc. then you need to escape those.

Luckily we can simply ask the Regex class to do that for us:

string a = "**Mustbe?Replaced**asdgasfsff**Mustbe?Replaced**asdfafasfsa";
int replacementIndex = 0;
string b = Regex.Replace(a, Regex.Escape("Mustbe?Replaced"), match =>
{
replacementIndex++;
return $"Replaced{replacementIndex}";
});

Change method data type dynamically / at runtime

If I understand your question, you are attempting to call a third party (Dapper) generic method without foreknowledge of the generic type argument, which normally must be supplied at compile time.

This can be accomplished via Reflection. In your wrapper class (which I believe you call "DbConnector") add a new method called "InsertDynamicObject" and code it to use Reflection to find the method definition that you wish to call. You can then call MakeGenericMethod, passing the generic type parameters. An example could look like this:

namespace Dapper  //This is a stub for the Dapper framework that you cannot change
{
class DbConnection
{
public void Insert<T>(T obj)
{
Console.WriteLine("Inserting an object with type {0}", typeof(T).FullName);
}
}
}

namespace MyProgram
{
class DbConnector //Here is your DbConnector class, which wraps Dapper
{
protected readonly Dapper.DbConnection _connection = new Dapper.DbConnection();

public void InsertDynamicObject(object obj)
{
typeof(Dapper.DbConnection)
.GetMethod("Insert")
.MakeGenericMethod(new [] { obj.GetType() })
.Invoke(_connection, new[] { obj });
}
}

public class Program
{
public static void Main()
{
object someObject = "Test"; //This is the object that you deserialized where you don't know the type at compile time.

var connector = new DbConnector();
connector.InsertDynamicObject(someObject);
}
}
}

Output:

Inserting an object with type System.String

Here is a link to a working example on DotNetFiddle: Link



Related Topics



Leave a reply



Submit