Getting object reference error on a base.Method() in release mode - c#

I'm using Eyeshot 12 to render a 3D Model for my app. The model works fine in debug mode, but throws an object reference error if I try to zoom in on the model using the mouse wheel in release mode.
This is my model so far (using try-catch to stop the app from crashing suddenly):
public class Model3D : devDept.Eyeshot.Model
{
protected override void OnMouseWheel(MouseWheelEventArgs e)
{
try
{
base.OnMouseWheel(e);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
The error is this:
Object reference not set to an instance of an object
What can I do to fix this problem?

I've come across this before when you can't instantiate, use a Nullable type or etc, and this is difficult because its a bug with the 3rd party product. Can you try if (base.GetType() == typeof(BaseClass))
Since GetType is a method of object (the core reference type) its always available, regardless of whether the derived object has been instantiated or not.

I didn't find out what was causing the error, but I fixed it by overriding OnMouseWheel and writing my own logic, like this:
public class Model3D : devDept.Eyeshot.Model
{
protected override void OnMouseWheel(MouseWheelEventArgs e)
{
ZoomCamera(new System.Drawing.Point((int)e.GetPosition(this).X, (int)e.GetPosition(this).Y), e.Delta, false);
Invalidate();
}
}

Related

How to create a form in C# ONLY if a referenced DLL exists

I developed a Winforms C# application in which there's one single form that requires a referenced dll to work. All the other application forms (including the main one) don't need it. I want to be able to check at program start if the referenced DLL exists, and create/load that specific form only if that is true. How could I do that? In its current state, my application crashes while starting if the dll doesnt exist.
Thanks
Unlike native imports, C# does all loading of dependent assemblies dynamically. It's still possible to have a dependency failure crash the program before any user code is executed, but it is very rare.
In order to call your Main function (usually in Program.cs), the runtime must resolve all types used for class members, as well as types used by Main(string[] args) itself. Types used by a function called from Main (such as your Form constructor) won't be loaded until Main begins executing and reaches that function.
In almost all cases, the exception related to loading the DLL will appear as an InnerException property on a TypeLoadException. Break in the debugger when the TypeLoadException happens, and check the call stack. That will let you know where to add a try/catch... and if it really does happen "while starting", it should tell you what class you need to avoid using inside Program.cs (or wherever your Main lives, if you've moved it)
The TypeLoadException can be caught, and if you do so, there's no hope of using the function that failed to compile, but you can still use your other classes, and even other methods in the same class as the function that couldn't compile. You don't have to play any tricks with explicit loading or assemblies.
Here is an illustration of usage which will cause either the whole class to fail to load (EarlyDependency) or allow the entire class to be usable except for MethodA (LateDependency):
class ClassA : EarlyDependency, IComparable<EarlyDependency>
{
EarlyDependency field;
property EarlyDependency PropertyA { get; set; }
int initialized = new EarlyDependency().Calculate();
int initializedB = LateDependency.LiteralConstant;
static ClassA
{
EarlyDependency localInStaticConstructor;
}
public ClassA()
{
EarlyDependency localInInstanceConstructor;
if (new Random().NextDouble() < .000001) {
try {
// you can't catch inside the function that fails to compile
// because code inside that function can't ever run
UsedByConstructor();
}
catch (TypeLoadException)
{
}
}
}
public EarlyDependency MethodWithReturnType();
public static EarlyDependency StaticMethodWithReturnType();
public void MethodWithParameter(EarlyDependency parameter);
public void UseIt()
{
LateDependency localInNonSpecialMethod;
}
public void Safe()
{
try {
// you can't catch inside the function that fails to compile
// because code inside that function can't ever run
UseIt();
}
catch (TypeLoadException)
{
}
}
public static void UseItSomeMore()
{
LateDependency localInStaticMethod;
}
private void UsedByConstructor()
{
LateDependency localInMethodNamedInConstructor;
}
}
You're going to need to ensure that the referenced DLL exists and then dynamically load a separate assembly that contains the form you want to show. If you try to load the assembly normally then you app will crash in the way you've described.
Try something like this:
if (File.Exists("Referenced.dll")
{
var assembly = Assembly.LoadFile("AssemblyContainingFormThatReferencesReferenced.dll");
var type = assembly.GetType("TheForm");
var form = Activator.CreateInstance(type) as Form;
form.ShowDialog();
}
You could check if the file exists, and if it does, then create/load your form.
if(File.Exists("myLibrary.dll")
{
MyForm frm = new MyForm();
frm.ShowDialog();
}
Of course, you'll have to make sure that you are looking in the proper path.

How can i use simple aspect oriented concept to handle exception handling without postsharp?

i want to use AOP to handle my error exception in Console application. ( it is not MVC i used attribute vase programing to handle errors in mvc but this is console app) My code below: ( if error occurs ,it should throw an error yo my attribute side code )
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
public class HandleError : Attribute
{
public HandleError(string description)
{
try
{
this.Description = description;
}
catch (Exception)
{
throw;
}
}
public string Description { get; set; }
}
this will call from my method :
[HandleError("Error occurs here")]
public static void MyMethod(string data)
{
throw new Exception();
Actually; i want to use AOP to handle exceptions inside my method. i have to call attributes if it error occurs. But How? ( please don't offer postsharp, it needs money. but i am open for opensource also)By the way; why it is not easy ,i don't understand.
Basically, what PostSharp does is to weave code into your assembly at compile time that is run before and after the methods that are marked with the attributes. This is very good from a performance point of view because there is no use of code that is created dynamically at runtime.
Some other AOP frameworks (or IoC containers) offer the option to generate dynamic proxies that contain code that intercepts the calls to the methods at runtime.
Either you use one of those frameworks (look for IoC and interception) or you implement a comparable functionality by yourself. Basically what you have to do is to move the code you want to intercept into a class and mark the methods as virtual. At runtime, you decorate the instance of the class with a dynamically created class that inherits from your class and overrides the methods so that the additional code is run before and after the call to the method.
However, there might be a simpler approach that fits the needs of a console application. Instead of marking the methods with an attribute, you could also create some helper functions that contain the code that you want to run before and after the method:
void Main()
{
int value = GetValue(123);
DoSomething(value);
}
void DoSomething(int myParam)
{
RunAndLogError(() => {
// Place code here
Console.WriteLine(myParam);
});
}
int GetValue(int myParam)
{
return RunAndLogError(() => {
// Place code here
return myParam * 2;});
}
void RunAndLogError(Action act)
{
try
{
act();
}
catch(Exception ex)
{
// Log error
throw;
}
}
T RunAndLogError<T>(Func<T> fct)
{
try
{
return fct();
}
catch(Exception ex)
{
// Log error
throw;
}
}
As you can see, there are two overloads of RunAndLogError, one for void methods, the other one for methods that return a value.
Another option is to use a global exception handler for this purpose; see this answer for details: .NET Global exception handler in console application

How to properly write a custom UncaughtExceptionHandler in Xamarin.Android

All I want to achieve is to catch exceptions on my app so that I can send them to a server. I figured out that I can do this by writing my custom UncaughtExceptionHandler base on native Android code in Java answered here in StackOverflow.
This is my CustomExceptionHandler class:
public class CustomExceptionHandler : Thread.IUncaughtExceptionHandler
{
public IntPtr Handle { get; private set; }
public CustomExceptionHandler(Thread.IUncaughtExceptionHandler exceptionHandler)
{
Handle = exceptionHandler.Handle;
}
public void UncaughtException(Thread t, Throwable e)
{
// Submit exception details to a server
...
// Display error message for local debugging purposes
Debug.WriteLine(e);
}
public void Dispose()
{
throw new NotImplementedException();
}
}
Then I used this class to set the DefaultUncaughtExceptionHandler in my Activity:
// Set the default exception handler to a custom one
Thread.DefaultUncaughtExceptionHandler = new CustomExceptionHandler(
Thread.DefaultUncaughtExceptionHandler);
I don't know what is wrong with this approach, it did build but I got an InvalidCastException on runtime.
I have the same Thread.IUncaughtExceptionHandler interface types for my CustomExceptionHandler and the DefaultUncaughtExceptionHandler, but why am I getting this error? Please enlighten me. Thank you.
And it strikes again :D This is a common mistake. You have to inherit Java.Lang.Object if you implement Java interfaces.
public class CustomExceptionHandler : Java.Lang.Object, Thread.IUncaughtExceptionHandler
{
public void UncaughtException(Thread t, Throwable e)
{
// Submit exception details to a server
...
// Display error message for local debugging purposes
Debug.WriteLine(e);
}
}

Get .NET MVC to completely ignore error

I have a legacy library in my ASP.NET MVC app that raises a lot of exceptions I need to ignore. I ignore these exceptions in Application_Error like this
protected void Application_Error()
{
if (exception is PolicyViolationException)
{
Response.Clear();
Server.ClearError();
}
}
I know this is a code smell, but I can't do much about it at the moment.
Is there a way to stop them even getting to Application_Error?
Use a Wrapper class (the Adapter Pattern). Then, instead of referencing the legacy library, you use the wrapper class. And the wrapper can handle (or ignore) the exceptions as needed.
class Legacy
{ public void DoThis()
{ ... }
public void DoThat()
{ ... }
}
class Wrapper
{ Legacy _legacy;
public Wrapper() { _legacy = new Legacy(); }
public void DoThis()
{
try {
_legacy.DoThis();
}
catch (PolicyViolationException exception) {
//ignore
}
}
...
}
In this example, I would never reference the class Legacy. Instead, I would reference the class Wrapper. Then I don't have to worry about the exceptions because they won't get out of the Wrapper instance if I don't want them to.

C# (.NET) Objects with dependent life-cycle on owning objects

I am coming from C++ background and would like to have some thoughts from C# (.NET) experts on the problem statement below, I am open to solution approaches but requirements are frozen.
Problem Statement:
To have a system that provides automatic cleaning of dependent objects as soon as the owning objects are deleted (bit different from what GC provides explained below.)
Dependent objects may have other references other than its owning object, but as soon as owning object is deleted the dependent objects needs to go
To be able to replace the other outstanding references with stub object (placeholder) references as the actual object no longer exit
The system needs to be object agnostic and should be able to detect references or replace them with stubs for any object inherited from System.Object (.net)
Definition of terms:
Dependent Object: An object that always needs an owner, but may be referenced by other objects as well. The Life cycle of dependent object will however be completely owned by owning object. If the owning object is deleted the dependent object must be deleted.
Stub objects These are the objects that represents the reference that got deleted.
Functional Background
To be able to support the functional requirements we need a system that will automatically clean up the dependent objects who's owner are deleted and then it would replace other references with the stub to indicate that the object it was holding has been deleted or unloaded,
To explain this with a simple example
Time T1 - Lets say we create a Line object. Since creating a line needs a start and end point it created 2 Point (Pt1 and Pt2) objects. The Point objects are marked as Dependent objects and Line Object is the Owner. So at any point of time if we delete Line it should go and delete Pt1 and Pt2.
Time T2: We create two new points Pt3 and Pt4 (these are now independent objects)
Time T3: We create a Curve object which is referencing (Pt2, Pt3 and Pt4). Here the Pt2's lifecycle is controled by Line object.
Time T4: We delete the Line object from graphics, now as a requirement this operation must go and delete Pt1 and Pt2 as they were create by Line and Line object has been deleted.
Time T5: Since curve was also referencing Pt2 hence now its geometric computation is incomplete and will be made to reference to a stub object. The Curve object will be marked as broken so that in future point of time we can edit it to refer to new point.
The key issues in having this system is that because deleting is controlled by .NET system, we do not have control over it. Any thought how this can be achieved in C# or .NET (In C++ we have complete control over memory management so it possible to determine active references from a pointer before we delete it and remove or replace them in memory).
I understand the Garbage Collector has its own tremendous benefits, but this is critical requirements which we need to support in .NET based C# model as well.
Any thought, suggestions are appreciated.
In general you can't control the deallocation of memory in C#. As suggested by Ameya, what you can do is have a "dirty" flag.
Yes I thought about the Dirty field approach, but as i have said this needs to be managed by system level. If an object is marked as Dirty other objects
Note that in .NET there are plenty of classes that do exactly this: many IDisposable classes (the ones that inherit from Stream especially!) When Dispose()d, theiy set a disposed flag to true, and in properties/methods they do a if (disposed) throw ObjectDisposedException(). In your case you shouldn't do this, you should simply return; or return (some default value);
public class ObjectWithReferences : IDisposable
{
private List<ObjectWithReferences> childs;
protected readonly ObjectWithReferences Parent;
public bool IsDisposed { get; private set; }
protected ObjectWithReferences(ObjectWithReferences parent)
{
Parent = parent;
if (parent != null)
{
parent.AddChild(this);
}
}
private void AddChild(ObjectWithReferences child)
{
if (IsDisposed)
{
child.Dispose();
return;
}
if (childs == null)
{
childs = new List<ObjectWithReferences>();
}
childs.Add(child);
}
private void DisposeChilds()
{
if (childs == null)
{
return;
}
foreach (ObjectWithReferences child in childs)
{
if (!child.IsDisposed)
{
child.Dispose();
}
}
childs = null;
}
public void Dispose()
{
if (!IsDisposed)
{
try
{
Dispose(true);
}
finally
{
try
{
DisposeChilds();
}
finally
{
IsDisposed = true;
GC.SuppressFinalize(this);
}
}
}
}
~ObjectWithReferences()
{
if (!IsDisposed)
{
try
{
Dispose(false);
}
finally
{
try
{
DisposeChilds();
}
finally
{
IsDisposed = true;
}
}
}
}
protected virtual void Dispose(bool disposing)
{
// Does nothing, not necessary to call!
}
}
Example of use:
public class ExampleRoot : ObjectWithReferences
{
public ExampleRoot() : base(null)
{
}
public void Foo()
{
if (IsDisposed)
{
return;
}
// Do Foo things
}
public void CreateChild()
{
if (IsDisposed)
{
return;
}
// Auto-adds itself!
var child = new ExampleChild(this);
}
}
public class ExampleChild : ObjectWithReferences
{
private byte[] BigBuffer = new byte[1000000];
public ExampleChild(ExampleRoot parent) : base(parent)
{
}
protected override void Dispose(bool disposing)
{
// The ExampleChild object has a very long possible lifetime,
// because it will live even in the IsDisposed == true state,
// so it is better to free even managed resources.
BigBuffer = null;
}
}
The code is quite simple/clear... There are two example classes (a Root and a Child). The basic idea is a "special" object, ObjectWithReferences that keeps the references of its childs. It is IDisposable, and when Dispose() is called (or when it is finalized) it Dispose() all its child objects. You can inherit from this object with your classes. Everyone of your methods/properties should always check the IsDisposed property to see if the object has been disposed. If it has been disposed, they should do nothing and return default values (0, null, string.Empty, ...). Note that if one of this objects keeps references to big managed objects (arrays for example), contrary to suggested .NET guidelines, it should null these references to let the GC collect them.
Note that it is the constructor that adds the object that is being built to its parent!
The normal thing to do here would be to use a WeakReference.
If you need the stub behaviour to be automatic, you could do something like:
public class AutoStubbed<T> where T:class
{
private WeakReference<T> _reference;
private T _stub;
private readonly Func<T> _stubFactory;
public AutoStubbed(T value, T stub)
{
_reference = new WeakReference<T>(value);
_stub = stub;
}
public AutoStubbed(T value, Func<T> factory)
{
_reference = new WeakReference<T>(value);
_stubFactory = factory;
}
public T Target
{
get
{
T ret;
if(_reference.TryGetTarget(out ret))
return ret;
if(_stub == null && _stubFactory != null)
_stub = _stubFactory();
return _stub;
}
}
}
And type T to a interface both your object and your stub defines, rather the type of the object.

Categories