this code works for me but there must be a better way to accomplish the same thing. The method Search exists in multiple namespaces. the correct namespace to use depends on code that is irrelevant just like some of the other code displayed. any thoughts on rewritting this better?
example namespaces used
MTG.Sites.Test1
MTG.Sites.Test2
static public async Task<List<Card>> Search(string sNamespace)
{
List<Card> rawCards = null;
try
{
Type t = Assembly.GetExecutingAssembly().GetType($"MTG.Sites.{sNamespace}");
if (t != null)
{
dynamic classInstance = Activator.CreateInstance(t);
rawCards = await classInstance.Search(httpClient);
}
}
catch(Exception ex)
{
log.Error(ex);
}
return rawCards;
}
the code i want to improve is the use of Assembly.GetExecutingAssembly().GetType("");
the short answer is to use AutoFac. the longer answer is a complete rewrite of how the code is used. i essentially need to register each Search class that exists in each Namespace that contains one. then using the AutoFac examples (AttributeMetadataExample & AspNetCoreExample), i was able to eliminate the need for reflection to find the Search method in each Namespace (passed as a string to GetType)
public static void CacheUncachedMessageIDs(List<int> messageIDs)
{
var uncachedRecordIDs = LocalCacheController.GetUncachedRecordIDs<PrivateMessage>(messageIDs);
if (!uncachedRecordIDs.Any()) return;
using (var db = new DBContext())
{
.....
}
}
The above method is repeated regularly throughout the project (except with different generics passed in). I'm looking to avoid repeated usages of the if (!uncachedRecordIDs.Any()) return; lines.
In short, is it possible to make the LocalCacheController.GetUncachedRecordIDs return the CacheUncachedMessageIDs method?
This will guarantee a new data context is not created unless it needs to be (stops accidentally forgetting to add the return line in the parent method).
It is not possible for a nested method to return from parent method.
You can do some unhandled Exception inside GetUncachedRecordIDs, that will do the trick, but it is not supposed to do this, so it creates confusion. Moreover, it is very slow.
Another not suggested mechanic is to use some goto magic. This also generates confusion because goto allows unexpected behaviour in program execution flow.
Your best bet would be to return a Result object with simple bool HasUncachedRecordIDs field and then check it. If it passes, then return. This solution solves the problem of calling a method, which is Any() in this case.
var uncachedRecordIDsResult = LocalCacheController.GetUncachedRecordIDs<PrivateMessage>(messageIDs);
if(uncachedRecordIDsResult.HasUncachedRecordIDs) return;
My reasoning for lack of this feature in the language is that calling GetUncachedRecordIDs in basically any function would unexpectedly end that parent function, without warning. Also, it would intertwine closely both functions, and best programming practices involve loose coupling of classes and methods.
You could pass an Action to your GetUncachedRecordIDs method which you only invoke if you need to. Rough sketch of the idea:
// LocalCacheController
void GetUncachedRecordIDs<T>(List<int> messageIDs, Action<List<int>> action)
{
// ...
if (!cached) {
action(recordIds);
}
}
// ...
public static void CacheUncachedMessageIDs(List<int> messageIDs)
{
LocalCacheController.GetUncachedRecordIDs<PrivateMessage>(messageIDs, uncachedRecordIDs => {
using (var db = new DBContext())
{
// ...
}
});
}
I tried to find an example of this but without success so that's is why I asked this question.
Lets start with some code. Here's my code:
class Dummy
{
public void DoDummyThings1()
{
Console.WriteLine("Sorry, I'm dummy 1...");
}
public void DoDummyThings2()
{
Console.WriteLine("Sorry, I'm dummy 2...");
}
public void DoDummyThings3()
{
Console.WriteLine("Sorry, I'm dummy 3...");
}
}
And my test code:
[TestClass]
public class UnitTest
{
private Dummy dum = new Dummy();
[TestInitialize()]
public void SetUp()
{
MethodInfo mi = typeof (UnitTest).GetMethod("TestDummy");
MethodBody mb = mi.GetMethodBody();
}
[TestMethod]
public void TestDummy()
{
this.dum.DoDummyThings1();
this.dum.DoDummyThings2();
this.dum.DoDummyThings3();
}
}
Here's what I'm trying to do. I want to, before execution of each test method, look to the test method and check if methods DoDummyThings1,DoDummyThings2 and DoDummyThings3 of Dummy class will be called or not.
The purpose of this is, depending of which DoDummyThingsX methods are called, I want to inject different implementation somewhere deep inside the code to modify during runtime the behavior of some class (swap the inject implementation of an interface for another one).
Can somebody explain me how to do this correctly (with lastest version of Cecil or something else for C#)?
Is there a way to do this without using the .dll files? (Currently, this is the only way I figured out how to do this but, using strings as "MyDllName.dll" and "MyNamespace.MyClassName" hard coded are not possible for me)
Other stackoverflow threads I'm already aware of:
Look if a method is called inside a method using reflection
How to determine which methods are called in a method?
Can I use reflection to inspect the code in a method?
Can anyone help me with a complete (but simple) example (if it's possible)?
Thank you!
This answer demonstrates how to determine which tests execute a Dummy method but does not answer:
inject different implementation somewhere deep inside the code to modify during runtime the behavior of some class
Reflection doesn't provide granular access to the IL Body of the unit test methods which you will need; however Cecil provides this functionality. The following linq returns a list of methods that internally call DoDummyThings1. The linq could be more efficient but I wanted to make it as clear as possible. The where clause is the important part.
//syntax based on version 0.9.5.4 (http://nuget.org/packages/Mono.Cecil/0.9.5.4)
using Mono.Cecil;
using Mono.Cecil.Cil;
//...
string assemblyPath = (#"path to your unit test assembly\MyTests.dll");
AssemblyDefinition asm = AssemblyDefinition.ReadAssembly(assemblyPath);
List<MethodDefinition> testsThatCallDummyMethods =
(from mod in asm.Modules
from t in mod.Types
from meth in t.Methods
where meth.HasBody
from instr in meth.Body.Instructions
let op = instr.Operand as MethodDefinition
where
instr.OpCode == OpCodes.Callvirt &&
op != null &&
op.DeclaringType.FullName ==
"Lib.Dummy" //namespace qualified type name
&& op.Name ==
"DoDummyThings1" //method names...
select meth)
.ToList();
Disassemble the test assembly using ILDasm to figure out the OpCodes / Operands. The relevant part of the TestDummy method will be something like:
//this.dum.DoDummyThings1();
IL_0001: ldarg.0
IL_0002: ldfld class Lib.Dummy Lib.UnitTest::dum
IL_0007: callvirt instance void Lib.Dummy::DoDummyThings1()
My unit testing frameworks consists of TestFixtures, TestMethods and Actions. Action is additional smaller container inside TestMethod, Actions comes from internal Dll written in our company. Actions are used inside methods like that:
[Test]
void TestMethod1()
{
Run(new Sleep { Seconds = 10 } );
}
I have to write an application, which collect all the information about fixtures, tests and actions from DLL. I have found how to enumerate test fixtures and test methods by reflection using type / method attributes.
But I have no idea how enumerate actions inside test methods.
Could you please help? Is it possible to do using reflection at all?
UPDATED:
See the accepted answer. Really cool library. Also you can look here ( WPF: Binding TreeView in MVVM way step by step tutorial ), if you are interested in how I created entity model for fixtures, tests and actions, and binded in MVVM way to TreeView.
Yes to extent.
Reflection will give you method body, than you need to disassemble the IL to read method body and obtain any information you want.
var bytes = mi.GetMethodBody().GetILAsByteArray();
One of possible tools to disassembe is Cecil
Check out Traverse a c# method and anazlye the method body for more links.
Instead of using reflection, why don't you roll out your own method that will log all Action executions.
void ExecuteAction(Action action)
{
//Log TestFixture, TestMethod, Action
//Execute actual action
}
[Test]
void TestMethod1()
{
ExecuteAction(Run(new Sleep { Seconds = 10 } ));
}
ExecuteAction method can be in a base or helper class
Thanks, Alexei Levenkov! Finally I have found a solution using your tip. Sharing. The only thing you should do -> download and reference Mono.Reflection.dll from https://github.com/jbevain/mono.reflection.
using System;
using System.Linq;
using System.Reflection;
using MINT;
using MbUnit.Framework;
using Mono.Reflection;
namespace TestDll
{
internal class Program
{
private static void Main(string[] args)
{
const string DllPath = #"d:\SprinterAutomation\Actions.Tests\bin\x86\Debug\Actions.Tests.dll";
Assembly assembly = Assembly.LoadFrom(DllPath);
// enumerating Fixtures
foreach (Type fixture in assembly.GetTypes().Where(t => t.GetCustomAttributes(typeof(TestFixtureAttribute), false).Length > 0))
{
Console.WriteLine(fixture.Name);
// enumerating Test Methods
foreach (var testMethod in fixture.GetMethods().Where(m => m.GetCustomAttributes(typeof(TestAttribute), false).Length > 0))
{
Console.WriteLine("\t" + testMethod.Name);
// filtering Actions
var instructions = testMethod.GetInstructions().Where(
i => i.OpCode.Name.Equals("newobj") && ((ConstructorInfo)i.Operand).DeclaringType.IsSubclassOf(typeof(BaseAction)));
// enumerating Actions!
foreach (Instruction action in instructions)
{
var constructroInfo = action.Operand as ConstructorInfo;
Console.WriteLine("\t\t" + constructroInfo.DeclaringType.Name);
}
}
}
}
}
}
This question already has answers here:
Where do I use delegates? [closed]
(8 answers)
Closed 9 years ago.
I think I understand the concept of a delegate in C# as a pointer to a method, but I cant find any good examples of where it would be a good idea to use them. What are some examples that are either significantly more elegant/better with delegates or cant be solved using other methods?
The .NET 1.0 delegates:
this.myButton.Click += new EventHandler(this.MyMethod);
The .NET 2.0 delegates:
this.myOtherButton.Click += delegate {
var res = PerformSomeAction();
if(res > 5)
PerformSomeOtherAction();
};
They seem pretty useful. How about:
new Thread(new ThreadStart(delegate {
// do some worker-thread processing
})).Start();
What exactly do you mean by delegates? Here are two ways in which they can be used:
void Foo(Func<int, string> f) {
//do stuff
string s = f(42);
// do more stuff
}
and
void Bar() {
Func<int, string> f = delegate(i) { return i.ToString(); }
//do stuff
string s = f(42);
// do more stuff
}
The point in the second one is that you can declare new functions on the fly, as delegates. This can be largely replaced by lambda expressions,and is useful any time you have a small piece of logic you want to 1) pass to another function, or 2) just execute repeatedly. LINQ is a good example. Every LINQ function takes a lambda expression as its argument, specifying the behavior. For example, if you have a List<int> l then l.Select(x=>(x.ToString()) will call ToString() on every element in the list. And the lambda expression I wrote is implemented as a delegate.
The first case shows how Select might be implemented. You take a delegate as your argument, and then you call it when needed. This allows the caller to customize the behavior of the function. Taking Select() as an example again, the function itself guarantees that the delegate you pass to it will be called on every element in the list, and the output of each will be returned. What that delegate actually does is up to you. That makes it an amazingly flexible and general function.
Of course, they're also used for subscribing to events. In a nutshell, delegates allow you to reference functions, using them as argument in function calls, assigning them to variables and whatever else you like to do.
I primarily use the for easy asynch programming. Kicking off a method using a delegates Begin... method is really easy if you want to fire and forget.
A delegate can also be used like an interface when interfaces are not available. E.g. calling methods from COM classes, external .Net classes etc.
Events are the most obvious example. Compare how the observer pattern is implemented in Java (interfaces) and C# (delegates).
Also, a whole lot of the new C# 3 features (for example lambda expressions) are based on delegates and simplify their usage even further.
For example in multithread apps. If you want several threads to use some control, You shoul use delegates. Sorry, the code is in VisualBasic.
First you declare a delegate
Private Delegate Sub ButtonInvoke(ByVal enabled As Boolean)
Write a function to enable/disable button from several threads
Private Sub enable_button(ByVal enabled As Boolean)
If Me.ButtonConnect.InvokeRequired Then
Dim del As New ButtonInvoke(AddressOf enable_button)
Me.ButtonConnect.Invoke(del, New Object() {enabled})
Else
ButtonConnect.Enabled = enabled
End If
End Sub
I use them all the time with LINQ, especially with lambda expressions, to provide a function to evaluate a condition or return a selection. Also use them to provide a function that will compare two items for sorting. This latter is important for generic collections where the default sorting may or may not be appropriate.
var query = collection.Where( c => c.Kind == ChosenKind )
.Select( c => new { Name = c.Name, Value = c.Value } )
.OrderBy( (a,b) => a.Name.CompareTo( b.Name ) );
One of the benefits of Delegates is in asynchronous execution.
when you call a method asynchronously you do not know when it will finish executing, so you need to pass a delegate to that method that point to another method that will be called when the first method has completed execution. In the second method you can write some code that inform you the execution has completed.
Technically delegate is a reference type used to encapsulate a method with a specific signature and return type
Some other comments touched on the async world... but I'll comment anyway since my favorite 'flavor' of doing such has been mentioned:
ThreadPool.QueueUserWorkItem(delegate
{
// This code will run on it's own thread!
});
Also, a huge reason for delegates is for "CallBacks". Let's say I make a bit of functionality (asynchronously), and you want me to call some method (let's say "AlertWhenDone")... you could pass in a "delegate" to your method as follows:
TimmysSpecialClass.DoSomethingCool(this.AlertWhenDone);
Outside of their role in events, which your probably familiar with if you've used winforms or asp.net, delegates are useful for making classes more flexible (e.g. the way they're used in LINQ).
Flexibility for "Finding" things is pretty common. You have a collection of things, and you want to provide a way to find things. Rather than guessing each way that someone might want to find things, you can now allow the caller to provide the algorithm so that they can search your collection however they see fit.
Here's a trivial code sample:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Delegates
{
class Program
{
static void Main(string[] args)
{
Collection coll = new Collection(5);
coll[0] = "This";
coll[1] = "is";
coll[2] = "a";
coll[3] = "test";
var result = coll.Find(x => x == "is");
Console.WriteLine(result);
result = coll.Find(x => x.StartsWith("te"));
Console.WriteLine(result);
}
}
public class Collection
{
string[] _Items;
public delegate bool FindDelegate(string FindParam);
public Collection(int Size)
{
_Items = new string[Size];
}
public string this[int i]
{
get { return _Items[i]; }
set { _Items[i] = value; }
}
public string Find(FindDelegate findDelegate)
{
foreach (string s in _Items)
{
if (findDelegate(s))
return s;
}
return null;
}
}
}
Output
is
test
there isn't really anything delgates will solve that can't be solved with other methods, but they provide a more elegant solution.
With delegates, any function can be used as long as it has the required parameters.
The alternative is often to use a kind of custom built event system in the program, creating extra work and more areas for bugs to creep in
Is there an advantage to use a delegate when dealing with external calls to a database?
For example can code A :
static void Main(string[] args) {
DatabaseCode("test");
}
public void DatabaseCode(string arg) {
.... code here ...
}
Be improved in code B :
static void Main(string[] args) {
DatabaseCodeDelegate slave = DatabaseCode;
slave ("test");
}
public void DatabaseCode(string arg) {
.... code here ...
}
public delegate void DatabaseCodeDelegate(string arg);
It seems that this is subjective, but an area where there are strong conflicting view points?