What's the explanation of this behavior in C# - c#

Consider this simple console application:
class Program
{
static void Main(string[] args)
{
var human = CreateHuman(args[0]);
Console.WriteLine("Created Human");
Console.ReadLine();
}
public static object CreateHuman(string association)
{
object human = null;
if (association == "is-a")
{
human = new IsAHuman();
}
else
{
human = new HasAHuman();
}
return human;
}
}
public class IsAHuman : Human
{
}
public class HasAHuman
{
public Human Human { get; set; }
}
The Human class is in another assembly, say HumanAssembly.dll. If HumanAssembly.dll exists in the bin directory of our console app, everything would be fine. And as we might expect, by removing it we encounter FileNotFoundException.
I don't understand this part though. Comment human = new IsAHuman(); line, recompile and remove HumanAssembly.dll. Console app won't throw any exception in this case.
My guess is that CLR compiler differentiates between is a and has a associations. In other words, CLR tries to find out and understand and probably load all the types existing in the class definition statement, but it can instantiate a class without knowing what's inside it. But I'm not sure about my interpretation.
I fail to find a good explanation. What is the explanation for this behavior?

You are seeing the behavior of the JIT compiler. Just In Time. A method doesn't get compiled until the last possible moment, just before it is called. Since you removed the need to actually construct a Human object, there is no code path left that forces the jitter to load the assembly. So your program won't crash.
The last remaining reference to Human is the HashAHuman.Human property. You don't use it.
Predicting when the jitter is going to need to load an assembly is not that straight-forward in practice. It gets pretty difficult to reason through when you run the Release build of your code. That normally enables the optimizer that's built into the jitter, one of its core optimization strategies is to inline a method. To do that, it needs access to the method before it is called. You'd need an extra level of indirection, an extra method that has the [MethodImpl(MethodImplOptions.NoInlining)] attribute to stop it from having a peek. That gets to be a bit off into the deep end, always consider a plug-in architecture first, something like MEF.

Here is great explanation of what you are looking for.
The CLR Loader
Specially in the following lines -
This policy of loading types (and assemblies and modules) on demand means that parts of a program that are not used are never brought into
memory. It also means that a running application will often see new
assemblies and modules loaded over time as the types contained in
those files are needed during execution. If this is not the behavior
you want, you have two options. One is to simply declare hidden static
fields of the types you want to guarantee are loaded when your type is
loaded. The other is to interact with the loader explicitly.
As the Bold line says, if you code does not execute a specific line then the types won't be loaded, even if the code is not commented out.
Here is also a similar answer that you might also be interested in -
How are DLLs loaded by the CLR?

Related

How to quickly debug my code in isolation - internal, developer only, throw-away test

I'm looking for ways to quickly debug the code I've just written to see if it behaves correctly and all my assumptions are correct. I don't want to run the full system yet because parts of infrastructure to get to this code are missing. I use unit testing for it but I find it cumbersome. Is there anything better?
Objectives are:
Debug any code quickly without creating additional projects, applications etc.
Easily repeat debugging.
The test is for this specific purpose, might use fixed file paths, database connections, anything. Typically thrown away after getting things right.
Need to access internal members of my objects.
Accessing private member would be great benefit.
I'm fine with writing test functions directly in my object. Actually this would be preferred.
The dream way of doing it would be:
namespace Aaa
{
class SomeClass
{
public string Name { get; private set; }
public SomeClass(string name, int value)
{
this.Name = name;
InitializeSth();
}
public DoSomethingPublic()
{
// ...
}
private DoSomethingPrivate()
{
// ...
}
public static void TestThis() // <-- debug this
{
var obj = new SomeClass("a", 1); // <-- put breakpoint here
obj.DoSomethingPublic();
obj.DoSomethingPrivate();
}
}
}
This is possible in Java and is such a great thing. This allows for accessing private things too.
But I'm open to other options as well. Is there anything like this in VS2015?
What I have tried so far:
Immediate Window - I don't think it can be configured for such purpose
C# Interactive - this doesn't seem to support debugging. Or does it?
Unit testing - this is what I use now (with MSTest). But I find it very cumbersome, because:
I need to create new projects, or include references to MS testing assemblies
I need to make extra steps to access internal types and members, or change things to public (I don't like this).
Even more steps to access private members.
I mess with other tests if Unit Testing is used in the project.
Starting debugging again needs many clicks instead of sth+sth+F5.
There are some workarounds for some of these items, but in general the testing infrastructure seems to be made for different purposes and I always have a feeling I'm fighting against it.
I also found some information about Resharper having ability to debug any static function. But I don't want to use Resharper, mainly because of performance.
To debug one method without running the whole app, I often use the unit test in VS IDE, since it would not really impact our app's development.
I also got the method using the Resharper tool before: https://blog.jetbrains.com/dotnet/2015/08/28/run-configurations-debug-any-static-method-in-visual-studio-and-more/
In VS IDE, to debug the method directly without debugging/running the app, it really has no better suggestions than unit test project.
Of course, it also has other third party tool if you want to debug code without running the app:
http://www.linqpad.net/
Take a look at this answer: #if DEBUG vs. Conditional(“DEBUG”)
Basically you could use something like the following:
#if DEBUG
public void DoSomething() { }
#endif
public void Foo()
{
#if DEBUG
DoSomething();
#endif
}
Answering my own question - it seems I didn't evaluate Immediate Window enough.
It is possible to invoke any static method either using
Immediate Window (just type TestThis())
Command Window (type ?TestThis() or Debug.EvaluateStatement TestThis())
This even allows to invoke private static methods. The projects will be built before starting the method if they need to be and the method is executed in debugger, so it will stop at any breakpoint.
So summarizing: press Alt+Ctrl+I to get to the Immediate Window, type-in method name with parentheses and press Enter.
There are two disadvantages:
If the method is not in main class (one with Main method), you have to use full namespace and class name, for example MyCompany.MyApp.Logic.SomeClass.TestMethod() to run it
to start debugging again, you have to go to immediate window and recall last command with Up-Arrow, Enter. This is better than right-clicking on a test and selecting "Debug this test", but not optimal.
Please add an answer if you know anything better or some ways to make these two issues better. I looked for quite some time to find a keyboard shortcut to repeat last Immediate Window command, but cannot find one. I don't mark this answer as accepted for now, in case something better is posted.

Process huge amount of data with dynamic code

I want to be able to change the code of my game dynamicly. For example lets say my game is structured this way:
class GameState {
public int SomeData;
public Entity[] EntityPool;
}
interface IServices {
IRenderer Renderer { get; }
}
interface IGameCode {
void RenderAndUpdate(GameState currentState, IServices serviceProvider);
}
I now want be able to write code like this:
void MainLoop() {
IGameCode gameCode = new DefaultGameCode();
while(true) {
// Handle Plattform things
if(shouldUseNewGameCode) {
UnloadCode(gameCode);
gameCode = LoadCode("new.dll");
// or
gameCode = LoadCode("new.cs");
}
// Call GameTick
gameCode.RenderAndUpdate(gameState, services);
}
}
I already used AppDomains and a Proxyclass but it is too slow to serialize every frame. I tried to just pass a pointer but since AppDomains use their own virtual address space i cant access the GameState Object. My other idea was to use Reflection to get the IL from the compiled method via GetMethodBody() and pass it to an DynamicMethod but this would limit the way how I could write the RenderAndUpdate method since I can not use Submethods or Variables in the IGameCode implementation.
So how can I achive what I want to do?
As you've seen, you really don't want to be crossing AppDomain boundaries on every frame, especially if that code has to call back to the main code e.g. IServices a bunch of times. Even with MarshalByRefObject, which can improve things a little, it's going to be too slow. So you need a solution that doesn't involve the AppDomain.
How big is your assembly? How often do you expect to change it?
Noting that .NET assemblies are generally fairly space-efficient, and that in your scenario it seems unlikely a user would switch assemblies more than a few times in a session, I would just read your DLL into memory as a byte[] and then use Assembly.Load(byte[]); to load it.
Alternatively, if you really can't tolerate a dead assembly in your process memory space, I think it would be better to use a helper process, aka "launcher": when you want to switch implementations, start up the helper process (or just leave it running all the time if you want), which in turn will wait for the current game process to exit, and then will start a new one with the new settings.
This will be slower to switch, but of course is a one-time cost for each switch and then the program can run full-speed during the actual gameplay.

MonoTouch mysteriously not aot-compiling methods and properties?

I have a strange problem where MonoTouch seems to be either not compiling methods or not able to find a compiled method it is instructed to call, and only on the device in the Release configuration - Debug builds are fine. I've tried reproducing it with a simpler code sample with no luck, so I doubt you will be able to see the behavior with the code below. But this is essentially what I'm doing:
using System;
using MonoTouch.UIKit;
public class MyClass
{
private UINavigationController _navController;
private UIViewControler _viewController;
public UINavigationController NavController
{
get
{
if (_navController == null)
{
if (_viewController == null)
{
_viewController = new UIViewController();
}
_navController = new UINavigationController(_viewController);
}
return _navController;
}
}
}
Then, in some other method...
public void SomeMethod()
{
MyClass myClass = new MyClass();
var navController = myClass.NavController; // <-- This is where it throws
}
The exception I get is the standard JIT compile message, saying that it attempted to JIT get_NavController(). I find this very strange, because there's no virtual generics, no LINQ, the linker is off, and nothing else that normally causes JITs seems to be involved. I've also verified that it will throw for other methods and properties defined on MyClass, but not the constructor or System.Object inherited methods. Reflection reveals that myClass.GetType().GetMembers() has a MemberInfo for everything I would expect. Yet, only for Release|iPhone, I can't access these methods or properties. The only logical conclusion I can come to is that the aot compilation step is missing them, and I don't know why that would happen at all, let alone only in the Release configuration.
My question is, what could be causing such a situation, and what is the next step to fixing it? I'm not even sure where to go from here on debugging this, or what to file a bug about, because I can't reproduce it out of the context of our (much) larger project.
Update: The exact exception text was requested.
System.ExecutionException: Attempting to JIT compile method
'MyNamespace.MyClass.get_NavController ()' while running with --aot-only
This doesn't look like something that can be solved here.
I suggest filing a bug, and attach the entire project if you're unable to make a smaller test case. You can file private bugs only Xamarin employees have access to if you don't want your project to be publicly visible.
Could you try to explicitly declare the variable
UINavigationController navController = myClass.NavController;
Alternatively, I wonder if this is at all associated with needing to wait for the UIViewController.ViewDidLoad method to be called as the internals of the class may not yet have been initialized?
Just shots in the dark here, I can't think of a reason why your code wouldn't work.

How to enforce the use of a method's return value in C#?

I have a piece of software written with fluent syntax. The method chain has a definitive "ending", before which nothing useful is actually done in the code (think NBuilder, or Linq-to-SQL's query generation not actually hitting the database until we iterate over our objects with, say, ToList()).
The problem I am having is there is confusion among other developers about proper usage of the code. They are neglecting to call the "ending" method (thus never actually "doing anything")!
I am interested in enforcing the usage of the return value of some of my methods so that we can never "end the chain" without calling that "Finalize()" or "Save()" method that actually does the work.
Consider the following code:
//The "factory" class the user will be dealing with
public class FluentClass
{
//The entry point for this software
public IntermediateClass<T> Init<T>()
{
return new IntermediateClass<T>();
}
}
//The class that actually does the work
public class IntermediateClass<T>
{
private List<T> _values;
//The user cannot call this constructor
internal IntermediateClass<T>()
{
_values = new List<T>();
}
//Once generated, they can call "setup" methods such as this
public IntermediateClass<T> With(T value)
{
var instance = new IntermediateClass<T>() { _values = _values };
instance._values.Add(value);
return instance;
}
//Picture "lazy loading" - you have to call this method to
//actually do anything worthwhile
public void Save()
{
var itemCount = _values.Count();
. . . //save to database, write a log, do some real work
}
}
As you can see, proper usage of this code would be something like:
new FluentClass().Init<int>().With(-1).With(300).With(42).Save();
The problem is that people are using it this way (thinking it achieves the same as the above):
new FluentClass().Init<int>().With(-1).With(300).With(42);
So pervasive is this problem that, with entirely good intentions, another developer once actually changed the name of the "Init" method to indicate that THAT method was doing the "real work" of the software.
Logic errors like these are very difficult to spot, and, of course, it compiles, because it is perfectly acceptable to call a method with a return value and just "pretend" it returns void. Visual Studio doesn't care if you do this; your software will still compile and run (although in some cases I believe it throws a warning). This is a great feature to have, of course. Imagine a simple "InsertToDatabase" method that returns the ID of the new row as an integer - it is easy to see that there are some cases where we need that ID, and some cases where we could do without it.
In the case of this piece of software, there is definitively never any reason to eschew that "Save" function at the end of the method chain. It is a very specialized utility, and the only gain comes from the final step.
I want somebody's software to fail at the compiler level if they call "With()" and not "Save()".
It seems like an impossible task by traditional means - but that's why I come to you guys. Is there an Attribute I can use to prevent a method from being "cast to void" or some such?
Note: The alternate way of achieving this goal that has already been suggested to me is writing a suite of unit tests to enforce this rule, and using something like http://www.testdriven.net to bind them to the compiler. This is an acceptable solution, but I am hoping for something more elegant.
I don't know of a way to enforce this at a compiler level. It's often requested for objects which implement IDisposable as well, but isn't really enforceable.
One potential option which can help, however, is to set up your class, in DEBUG only, to have a finalizer that logs/throws/etc. if Save() was never called. This can help you discover these runtime problems while debugging instead of relying on searching the code, etc.
However, make sure that, in release mode, this is not used, as it will incur a performance overhead since the addition of an unnecessary finalizer is very bad on GC performance.
You could require specific methods to use a callback like so:
new FluentClass().Init<int>(x =>
{
x.Save(y =>
{
y.With(-1),
y.With(300)
});
});
The with method returns some specific object, and the only way to get that object is by calling x.Save(), which itself has a callback that lets you set up your indeterminate number of with statements. So the init takes something like this:
public T Init<T>(Func<MyInitInputType, MySaveResultType> initSetup)
I can think of three a few solutions, not ideal.
AIUI what you want is a function which is called when the temporary variable goes out of scope (as in, when it becomes available for garbage collection, but will probably not be garbage collected for some time yet). (See: The difference between a destructor and a finalizer?) This hypothetical function would say "if you've constructed a query in this object but not called save, produce an error". C++/CLI calls this RAII, and in C++/CLI there is a concept of a "destructor" when the object isn't used any more, and a "finaliser" which is called when it's finally garbage collected. Very confusingly, C# has only a so-called destructor, but this is only called by the garbage collector (it would be valid for the framework to call it earlier, as if it were partially cleaning the object immediately, but AFAIK it doesn't do anything like that). So what you would like is a C++/CLI destructor. Unfortunately, AIUI this maps onto the concept of IDisposable, which exposes a dispose() method which can be called when a C++/CLI destructor would be called, or when the C# destructor is called -- but AIUI you still have to call "dispose" manually, which defeats the point?
Refactor the interface slightly to convey the concept more accurately. Call the init function something like "prepareQuery" or "AAA" or "initRememberToCallSaveOrThisWontDoAnything". (The last is an exaggeration, but it might be necessary to make the point).
This is more of a social problem than a technical problem. The interface should make it easy to do the right thing, but programmers do have to know how to use code! Get all the programmers together. Explain simply once-and-for-all this simple fact. If necessary have them all sign a piece of paper saying they understand, and if they wilfully continue to write code which doesn't do anythign they're worse than useless to the company and will be fired.
Fiddle with the way the operators are chained, eg. have each of the intermediateClass functions assemble an aggregate intermediateclass object containing all of the parameters (you mostly do it this was already (?)) but require an init-like function of the original class to take that as an argument, rather than have them chained after it, and then you can have save and the other functions return two different class types (with essentially the same contents), and have init only accept a class of the correct type.
The fact that it's still a problem suggests that either your coworkers need a helpful reminder, or they're rather sub-par, or the interface wasn't very clear (perhaps its perfectly good, but the author didn't realise it wouldn't be clear if you only used it in passing rather than getting to know it), or you yourself have misunderstood the situation. A technical solution would be good, but you should probably think about why the problem occurred and how to communicate more clearly, probably asking someone senior's input.
After great deliberation and trial and error, it turns out that throwing an exception from the Finalize() method was not going to work for me. Apparently, you simply can't do that; the exception gets eaten up, because garbage collection operates non-deterministically. I was unable to get the software to call Dispose() automatically from the destructor either. Jack V.'s comment explains this well; here was the link he posted, for redundancy/emphasis:
The difference between a destructor and a finalizer?
Changing the syntax to use a callback was a clever way to make the behavior foolproof, but the agreed-upon syntax was fixed, and I had to work with it. Our company is all about fluent method chains. I was also a fan of the "out parameter" solution to be honest, but again, the bottom line is the method signatures simply could not change.
Helpful information about my particular problem includes the fact that my software is only ever to be run as part of a suite of unit tests - so efficiency is not a problem.
What I ended up doing was use Mono.Cecil to Reflect upon the Calling Assembly (the code calling into my software). Note that System.Reflection was insufficient for my purposes, because it cannot pinpoint method references, but I still needed(?) to use it to get the "calling assembly" itself (Mono.Cecil remains underdocumented, so it's possible I just need to get more familiar with it in order to do away with System.Reflection altogether; that remains to be seen....)
I placed the Mono.Cecil code in the Init() method, and the structure now looks something like:
public IntermediateClass<T> Init<T>()
{
ValidateUsage(Assembly.GetCallingAssembly());
return new IntermediateClass<T>();
}
void ValidateUsage(Assembly assembly)
{
// 1) Use Mono.Cecil to inspect the codebase inside the assembly
var assemblyLocation = assembly.CodeBase.Replace("file:///", "");
var monoCecilAssembly = AssemblyFactory.GetAssembly(assemblyLocation);
// 2) Retrieve the list of Instructions in the calling method
var methods = monoCecilAssembly.Modules...Types...Methods...Instructions
// (It's a little more complicated than that...
// if anybody would like more specific information on how I got this,
// let me know... I just didn't want to clutter up this post)
// 3) Those instructions refer to OpCodes and Operands....
// Defining "invalid method" as a method that calls "Init" but not "Save"
var methodCallingInit = method.Body.Instructions.Any
(instruction => instruction.OpCode.Name.Equals("callvirt")
&& instruction.Operand is IMethodReference
&& instruction.Operand.ToString.Equals(INITMETHODSIGNATURE);
var methodNotCallingSave = !method.Body.Instructions.Any
(instruction => instruction.OpCode.Name.Equals("callvirt")
&& instruction.Operand is IMethodReference
&& instruction.Operand.ToString.Equals(SAVEMETHODSIGNATURE);
var methodInvalid = methodCallingInit && methodNotCallingSave;
// Note: this is partially pseudocode;
// It doesn't 100% faithfully represent either Mono.Cecil's syntax or my own
// There are actually a lot of annoying casts involved, omitted for sanity
// 4) Obviously, if the method is invalid, throw
if (methodInvalid)
{
throw new Exception(String.Format("Bad developer! BAD! {0}", method.Name));
}
}
Trust me, the actual code is even uglier looking than my pseudocode.... :-)
But Mono.Cecil just might be my new favorite toy.
I now have a method that refuses to be run its main body unless the calling code "promises" to also call a second method afterwards. It's like a strange kind of code contract. I'm actually thinking about making this generic and reusable. Would any of you have a use for such a thing? Say, if it were an attribute?
What if you made it so Init and With don't return objects of type FluentClass? Have them return, e.g., UninitializedFluentClass which wraps a FluentClass object. Then calling .Save(0 on the UnitializedFluentClass object calls it on the wrapped FluentClass object and returns it. If they don't call Save they don't get a FluentClass object.
In Debug mode beside implementing IDisposable you can setup a timer that will throw a exception after 1 second if the resultmethod has not been called.
Use an out parameter! All the outs must be used.
Edit: I am not sure of it will help, tho...
It would break the fluent syntax.

A product release changes its library name, how to be compatible with old and new?

We have a product that uses a Reference from a 3rd party supplier. With the release of their new product they have renamed this Reference to a new name.
What we want to do is have the one version of our application compiled so that it can run against both the old and new names of the library.
There is basically no change, only 1 method rename, between the parts of the library we use, but I have no idea how to develop our application to handle both.
If I have to we can branch the code to work with both, but I'd really like to have some sort of adapter that all calls go through that then dispatches to either the old or new.
Once I install the new application, it removes the old library, so the old code won't compile.
Any pointers on what I can try or how I can work around this issue?
Also, the application is developed in C# using Visual Studio 2005.
Look at Assembly Binding Redirection... You can redirect the old DLL references to the new one. You will need to write a wrapper method for the renamed method.. That's a real pain in the butt. I'm gonna spitball this off the top of my head, so I don't guarantee name accuracy or compilability, but you can consider it pseudo code...
private bool _useOldMethodName = false;
public void MethodAlias(string arg1)
{
if (_useOldMethodName)
{
Reference.OldFunctionName(arg1);
}
else
{
try
{
Reference.NewFunctionName(arg1);
}
catch (MethodNotFoundException mnfe)
{
_useOldMethodName = true;
}
}
}
Something like that. It's not ideal in any case.
I am curious, why can't you just always use the new reference? Just distribute the new reference DLL with your code, and you'll never have an issue...
I would suggest you the following steps:
Refactor your code to isolate the call to the library by having your own class which inherits from the library (no own methods for now - just one single place of change)
Use Reflection inside this single class to find out which of the two method is available. Cache the actual method to avoid a performance penalty when you call the library very frequently. The actual reflection will look like this:
Type type = Type.GetType(alien);
MemberInfo[] mbrInfoArray=type.GetMethods();
The method will be called using Invoke.

Categories