SSRS ReportViewer nullreference exception on Disposing - reporting-services

We're currently using a Windows Service to generate PDF files. I was recently optimizing the code and noticed the abusive use of memory. This was caused by the lack of a using statement around var reportViewer = new ReportViewer()
However, after adding this the code threw a runtime nullreference exception after closing the using block, the code originating in the internal Dispose method.
Why does this error occur and how can I dispose the object properly?

The answer, as can be found in Visual Basic here is because for some reason the ReportViewer expects a HttpContext. If none is present, this error will occur.
As a workaround the following lines can be added to resolve the issue:
if (System.Web.HttpContext.Current == null)
{
System.Web.HttpContext.Current = new System.Web.HttpContext(
new System.Web.HttpRequest(System.IO.Path.GetRandomFileName(), "https://www.stackoverflow.com", string.Empty),
new System.Web.HttpResponse(System.IO.TextWriter.Null)
);
}
This will create a fake HttpContext, allowing somehow to dispose the ReportViewer instance properly.

Related

The noticeError method was not found. while using Coldbox and NewRelic for Error tracking

I'm just using NewRelic error trapping for my coldbox application. From OnException method, I'm just sending the error struct to log the error.
My code in onexception method
public function onException(event,rc,prc){
NewRelic.logError( prc.exception.getExceptionStruct());
}
The logerror() method resides in NewRelic.cfc and contains the following code
public boolean function logError(
required struct exception
) {
var cause = arguments.exception;
var params = {
error_id = createUUID(),
type: arguments.exception.type,
message: arguments.exception.message
};
writeDump(this.newRelic);
this.newRelic.noticeError(cause, params);abort;
return true;
}
So while error, I'm gettig the following error.
The noticeError method was not found.
You can see that, the noticeError() method is there in the object, but it is overloaded with arguments.
I'm using the same code for NewRelic error trapping in another coldfusion project without any frameworks.
Calling error.cfm through Cferror tag, and the code in error.cfm as follows
<cfset Application.newRelic.logError( variables.error )>
And in NewRelic.cfc, the logerror() method contains the same code as in the coldbox application. But it is logging errors in NewRelic without any issues.
This is the method I need to notice errors and log it in NewRelic.
noticeError(java.lang.Throwable, java.util.Map)
So I just thought to get the classname of the first argument Cause through the following code from both applications within logError() in NewRelic.cfc, to get the difference.
writeDump(cause.getClass().getName());
I'm getting
coldfusion.runtime.ExceptionScope for Coldbox application
and
coldfusion.runtime.UndefinedVariableException for normal coldfusion application
The cause argument is not throwable from coldbox application. So how to get the original error struct from coldbox application? and make it throwable to fix the noticeError method was not found issue.
The change in the underlying class happens when ColdBox duplicates the error object with CFML's duplicate() method. I doubt that ColdFusion behavior is documented anywhere, but I don't see an easy way to get around it right now other than creating your own instance of a java.langException and populating it with the details of the original error.
If you want to modify the ColdBox core code, this happens here:
https://github.com/ColdBox/coldbox-platform/blob/master/system/web/context/ExceptionBean.cfc#L43
I have entered this ticket for the ColdBox framework for us to review if we can stop duplicating the error object in future versions of the framework.
https://ortussolutions.atlassian.net/browse/COLDBOX-476
Update: Adam Cameron pointed out this ticket in the Adobe bug tracker that details this behavior in the engine. It was closed as "neverFix".
https://bugbase.adobe.com/index.cfm?event=bug&id=3976478

How to solve "Native methods are not allowed in loaded code" error

I want to let my app to run sound while the playbook in standby mode, I put this statement in the start up
QNXSystem.system.inactivePowerMode = QNXSystemPowerMode.THROTTLED;
Now when I debug the app on the simulator (not desktop debugger) I got this error
VerifyError: Error #1079: Native methods are not allowed in loaded code.
And this error I got also when using AlertDialog.
Note: I am using Flash builder, and I have put the qnx SWC in the libraries path.
.... so to solve these problems?
To allow code compiled w/native extensions to run on the simulator, we had to put code that used native extensions in methods that would never get executed (when on the simulator).
It wasn't enough to just wrap the offending code in an if/else block. The if/else needs to call another method that either has the native version or the simulator version of the code.
For example:
private function showNativeOrFlexAlert(message:String):void
{
// we used the Capabilities class to determine this, might be a better way
if (isMobile)
showNativeAlert(message);
else
showFlexAlert(message);
}
// have to be careful here, this method signature CANNOT include
// any classes from native extension -- no errors on device, but fails on simulator
private function showNativeAlert(message:String):void
{
// use native API to show alert
}
private function showFlexAlert(message:String):void
{
// use the Flex Alert class
}
Set the qnx-air.swc linkage to "external".

event listener for flex/air action script errors

I'm trying to add an event listener to my air application that would prevent the "ActionScript error" window from appearing, so I can handle the error within my application.
I was able to find a little information about this from adobe. I'm just not sure what I should be listening for.
It depends quite a lot on what error is thrown, and why.
Your best bet is to carefully read the ActionScript documentation and add listeners to react to all of the errors that have explicit ErrorEvents (such as IOErrorEvent and SecurityErrorEvent). Those are usually related to network and/or file access, and security issues.
For most other errors, there is the try {} catch() {} finally {} statements. This tutorial might be a good place to start.
And if all else fails, there's UncaughtErrorEvent.
But you should really be using that one as a last resort, not as a magic bullet - the best error handling is a) trying to prevent errors from being thrown in the first place (make sure all variables are properly initialized, test for null, etc.), and b) handling expected runtime errors by catching them explicitly, in order to keep the application running and stable.
You have a couple options. As you know, exception handling is not always possible for certain asynchronous operations.
First off, you need to know what object is responsible for the asynchronous operation that is causing the error. The most sensible approach would be to add the necessary error event handlers to this object.
For instance, a URLLoader performs asynchronous operations; and it's failure can only be handled by adding error event listeners. For example:
var loader: URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, completeHandler);
loader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
Another 'catch-all' option is to take advanage of the new UncaughtErrorEvent feature of Flash Player 10.1. For this to work, you need to attach the uncaught error handler to the loader of the main application; this will catch everything! For example:
loader.uncaughtErrorEvents.addEventListener(UncaughtErrorEvent.UNCAUGHT_ERROR, loaderErrorHandler);
private function loaderErrorHandler(e:UncaughtErrorEvent):void {
if(event.error is Error) {
// handle error from embedded SWF
}
// suppress error dialog
e.preventDefault();
}
The last option may not be the best approach as it promotes the swallowing of exceptions instead of addressing and handling the problem properly; nevertheless it can be useful in certain unique circumstances (embedding SWFs).
The window won't appear if you're running the standard version of Flash Player.
It will manifest only as a dialog box on the debugger versions of the
browser plug-ins and stand-alone players, as a message in the output
panel in the authoring player, and as an entry in the log file for
Adobe Flex Builder 3. It will not manifest at all in the release
versions of Flash Player or AIR.
Source : here.

MSMQ asynchronous exception behavior - .NET 4.0 vs .NET 2.0

I recently encountered a problem with asynchronous operations in MSMQ. In .NET 2.0, 3.0 and 3.5, if there is a pending asynchronous receive, and the queue is deleted, the callback is invoked and upon calling EndReceive, the exception is thrown.
In .NET 4.0, the callback is never invoked, but the exception can be caught by the AppDomain.UnhandledException event handler. When running in the debugger, the application will simply terminate with no notification from Visual Studio that an exception occurred.
This code is executing on Windows 7 Professional, 64-bit. However the behavior is the same whether the application is targeting x86 or x64. (Edit: verified this behavior on XP SP3 32-bit as well - this appears to be a framework bug, not OS-related)
I am assuming this new behavior is related to .NET 4.0 being a completely new runtime. I'm not sure what to do at this point, but essentially I am looking to get the pre-.NET 4.0 behavior back, while still targeting the .NET 4.0 runtime. Any help or advice would be greatly appreciated. Here is sample code to reproduce the problem:
class Program
{
static void Main( string[] args )
{
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler( CurrentDomain_UnhandledException );
string path = #".\private$\mytestqueue";
// Create queue only if it doesn't already exist.
var queue = MessageQueue.Exists( path ) ? new MessageQueue( path ) : MessageQueue.Create( path );
queue.BeginReceive( TimeSpan.FromSeconds( 15 ), queue, new AsyncCallback( ReceiveComplete ) );
Thread.Sleep( 5000 );
MessageQueue.Delete( path );
}
static void CurrentDomain_UnhandledException( object sender, UnhandledExceptionEventArgs e )
{
var mqEx = (MessageQueueException) e.ExceptionObject;
// .NET 4.0:
// "The queue does not exist or you do not have sufficient
// permissions to perform the operation."
Console.WriteLine( mqEx.Message );
// "QueueNotFound"
Console.WriteLine( mqEx.MessageQueueErrorCode );
}
static void ReceiveComplete( IAsyncResult ar )
{
// This callback is never invoked under .NET 4.0.
Console.WriteLine( "Finishing Receive." );
var queue = (MessageQueue) ar.AsyncState;
try
{
queue.EndReceive( ar );
}
catch ( MessageQueueException mqEx )
{
// .NET 2.0 through 3.5:
// "Queue handle can no longer be used to receive messages
// because the queue was deleted. The handle should be closed."
Console.WriteLine( mqEx.Message );
// "QueueDeleted"
Console.WriteLine( mqEx.MessageQueueErrorCode );
}
}
}
Addendum:
After spending way too much time trying to use source stepping (System.Messaging source is available for 4.0 but not for 2.0/3.5, it appears), and hunting through the two different System.Messaging assemblies with Reflector, I finally found the problem.
In the 2.0 assembly, some try/catch blocks are used in the MessageQueue.AsynchronousRequest.RaiseCompletionEvent method to catch exceptions and store an error code so that the exception can be raised when .EndReceive() is called. However, in the 4.0 assembly, these try/catches are gone, so when an exception occurs the process must terminate since they are un-caught on a background thread.
Unfortunately this doesn't help me fix the problem. I am considering switching to a synchronous Receive, but I liked the idea of taking advantage of I/O completion ports for this.
Well, I am going to answer this and accept it, since I think it's the best answer for the near future. It could be months (or more) before there is a proper solution.
As mentioned above, I filed a bug report on Microsoft Connect, so it is pretty much up to them to revert the behavior to how it worked in CLR 2.0.
Microsoft Connect: http://connect.microsoft.com/VisualStudio/feedback/details/626177/messagequeue-beginreceive-asynchronous-exception-behavior
As far as how this affects my application, I am not willing to switch to a synchronous Receive method, as that would consume all of the available worker threads on the thread pool. My application frequently creates and removes a lot of queues, and this issue arose when a command to remove a queue was issued, but an outstanding read operation was pending. Instead, I will just mark that a queue needs to be removed, and once a safe period of time has elapsed (two times the BeginReceive timeout, for instance), I will actually remove the queue.
Or switch to a different queuing system than MSMQ, though I've been happy with it so far.

MEF: "Unable to load one or more of the requested types. Retrieve the LoaderExceptions for more information"

Scenario: I am using Managed Extensibility Framework to load plugins (exports) at runtime based on an interface contract defined in a separate dll. In my Visual Studio solution, I have 3 different projects: The host application, a class library (defining the interface - "IPlugin") and another class library implementing the interface (the export - "MyPlugin.dll").
The host looks for exports in its own root directory, so during testing, I build the whole solution and copy Plugin.dll from the Plugin class library bin/release folder to the host's debug directory so that the host's DirectoryCatalog will find it and be able to add it to the CompositionContainer. Plugin.dll is not automatically copied after each rebuild, so I do that manually each time I've made changes to the contract/implementation.
However, a couple of times I've run the host application without having copied (an updated) Plugin.dll first, and it has thrown an exception during composition:
Unable to load one or more of the requested types. Retrieve the LoaderExceptions for more information
This is of course due to the fact that the Plugin.dll it's trying to import from implements a different version of IPlugin, where the property/method signatures don't match. Although it's easy to avoid this in a controlled and monitored environment, by simply avoiding (duh) obsolete IPlugin implementations in the plugin folder, I cannot rely on such assumptions in the production environment, where legacy plugins could be encountered.
The problem is that this exception effectively botches the whole Compose action and no exports are imported. I would have preferred that the mismatching IPlugin implementations are simply ignored, so that other exports in the catalog(s), implementing the correct version of IPlugin, are still imported.
Is there a way to accomplish this? I'm thinking either of several potential options:
There is a flag to set on the CompositionContainer ("ignore failing imports") prior to or when calling Compose
There is a similar flag to specify on the <ImportMany()> attribute
There is a way to "hook" on to the iteration process underlying Compose(), and be able to deal with each (failed) import individually
Using strong name signing to somehow only look for imports implementing the current version of IPlugin
Ideas?
I have also run into a similar problem.
If you are sure that you want to ignore such "bad" assemblies, then the solution is to call AssemblyCatalog.Parts.ToArray() right after creating each assembly catalog. This will trigger the ReflectionTypeLoadException which you mention. You then have a chance to catch the exception and ignore the bad assembly.
When you have created AssemblyCatalog objects for all the "good" assemblies, you can aggregate them in an AggregateCatalog and pass that to the CompositionContainer constructor.
This issue can be caused by several factors (any exceptions on the loaded assemblies), like the exception says, look at the ExceptionLoader to (hopefully) get some idea
Another problem/solution that I found, is when using DirectoryCatalog, if you don't specify the second parameter "searchPattern", MEF will load ALL the dlls in that folder (including third party), and start looking for export types, that can also cause this issue, a solution is to have a convention name on all the assemblies that export types, and specify that in the DirectoryCatalog constructor, I use *_Plugin.dll, that way MEF will only load assemblies that contain exported types
In my case MEF was loading a NHibernate dll and throwing some assembly version error on the LoaderException (this error can happen with any of the dlls in the directory), this approach solved the problem
Here is an example of above mentioned methods:
var di = new DirectoryInfo(Server.MapPath("../../bin/"));
if (!di.Exists) throw new Exception("Folder not exists: " + di.FullName);
var dlls = di.GetFileSystemInfos("*.dll");
AggregateCatalog agc = new AggregateCatalog();
foreach (var fi in dlls)
{
try
{
var ac = new AssemblyCatalog(Assembly.LoadFile(fi.FullName));
var parts = ac.Parts.ToArray(); // throws ReflectionTypeLoadException
agc.Catalogs.Add(ac);
}
catch (ReflectionTypeLoadException ex)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
}
}
CompositionContainer cc = new CompositionContainer(agc);
_providers = cc.GetExports<IDataExchangeProvider>();