Fo-dicom code compiling but not executing - c#

I am trying following code to convert a dicom file to jpeg:
using System;
using System.IO;
using System.Drawing;
using Dicom.Imaging;
class RnReadDicom{
public static void Main(string[] args){
string fileName = "33141578.dcm";
var image = new DicomImage(fileName);
image.RenderImage().AsSharedBitmap().Save(#"test.jpg");
}}
I am compiling it with following command:
$ mcs a.cs -r:Dicom.Core.dll -r:Dicom.Native.dll -r:System.Drawing
The code compiles without any error but on running the exe file, it gives following error:
$ ./a.exe
Unhandled Exception:
System.TypeInitializationException: The type initializer for 'Dicom.DicomEncoding' threw an exception. ---> System.NullReferenceException: Object reference not set to an instance of an object
at Dicom.IO.IOManager.get_BaseEncoding () [0x00000] in <4b7c269b3e704f3f83dd85bb2721c76a>:0
at Dicom.DicomEncoding..cctor () [0x00000] in <4b7c269b3e704f3f83dd85bb2721c76a>:0
--- End of inner exception stack trace ---
at Dicom.Imaging.DicomImage..ctor (System.String fileName, System.Int32 frame) [0x00000] in <4b7c269b3e704f3f83dd85bb2721c76a>:0
at RnReadDicom.Main (System.String[] args) [0x00006] in <5c119b113a6e4d4b8058662dd31bab14>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.TypeInitializationException: The type initializer for 'Dicom.DicomEncoding' threw an exception. ---> System.NullReferenceException: Object reference not set to an instance of an object
at Dicom.IO.IOManager.get_BaseEncoding () [0x00000] in <4b7c269b3e704f3f83dd85bb2721c76a>:0
at Dicom.DicomEncoding..cctor () [0x00000] in <4b7c269b3e704f3f83dd85bb2721c76a>:0
--- End of inner exception stack trace ---
at Dicom.Imaging.DicomImage..ctor (System.String fileName, System.Int32 frame) [0x00000] in <4b7c269b3e704f3f83dd85bb2721c76a>:0
at RnReadDicom.Main (System.String[] args) [0x00006] in <5c119b113a6e4d4b8058662dd31bab14>:0
Where is the problem and how can it be solved? Thanks for your help.
Edit: I am having similar problem with another library for which I have posted another question. This is using a different library and the error is also different. I suspect answers to these questions will be different hence these are not duplicate question. Moreover, the other question does not have any answer yet.

This is probably due to the garbage collector destroying the image object. The Bitmap only contains a reference to the pixel data of the image to save space.
This has been described here before: C# System.Drawing.Image.get_Width() throws exception on WinForms form is maximized
To solve this, use it as this:
var image = new DicomImage(fileName);
image.RenderImage().AsClonedBitmap().Save(#"test.jpg");
By cloning, a real copy of the pixel data is performed.
However, it could be sometimes even trickier: If you e. g. use .NET Core as a starting project and the library, which references fo-dicom uses .NET Standard, you have to add either of these to the start of your program:
TranscoderManager.SetImplementation(new MonoTranscoderManager()); // limited codecs, but full .NET Core, runs on Linux. Or:
TranscoderManager.SetImplementation(new DesktopTranscoderManager()); // loads also native dlls, runs on Windows
ImageManager.SetImplementation(new RawImageManager()); // if you need .NET Core, you only have byte arrays
ImageManager.SetImplementation(new WinFormsImageManager()); //if you run Windows and have GDI
NetworkManager.SetImplementation(new DesktopNetworkManager()); // if you want to run dicom services

Related

System.DllNotFoundException: libpcsclite.so.1 assembly:<unknown assembly> type:<unknown type> member:(null)

Researched this issue many times but didn't found solution of it. Working with xamarin forms version 5.0.0.2012, on win 10 os (saw many solutions for mac or linux but didn't found any for windows), using PCSC library version 5.0.0. Trying to invoke context.Establish method while debugging on Android 8.0:
public SimpleReader(ISCardContext context, bool releaseContextOnDispose = false)
{
if (context == null)
{
context = (ISCardContext) new SCardContext();
context.Establish(SCardScope.System);
releaseContextOnDispose = true;
}
this._context = context;
this._reader = (ISCardReader) new SCardReader(context);
this._releaseContextOnDispose = releaseContextOnDispose;
this._disconnectReaderOnDispose = true;
}
When, exception occur with message below:
System.DllNotFoundException: libpcsclite.so.1 assembly:<unknown assembly> type:<unknown type> member:(null)
at (wrapper managed-to-native) PCSC.Interop.Linux.LinuxNativeMethods.SCardEstablishContext(intptr,intptr,intptr,intptr&)
at PCSC.Interop.Linux.PCSCliteLinux.EstablishContext (PCSC.SCardScope dwScope, System.IntPtr pvReserved1, System.IntPtr pvReserved2, System.IntPtr& phContext) [0x00006] in C:\Users\danm\src\pcsc-sharp\src\PCSC\Interop\Linux\PCSCliteLinux.cs:39
at PCSC.SCardContext.Establish (PCSC.SCardScope scope) [0x00020] in C:\Users\danm\src\pcsc-sharp\src\PCSC\SCardContext.cs:81
at App1xx.Services.SimpleReader.SimpleReader..ctor (PCSC.ISCardContext context, System.Boolean releaseContextOnDispose) [0x00023] in C:\Users\vzhynkin\source\repos\App1xx\App1xx\App1xx\Services\SimpleReaderLib\SimpleReader.cs:59
at App1xx.Services.SimpleReader.SimpleReader..ctor () [0x00000] in C:\Users\vzhynkin\source\repos\App1xx\App1xx\App1xx\Services\SimpleReaderLib\SimpleReader.cs:70
at App1xx.Services.UaIdRLib.IdCardReader.connect () [0x00002] in C:\Users\vzhynkin\source\repos\App1xx\App1xx\App1xx\Services\UaIdRLib\IdCardReader.cs:371
at App1xx.Views.AboutPage.OnButtonClicked (System.Object sender, System.EventArgs args) [0x0000f] in C:\Users\vzhynkin\source\repos\App1xx\App1xx\App1xx\Views\AboutPage.xaml.cs:22
at Xamarin.Forms.Button.Xamarin.Forms.Internals.IButtonElement.PropagateUpClicked () [0x00000] in D:\a\1\s\Xamarin.Forms.Core\Button.cs:187
at Xamarin.Forms.ButtonElement.ElementClicked (Xamarin.Forms.VisualElement visualElement, Xamarin.Forms.Internals.IButtonElement ButtonElementManager) [0x0001f] in D:\a\1\s\Xamarin.Forms.Core\ButtonElement.cs:61
at Xamarin.Forms.Button.SendClicked () [0x00000] in D:\a\1\s\Xamarin.Forms.Core\Button.cs:173
at Xamarin.Forms.Platform.Android.ButtonElementManager.OnClick (Xamarin.Forms.VisualElement element, Xamarin.Forms.IButtonController buttonController, Android.Views.View v) [0x00000] in D:\a\1\s\Xamarin.Forms.Platform.Android\ButtonElementManager.cs:25
at Xamarin.Forms.Platform.Android.FastRenderers.ButtonRenderer.Android.Views.View.IOnClickListener.OnClick (Android.Views.View v) [0x00000] in D:\a\1\s\Xamarin.Forms.Platform.Android\FastRenderers\ButtonRenderer.cs:72
at Android.Views.View+IOnClickListenerInvoker.n_OnClick_Landroid_view_View_ (System.IntPtr jnienv, System.IntPtr native__this, System.IntPtr native_v) [0x00010] in /Users/builder/azdo/_work/278/s/xamarin-android/src/Mono.Android/obj/Release/monoandroid10/android-30/mcw/Android.Views.View.cs:2252
at (wrapper dynamic-method) Android.Runtime.DynamicMethodNameCounter.68(intptr,intptr,intptr)
Does anyone faced with this issue?
The PCSC library does not appear to explicitly support Android. In my experience, nugets that work with Xamarin.Android have explicit dependencies set for the platform, but this one does not.
The library tries to use P/Invoke wrappers around native code. You can see that there are implementations for a number of operating systems here, but I don't see any references to Android. The stack trace shows that the code is deciding to use the Linux wrapper, which makes sense. It's looking for the libpcsclite.so.1 native "C/C++" library, but it's not finding it. That library has a home page that does not reference Android.
The PCSC nuget docs state:
pcsc-sharp does not contain any device drivers. A PC/SC compliant
reader + driver is mandatory.
That's the libpcsclite.so.1 . Either your Android device doesn't provide it, or if it does, it's not in a location that your Android app can find it. My Android device (running Android 9) does not have that library in any of /system/*lib* directories, which means that at least for my device someone would need to compile that native library for the CPU (usually arm64) for the device. If you can either compile the native code yourself or find someone who has, AND the native code supports the reader on your Android device, then you could get the whole thing to work.
I don't have any experience with PCSC myself - just some experience with Xamarin and native libraries.

How to use message pack in xamarin forms

I have to use MessagePack to deserialize data returned from a web API (ASP.net), which was Serialized using the same package.
Used the following code
public async static Task<T> DeserializeAsync<T>(Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream), "Stream value cannot be null");
}
stream.Position = 0;
T deserialized = await MessagePackSerializer.DeserializeAsync<T>(stream, MessagePack.Resolvers.ContractlessStandardResolver.Options).ConfigureAwait(false);
return deserialized;
}
All was working fine in Android in debug mode but in iOS both debug and release and in Android release mode. The deserialization code crashed with the following exceptions
Android -> Release
[MonoDroid] at MessagePa07-10 18:06:01.269 I/MonoDroid(13495): MessagePack.MessagePackSerializationException: Failed to deserialize Project.Core.Models.SomeData Class value. ---> System.TypeInitializationException: The type initializer for 'FormatterCache`1' threw an exception. ---> MessagePack.Internal.MessagePackDynamicObjectResolverException: can't find public constructor. type:System.Drawing.Drawing2D.Matrix
[MonoDroid] at MessagePack.Internal.ObjectSerializationInfo.CreateOrNull (System.Type type, System.Boolean forceStringKey, System.Boolean contractless, System.Boolean allowPrivate) [0x009a0] in <23c4c9b023514c20801c8f07fd69206c>:0
[MonoDroid] at MessagePack.Internal.DynamicObjectTypeBuilder.BuildType (MessagePack.Internal.DynamicAssembly assembly, System.Type type, System.Boolean forceStringKey, System.Boolean contractless) [0x00015] in <23c4c9b023514c20801c8f07fd69206c>:0
iOS->
System.TypeInitializationException: The type initializer for 'Project.Core.Helpers.BinarySerializer' threw an exception. ---> System.TypeInitializationException: The type initializer for 'MessagePack.Resolvers.ContractlessStandardResolver' threw an exception. ---> System.TypeInitializationException: The type initializer for 'MessagePack.Internal.StandardResolverHelper' threw an exception. ---> System.TypeInitializationException: The type initializer for 'MessagePack.Resolvers.DynamicEnumResolver' threw an exception. ---> System.PlatformNotSupportedException: Operation is not supported on this platform.
at MessagePack.Internal.DynamicAssembly..ctor (System.String moduleName) [0x0001a] in <f04e2061de5c414991b8e36a20354820>:0
at MessagePack.Resolvers.DynamicEnumResolver..cctor () [0x00010] in <f04e2061de5c414991b8e36a20354820>:0
--- End of inner exception stack trace ---
at (wrapper managed-to-native) System.Object.__icall_wrapper_mono_generic_class_init(intptr)
at MessagePack.Internal.StandardResolverHelper..cctor () [0x00000] in <f04e2061de5c414991b8e36a20354820>:0
--- End of inner exception stack trace ---
Found the section in the MessagePack git page specifying a way to overcome this issue using an Ahead of time code generator. I followed the steps but was not able to fix the issue. Also I'm sure I'm doing it right.
How do I use MessagePack in Xamarin.Forms. Can anyone who has already suggest me or provide a reference.
Update on steps followed
Used message pack serialization in a button click.
Installed mpc tool.
Used don't mpc -i "{FormsProject.csproj path}" -o "{FormsProject directory path}"
Added the created message pack generated class to the forms project.
Used the following code in App.xaml.cs Initialize method
StaticCompositeResolver.Instance.Register(
MessagePack.Resolvers.GeneratedResolver.Instance,
MessagePack.Resolvers.StandardResolver.Instance
Now also the (Operation is not supported in the platform) Exception is thrown. I'm not quite getting what I'm doing wring here.
Update 2:
Exception in the MessagePackSerializerOptions
System.TypeInitializationException: The type initializer for 'MessagePackSerializerOptionsDefaultSettingsLazyInitializationHelper' threw an exception. ---> System.TypeInitializationException: The type initializer for 'MessagePack.Resolvers.StandardResolver' threw an exception. ---> System.TypeInitializationException: The type initializer for 'MessagePack.Internal.StandardResolverHelper' threw an exception. ---> System.TypeInitializationException: The type initializer for 'MessagePack.Resolvers.DynamicEnumResolver' threw an exception. ---> System.PlatformNotSupportedException: Operation is not supported on this platform.
at System.Reflection.Emit.AssemblyBuilder.DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access) [0x00000] in /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/src/Xamarin.iOS/mcs/class/corlib/System.Reflection.Emit/AssemblyBuilder.pns.cs:129
at MessagePack.Internal.DynamicAssembly..ctor (System.String moduleName) [0x0001a] in <f04e2061de5c414991b8e36a20354820>:0
at MessagePack.Resolvers.DynamicEnumResolver..cctor () [0x00010] in <f04e2061de5c414991b8e36a20354820>:0
Require to set StaticCompositeResolver.Instance as default.
You lacks following code.
var option = MessagePackSerializerOptions.Standard.WithResolver(StaticCompositeResolver.Instance);
MessagePackSerializer.DefaultOptions = option;
Upgrade to version of MessagePack 2.1.165 or higher.
This issue was fixed in Message pack in version 2.1.165. Regarding the lazy loading of DynamicAssembly.
Issue link

Using Spire.Doc in Xamarin C#

Help me to correct this exception, idk what's that. I couldn't find any information about that. What do I need to do?
using System;
using Spire.Doc;
using Spire.Doc.Documents;
namespace TOC
{
class MainClass
{
public static void Main (string[] args)
{
Document document = new Document();
}
}
}
Unhandled Exception:
System.TypeLoadException: Could not load type 'Spire.Doc.Document'
from assembly 'Spire.Doc, Version=5.2.48.3040, Culture=neutral,
PublicKeyToken=663f351905198cb3'.
[ERROR] FATAL UNHANDLED EXCEPTION: System.TypeLoadException:
Could not load type 'Spire.Doc.Document' from assembly
'Spire.Doc, Version=5.2.48.3040, Culture=neutral,
PublicKeyToken=663f351905198cb3'.
I tried to create the solution again, then the problem disappeared and appear another one.
Unhandled Exception:
System.InvalidProgramException: Invalid IL code in
Spire.Doc.Document:ᜤ (): IL_0003: pop
at Spire.Doc.Document..ctor () [0x00000] in <filename unknown>:0
at TOC.MainClass.Main (System.String[] args) [0x00001] in
/Users/mac/Documents/Csharp/TOC/Program.cs:11
[ERROR] FATAL UNHANDLED EXCEPTION: System.InvalidProgramException:
Invalid IL code in Spire.Doc.Document:ᜤ (): IL_0003: pop
at Spire.Doc.Document..ctor () [0x00000] in <filename unknown>:0
at TOC.MainClass.Main (System.String[] args) [0x00001] in
/Users/mac/Documents/Csharp/TOC/Program.cs:11
It looks like so weird...
You have to contact Spire.Doc vendor as,
Mono CLR is different from .NET CLR, and therefore the obfuscated assembly optimized for .NET might not work for Mono. They should provide you probably another obfuscated version.
Mono API is not 100% the same as .NET API, so you need the vendor to confirm that they fully test the product against Mono.
Don't simply rely on MoMA for compatibility testing. That's only a prototype and it only provides very basic functionality.

Error with Unity iOS compile: Cross Compilation job Mono.WebBrowser.dll failed

have been working on a project intended for iOS deployment. Until recently, we have been building and deploying to our client via webplayer. However, I am now attempting to shift to releasing builds on iOS . But, no matter what I try, when I go to compile the project I receive the following error messages:
Cross compilation job Mono.WebBrowser.dll failed.
UnityEngine.UnityException: Failed AOT cross compiler: /Applications/Unity_45/Unity.app/Contents/PlaybackEngines/iOSSupport/Tools/OSX/mono-xcompiler --aot=full,asmonly,nodebug,static,outfile="Mono.WebBrowser.dll.s" "Mono.WebBrowser.dll" current dir : /Users/admin/Desktop/UI_gg_current/Temp/StagingArea/Data/Managed
Env: Apple_PubSub_Socket_Render = '/tmp/launch-7SV8Ex/Render'
LOGNAME = 'admin'
PATH = '/usr/bin:/bin:/usr/sbin:/sbin'
TMPDIR = '/var/folders/7c/s32nkpmx0yvgw4mmw_5vhxx40000gn/T/'
MONO_PATH = '/Users/admin/Desktop/UI_gg_current/Temp/StagingArea/Data/Managed'
SSH_AUTH_SOCK = '/tmp/launch-wpdtRI/Listeners'
USER = 'admin'
GC_DONT_GC = 'yes please'
Apple_Ubiquity_Message = '/tmp/launch-cfnoHv/Apple_Ubiquity_Message'
SHELL = '/bin/bash'
__CF_USER_TEXT_ENCODING = '0x1F5:0:0'
GAC_PATH = '/Users/admin/Desktop/UI_gg_current/Temp/StagingArea/Data/Managed'
HOME = '/Users/admin'
COMMAND_MODE = 'unix2003'
result file exists: False. Timed out: False
stdout:
stderr:
at UnityEditor.MonoProcessUtility.RunMonoProcess (System.Diagnostics.Process process, System.String name, System.String resultingFile) [0x00000] in <filename unknown>:0
at UnityEditor.MonoCrossCompile.CrossCompileAOT (BuildTarget target, System.String crossCompilerAbsolutePath, System.String assembliesAbsoluteDirectory, CrossCompileOptions crossCompileOptions, System.String input, System.String output, System.String additionalOptions) [0x00000] in <filename unknown>:0
at UnityEditor.MonoCrossCompile+JobCompileAOT.ThreadPoolCallback (System.Object threadContext) [0x00000] in <filename unknown>:0
UnityEditor.HostView:OnGUI()
and
Error building Player: UnityException: Cross compilation failed.
I am using Unity 4.5. To date I have : deleted third party dlls (including xml.linq.dll) , removed any instance of Lambda search operators (=>), and deleted the temp folder because I have seen these approaches used in similar situations (I know some aspects of Linq are not supported in iOS cross compile).
I have looked at similar issues such as this one: http://answers.unity3d.com/questions/439367/cross-compilation-failed-csharpdll.html. But, I am so perplexed, because it isn't the CSharp assembly causing my problem (which means it isn't one of my scripts?) I am not sure why it would even be including a WebBrowser.dll for an iOS build. Any help is greatly appreciated, as I feel I have searched far and wide for a resolution with no luck.
See the resolution that for this question here.

Why its not working?

BinaryReader br = new BinaryReader(Console.OpenStandardInput());
BinaryWriter bw = new BinaryWriter(Console.OpenStandardOutput());
int n = br.ReadInt32();
bw.Write(n);
always getting this error:
Unhandled Exception: System.IO.EndOfStreamException: Failed to read past end of stream.
at System.IO.BinaryReader.FillBuffer (Int32 numBytes) [0x00000] in <filename unknown>:0
at System.IO.BinaryReader.ReadInt32 () [0x00000] in <filename unknown>:0
at Program.Main () [0x00025] in /home/skydos/ACM/Csharp/Csharp/Main.cs:24
Is there any way to make reading data in C# faster from Console?
Are you writing anything to the standard input of your program? The error says there's no data available, quite simple.
There are plenty of examples in the MSDN documentation on how to go about dealing with System.IO stuff. Maybe this link will get you started?
http://msdn.microsoft.com/en-us/library/ms404278.aspx?appId=Dev10IDEF1&l=EN-US&k=k(SYSTEM.IO.BINARYREADER);k(TargetFrameworkMoniker-%22.NETFRAMEWORK&k=VERSION=V4.0%22);k(DevLang-CSHARP)&rd=true
If speed is your main concern, perhaps this article at Code Project will give you some ideas:
http://www.codeproject.com/KB/files/fastbinaryfileinput.aspx

Categories