C# | Catch exception from a dynamically loaded dll - c#-4.0

I'm trying to write a C# (WPF - not that it matters in that context) application that loads a DLL dynamically using this code:
private Assembly GetAssembly(string assemblyPath)
{
AssemblyName assemblyName = AssemblyName.GetAssemblyName(assemblyPath);
return AppDomain.CurrentDomain.Load(assemblyName);
}
Loading the dll works fine and also using it works.
The problem is - when I try catching an exception when calling a function on that dynamically loaded DLL it is not caught in my application
Note: The dynamically loaded dll was also written by me so I know for a fact that an exception occurs
The try/catch section looks like that
try
{
result = aseInstance.Compile();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
I also tried using the following code:
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
but didn't help..
One more thing that might be worth mentioning - useInstance is a dynamic
I don't want my code to have to "know" which class it is loading so I'm using dynamic
If i do the same using references everything works and the exception is caught
I'd love some help here!
Thanks

Related

Loaded SWF's wont preform their functions in air

Back for some help! So I am making an AIR application that loads SWF's into a container to be viewed by the user. However when I load the files into their containers, the SWF's that are loaded are unable to execute their own code. IE press an invisible button on the loaded SWF and it changes colour. I tried to google solutions for this since Security.allowDomain("*"); is throwing this error in flash. However from what I have read, AIR doesn't allow loaded swfs to execute code for some security reason but im not 100% sure on that either.
SecurityError: Error #3207: Application-sandbox content cannot access this feature.
at flash.system::Security$/allowDomain()
at BugFree()[D:\Desktop\BugFree\BugFree.as:72]
Without the Allow domain it throws this security error when attempting to click the invisible button.
*** Security Sandbox Violation ***
SecurityDomain 'file:///D:/Desktop/Rewritten Tester/TechDemoSwordNew.swf'
tried to access incompatible context 'app:/BugFree.swf'
*** Security Sandbox Violation ***
SecurityDomain 'file:///D:/Desktop/Rewritten Tester/TechDemoSwordNew.swf'
tried to access incompatible context 'app:/BugFree.swf'
SecurityError: Error #2047: Security sandbox violation: parent:
file:///D:/Desktop/Rewritten Tester/TechDemoSwordNew.swf cannot access
app:/BugFree.swf.
at flash.display::DisplayObject/get parent()
at TechDemoSwordNew_fla::Button_Play_21/onButtonPress()
This only shows in the Animate output bar. When I publish it, with application with runtime embeded, and open the exe it throws no errors but the invisible button still doesnt work.
Here is the code for the swf being loaded.
btnButton.addEventListener(MouseEvent.CLICK, onButtonPress, false, 0, true);
function onButtonPress(event:MouseEvent):void
{
MovieClip(parent).play();
}
stop();
This is timeline code within the button since that is how the game company who put my item in game did it. I originally submitted it with it all done in classes but that is besides the point. When the button is pressed the loaded SWF should play and then stop. But I get the above mentioned Sandbox violation.
The code used to load the SWF is below
public function WeaponLoad()
{
if(FileMenu.WeaponFileTxt.text != "")
{
LoadWeapon(FileMenu.WeaponFile.nativePath);
}
else if(FileMenu.WeaponFileTxt.text == "")
{
Character.mcChar.weapon.removeChildAt(0);
Character.mcChar.weaponOff.removeChildAt(0);
}
}
public function LoadWeapon(strFilePath: String)
{
WeaponLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, CompleteWeaponLoad);
WeaponLoader.load(new URLRequest(strFilePath), new LoaderContext(false, new ApplicationDomain(ApplicationDomain.currentDomain)));
}
public function CompleteWeaponLoad(e: Event)
{
var WeaponClass: Class;
if (MiscMenu.WeaponSelect.MainClick.currentFrame != 3)
{
try
{
trace("WeaponOff");
WeaponClass = WeaponLoader.contentLoaderInfo.applicationDomain.getDefinition(FileMenu.WeaponLinkTxt.text) as Class;
this.Character.mcChar.weapon.removeChildAt(0);
this.Character.mcChar.weaponOff.removeChildAt(0);
this.Character.mcChar.weapon.addChild(new(WeaponClass)());
}
catch (err: Error)
{
trace("Either the weapon class doesnt exist or it is wrong");
this.Character.mcChar.weapon.removeChildAt(0);
this.Character.mcChar.weaponOff.removeChildAt(0);
}
}
else if (MiscMenu.WeaponSelect.MainClick.currentFrame == 3)
{
try
{
WeaponClass = WeaponLoader.contentLoaderInfo.applicationDomain.getDefinition(FileMenu.WeaponLinkTxt.text) as Class;
this.Character.mcChar.weapon.removeChildAt(0);
this.Character.mcChar.weaponOff.removeChildAt(0);
this.Character.mcChar.weapon.addChild(new(WeaponClass)());
this.Character.mcChar.weaponOff.addChild(new(WeaponClass)());
}
catch (err: Error)
{
trace("Either the weapon class doesnt exist or it is wrong");
this.Character.mcChar.weapon.removeChildAt(0);
this.Character.mcChar.weaponOff.removeChildAt(0);
}
}
}
Any help would be apreciated since I have no idea how to change any security sandbox settings within the publish settings since it is greyed out for me. Like I said I tried googling it but I couldn't seem to come up with any answers. Also worth noting is im a self taught novice and I do not know a lot of things in regards to AS3. I know my codes could be cleaner and I plan to clean it up and properly reduce memory consumption once I have the base program up and running. Thank you for the help!
It seems that you're not setting the application domain properly. Here is the code included in as3 documentation:
var loader:Loader = new Loader();
var url:URLRequest = new URLRequest("[file path].swf");
var loaderContext:LoaderContext = new LoaderContext(false, ApplicationDomain.currentDomain, null);
loader.load(url, loaderContext);
Use it in your LoadWeapon function.
In the meantime try not to use Uppercase letters for starting variables and method names. In ActionScript names starting with Uppercase represent Class names. It will widely improve readability of your code.
Can't you bundle your swfs with the AIR app and use File class to load them? If you want to use classes from the swfs, maybe consider making swc library?

WPF Designer throws error when string resources are used in code behind

I have a wpf custom control (in AssemblyA) that references a string resource from an resx file in an external assembly (AssemblyB).
public override void OnApplyTemplate()
{
try
{
base.OnApplyTemplate();
// ...
// Do Stuff
// ...
}
catch (Exception ex)
{
Logger.Error(ExceptionCodes.Ex50000, ex);
}
}
When I add the custom control (in AssemblyA) via a dll reference to a page in another project (AssemblyC) in another solution, the control fails to display in the designer. Instead, the designer displays a nice big red cross with the message
FileNotFoundException: Could not load file or assembly 'AssemblyB'.
The AssemblyB was also added as a dll reference to AssemblyC.
Removing the the references to the string resource in AssemblyA removes the error and allows the control to display correctly in the designer. Unfortunately, this is not an option as the string resources are used throughout the application for support reasons.
Creating an resx file in AssemblyA also removes the error but decentralises the resources which is not an option for on going development.
Based on the above, the designer is obviously not loading the resource assembly. Any insights would be appreciated.
To Summarise
CustomControl in Assembly A in Solution 1 references a string resourced from a resx file in Assembly B in Solution 1. Assembly C in Solution 2 has a dll reference to both Assembly A and Assembly B. A UserControl in Assembly C uses CustomControl in Assembly A. The Visual Studio WPF designer throws a FileNotFound exception when displaying the UserControl.
Let it throw error, just check whether your are able to complie and run, the Make the assembly In Solution C as exe and try to run it. Because with Visual studio 10.0.4, i have see that exception many times, but if it is complied it doesn't give any compiler error, just try to compile and run it

Thread.Sleep causes exception in JMeter when using socket.io-java-client library in AbstractJavaSamplerClient custom code

I implemented a custom AbstractJavaSamplerClient for JMeter, and the core runTest is like:
SampleResult results = new SampleResult();
results.sampleStart();
client.request("connector.ninjaHandler.savemove", opMsg, this);
while(optcode == null){
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
results.sampleEnd();
results.setSuccessful(optcode);
However, I found Thread.sleep() will cause such exception:
Uncaught Exception java.lang.IllegalStateException: Timer already cancelled.. See log file for details.
I googled around and people say thread.sleep will cause the timer failed. However, I cannot avoid it since I'm testing a web-socket server, which means I need to wait the server response back...(It runs OK if I delete the thread.sleep between sample start/end)
However, the sample test org.apache.jmeter.protocol.java.test.SleepTest works well, which use the thread.sleep.
Any suggestions?
It is quite ridiculous since I found the problem comes from the library that I use...
After fix the patch from here, it works!

Switch to a Visual Design from another Visual Design

I'm working in java me. I created two visual designs, First.java and Second.java both of which contains form displayables.
I added an Ok command to a form in First.Java and the user is expected to switch to SecondForm in Second.java but I get this error non-static method getSecondForm() cannot be referenced from a static context.
How can I fix this?
Both files are in the same package. Here's the source code
public void commandAction (Command command, Displayable displayable) {
if (displayable == firstForm) {
if (command == exitCommand) {
exitMIDlet();
} else if (command == okCommand) {
switchDisplayable(null, Second.getSecondForm());
}
}
}
You need to change declaration of the method getSecondForm in Second.java to make it static.
If it currently looks like
Displayable getSecondForm() //... whatever code is there
then after change it should look like
static Displayable getSecondForm() //... whatever code is there
Note above change will fix the non-static method getSecondForm... error you mentioned but there is a chance that it will cause new compilation errors in file Second.java. You will need to fix these new errors, most likely by adding couple static keywords here and there, similar to how it is shown above.
Note this is java language basic stuff; if you get stuck fixing this, consider taking a break to study some tutorial for beginners.

Possible C# 4.0 compiler error, can others verify?

Since I don't know exactly what part of it alone that triggers the error, I'm not entirely sure how to better label it.
This question is a by-product of the SO question c# code seems to get optimized in an invalid way such that an object value becomes null, which I attempted to help Gary with yesterday evening. He was the one that found out that there was a problem, I've just reduced the problem to a simpler project, and want verification before I go further with it, hence this question here.
I'll post a note on Microsoft Connect if others can verify that they too get this problem, and of course I hope that either Jon, Mads or Eric will take a look at it as well :)
It involves:
3 projects, 2 of which are class libraries, one of which is a console program (this last one isn't needed to reproduce the problem, but just executing this shows the problem, whereas you need to use reflector and look at the compiled code if you don't add it)
Incomplete references and type inference
Generics
The code is available here: code repository.
I'll post a description below of how to make the projects if you rather want to get your hands dirty.
The problem exhibits itself by producing an invalid cast in a method call, before returning a simple generic list, casting it to something strange before returning it. The original code ended up with a cast to a boolean, yes, a boolean. The compiler added a cast from a List<SomeEntityObject> to a boolean, before returning the result, and the method signature said that it would return a List<SomeEntityObject>. This in turn leads to odd problems at runtime, everything from the result of the method call being considered "optimized away" (the original question), or a crash with either BadImageFormatException or InvalidProgramException or one of the similar exceptions.
During my work to reproduce this, I've seen a cast to void[], and the current version of my code now casts to a TypedReference. In one case, Reflector crashes so most likely the code was beyond hope in that case. Your mileage might vary.
Here's what to do to reproduce it:
Note: There is likely that there are more minimal forms that will reproduce the problem, but moving all the code to just one project made it go away. Removing the generics from the classes also makes the problem go away. The code below reproduces the problem each time for me, so I'm leaving it as is.
I apologize for the escaped html characters in the code below, this is Markdown playing a trick on me, if anyone knows how I can rectify it, please let me know, or just edit the question
Create a new Visual Studio 2010 solution containing a console application, for .NET 4.0
Add two new projects, both class libraries, also .NET 4.0 (I'm going to assume they're named ClassLibrary1 and ClassLibrary2)
Adjust all the projects to use the full .NET 4.0 runtime, not just the client profile
Add a reference in the console project to ClassLibrary2
Add a reference in ClassLibrary2 to ClassLibrary 1
Remove the two Class1.cs files that was added by default to the class libraries
In ClassLibrary1, add a reference to System.Runtime.Caching
Add a new file to ClassLibrary1, call it DummyCache.cs, and paste in the following code:
using System;
using System.Collections.Generic;
using System.Runtime.Caching;
namespace ClassLibrary1
{
public class DummyCache<TModel> where TModel : new()
{
public void TriggerMethod<T>()
{
}
// Try commenting this out, note that it is never called!
public void TriggerMethod<T>(T value, CacheItemPolicy policy)
{
}
public CacheItemPolicy GetDefaultCacheItemPolicy()
{
return null;
}
public CacheItemPolicy GetDefaultCacheItemPolicy(IEnumerable<string> dependentKeys, bool createInsertDependency = false)
{
return null;
}
}
}
Add a new file to ClassLibrary2, call it Dummy.cs and paste in the following code:
using System;
using System.Collections.Generic;
using ClassLibrary1;
namespace ClassLibrary2
{
public class Dummy
{
private DummyCache<Dummy> Cache { get; set; }
public void TryCommentingMeOut()
{
Cache.TriggerMethod<Dummy>();
}
public List<Dummy> GetDummies()
{
var policy = Cache.GetDefaultCacheItemPolicy();
return new List<Dummy>();
}
}
}
Paste in the following code in Program.cs in the console project:
using System;
using System.Collections.Generic;
using ClassLibrary2;
namespace ConsoleApplication23
{
class Program
{
static void Main(string[] args)
{
Dummy dummy = new Dummy();
// This will crash with InvalidProgramException
// or BadImageFormatException, or a similar exception
List<Dummy> dummies = dummy.GetDummies();
}
}
}
Build, and ensure there are no compiler errors
Now try running the program. This should crash with one of the more horrible exceptions. I've seen both InvalidProgramException and BadImageFormatException, depending on what the cast ended up as
Look at the generated code of Dummy.GetDummies in Reflector. The source code looks like this:
public List<Dummy> GetDummies()
{
var policy = Cache.GetDefaultCacheItemPolicy();
return new List<Dummy>();
}
however reflector says (for me, it might differ in which cast it chose for you, and in one case Reflector even crashed):
public List<Dummy> GetDummies()
{
List<Dummy> policy = (List<Dummy>)this.Cache.GetDefaultCacheItemPolicy();
TypedReference CS$1$0000 = (TypedReference) new List<Dummy>();
return (List<Dummy>) CS$1$0000;
}
Now, here's a couple of odd things, the above crash/invalid code aside:
Library2, which has Dummy.GetDummies, performs a call to get the default cache policy on the class from Library1. It uses type inference var policy = ..., and the result is an CacheItemPolicy object (null in the code, but type is important).
However, ClassLibrary2 does not have a reference to System.Runtime.Caching, so it should not compile.
And indeed, if you comment out the method in Dummy that is named TryCommentingMeOut, you get:
The type 'System.Runtime.Caching.CacheItemPolicy' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime.Caching, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.
Why having this method present makes the compiler happy I don't know, and I don't even know if this is linked to the current problem or not. Perhaps it is a second bug.
There is a similar method in DummyCache, if you restore the method in Dummy, so that the code again compiles, and then comment out the method in DummyCache that has the "Try commenting this out" comment above it, you get the same compiler error
OK, I downloaded your code and can confirm the problem as described.
I have not done any extensive tinkering with this, but when I run & reflector a Release build all seems OK (= null ref exception and clean disassembly).
Reflector (6.10.11) crashed on the Debug builds.
One more experiment: I wondered about the use of CacheItemPolicies so I replaced it with my own MyCacheItemPolicy (in a 3rd classlib) and the same BadImageFormat exception pops up.
The exception mentions : {"Bad binary signature. (Exception from HRESULT: 0x80131192)"}

Resources