Creating BitmapImage from MemoryStream causes crash - used to work - wpf

I'm really perplexed at this. I'm creating a BitmapImage with a raw byte array like so:
void SetBitmapData(byte[] imageData)
{
var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = new MemoryStream(imageData);
bitmapImage.EndInit();
this.Bitmap = bitmapImage;
}
Until an hour ago, it worked - and had been working for months. Now, on bitmapImage.EndInit(), it's giving me a NotSupportedException - "No imaging component suitable to complete this operation was found."
I'm really confused because as of this morning, this worked. Nothing has changed. In fact, to make sure that my changes (which were in completely unrelated parts of the application) weren't causing the crash, I checked out the code fresh from SVN using the head. The head did not crash yesterday when I committed it. This fresh copy also exhibits the same behavior.
It crashes from VS and when running the executable itself.
I'm running Visual Studio 2010 with the following plugins: ReSharper, StyleCop for ReSharper, VisualSVN.
Right before this started happening, Visual Studio did something odd - the keyboard cursor disappeared, but I could still type. I could select multiple characters with the mouse and keyboard, and, if I hit 'Delete' they would be deleted. I restarted Visual Studio, and the invisible cursor problem went away.
I've tried rebooting my computer, but that didn't help.

"No imaging component suitable to complete this operation was found." gets thrown when the call to IWICBitmapEncoder_Initialize_Proxy fails. Because your VS2010 (which also uses this stuff) is acting funny as well I'm guessing that some of your dlls are hosed. Your best bet may be to ask how to restore Windowscodecs.dll and Wincodec.lib on SuperUser

Related

DllHost.exe memory leak when getting PrintTicket

I have a x86 application working on windows10 (64 bit environment).
One pf the app's features is to generate a lot of reports, so there is a lot of printing involved.
However, I noticed that every time I try to use call DefaultPrintTicket on the print queue the dllhost process (COM Surrogate) grows in memory.
I managed to isolate the code responsible and moved it to a test WPF app. When a button is clicked this code is being fired:
var localPrintServer = new LocalPrintServer();
var oneNotePrintQueue = localPrintServer.GetPrintQueues().FirstOrDefault(p => p.Description.Contains(OneNote));
var printTicket = oneNotePrintQueue?.DefaultPrintTicket;
The printing queue is irrelevant as I tried them all and the problem remains.
I am aware that this might be a duplicate to: PrintTicket DllHost.exe Memory Climbs
However, the solution provided there does not work as PrintTicked is not an IDisposable object.
I also tried some tweaks in the registry (i.e. finding AppId AA0B85DA-FDDF-4272-8D1D-FF9B966D75B0 and removing "AccessPermission", "LaunchPermission" and "RunAs") with no result.
I cannot rebuild the app as AnyCpu and I would like to avoid creating a separate 64bit process just for printing as it would be difficult to send a report generated in one app to another.
Any suggestions are greatly appreciated.
It seems that the topic is difficult.
Just want to share the solution I went with in case anyone else has the same problem.
In the end I created a separate x64 app which handles the printing.
Initially I wanted to go with a WCF service. However, I ran into problems with serializing of FixedDocuments and PrintQueue. Hence the separate app.
The solution if far from perfect and in my opinion is not nice at all. However, it solved the memory leak issue.

WPF not releasing memory on certain computers

On certain computers I have a WPF application that doesn't release memory when working with it. For instance when sending a document to the printer, on most computers it's releasing memory all the 2-3 seconds (it's going up for maybe 200 megs then coming back down), which is normal behaviour and when the printing is done I go back to my initial memory state.
But on some computers (over 20 computers installed and only one is giving me this issue) it's not freeing the memory. It keeps piling up. I don't mind seeing memory going to 1.5 Gb as long as it's releasing it in the end, but it's not and I get an OutOfMemoryException.
I don't have full access to the problematic computer (they're a client's computer we installed a week ago and we just saw this problem) so I can't really test it but it's a standard Windows 7 Pro x64, with 10Gb of RAM and aside from that, it's working like a charm.
Also it's not ONLY when printing. The application is kind of a PDF viewer and everytime a new page is loaded for the user, the previous page is freed from memory. Again, it's working fine on most PC, but not in these case.
Is there anything that could prevent the memory from being released? I can't seem to find a similar problem anywhere on the web.
EDIT: Okay I got a hold of the computer for an hour. I was able to test two things :
GC.Collect() didn't arrange anything (I even forced it with GC.WaitForPendingFinalizer)
I tried disposing of the DocumentPage in my Paginator, no luck. I also kept a reference of a ViewModel I was using to display my page on printing, I tried disposing it : didn't work.
What I can say is that in both cases it must be because of the images displayed in my pages. Here's the function I call to get a new page image :
'First I get the path to the images
Dim path As String = String.Format("{0}\{1}.png", Me.TemporaryFolderPath, page.PageId)
Dim imgSource As CachedBitmap
'If the file doesn't exist
If Not IO.File.Exists(path) Then
'A function is called which creates the png file for next uses (this way the first loading is slow, but the next times it's faster)
imgSource = Pdf.GetPageImage(page.PageNumber, path)
Else
'If the file exists I instantiate a new BitmapImage
Dim img As New BitmapImage
'And I load it in a stream
Using stream As IO.FileStream = IO.File.OpenRead(path)
'I apply the stream to my image
img.BeginInit()
img.CacheOption = BitmapCacheOption.OnLoad
img.StreamSource = stream
img.EndInit()
'Flush, close, dispose of my stream
stream.Flush()
stream.Close()
End Using
'And I create a CachedBitmap with this image (which is almost like an ImageSource)
imgSource = New CachedBitmap(img, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad)
img = Nothing
End If
'If my ImageSource is something, I freeze it so that the memory is freed afterwards
If imgSource IsNot Nothing Then imgSource.Freeze()
Return imgSource
All this (freezing the image, setting the cacheOption to OnLoad, loading from a stream) I did to avoid memory leaks. My first attempt to load an image has a huge leak and I refactored my function so that I didn't have this problem anymore.
Is there anything there that could be the problem?
Finally my problem was that I was keeping my current page image in a ReadOnly Property. Even though I was disposing the image (the local variable used by the ReadOnly Property) it wasn't releasing it.
Maybe because of the OnPropertyChanged implemented on my ViewModels, because when I made it a read/write property and I disposed of it and set it to null on every change of page, it was releasing the memory on the problematic computers.

Microsoft.Expression.DesignHost.Isolation.Remoting.RemoteException - Type universe cannot resolve assembly

I'm posting this to basically continue a thread that was closed:
"Error trying to open a VS 2010 project in VS 2012 : Type universe cannot resolve assembly" by user1766173
I've dug deeper into the issue and narrowed some things down, so hopefully the discussion can be resumed.
I'm using VS 2012 (and I don't have 2010 to compare to). My solution, "TWConsole", was working fine on Friday, and as of Tuesday it was not. Both versions compile and run fine, but in the designer, no XAML file in the project can be opened without crashing. However, opening an XAML from a different project within the same solution works fine. Everything I've googled regarding this issue results in someone dealing with a 3rd party assembly.
However, in my case the assembly that can't be resolved is my own--the one generated by the build.
Interestingly, I've found that by "secretly" replacing the TWConsole.exe in the bin\Debug folder with from last monday's build, everything works! ... that is, until I rebuild the solution, and that exe gets replaced, and then the XAML designer begins crashing.
So there's something relating to new code I've added that is somehow "infecting" the main assembly. In the meantime before anyone can come to my rescue with a solution, I will start with the last-working solution and just add one line of code at a time until the problem surfaces, so as to pin-point the exact cause.
Thanks
EDIT:
I've been able to narrow down the source of the problem to one line of code:
public static bool GetFavWashPkgs(out List<WashPkg> wPkgs)
If I remove the "out" keyword, then compile, the designer crashing problem is resolved. Same applies to the "ref" keyword--also a no-no in this case. I have tried for an hour to re-create this anomaly in a more basic test, using a test class and test function, but to no avail. All I can report is that this "sensitive" function is overloaded, the custom class WashPkg has the attribute [serializable()], and the class in which this function resides is static. If I modify the function declaration so that the type of List is int instead of WashPkg, the problem is also resolved.
So at this point it's still a mystery as to why the designer doesn't like that function declaration.

Netbeans ghost file a show stopper, how to fix it?

In the last few years I've encountered "ghost files" in Netbeans, but I didn't have proof of it, so I had to live with it and when I tried to explain the situation, it's hard to believe, now I have proof of it and it's a show stopper, any fix for it ?
It goes like this, I have a Java class that I've been using for many years, sort of a tool, I add a bit as I have more experience, but once in a while, after I added a new method, and used it in another class, Netbeans couldn't recognize it, it seemed to me Netbeans was still looking at the old copy of the class where the newly added method didn't exist. And yet if I copied this updated class to another project, the new method works fine and Netbeans can find it. In NB 6.7 it just acted like the class froze in time, any new additions to it wouldn't be recognized, now when I tried it in NB 6.9 I could catch the "ghost" !
It happened by accident, yesterday after I updated the class, I tried to use the new method in another class in the same project, the red flag went up, it couldn't find the new method, so I moused over the new method call, and right clicked on it, "Navigate" => "Go to source", bang the ghost showed up ! If I do this in NB 6.7, it just rang a bell as if it's telling me it couldn't find it. But in NB 6.9 it goes to the "source" which is not my java class source file[Get_Time.java], it's another generated file, so I moused over the opened "ghost" file name in the editor, the name was "C:\Users\USER.netbeans\6.9\var\cache\index\s117\java\14\gensrc\Get_Time.java(read-only)", the content seemed like a skeleton of my source file Get_Time.java , but definitely different, and I am pretty sure it's this "ghost file" that's been causing problems.
During the course of development I occasionally changed the system time to test different functions in the class, could this caused the ghost file to mess up, if I change the current time to 2016 and modified the source file, then NB might record the file last changed in 2016, and if I change the time back to 2011, and add a new function, it wouldn't accept it, because it might compare the dates of different versions of source file and stick with the "latest time stamp" ?!
I wish NB never keep ghost files, "Always Use The Actual Source File", this would avoid a lot of such problems. I did try to delete that ghost file, but the next time I compiled, it's generated again. I don't want to delete too much content from "C:\Users\USER.netbeans\6.9...", it might mess up my NB setting. Anyhow, it's now a show stopper, I can't add more changes to the class, it's frozen in time, what's the fix ?
Just some suggestions as I got stung by this problem before.
Did you built a jar and added dependency to this jar manually?
e.g.
1) project A is packaged into A.jar with a class Time.
2) project B depends on A.jar and project A
3) Time.java in project A is changed
4) project B will not see the changes as it'll always read from the A.jar built before the change happen.
Try deleting NetBeans' cache (~/.netbeans/6.9/var/cache/index/ directory) when you go back to the future and forward to the past. NetBeans is probably getting a bit confused by the file timestamps. Since it is somewhat of an edge case to be hopping around dates like that, I doubt it would be something NetBeans would give a high priority in attempting to fix/handle.

How to Debug XAML Parsing Errors in Silverlight?

I run into the following issue semi-regularly: I make changes to XAML or some resources used by it and when I go to load up the Silverlight project in debug mode it only gets as far as the spinning Silverlight-loading animation.
I've tried attaching the VS08 debugger to the process but it doesn't do anything at this point (works fine once I'm in the Silverlight but not before.)
From previous experience I've noticed this happens when there're problems with the XAML or the resources in it but my only solution so far has been to dissect the code line-by-line until I spot the problem.
Is there an easy way to debug/diagnose these situations?
UPDATE
I found this question with some help, but it still doesn't provide a good way to debug these types of issues.
This has been a real pain to debug but I finally found the problem hidden deep in the constructor to one of our custom controls (which was looking for a resource that wasn't there.) The real problem isn't fixing the issue but finding it.
I found that IE responds to exceptions in passed from Silverlight to the DOM but you don't get that same sort of feedback in the Chrome browser (which I use.) A solution that actually helps a great deal (even moreso than the IE tip) is to modify the ReportErrorToDOM() method in App.xaml.cs to the following:
private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
{
string errorMsg = String.Empty;
try
{
errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", #"\n");
System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");");
}
catch (Exception)
{
#if DEBUG
MessageBox.Show(errorMsg);
#endif
}
}
This gives you the position in the XAML where the issue is starting. It's not an ideal debugger, but it does help.
This is not the ultimate answer but can often help
In Visual Studio :
Click Debug > Exceptions
Click 'Find' and search for XAML
Click the 'Thrown' button next to System.Windows.Markup.XamlParseException
Start your project in debug mode. Any Xaml exceptions will be shown immediately. Check the inner exception sometimes for further information.
I wasted soooo much time before I finally figured this one out!
This may not apply, but one frequent source of XAML errors is due to uncaught exceptions within converters that you're using as resources. People often forget to use a try-catch block in their converters, and when something blows up in there you end up having to dissect your code line by line.
And, take this with a grain of salt, but depending upon the situation, you may be able to copy-and-paste some of your XAML into a WPF project and get better error messages. I've never relied on this tactic myself, but I recently heard about it from an experienced WPF/SL developer who's far smarter than me, so it might be worth a shot. :-)
Per microsoft: The end user at this time cannot debug the XAML Parser, only MS can do this. The new version of Silverlight 4 XAML Parser has been completely re-written using managed code and hopfully they will give us a better way to debug it. I know this as I just had an issue and opened a support case and was informed this by a Silverlight Dev.
The clkosest I could ever come to seeing what was going on with the parser was using Silverlight Spy:
http://firstfloorsoftware.com/silverlightspy/download-silverlight-spy/
Great tool.

Resources