I have a command line application where I want to load some DLLs at some paths outside my application directory. I can successfully do this by adding my own ResolveEventHandler. However, I then get unwanted output in the console like this:
Checking for existing AssemblyResolve handler
Removed existing AssemblyResolve handler
How can I suppress this output?
Here's my current code:
static Assembly LoadPrereq(object sender, ResolveEventArgs args)
{
if (args.Name.StartsWith("DebugDiag.DotNet"))
return Assembly.LoadFile("C:\\Program Files\\DebugDiag\\DebugDiag.DotNet.dll");
return null;
}
...
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(LoadPrereq);
Maybe this might help Console.SetOut(TextWriter)
Sets the Out property to target the TextWriter object.
For which, you could call the following to disable it
Console.SetOut(TextWriter.Null);
You might be able save the original with Console.Out so it can be re-enabled again
Gets the standard output stream.
Note : This is untested, and only found via the documentation
Related
I made a custom Debug.Log using Conditional attribute like this
[Conditional("DEBUG_BUILD"), Conditional("UNITY_EDITOR")]
public static void Print(object str)
{
UnityEngine.Debug.Log(str);
}
And I use it like this
void Something()
{
CustomDebug.Print("Error");
}
But when I click the console, It open the custom log script not the script that caused error.
I wonder if I can make link the console with error script.
It's simply returning the last most call in the stack, which is going to be the code in your custom Debug script.
You can get around this easily by compiling this into it's own assembly though, move your code to a Managed Unity DLL, then it will ignore the DLL level stack trace and only return the location your custom method was called from.
Maybe you can try Application.logMessageReceived to implement your custom debug log.
And you can use UnityEngine.Debug.Log() or MonoBehaviour.print() to record logs. It still can link to the scripts.
I'm trying to write a simple Visual Studio extension that performs an action when a file is saved:
protected override void Initialize()
{
base.Initialize();
var dte = (DTE)GetService(typeof(DTE));
dte.Events.DocumentEvents.DocumentSaved += DocumentEvents_DocumentSaved;
}
void DocumentEvents_DocumentSaved(Document doc)
{
// Do something
}
But apparently the DocumentsSaved event is never raised, so the DocumentEvents_DocumentSaved is not called...
Am I missing something? Isn't this event supposed to be raised every time a file is saved? If not, is there another way I can detect changes to the files in the solution? (I'd rather avoid resorting to a FileSystemWatcher if possible...)
(note: I know that the extension is properly loaded, since a breakpoint in the Initialize method is hit, so the problem is not there)
According to this: http://social.msdn.microsoft.com/Forums/en-US/vsx/thread/0857a868-e650-42ed-b9cc-2975dc46e994
You need to keep a strong reference to both the Events and DocumentEvents objects for it to work.
I have an asp.net application. I want to load some assemblies dynamically.
this is my code on application start
protected void Application_Start(Object sender, EventArgs e)
{
LoadPrivateAssemblies();
}
private static void LoadPrivateAssemblies()
{
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainAssemblyResolve;
Assembly.Load("MyDLL");
}
static Assembly CurrentDomainAssemblyResolve(object sender, ResolveEventArgs args)
{
//loads and returns assembly successfully.
}
this code works fine except when a nested c# code calls a class from my dynamic dll Inside an asp.net page (not code-behind)
sample :
<%if(MyDLL.TestObject.Value){%>white some ting<%}%>
what should I do now ?
I think If I know When a new AppDomain is created, it may solve my problem.
I really think you are barking up the wrong tree here.
Assembly.Load(byte[]) does "persist" the assembly in the app domain - otherwise, what else would it be doing?
To illustrate the fact it does, try this:
Create a solution with one console application, and one class library, named OtherAssembly.
In the class library, OtherAssembly, add a single class:
namespace OtherAssembly
{
public class Class1
{
public string HelloWorld()
{
return "Hello World";
}
}
}
In the console application, use this as your program:
public class Program
{
static void Main(string[] args)
{
try
{
using (var fs = new FileStream("OtherAssembly.dll", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
var buffer = new byte[fs.Length];
// load my assembly into a byte array from disk
fs.Read(buffer, 0, (int) fs.Length);
// load the assembly in the byte array into the current app domain
AppDomain.CurrentDomain.Load(buffer);
}
// get my type from the other assembly that we just loaded
var class1 = Type.GetType("OtherAssembly.Class1, OtherAssembly");
// create an instance of the type
var class1Instance = class1.GetConstructor(Type.EmptyTypes).Invoke(null);
// find and invoke the HelloWorld method.
var hellowWorldMethod = class1.GetMethod("HelloWorld");
Console.WriteLine(hellowWorldMethod.Invoke(class1Instance, null));
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
finally
{
Console.ReadLine();
}
}
}
Don't reference OtherAssembly from your main program assembly, instead, compile the solution and manually drop OtherAssembly.dll in the main program's bin folder.
Run the main program. It outputs "Hello World", which it can only have done if the assembly was loaded and retained in memory. You'll note I've been very careful not to give Visual Studio or C# any hint to load this OtherAssembly. No reference was added, the type is not explicitly referenced in C#.
You need to look again at your problem.
[EDIT: in response to you commenting on the fact this is not an ASP.NET application]
OK - I've moved my main program to an ASP.NET web page and tried accessing the assembly both from code behind and the markup - and it works in both situations. I'm sure you are missing something here - it just doesn't make sense that the behaviour of this method - whose job it is to load an assembly into the current app domain - is different in an ASP.NET scenario.
It seems to me there are at least two things to investigate:
If it really is a new app domain being created on each call, it would only be because of an unhandled exception in your application. The quickest way to diagnose this is to use SysInternals Process Explorer. Fire it up - add .Net -> Total AppDomains to the list of columns and watch the app domain count for your process (IIS worker process or web dev) as you run your app. If this increases on each call, you've got unhandled exceptions tearing down one AppDomain and forcing another to be created.
Are you sure this assembly is really being loaded? When you pass the byte array to Assembly.Load, try also writing it out to disk using FileStream.Write. Open the file in Reflector or some similar tool. Is this the assembly you expected it to be. Is it really being loaded at all, or is it an empty/corrupt array?
I'm not trying to be argumentative, but this really feels like you are looking in the wrong place for the cause of the problem.
I think If I know When a new AppDomain is created, it may solve my problem
You should use AssemblyLoad event. AssemblyResolved occurs when the resolution of assembly is fails
I found that the problem is because Assembly.Load(bytes); does not persist the assembly in appdomain. does any body know how to persist loaded assembly using Assembly.Load(bytes); in appdomain ?
finally I decided to switch to LoadFile method instead of load.
EDIT
Finally I switched from Assemly.Load(byte[]) to Assembly.LoadFile(string).
But it did not correct the problem itself. I have added <%#Assembly name="MyDLL"%> To All of my ASPX files that has markup C# code emebeded.
And This Solved my Problem.
Thanks to your answers. I have voted up answers that helped me, but I can not accept your solutions because no one is not complete enough.
I'm using a method to load a dll on an AssemblyResolve event. It's not quite working the way I want it to. Here's some code:
in my form load:
var a = AppDomain.CurrentDomain;
a.AssemblyResolve += (object sender, ResolveEventArgs args) => LoadDLL(sender, args, anArg);
LoadDLL:
public Assembly LoadDLL(object sender, ResolveEventArgs agrs, bool anArg){
//Let's just ignore anArg, it doesn't affect anything related to the problem
asseblyPath = #"XXX";//path to my dll
return Assembly.LoadFrom(assemblyPath);
}
So that's all well and good. I set Copy Local to false for my DLL so the AssemblyResolve event is called and I can load the desired version of my DLL.
One strange thing that is happening is this: After running this code, my code tries to access a public variable from a class containing global constant values (this class should be in my DLL).
public class GCV{
public GCV(){}
public string value1= "asdf";
}
Unfortunately, when I'm in debug mode, GCV.value1 is set to null when it clearly has a value in the class definition. This is one symptom that I can describe here, hopefully enough to diagnose the problem?
Thanks!
It seems that in debug the version loaded differ from the one it load in release. Try to look in the Output folder when debugging, and look for the Loaded .... to find your dll. This should point to a different version that the one you expect.
I have a function that I want to be sure is compiled JIT (i.e. right before it's called). Are there attributes or assembly settings that will ensure this? If not, then how can I guarantee that a function is compiled JIT?
Thanks!
EDIT:
I want to do this to prevent my application from crashing due to a missing referenced assembly. If my function is compiled JIT, I can wrap the function call that references the missing assembly in a try...catch block and gracefully handle the situation.
It is my understanding that there could be times when whole classes (or even the whole application) could be Jitted - this would cause an error I couldn't possibly catch.
If I read this correctly, you are worried about errors occurring when a class/method is first compiled. This requires awareness of the boundaries. It is obtainable with an extra layer.
If something is 'wrong with SuspectType (ie a required assembly not loading), the try/catch in the following is of no use because the Jitting of Scenario1() itself will fail.
void Scenario1()
{
try
{
var x = new SuspectType();
...
}
catch (..) { ... }
}
It could be rewritten as
void Scenario1a()
{
try
{
Scenario1b();
}
catch (..) { ... }
}
void Scenario1b()
{
var x = new SuspectType();
...
}
But, per Jon Skeet's comment, I'm not sure if this holds for the CFx.
I may be answering the wrong question, but it looks like you mainly want to be able to intercept assembly load failures (whole classes being JITted defeat the try/catch guards around the calls but that's a side effect of using explicit guards around method calls).
If you want to catch assembly resolution woes, instead of specifying a try/catch around every possible call, you could just listen to the global AssemblyResolve event and respond to the assembly loading failures (we're talking about .Net assemblies here, native dll's load failures would have to be tracked with a different mechanism).
static void Main()
{
AppDomain.CurrentDomain.AssemblyResolve += OnResolveFailure;
//...
}
static Assembly OnResolveFailure(object sender, ResolveEventArgs args)
{
//Do something here...
}
The downside of this is you can't do much, except looking for the assembly somewhere else (or logging the error). Specific and graceful logic when a resolution fails is not provided with this way of catching load failures.
Is this something that your app needs to be able to resolve on it's own, or are you debugging some kind of assembly load problem right now?
If the latter, have a look at the fusion log. This is log that is generated by the subsystem that probes for and loads assemblies at run time.
Here's an article: http://www.hanselman.com/blog/BackToBasicsUsingFusionLogViewerToDebugObscureLoaderErrors.aspx