How to use message pack in xamarin forms - c#

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

Related

Fo-dicom code compiling but not executing

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

Exception when trying to get reference to MongoDB collections with .Net Core 3.0 (MongoDB.Driver 2.8.0)

My Environment:
Microsoft.NETCore.Platforms (3.0.0-preview5.19224.8)
MongoDB.Driver (2.8.0)
My problem:
Before updating the version of "Microsoft.NETCore.Platforms" the following code worked perfectly:
//Collection of resales
public IMongoCollection<Revenda> CollRevendas;
public BaseRepository(IConfiguration config)
{
try
{
// Location of the database, configured in the "appsettings.json" file
var client = new MongoClient(config.GetConnectionString("Config.api.mstiDFE"));
// Name of the database
Database = client.GetDatabase("api_mstiDFE_II");
// Get the reference for the collection "Resales"
CollRevendas = Database.GetCollection<Revenda>("Revendas");
}
catch (System.Exception ex)
{
throw;
}
}
After updating, when attempting to execute the "CollRevendas = Database.GetCollection("Revendas");" statement, the following exception is thrown:
{"The type initializer for 'MongoDB.Bson.Serialization.BsonClassMap' threw an exception."}
With the following stack trace:
System.TypeInitializationException: The type initializer for 'MongoDB.Bson.Serialization.BsonClassMap' threw an exception. ---> System.ArgumentNullException: Value cannot be null.
Parameter name: type
at System.Reflection.IntrospectionExtensions.GetTypeInfo(Type type)
at MongoDB.Bson.Serialization.BsonClassMap..cctor()
--- End of inner exception stack trace ---
at MongoDB.Bson.Serialization.BsonClassMap.LookupClassMap(Type classType)
at MongoDB.Bson.Serialization.BsonClassMapSerializationProvider.GetSerializer(Type type, IBsonSerializerRegistry serializerRegistry)
at MongoDB.Bson.Serialization.BsonSerializerRegistry.CreateSerializer(Type type)
at System.Collections.Concurrent.ConcurrentDictionary`2.GetOrAdd(TKey key, Func`2 valueFactory)
at MongoDB.Bson.Serialization.BsonSerializerRegistry.GetSerializer[T]()
at MongoDB.Driver.MongoCollectionImpl`1..ctor(IMongoDatabase database, CollectionNamespace collectionNamespace, MongoCollectionSettings settings, ICluster cluster, IOperationExecutor operationExecutor)
at MongoDB.Driver.MongoDatabaseImpl.GetCollection[TDocument](String name, MongoCollectionSettings settings)
at api.mstiDFE.Infra.Repositories.BaseRepository..ctor(IConfiguration config) in C:\Users\Source\Workspace\api.mstiDFE\api.mstiDFE\Infra\Repositories\BaseRepository.cs:line 27
Unfortunately I can not downgrade the "Microsoft.NETCore.Platforms". So any hint will be very welcome.
Version 2.8.1 of the MongoDB Driver for C # was released yesterday (05-15-19).
Soon after asking this question, I obtained the information in the following link:
CSHARP-2595: Fix initialization on .NET Core 3.0 preview 4.
After upgrading to version 2.8.1, the issue was resolved.
So I'll leave the question here as it can serve other people with the same problem.
The same issue was happening in 2.9.0-beta1 also but updating to 2.9.0-beta2 fixed the issue for me.
You need to install MongoDB.Bson package also.
<PackageReference Include="MongoDB.Bson" Version="2.11.4" />
It worked for me.

Enterprise Library issue

We are using Enterprise Library 6.0 and the following code to create database instance and execute a stored procedure? Any help highly appreciated. Thanks in Advance.
DatabaseProviderFactory factory = new DatabaseProviderFactory();
Database db = factory.CreateDefault();
DbCommand dbCommand = db.GetStoredProcCommand("ProcedureName");
OracleParameter outval = new OracleParameter("Test", OracleDbType.RefCursor);
outval.Direction = ParameterDirection.Output;
dbCommand.Parameters.Add(outval);
using (IDataReader reader = db.ExecuteReader(dbCommand))
{
while (reader.Read())
{
}
}
<add name="providerConnString" connectionString="Data Source=ABCD;Password=testuser;User ID=testpwd" providerName="Oracle.DataAccess.Client" />
Intermittently we are receiving the following exception. This is occurring when we are trying to access the application after an idle time. How the connection pooling happens in enterprise library?How will it work if the application is idle for long time? What is the default min pool size and default max pool size?
Exception has been thrown by the target of an invocation.
System.Reflection.TargetInvocationException: Exception has been thrown
by the target of an invocation. --->
System.TypeInitializationException: The type initializer for
'Oracle.DataAccess.Client.OracleClientFactory' threw an exception.
---> System.TypeInitializationException: The type initializer for 'Oracle.DataAccess.Client.CThreadPool' threw an exception. --->
System.Runtime.InteropServices.COMException: Retrieving the COM class
factory for component with CLSID
{CB2F6723-AB3A-11D2-9C40-00C04FA30A3E} failed due to the following
error: 800703fa Illegal operation attempted on a registry key that has
been marked for deletion. (Exception from HRESULT: 0x800703FA). at
Oracle.DataAccess.Client.CThreadPool..cctor() --- End of inner
exception stack trace --- at
Oracle.DataAccess.Client.OracleInit.Initialize() --- End of inner
exception stack trace --- --- End of inner exception stack trace
--- at System.RuntimeFieldHandle.GetValue(RtFieldInfo field, Object instance, RuntimeType fieldType, RuntimeType declaringType, Boolean&
domainInitialized) at
System.Reflection.RtFieldInfo.UnsafeGetValue(Object obj) at
System.Reflection.RtFieldInfo.InternalGetValue(Object obj,
StackCrawlMark& stackMark) at
System.Reflection.RtFieldInfo.GetValue(Object obj) at
System.Data.Common.DbProviderFactories.GetFactory(DataRow providerRow)
at
Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSyntheticConfigSettings.GetDefaultMapping(String
dbProviderName) at
Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSyntheticConfigSettings.GetDatabaseData(ConnectionStringSettings
connectionString, DatabaseSettings databaseSettings) at
Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSyntheticConfigSettings.GetDatabase(String
name) at
Microsoft.Practices.EnterpriseLibrary.Data.DatabaseProviderFactory.DatabaseConfigurationBuilder.b__2(String
n) at
System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey
key, Func2 valueFactory) at
Microsoft.Practices.EnterpriseLibrary.Data.DatabaseProviderFactory.DatabaseConfigurationBuilder.CreateDefault()
I had a issue with the App pool identity user in IIS. I removed the identity user and put the default identity user. Then reverted back to my custom user identity. This resolved my issue.

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.

Python.CreateEngine() eventually throws System.Reflection.TargetInvocationException

After several cycles of debugging, Python.CreateEngine() eventually throws the exception shown below. I don't know why this is occurring and the version that I have installed is actually 2.7.4.1. I end up reinstalling IronPython and the exception disappears, but it eventually returns. I am using VS2010 with Windows 7.
System.Reflection.TargetInvocationException occurred
HResult=-2146232828
Message=Failed to load language 'IronPython 2.7.2.1': Method not found: '!!1[] Microsoft.Scripting.Utils.ArrayUtils.ConvertAll(!!0[], System.Func`2<!!0,!!1>)'.
Source=Microsoft.Scripting
StackTrace:
at Microsoft.Scripting.Runtime.LanguageConfiguration.LoadLanguageContext(ScriptDomainManager domainManager, Boolean& alreadyLoaded)
at Microsoft.Scripting.Runtime.DlrConfiguration.LoadLanguageContext(ScriptDomainManager manager, LanguageConfiguration config)
at Microsoft.Scripting.Runtime.DlrConfiguration.TryLoadLanguage(ScriptDomainManager manager, AssemblyQualifiedTypeName providerName, LanguageContext& language)
at Microsoft.Scripting.Runtime.ScriptDomainManager.GetLanguageByTypeName(String providerAssemblyQualifiedTypeName)
at Microsoft.Scripting.Hosting.ScriptRuntime.GetEngineByTypeName(String assemblyQualifiedTypeName)
at IronPython.Hosting.Python.GetEngine(ScriptRuntime runtime)
at IronPython.Hosting.Python.CreateEngine()
at OneWireTest.Form1.InitializeScriptEngine() in D:\IPYTest\Form1.cs:line 374
InnerException: System.MissingMethodException
HResult=-2146233069
Message=Method not found: '!!1[] Microsoft.Scripting.Utils.ArrayUtils.ConvertAll(!!0[], System.Func`2<!!0,!!1>)'.
Source=IronPython
StackTrace:
at IronPython.Runtime.PythonContext..ctor(ScriptDomainManager manager, IDictionary`2 options)
InnerException:

Categories