Getting "File contains corrupted data" exception while opening the XPSDocument Package - xpsdocument

I am getting the exception within my Console Application
HResult -2146233033 InnerException null
Message File contains corrupted data.
Source WindowsBase SourceUri null StackTrace at MS.Internal.IO.Zip.ZipIOEndOfCentralDirectoryBlock.FindPosition(Stream archiveStream) at MS.Internal.IO.Zip.ZipIOEndOfCentralDirectoryBlock.SeekableLoad(ZipIOBlockManager blockManager) at MS.Internal.IO.Zip.ZipArchive..ctor(Stream archiveStream, FileMode mode, FileAccess access, Boolean streaming, Boolean ownStream) at MS.Internal.IO.Zip.ZipArchive.OpenOnStream(Stream stream, FileMode mode, FileAccess access, Boolean streaming) at System.IO.Packaging.ZipPackage..ctor(Stream s, FileMode mode, FileAccess access, Boolean streaming) at System.IO.Packaging.Package.Open(Stream stream, FileMode packageMode, FileAccess packageAccess, Boolean streaming)
Tried this looking in answers, but it did not help.
string xpsfilename = #"D:\test\sample_file.xps";
var webClient = new System.Net.WebClient();
var data = webClient.DownloadData(xpsfilename);
//var data = File.ReadAllBytes(xpsfilename);
using (MemoryStream stream = new System.IO.MemoryStream(data))
{
var package = System.IO.Packaging.Package.Open(stream); /* Exception thrown here */
var xpsDocument = new System.Windows.Xps.Packaging.XpsDocument(package, System.IO.Packaging.CompressionOption.SuperFast, xpsfilename);
var sequence = xpsDocument.GetFixedDocumentSequence();
SaveDocumentPagesToImages(sequence, #"D:\test");
}

Related

How can I use FFImageLoading to successfully cache and load svg resources with Xamarin Forms 5

I am trying to use FFImageLoading like this:
AppDelegate:
CachedImageRenderer.Init();
CachedImageRenderer.InitImageSourceHandler();
var config = new FFImageLoading.Config.Configuration()
{
VerboseLogging = true,
VerbosePerformanceLogging = false,
VerboseMemoryCacheLogging = false,
VerboseLoadingCancelledLogging = false
};
ImageService.Instance.Initialize(config);
var ignore = typeof(FFImageLoading.Svg.Forms.SvgCachedImage);
Preloading:
public void PreloadImages()
{
try
var resources = Assembly.GetExecutingAssembly().GetManifestResourceNames();
foreach (var r in resources)
{
if (!r.EndsWith(".svg")) continue;
try
{
var assemblyName = Application.Current?.GetType()?.GetTypeAssemblyFullName();
ImageService.Instance.LoadEmbeddedResource($"resource://{r}?assembly={Uri.EscapeUriString(assemblyName)}")
//ImageService.Instance.LoadEmbeddedResource($"resource://{r}?assembly={Assembly.GetExecutingAssembly().GetName().Name}")
.Success((info, result) =>
{
Debug.WriteLine($"Preloading success! Key: {info.CacheKey}");
})
.Preload();
}
catch (Exception ex)
{
Debug.WriteLine($"LoaderPage.PreloadImages[{r}]", ex);
}
}
}
When the code runs the images appear on the screens but my Application Output fills up with messages like this:
System.BadImageFormatException: Can't read image size properties. File corrupted?
at FFImageLoading.Decoders.GifDecoder.SourceRegfToDecodedImageAsync (Foundation.NSData nsdata, CoreGraphics.CGSize destSize, System.nfloat destScale, FFImageLoading.Config.Configuration config, FFImageLoading.Work.TaskParameter parameters, FFImageLoading.Decoders.GifDecoder+RCTResizeMode resizeMode, FFImageLoading.Work.ImageInformation imageinformation, System.Boolean allowUpscale) [0x00068] in C:\projects\ffimageloading\source\FFImageLoading.Shared.IosMac\Decoders\GifDecoder.cs:62
at FFImageLoading.Decoders.GifDecoder.DecodeAsync (System.IO.Stream stream, System.String path, FFImageLoading.Work.ImageSource source, FFImageLoading.Work.ImageInformation imageInformation, FFImageLoading.Work.TaskParameter parameters) [0x000e4] in C:\projects\ffimageloading\source\FFImageLoading.Shared.IosMac\Decoders\GifDecoder.cs:45
at FFImageLoading.Work.ImageLoaderTask`3[TDecoderContainer,TImageContainer,TImageView].GenerateImageAsync (System.String path, FFImageLoading.Work.ImageSource source, System.IO.Stream imageData, FFImageLoading.Work.ImageInformation imageInformation, System.Boolean enableTransformations, System.Boolean isPlaceholder) [0x0007c] in C:\projects\ffimageloading\source\FFImageLoading.Common\Work\ImageLoaderTask.cs:337
at FFImageLoading.Work.ImageLoaderTask`3[TDecoderContainer,TImageContainer,TImageView].RunAsync () [0x0047c] in C:\projects\ffimageloading\source\FFImageLoading.Common\Work\ImageLoaderTask.cs:643
2021-02-24 01:50:30.338196+0900 Memorise.iOS[41119:898256] Image loading failed: resource://Memorise.Resources.Cards.pause_Light.svg?assembly=Memorise,%20Version=1.0.0.0,%20Culture=neutral,%20PublicKeyToken=null
System.BadImageFormatException: Can't read image size properties. File corrupted?
Note that some of the SVG are very simple ones and I have no idea why or how they are corrupt and also the do show on the screen.
Has anyone been able to get the preload working. Note that I tried two different ways to do LoadEmbeddedResource but neither worked.

How can I uniquely identify textbox controls retrieved from another application?

I'm writing an application in C# to remote control another application. I don't have access to that application yet, but it's most likely written in either Visual C++ or VB6. I'm currently remote controlling a simple C# winforms program I created instead. So far, I can get all of the controls in a manner similar to Spy++ using PInvoke. I can also do things like setting the text in a textbox. The problem I have is that I can't uniquely identify a specific text box between executions of the application I'm controlling. I can't use hWnd for example because it's different every time you run the application. GetWindowLong returns whatever the hWnd is so that's no help. The internet speaks of this message called WM_GETCONTROLNAME. The scary code below attempts to use that message to get the name the developer used to uniquely identify the controls. The SendMessage seems like it's returning the number of bytes in the name. But the buffer containing that name comes back all zeros.
So here's the question. How can I fix the code below so that it returns that name correctly? (Hopefully it's a boneheaded mistake that's easy to fix) Or, just as good, is there some other ID that will be guaranteed to be the same every time I run the program? Without something to uniquely identify the textbox controls, my code can't tell them apart.
I do have a hack in mind. It seems to me that using the position of the textboxes to tell them apart would work. But I'd much prefer to have the code below working.
public static string GetWindowText(IntPtr Handle)
{
int BufferSize = 256;
uint Message = RegisterWindowMessage("WM_GETCONTROLNAME");
StringBuilder sb = new StringBuilder(BufferSize);
byte[] ControlName = new byte[BufferSize];
long BytesRead = 0;
IntPtr BytesReadPointer = new IntPtr(BytesRead);
IntPtr OtherMem = IntPtr.Zero;
try
{
OtherMem = VirtualAllocEx(Handle, IntPtr.Zero, new IntPtr(sb.Capacity), AllocationType.Commit, MemoryProtection.ExecuteReadWrite);
var Result = SendMessage(Handle, Message, new IntPtr(sb.Capacity), OtherMem);
//Result contains different numbers which seem like the correct lengths
var Result2 = ReadProcessMemory(Handle, OtherMem, ControlName, BufferSize, out BytesReadPointer);
//ControlName always comes back blank.
}
finally
{
var Result3 = VirtualFreeEx(Handle, OtherMem, BufferSize, FreeType.Release);
}
return ""; // Convert ControlName to a string
}
So after a good night's sleep and a little tinkering, I managed to fix the problem myself. There were two problems. First, I was passing in the handle to the control to VirtualAllocEx. But in the documentation for that function, it says that it takes a handle to the process. So started supplying that. Then VirtualAllocEx was telling me that I had an invalid handle. So it turns out the handle you pass to VirualAllocEx has to have PROCESS_VM_OPERATION set. So I made a call to OpenProcess to get that handle, then passed that to VirtualAllocEx. After that, everything worked. I just had to convert the byte array coming back into a string, and trim a bunch of nulls. This returns the Name property on the controls. I'll post the code here in case anyone else needs something like this.
[Flags]
public enum ProcessAccessFlags : uint
{
All = 0x001F0FFF,
Terminate = 0x00000001,
CreateThread = 0x00000002,
VirtualMemoryOperation = 0x00000008,
VirtualMemoryRead = 0x00000010,
VirtualMemoryWrite = 0x00000020,
DuplicateHandle = 0x00000040,
CreateProcess = 0x000000080,
SetQuota = 0x00000100,
SetInformation = 0x00000200,
QueryInformation = 0x00000400,
QueryLimitedInformation = 0x00001000,
Synchronize = 0x00100000
}
public static string GetWindowText(IntPtr ControlHandle, IntPtr ProcessHandle)
{
int BufferSize = 256;
StringBuilder sb = new StringBuilder(BufferSize);
byte[] ControlNameByteArray = new byte[BufferSize];
long BytesRead = 0;
IntPtr BytesReadPointer = new IntPtr(BytesRead);
IntPtr RemoteProcessMemoryAddress = IntPtr.Zero;
IntPtr RemoteProcessHandle = IntPtr.Zero;
try
{
uint Message = RegisterWindowMessage("WM_GETCONTROLNAME");
RemoteProcessHandle = OpenProcess(ProcessAccessFlags.CreateThread |
ProcessAccessFlags.QueryInformation |
ProcessAccessFlags.VirtualMemoryOperation |
ProcessAccessFlags.VirtualMemoryWrite |
ProcessAccessFlags.VirtualMemoryRead, false, Process.Id);
RemoteProcessMemoryAddress = VirtualAllocEx(RemoteProcessHandle, IntPtr.Zero, new IntPtr(sb.Capacity), AllocationType.Commit, MemoryProtection.ExecuteReadWrite);
if (RemoteProcessMemoryAddress == IntPtr.Zero)
{
throw new Exception("GetWindowText: " + GetLastWin32Error());
}
SendMessage(ControlHandle, Message, new IntPtr(sb.Capacity), RemoteProcessMemoryAddress);
ReadProcessMemory(RemoteProcessHandle, RemoteProcessMemoryAddress, ControlNameByteArray, BufferSize, out BytesReadPointer);
string ControlName = Encoding.Unicode.GetString(ControlNameByteArray).TrimEnd('\0');
return ControlName;
}
finally
{
VirtualFreeEx(RemoteProcessHandle, RemoteProcessMemoryAddress, BufferSize, FreeType.Release);
}
}

HDFS append in 0.23.5 using libhdfs

I am trying to append to a hdfs file on ver 0.23.5. I have set the property dfs.support.append to true in hdfs-site.xml. I am getting the following error when calling hdfsWrite() saying append is not supported.
Exception in thread "main" java.io.IOException: Not supported
at org.apache.hadoop.fs.ChecksumFileSystem.append(ChecksumFileSystem.java:345)
at org.apache.hadoop.fs.FileSystem.append(FileSystem.java:1046)
Call to org.apache.hadoop.conf.FileSystem::append((Lorg/apache/hadoop/fs/Path;)Lorg/apache/hadoop/fs/FSDataOutputStream;) failed!
I checked past literature on append in hdfs. Looks like append should work in 0.23.5.
I am able to insert and read. The problem is when I try to open for O_APPEND and write to the file. Here is the sample code -
int append(char *filepath, char *data, int size)
{
hdfsFS fs = hdfsConnect("default", 0);
int openFlags = O_WRONLY | O_APPEND;
hdfsFile fdData = hdfsOpenFile(fs, filepath, openFlags, 0, 0, 0);
if (!fdData)
return -1;
if (hdfsWrite(fs, fdData, data, size) == -1)
return -1;
hdfsCloseFile(fs, fdData);
return 0;
}
Am I missing something?
thanks.
FSDataOutputStream doesn't support the append method. Here's the relevant source:
public FSDataOutputStream append(Path f, int bufferSize, Progressable progress) throws IOException {
throw new IOException("Not supported");
}
You'll notice that its super class FileSystem notes that append is an optional method.

ZXING Barcode Decode error "Attempted to read or write protected memory"

I am attempting to use the ZXING demo "WindowsRTDemo", and I can't get it to work. The demo is downloaded from this site.
Here is the code that I'm running:
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
try
{
var cameras = await DeviceInformation.FindAllAsync(DeviceClass.VideoCapture);
if (cameras.Count < 1)
{
ScanResult.Text = "No camera found";
return;
}
var settings = new MediaCaptureInitializationSettings { VideoDeviceId = cameras[0].Id }; // 0 => front, 1 => back
await _mediaCapture.InitializeAsync(settings);
VideoCapture.Source = _mediaCapture;
await _mediaCapture.StartPreviewAsync();
while (_result == null)
{
var photoStorageFile = await KnownFolders.PicturesLibrary.CreateFileAsync("scan.jpg", CreationCollisionOption.GenerateUniqueName);
await _mediaCapture.CapturePhotoToStorageFileAsync(ImageEncodingProperties.CreateJpeg(), photoStorageFile);
var writeableBmp = new WriteableBitmap(3000, 2000);
writeableBmp.SetSource(await photoStorageFile.OpenReadAsync());
var barcodeReader = new BarcodeReader
{
TryHarder = true,
AutoRotate = true
};
_result = barcodeReader.Decode(writeableBmp);
if (_result != null)
{
CaptureImage.Source = writeableBmp;
}
await photoStorageFile.DeleteAsync(StorageDeleteOption.PermanentDelete);
}
await _mediaCapture.StopPreviewAsync();
VideoCapture.Visibility = Visibility.Collapsed;
CaptureImage.Visibility = Visibility.Visible;
ScanResult.Text = _result.Text;
}
catch (Exception ex)
{
ScanResult.Text = ex.Message;
}
}
This code is modified from the downloaded demo in only two places.
1) I changed the VideoDeviceId from [1] to [0] because I only have a front facing camera.
2) The other change is in the creation of the new WriteableBitmap. The downloaded demo has the size set to (640, 360). When I tried it with that, I got an exception about index being outside the bounds of the array. I figured this was because my webcam has a higher resolution than that, so I increased the size to match (and I've tried exceeding) the resolution of my webcam. Now, when I run it, I get the following exception on the call to barcodeReader.Decode(writeableBmp):
System.AccessViolationException was unhandled
HResult=-2147467261
Message=Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
Source=mscorlib
StackTrace:
at System.Runtime.InteropServices.Marshal.CopyToManaged(IntPtr source, Object destination, Int32 startIndex, Int32 length)
at System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions.CopyTo(IBuffer source, UInt32 sourceIndex, Byte[] destination, Int32 destinationIndex, Int32 count)
at System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions.ToArray(IBuffer source, UInt32 sourceIndex, Int32 count)
at ZXing.BitmapLuminanceSource..ctor(WriteableBitmap writeableBitmap) in c:\Users\michael.jahn\Documents\SVN\ZXing.Net.Build\Source\lib\BitmapLuminanceSource.Silverlight.cs:line 50
at ZXing.BarcodeReader.<.cctor>b__4(WriteableBitmap bitmap) in c:\Users\michael.jahn\Documents\SVN\ZXing.Net.Build\Source\lib\BarcodeReader.cs:line 60
at ZXing.BarcodeReaderGeneric`1.Decode(T barcodeBitmap) in c:\Users\michael.jahn\Documents\SVN\ZXing.Net.Build\Source\lib\BarcodeReaderGeneric.cs:line 376
at WindowsRT.MainPage.<OnNavigatedTo>d__2.MoveNext() in c:\Users\Joseph Martinez\Documents\Visual Studio 2012\Projects\WindowsRTBarcodeDemo\MainPage.xaml.cs:line 53
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.MoveNextRunner.InvokeMoveNext(Object stateMachine)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Runtime.CompilerServices.AsyncMethodBuilderCore.MoveNextRunner.Run()
at System.Threading.Tasks.SynchronizationContextAwaitTaskContinuation.<.cctor>b__3(Object state)
at System.Threading.WinRTSynchronizationContext.Invoker.InvokeCore()
at System.Threading.WinRTSynchronizationContext.Invoker.InvokeInContext(Object thisObj)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.WinRTSynchronizationContext.Invoker.Invoke()
InnerException:
Again, this isn't my code, except for those two minor changes.
What could the problem be?
I modified the WindowsRT demo. It should work now for you.
You can get the current version from the repository:
https://zxingnet.svn.codeplex.com/svn/trunk
I used the solution from Damir and added some small other changes.
Are you sure (3000, 2000) is the exact resolution of your webcam? I suppose the above error could occur if the actual camera resolution was smaller than that.
Try determining the exact size of the image before creating WriteableBitmap:
await _mediaCapture.CapturePhotoToStorageFileAsync(ImageEncodingProperties.CreateJpeg(), photoStorageFile);
var stream = await photoStorageFile.OpenReadAsync()
var bmp = new BitmapImage();
bmp.SetSource(stream);
var writeableBmp = new WriteableBitmap(bmp.PixelWidth, bmp.PixelHeight);
stream.Seek(0);
writeableBmp.SetSource(stream);
You can set the correct size of WriteableBitmap directly from the video device properties.
And you should await the Source setter.
var properties = _mediaCapture.VideoDeviceController.GetMediaStreamProperties(MediaStreamType.VideoPreview);
var videoEncodingProperties = properties as VideoEncodingProperties;
writeableBmp = new WriteableBitmap((int)videoEncodingProperties.Width, (int)videoEncodingProperties.Height);
await writeableBmp.SetSourceAsync(await photoStorageFile.OpenReadAsync());

XElement.Load(stream) throws System.NotSupportedException

when i am gettting the bytes data,and i am trying to convert into XELement like below
using (Stream streamResult = new MemoryStream(byteArray))
{
XElement xElement = XElement.Load(streamResult); // exception thrown here
}
Here's the exception details:
A first chance exception of type 'System.NotSupportedException'
occurred in System.Xml.dll PageRequest::PostProcess :
System.NotSupportedException: NotSupportedException at
System.Xml.XmlTextReaderImpl.ParseText(Int32& startPos, Int32& endPos,
Int32& outOrChars) at
System.Xml.XmlTextReaderImpl.FinishPartialValue() at
System.Xml.XmlTextReaderImpl.get_Value() at
System.Xml.Linq.XContainer.ReadContentFrom(XmlReader r) at
System.Xml.Linq.XContainer.ReadContentFrom(XmlReader r, LoadOptions o)
at System.Xml.Linq.XElement.ReadElementFrom(XmlReader r, LoadOptions
o) at System.Xml.Linq.XElement..ctor(XmlReader r, LoadOptions o)
at System.Xml.Linq.XElement.Load(XmlReader reader, LoadOptions
options) at System.Xml.Linq.XElement.Load(Stream stream,
LoadOptions options)
Is the problem with the XML?
I encountered the System.NotSupportedException in my Windows Phone app when the stream didn't contain valid XML.
In my case I was using the response stream from a web request that was returning an error page in some cases.

Resources