Recently I looked at some coding at the web. I found some people use Microsoft.VisualBasic.CompilerServices.ProjectData.ProjectData class in catch block.
catch (Exception exception1)
{
//ProjectData.SetProjectError(exception1);
Console.WriteLine(exception1.ToString());
Console.WriteLine();
Console.WriteLine(sSQL);
//ProjectData.ClearProjectError();
}
I searched it on msdn that mentioned that this API supports the .NET Framework infrastructure and is not intended to be used directly from your code.
I am curious what reason people use it. Would you explain it to me?
My experience has been that this type of code use is found in c#/VB.NET projects that have been converted from VB6. When developing new c#/VB.NET solutions/projects, this practice should not be used.
Note: This technique can safely be replaced with proper exception handling that you would be used to seeing in other .NET solutions/projects.
This code is either emitted by a code conversion tool that converted VB code to C#, or resulted from decompiling an assembly that was originally created using VB.
I'm porting a VB project to Mono, and found out that the VB compiler injects these calls ProjectData.SetProjectError(exception) and ProjectData.ClearProjectError() in any catch block, and try to find a way to prevent the compiler from doing so because Mono doesn't implement the ProjectData module. And found your question while doing my research!
so this is a result of old legacy vb6 for those interested. when vb6 started out there was an err object which is still around but has moved to the projectdata object in vb. if anybody like me remembers vb6 ( this is back when dinosaurs roamed the earth), there was a handy little call on error resume next. this is if you did not like those pesky little exceptions. most vb6 programs used it copiously and voila you had no exceptions because you ignored any. so here comes the explanation.
catch (Exception exception1) // catch any exceptions that just happened
{
ProjectData.SetProjectError(exception1); // set the information
//in the err object if anyone actually wants to check
ProjectData.ClearProjectError(); //clear the err object
}
as you can see this is completely ignoring any exceptions and in true vb6 fashion, your code just explodes without any explanation. needless to say if anyone writes code like this or uses vb in this way, I will find you and figure out a way to get you incarcerated.
Related
I'm trying to develop a .NET MAUI class library. During an event, if an exception raises a display alert window should be visualized. In a .NET MAUI project this works fine, but in .NET MAUI class library project there is something missing, maybe I should add a reference. Could someone provide a solution?
catch (Exception ex)
{
await DisplayAlert("EXCEPTION RAISED", ex.ToString(), "CANCEL");
}
This is really bad idea. For more than one reason.
Tomorrow when you try to reuse this library in a thread, that has no interface, what will you do?
How will you know the consumer of your library will know what exactly went wrong? I've dealt in the past with libs that basically return true/false, and hide the exception. Go figure out.
If you decide to make changes and fix it at some point, everyone that is using the old version of your library will have really bad time to edit every line he uses your library.
To answer your question. You can pass any object as parameter to any function. Or you can do this as initialization. If you still want to do it.
As alternative, I sometimes use messaging service. If the elements are de-coupled and I don't want them to be coupled. The code that does work broadcasts messages, and IF (this is important) there is interface registered to receive such messages, they are handled.
I have an OCX file built using VB6 that I'd like to access from C#. So I added a reference to the OCX in a C# project, and then added code to instantiate an object from the OCX:
var blah = new Blah();
This compiles just fine, without errors or warnings, and it seems to work as I would expect - I can call methods on the blah object and they seem to do what I would expect them to do. However, if I go to ReSharper / Inspect / Code Issues in Solution, ReSharper complains that the above quoted line is a "C# Compiler Error", saying "Cannot access internal constructor 'BlahClass' here".
Since it's claiming it's a C# compiler error, yet it seems to compile (and in fact work) just fine, I'm guessing it's just an issue with ReSharper itself. However, I'm pretty new to this, and I'd like to make sure. Perhaps what I'm doing is not the correct way of instantiating an object from an OCX, or something like that?
I am using VS2012 Professional and ReSharper 7.1.3.
The C# compiler looks at that coe and sees invocation of "dynamic" code (code whose objects may have new methods/properties available after execution started) and thus can't be sure that any particular method/property isn't there at compile time. Resharper tries to help out a bit more by trying to figure out circumstances that might fail at runtime. It may be using an out-dated description (type library) of that class to make its decision. Or, that description of that class is out of sync with what the code actually does. It's hard to tell solely based on what you've posted whether that's a good thing or a bad thing. If "it works", it seems like a good thing; but that's very subjective--it could be a problem waiting to happen.
I would see this as suspicious and maybe contact the vendor to get reassurance there isn't something lurking in there that will cause problems later.
I am trying to integrate a Lua Scripting interface into my C# project by using LuaInterface.
It works as expected if I execute syntactically correct code, but as soon as a syntax error (or any other error as it seems) is introduced to the script an SEHException gets thrown without any information regarding the error.
A simple example to trigger the behavior: new LuaInterface.Lua().DoString("die");
That of course completely nullifies Lua's error handling mechanisms and is a show-stopper for me.
Apparently this is a known bug which is open since 2011.
Are there any workarounds, a version of LuaInterface without this bug or is there an alternative lua wrapper which correctly handles errors?
Lua errors (syntax or runtime errors) encountered by DoString should result in a LuaException being thrown. Its message will contain the error string generated by Lua. For instance, given your example:
try
{
new LuaInterface.Lua().DoString("die");
}
catch (LuaException ex)
{
Console.WriteLine(ex.Message);
}
You should get the following error:
[string "chunk"]:1: '=' expected near '<eof>'
You don't show any context for your one liner. Is it wrapped in a try-catch block?
If so, perhaps it's a bug?
How can I execute some code when my program experiences a fatal error and crashes? For example, something goes wrong and the box pops up that say "TestApp.exe has encountered an error and needs to close." and then I want to write to a file with an error code and say a report of the last few things that were entered into the program. How would I do this in C#??
Depending on the type of application you are writing there are different ways. You may take a look at the following article to see how this could be achieved in a WinForms application.
Generally it's a bad idea to write handlers for Exception, FatalException and two more types, you should be more specific in try.. catch clause. Try explore the Application class, especially its SetUnhandledExceptionMode. You can find a nice example on how to use it here.
It depends on what you are asking here.
Regular exceptions you can get through try/catch.
However if you are running any external dll that may for example get Corrupted state exceptions (CSEs) you need to enable legacyCorruptedStateExceptionsPolicy in your app.config (but dont forget that there is a reason for Microsoft to remove this as default as it was before. You should try to fix this kind of errors not only catch them and forget them)
http://dotnetslackers.com/articles/net/All-about-Corrupted-State-Exceptions-in-NET4.aspx
For logging errors to the file you may use log4net
Any way it should look like:
try
{
// Something potentially dangerous
}
catch (Exception Ex)
{
Logger.Append(Ex.Message);
}
I'd liked to know whether it is possible to call a function in VBScript from C#. Let me try to clarify. I'm using an application (Quick Test Professional or "QTP") that automates another application, mostly using VBScript. There is the ability, via an add in model, to extend the test functionality by writing add-ins to the testing application (QTP) that are .NET assemblies. The basic workflow is that the VBScript tests automate the test application, and can call methods on a class in the extensibility add in assembly to do more complicated things. This part works fine.
What I'd like to know is whether it is possible for my C# code (in the extensibility add in assembly) to call back to a function in the VBScript. I don't think the test application framework (QTP) explicitly supports this, so I'm wondering if there is any way to do this using standard interop techniques. I was half way thinking of using GetRef() to get a reference to the VBScript function of interest, passing this as a parameter to a method I call in the extensibility addin (I suspect I would run into marshaling issues even at this point?) and then within the C# code of my extensibility add in, somehow call a method on this object; this is where I'm completely lost (since I don't know how to do this without the necessary type information normally used in reflection).
I'm thinking this may not be possible, but would like confirmation if that's the case.
Thank you!
In the end not so hard but finding it out was harder
In vbscript set a=getref
In c# declare the ref as an object
https://community.saas.hpe.com/t5/Unified-Functional-Testing/C-compile-on-the-fly-thru-dotnetfactory/m-p/1611299#M22811
private object _UFTCallBackFunction = null;
public int callMeBack2()
{
string[] retParts = {"Yep this is value 1"};
_UFTCallBackFunction.GetType().InvokeMember("",
System.Reflection.BindingFlags.InvokeMethod, null,
_UFTCallBackFunction, retParts);
return 0;
}
public void InitUFTCallBack(object UFTCallBackFunction)
{
_UFTCallBackFunction = UFTCallBackFunction;
}
And then in vbs
Set oCallMe = GetRef("CallMeBackWithAParameter")
oTestCom.InitUFTCallBack(oCallMe)
oTestCom.callMeBack2()
Function callMeBackWithAParameter(P1)
print "I wass called back from C# having value " & P1
End Function
How does the VBScript call the C# code? I suspect that it is really calling on QTP, and QTP is calling the C# code. In that case, only QTP could possibly call the VBScript back.
Under what circumstances would your C# code call back? I doubt that VBScript can be called back asynchronously.
That's a toughie.
You MAY want to try writing an event handler in the VBScript side for the .NET component and raising an event on the .NET side when you want the function to be called.
Just be warned it may not even work, as it really depends on QTP's scripting engine. And even if it should, don't be surprised if it becomes an exercise in frustration.
See examples on WSH and event handling http://msdn.microsoft.com/en-us/library/ms974564.aspx Again, this probably won't apply to QTP, but it's to give you an idea of potential approach to the problem.
Edit: Additional link which may or may not help!
http://www.west-wind.com/presentations/dotnetfromVfp/DotNetFromVfp_EventHandling.asp