WPF application throws an exception after printing to file via doPDF printer - wpf

I have made a wpf standalone application for accounting purposes. The application works and prints well to an external printer or microsoft XPS printer. The problem arises when i select doPDF(an application which outputs a pdf file) as printer. The output is just fine; it creates the pdf file and saves it, but, when i come back to the application and press any button, an XamlParseException was unhandled error is thrown which says
'The invocation of the constructor on type 'RegisterMaintenance.DisplayInvoice' that matches the specified binding constraints threw an exception.' Line number '5' and line position '7'
InnerException: Verify that the file exists in the specified location
InnerException: When using relative paths, make sure the current directory is correct
Why is this happening and what can i do to get rid of this problem.

Seems that this pdf printer changes the current directory for the process.
I can think of 2 possible workarounds for your problem.
The first and most obvious workaround for your problem would be to use a absolute path for "Transactions.xml" and store this in your app.config. This might however become problematic if your application is ditributed to various different machines and installed in different locations.
The second workaround is to temporarily store your current working directory before calling the print function, and then restore it afterwards, if it has changed. Something like this:
string path = Directory.GetCurrentDirectory();
//Do the print stuff
Directory.SetCurrentDirectory(path);

Seems like most probable cause is that some resource is not found or already occupied. Please share your code for Line number '5' and line position '7' with us.

You can use your debugger and set a breakpoint on line number 5 where the constructor for RegisteMaintenance.DisplayInvoice is called. Look at the file path being used and fix the problem. Alternately, if you're highly confident it's not a problem you can try/catch and ignore the exception but I don't really recommend that.

Related

How to get the icon path and index associated with a file type (again, with clarity)?

It's a long shot, but does anyone know of a working method to get the associated icon location (= path to an exe/dll/ico file) and ID for a given filename with WinAPI. The point is to create a shortcut to another file (which may or may not be of the same file type) and set THIS exact icon, overriding its default one, presumably with IShellLink::SetIconLocation.
Things that don't work:
-ExtractAssociatedIcon
-SHGetFileInfo
-IExtractIcon
Return random crap with GIL_NOTFILENAME flag set for any of the default file types I've tried (like txt).
There seem to be several topics on SO about this sorta thing, with answers/non-answers suggesting one of the above. This one [1] appears most close to being informative. Their preferred method doesn't work either, but their other notes gave me the hint to try using the registry.
So for the time being, I wrote my own function that uses the registry [2], but it's also not perfect: in some cases, the registry stores 'positive icon IDs' that cannot, it seems, be used with SetIconLocation.
Honestly didn't expect this to be such a year 2023 problem
You don't need to call IShellLink::SetIconLocation if you don't want to override the targets default icon. Just point the shortcut to a .txt file and the shortcut automatically gets the correct icon.
Positive icon IDs most certainly can be used with SetIconLocation, that is the common case. Are you calling PathParseIconLocation?
GIL_NOTFILENAME is just something you have to accept, it usually means the icon comes from the system image list. The shell is mainly interested in going from a file/type to a HICON, not the other way around. The icon for a file may even be dynamic if it is implemented by a shell extension.
You can add AssocQueryString to the list of functions to try that will never work 100% of the time...

Trash files inside user-selected folder inside iCloud Drive

My app works with user txt-files (create, change, delete) inside any user-selected folder. I just internally store the bookmark to get access to that user-selected folder and files.
Now, with macOS Catalina when the source folder is inside iCloud Drive, system still allows me to create and edit files. But doesn't allow to trash one. When I try to do it via [[NSFileManager defaultManager] trashItemAtURL: ... ] I get the following error:
Error Domain=NSCocoaErrorDomain
Code=3328
"<filename> couldn’t be moved to the trash
because the volume “<APFS volume name>”
doesn’t have one."
UserInfo={
NSURL=file:///... <filepath>.txt,
NSUserStringVariant=Trash
}
Note: this only happens when the app is sandboxed.
Any ideas how to get the file trashed correctly?
P.S. I know there is a NSWorkspace recycle... method, but it makes an extra deletion prompt that is not suitable for me.
P.P.S. I am still able to use [[NSFileManager defaultManager] removeItemAtURL: ...] method, but I need the target file to be restorable in case user changes his mind.
Ok. Looks like it's a rare case. But if you've got into the same situation, here is what I've ended up with:
There is a deprecated function - FSMoveObjectToTrashSync - that still works just fine. It saved my ass for now.

Difficulty with filename and filemime when using Migrate module

I am using the Drupal 7 Migrate module to create a series of nodes from JPG and EPS files. I can get them to import just fine. But I notice that when I am done importing them if I look at the nodes it creates, none of the attached filefield and thumbnail files contain filename information.
Upon inspecting the file_managed table I see that both the filename and filemime fields are empty for ONLY the files that I attached via the migrate module. This also creates an issue with downloading the files.
Now I think the problem has to do with the fact that I am using "file_link" instead of "file_copy" as the file operation I specify. The problem is I am importing around 2TB (thats Terabytes) of image files. We had to put in a special request with Rackspace just to get access to that much disk space on our server. So I can't go around copying from one directory to the next because of space issues. So "file_link" seems like the obvious choice.
Now you probably want to see how I am doing this exactly, so here is the code snippet:
$jpg_arguments = MigrateFileFieldHandler::arguments(NULL,
'file_link', FILE_EXISTS_RENAME, 'en', array('source_field' => 'jpg_name'),
array('source_field' => 'jpg_filename'), array('source_field' => 'jpg_filename'));
$this->addFieldMapping('field_image', 'jpg_uri')
->arguments($jpg_arguments);
As you can see I am specifying no base path (just like the beer.inc example file does). I have set file_link, the language, and the source fields for the description, title, and alt.
It is able to generate thumbnails from the JPGs. But still missing those columns of data in the db table. I traced through the functions the best I could but I don't see what is causing this. I tried running the uri in the table through the functions that generate the filename and the filemime and they output just fine. It is like something is removing just those segments of data.
Does anyone have any idea what this could be? I am using the Drupal 7 Migrate module version 2.2. It is running on Drupal 7.8.
Thanks,
Patrick
Ok, so I have found the answer to yet another question of mine. This is actually an issue with the migrate module itself. The issue is documented here. I will be repealing this bounty (as soon as I figure out how).

WPF - Saving font to disk, then instantiating GlyphTypeface for font throws exception. Why?

I am mucking about with WPF glyphs and documents and have run into a null reference exception in the .Net 4 framework.
I extract and save true-type fonts to disk as .ttf files, then try to create Glyphs based on the fonts. The first time I save a font to disk and instantiate a GlyphTypeface based on the font after creating a GlyphTypeface from another font in the same folder I get a null reference exception.
Say I have fonts A and B. B has not been saved to disk (A may or may not have been saved to disk; that doesn't seem to matter):
1) save B to disk in the same folder as A,
2) create GlyphTypeface using font A,
3) create GlyphTypeface using font B = exception.
Null reference exception at:
at MS.Internal.FontCache.FontFaceLayoutInfo.IntMap.TryGetValue(Int32 key, UInt16& value)
at MS.Internal.FontCache.FontFaceLayoutInfo..ctor(Font font)
at System.Windows.Media.GlyphTypeface.Initialize(Uri typefaceSource, StyleSimulations styleSimulations)
at System.Windows.Media.GlyphTypeface..ctor(Uri typefaceSource)
If I restart my app and run it again (with font B already on disk), step 3 doesn't throw an exception.
The code to save a font to disk is simply writing a section from a binary stream and letting go of the file:
if (!File.Exists(filename))
{
using (FileStream fs = File.Create(filename, length))
{
fs.Write(m_data, m_index, length);
fs.Close();
}
}
Any ideas? I don't want to have to put every font in its own folder...
Thanks for your time.
This bug has been driving me nuts but I think I have a better understanding of what is going on now.
For testing I used the following XAML:
<Page
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<Glyphs
FontUri="C:\Users\Public\Desktop\A.ttf"
FontRenderingEmSize="100"
Fill="Black"
UnicodeString="Test"/>
</Page>
Using the XamlPadX application which runs on the .NET 2 runtime I could reliably render the XAML no matter where I placed the font.
Using the Kaxaml application which runs on the .NET 4 runtime the XAML would often fail to render depending on where I placed the font in the file system. By moving the font file around and renaming I tried to discover a pattern in what was allowed. However, it was very hard to see a pattern.
For instance storing the font in the path below would render the glyphs:
C:\Users\Public\Desktop\A.ttf - OK
Renaming it from A.ttf to B.ttf would throw the exception:
C:\Users\Public\Desktop\B.ttf - throws exception
Changing the extension would also throw the exception:
C:\Users\Public\Desktop\A.odttf - throws exception
Renaming parts of the path would sometimes wreak havoc but I was unable to see any pattern. Initially I used the temp path and getting exceptions lead me to this question and the answer about not using that path. However, later I have actually been able to use that path as long as the name of the file is A.ttf and not B.ttf so avoiding the temp path is not a sure fix.
At some point during my tests using my own WPF application the B.ttf file name suddenly started working. However, I had to restart the Kaxaml application before it would accept the B.ttf file name. Also, at that point the A.odttf file name was still throwing exceptions.
My suggestion is to use an application like Kaxaml or to create a small WPF application to test which font file names are acceptable and then use them. However, I fear that the nature of this bug is such that a "good" font file name may turn "bad" at a later point in time. Only time will show.
I ended up using the workaround of saving each font to its own folder (using the font name for the folder name). The exception went away, so I guess we can chalk this up to a bug in .Net.
I (and a co-worker) finally found what our particular problem was: do not save the font files to %TEMP%. For some reason, having the fonts saved to some other folder makes it work (for us), and saving it to anywhere inside %TEMP% makes it break.
According to XamlToys Doesn't work on framework 4.0???, the problem is in the extension of the file for partial fonts.
When I renamed the .ofttf files I save to .ttf, it all works again. Haven't got the foggiest idea of why that is though. Seems to be new in .NET 4.0.
My workaround was to simply replace the < Glyphs > with equavalent < TextBlock >s. The couple of pixels difference in layout was not a problem in my case.
Like you noted was the case for you, in my case also it was not a problem in .Net 3.5, but appeared in .Net 4.0.

How do you debug a XamlParseException?

I'm trying to use a 3rd party component in my Silverlight application and when I try to create an instance of the control, I get a XamlParseException:
{System.Windows.Markup.XamlParseException: **Set property 'System.Windows.FrameworkElement.Style' threw an exception.** [Line: 0 Position: 0]
---> System.Windows.Markup.XamlParseException: **Elements in the same ResourceDictionary cannot have the same x:Key** [Line: 1739 Position: 47]
at MS.Internal.XcpImports.CreateFromXaml(UnmanagedMemoryStream stream, String sourceAssemblyName, boolean createNamescope, Boolean requireDefaultNamespace, Boolean allowEventHandlers)
at System.Windows.Controls.Control.GetBuiltInStyle(IntPtr nativeTarget, IntPtr& nativeStyle)
--- End of inner exception stack trace ---
at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
at SpellCheckerSample.StandardSpellDialog.InitializeComponent()
at SpellCheckerSample.StandardSpellDialog..ctor()}
How can I debug this? How do I know what file line 1739, Position 47 is in?
Could be a bit of a bugger to find. Basically try to gather as many details as possible from the debugger.
Set the debugger to break on XamlParseException.
Have a look at the callstack. It could be possible that the offending control's constructor is on the callstack.
When paused go to the Locals debug window to see if any parameters to the function reveal more about which component this is.
If not double-click the next stack entry down and go to step 3.
Repeat steps 3 and 4.
After I wrote this I realised that the control's constructor is indeed on the callstack and it is SpellCheckerSample. Very likely it is .XAML page for that control. If you can get access to the source, the file name is most likely something like SpellCheckerSample.xaml.
The error itself is pretty straight forward, looks like there multiple things defined with the same key in the same ResourceDictionary. The below code will cause this to happen:
<Window.Resources>
<myConverters:BananaToCarrotConverter x:Key="StupidestConverterEver" />
<myConverters:BananaToAppleConverter x:Key="StupidestConverterEver" />
<Window.Resources>
Turns out my specific problem was that the ComponentOne component only works under Silverlight 4. Once I changed to target SL4 it all worked.
Check what ResourceDictionary references you got - the propblem is usually that one one of them got an error that needs to be fixed.
If your exception is cause from App it's probably one of your merged dirs there, otherwise the control in question.
Also check that you're not missing resource dir usage for styles (helps if you got ReSharper since you'll get a warning in XAML design time).
Set the debugger to break on XamlParseException (Debug -> Exceptions -> Common Language Runtime Exceptins -> System.Windows.Markup -> XamlParseException line -> set tick in Thrown column)
Take a look at the exception in debugger (especially on InnerException and LineNumber properties)
Try to go through the callstack line by line. While selecting a line look at the Locals window. It reveals some variables even in Framework code that is might be helpful.
Try to delete some part of XAML and see if exception happens again. This will help you to locate code that cause problems.
You should see an error in .cs file while trying to run the app.
And the corresponding .xaml file for this .cs file with given line number and column is the right one.

Resources