TypeLoadException with D3DotNetAPI - c#

I'm trying to use the D3DotNetAPI to create a Windows Phone 7 application.
Here is the link with the documentation : D3DotNetAPI documentation link
I'm just trying to follow the sample and to do this :
D3Explorer explorer = new D3Explorer(Region.EU);
//Career data for Battletag Gaidin#2380
Career myCareer = explorer.GetCareer("Gaidin", 2380);
MessageBox.Show("Has killed "+ myCareer.Kills.Monsters+" monstters, with "+ myCareer.Kills.Elites+" elites.");
And I throw this exception :
System.TypeLoadException: Could not load type 'System.Runtime.Serialization.ISerializable' from assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e'.
at D3DotNetAPI.D3Explorer.TryGetData[T](String url, T& requestedObject)
at D3DotNetAPI.D3Explorer.GetCareer(String battleTagName, Int32 battleTagCode)
at d3.MainPage..ctor()
I'm not sure, but my exception can be similar with this stack overflow answer
PS : The same example works fine on a Win32 application.

Auto Answer :
ISerializable is not available in WP (WP = a part of .NET framework)

Related

Why SortedSet cannot be deserialized using Blazor webassembly on GitHub Pages?

I tried to make a blazor WebAssembly web site (hosted on Github Pages) that calls a cloud-based API (AWS). It receives a Json-serialized that contains a SortedSet value and deserialized it.
I tried to isolate the issue, and finally got to the minimum code where it can be reproduced, namely it's when you try to deserialize a SortedSet right away.
#page "/"
<button onclick="#Deserialize">Deserialize</button>
<br />Message: #message
#code
{
private string message = "Nothing happened yet";
private void Deserialize()
{
try
{
SortedSet<int> sortedSet = JsonSerializer.Deserialize<SortedSet<int>>("[1,2,3]");
message = $"Deserialized SortedSet: {string.Join(",", sortedSet)}";
}
catch (Exception e)
{
message = $"Deserialization ended up in an exception: {e}";
}
}
}
Here is an error:
System.NotSupportedException: DeserializeNoConstructor, JsonConstructorAttribute,
System.Collections.Generic.SortedSet`1[System.Int32]
Path: $ | LineNumber: 0 | BytePositionInLine: 1.
---> System.NotSupportedException: DeserializeNoConstructor,
JsonConstructorAttribute,
System.Collections.Generic.SortedSet`1[System.Int32]
Exception_EndOfInnerExceptionStack
at System.Text.Json.ThrowHelper.ThrowNotSupportedException(ReadStack& , Utf8JsonReader& , NotSupportedException )
at System.Text.Json.ThrowHelper.ThrowNotSupportedException_DeserializeNoConstructor(Type , Utf8JsonReader& , ReadStack& )
at System.Text.Json.Serialization.Converters.ISetOfTConverter`2[[System.Collections.Generic.SortedSet`1[[System.Int32, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Collections, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a],[System.Int32, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].CreateCollection(Utf8JsonReader& , ReadStack& , JsonSerializerOptions )
at System.Text.Json.Serialization.JsonCollectionConverter`2[[System.Collections.Generic.SortedSet`1[[System.Int32, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Collections, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a],[System.Int32, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]].OnTryRead(Utf8JsonReader& , Type , JsonSerializerOptions , ReadStack& , SortedSet`1& )
at System.Text.Json.Serialization.JsonConverter`1[[System.Collections.Generic.SortedSet`1[[System.Int32, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Collections, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a]].TryRead(Utf8JsonReader& , Type , JsonSerializerOptions , ReadStack& , SortedSet`1& )
at System.Text.Json.Serialization.JsonConverter`1[[System.Collections.Generic.SortedSet`1[[System.Int32, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]], System.Collections, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a]].ReadCore(Utf8JsonReader& , JsonSerializerOptions , ReadStack& )
at System.Text.Json.JsonSerializer.ReadFromSpan[SortedSet`1](ReadOnlySpan`1 , JsonTypeInfo , Nullable`1 )
at System.Text.Json.JsonSerializer.ReadFromSpan[SortedSet`1](ReadOnlySpan`1 , JsonTypeInfo )
at System.Text.Json.JsonSerializer.Deserialize[SortedSet`1](String , JsonSerializerOptions )
at SortedSetDeserializationDemo.Pages.Index.Deserialize()
It appears only when hosting on GitHub Pages, and I could not reproduce it when running from Visual Studio.
I have found how it can be fixed. You should serialize any (possibly non-empty) SortedSet before deserializing any SortedSet.
Here are some strange details:
There is still an error if I add serialization right after the deserialization attempt
There is no error if I do serialization in another method, bound to a button. Even if I don't use that button.
No errors when deserializing a List
Some other details that may be relevant:
It does not depend on Release/Debug configuration. I did not test all the possible scenarios, but the ones I tested yield to the same result. It seems that it may be related to JIT.
It can be reproduced in Chrome and Edge.
.NET 6.0 is used (tried both 6.0.10 and 6.0.11)
Here are my questions:
What it might be?
If it's a bug, is it a .NET/Blazor bug, GitHub Pages bug or browser bug?
As #HenkHolterman mentioned in the comments, something happens during publish. I tried to compare publish output with and without serialization before deserialization, and it appears that there was different System.Collections.dll. Without s11n it is 8.5KB and with s11n it is 13KB. If I replace only System.Collections.dll to the 13KB version and adjust its hash in blazor.boot.json, everything works correctly. I'm going to create a bug report for dotnet about it.
Upd: it appears that it's enough to add a SortedSet constructor.
It explains the odd behavior I observed. It worked with the deserialization before serialization because I had to create a SortedSet to serialize, and I called a SortedSet constructor. When I called Serialize(SortedSet) after deserialization, I used a value that I got from deserialization, so no SortedSet constructor was called from compiled code directly.
In my case serialization in a reflection mode takes place, thus the publishing code is not aware that the SortedSet constructor is used in my application. Thus publishing trims the SortedSet parameterless constructor.
Another wourkaround would be to use source generation
Apparently, they aren't going to change anything about it, see https://github.com/dotnet/runtime/issues/78776 for the details.

Creating a signalR client HubConnection with Powershell

I am trying to connect to a SignalR hub using a powershell script. I am very new to powershell, so please excuse any rookie mistake.
I have set up a minimal not working example of what I have tried here :
Gist
Relevant code:
Load dlls
$dllFolder = -join((Get-Item -Path ".\" -Verbose).FullName, "\bin\Debug\")
[string[]] $dllPathsToLoad = #("\Newtonsoft.Json.dll", "\Microsoft.AspNet.SignalR.Client.dll")
$token = "insertyourtokenhere"
function LoadDllPaths($dlls)
{
foreach ($dll in $dlls)
{
$dllpath = $dllFolder + $dll
[System.Reflection.Assembly]::LoadFrom($dllpath)
}
}
[...]
LoadDllPaths($dllPathsToLoad)
Create HubConnection:
$server = "https://localhost/rest/"
[...]
$hub = New-Object Microsoft.AspNet.SignalR.Client.HubConnection($server)
Steps:
Create a new Visual Studio project
Add Newtonsoft.Json v10.0.2 Nuget package (latest)
Add Microsoft.AspNet.SignalR.Client v2.2.2 Nuget package (latest)
Add powershell script to the root of the project
With powershell (run as admin), type .\HubConnectionTestsScript.ps1
Result:
View on imgur
Error : System.Management.Automation.MethodInvocationException: Exception calling ".ctor" with "1" argument(s): "Could not load file or assembly 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The system cannot find the file specified." ---> System.IO.FileNotFoundException: Could not load file or assembly 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The system cannot find the file specified.
at Microsoft.AspNet.SignalR.Client.Connection..ctor(String url, String queryString)
at Microsoft.AspNet.SignalR.Client.HubConnection..ctor(String url, Boolean useDefaultUrl)
--- End of inner exception stack trace ---
at System.Management.Automation.DotNetAdapter.AuxiliaryConstructorInvoke(MethodInformation methodInformation, Object[] arguments, Object[] originalArguments)
at System.Management.Automation.DotNetAdapter.ConstructorInvokeDotNet(Type type, ConstructorInfo[] constructors, Object[] arguments)
at Microsoft.PowerShell.Commands.NewObjectCommand.CallConstructor(Type type, ConstructorInfo[] constructors, Object[] args)
This signalR source code object seems to be the problem, I just don't see what part of it can be throwing this error.
Question:
Why does the error mention Newtonsoft.Json v6.0.0 when signalR dependencies say >=6.0.4, and I have 10.0.2?
Am I doing anything wrong in my Powershell script which could be causing this?
Thank you very much! Any help is appreciated at this point
I managed to solve this issue with some help from a colleague. Sharing the solution here in case anyone ever struggles on the same problem.
It appears that one of SignalR dependencies tries to load an old version of Newtonsoft.Json. We can force it to redirect him to our own instance of Newtonsoft.Json
Inspired by this gist, here is the idea :
When you load your Json Assembly, store it in a variable
$newtonsoftAssembly = [System.Reflection.Assembly]::LoadFrom($dllFolder + "\Newtonsoft.Json.dll")
Afterwards, setup the redirect bindings. My best guess is that this intercepts any call to load an assembly, giving us the opportunity to return our own Json assembly instead of letting him fail to find the version he wants (6.0.0 in my case).
function RedirectJsonBindings()
{
$onAssemblyResolveEventHandler = [System.ResolveEventHandler] {
param($sender, $e)
# You can make this condition more or less version specific as suits your requirements
if ($e.Name.StartsWith("Newtonsoft.Json")) {
Write-Host "Newtonsoft assembly" $e.Name -ForegroundColor DarkGreen
return $newtonsoftAssembly
}
foreach($assembly in [System.AppDomain]::CurrentDomain.GetAssemblies()) {
if ($assembly.FullName -eq $e.Name) {
return $assembly
}
}
return $null
}
[System.AppDomain]::CurrentDomain.add_AssemblyResolve($onAssemblyResolveEventHandler)
}
And finally, at the end of your script, unbind
# Detach the event handler (not detaching can lead to stack overflow issues when closing PS)
[System.AppDomain]::CurrentDomain.remove_AssemblyResolve($onAssemblyResolveEventHandler)

How can I make SourceAFIS work on Ubuntu?

I am trying to use SourceAFIS 1.7.0 on Ubuntu with mono and get a few error.
1.
$ mono DatabaseAnalyzer.exe
Scanning folder TestDatabase
Running extractor benchmark
Unhandled Exception: System.IO.FileNotFoundException: Could not load
file or assembly 'PresentationCore, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35' or one of its dependencies.
File name: 'PresentationCore, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35'
at DatabaseAnalyzer.DatabaseAnalyzer.RunExtractorBenchmark ()
<0x40674790
+ 0x00033> in :0 at DatabaseAnalyzer.DatabaseAnalyzer.RunMatcherBenchmark () <0x40674600 +
0x000eb> in :0
at DatabaseAnalyzer.DatabaseAnalyzer.Run () <0x40642a40 + 0x000bf> in
:0
at DatabaseAnalyzer.DatabaseAnalyzer.Main (System.String[] args)
<0x4063bd50 + 0x00037> in :0
[ERROR] FATAL UNHANDLED EXCEPTION: System.IO.FileNotFoundException:
Could not load file or assembly 'PresentationCore, Version=4.0.0.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its
dependencies.
File name: 'PresentationCore, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35' at
DatabaseAnalyzer.DatabaseAnalyzer.RunExtractorBenchmark () <0x40674790
+ 0x00033> in :0 at DatabaseAnalyzer.DatabaseAnalyzer.RunMatcherBenchmark () <0x40674600 +
0x000eb> in :0
at DatabaseAnalyzer.DatabaseAnalyzer.Run () <0x40642a40 + 0x000bf> in
:0
at DatabaseAnalyzer.DatabaseAnalyzer.Main (System.String[] args)
<0x4063bd50 + 0x00037> in :0
According to https://sourceforge.net/p/sourceafis/discussion/1051112/thread/dd8df289/#a006, WinForms should be applied here instead of WPF and use bitmap class to replace the bitmapimage class of WPF, but I don't know how to do it exactly. Does anybody have such experience?
This is the original function used WPF bitmap class
static MyPerson Enroll(string filename, string name)
{
Console.WriteLine("Enrolling {0}...", name);
// Initialize empty fingerprint object and set properties
MyFingerprint fp = new MyFingerprint();
fp.Filename = filename;
// Load image from the file
Console.WriteLine(" Loading image from {0}...", filename);
BitmapImage image = new BitmapImage(new Uri(filename, UriKind.RelativeOrAbsolute));
fp.AsBitmapSource = image;
// Above update of fp.AsBitmapSource initialized also raw image in fp.Image
// Check raw image dimensions, Y axis is first, X axis is second
Console.WriteLine(" Image size = {0} x {1} (width x height)", fp.Image.GetLength(1), fp.Image.GetLength(0));
// Initialize empty person object and set its properties
MyPerson person = new MyPerson();
person.Name = name;
// Add fingerprint to the person
person.Fingerprints.Add(fp);
// Execute extraction in order to initialize fp.Template
Console.WriteLine(" Extracting template...");
Afis.Extract(person);
// Check template size
Console.WriteLine(" Template size = {0} bytes", fp.Template.Length);
return person;
}
$ mono SourceAFIS.FingerprintAnalysis.exe
The entry point method could not be loaded
How can I fix this with a more meaningful exception?
WinForms should be applied here instead of WPF and use bitmap class to
replace the bitmapimage class of WPF, but I don't know how to do it
exactly. Does anybody have such experience?
Do you know how to program in C# language? What they mean in that forum is that you need to change the code to not use the WPF library, but Windows Forms UI toolkit.
If you get exceptions trying to load "PresentationCore" at runtime, it means it's still trying to load WPF.
Try installing mono-complete package, e.g.
apt-get install mono-complete
Related: Mono, failing to open executable.
Also make sure you've .NET Framework installed, e.g. by using winetricks:
apt-get install winetricks
winetricks dotnet46
See: Could not load file or assembly 'PresentationCore'.
PresentationCore is .NET 4
Further more, you can try the following suggestions:
In IIS try to Enable 32-Bit Applications in the Application Pools's Advanced Settings
Configure authentication as follow:
Disable Anonymous Authentication.
Enable ASP.NET Impersonation.
Enable Windows Authentication.

Unable to access .resx file from Windows 8.1 Runtime windows store app project

I am developing Windows Phone 8.1(WinRT) windows store app project. I have developed different PCL project for DataConnection, ServiceConnection etc...which I am referencing in WP 8.1 project. In DataConnection pcl I have all .resx files which were created under .net 4.0 target. All my PCL projects were created in Xamarin Studio for cross platform(Android, iOS, WP). Now I opened my project in Visual Studio Premium 2013 in-order to develop WP project and changed my target framework from .net 4.0 to 4.5, since WP 8.1 requires 4.5 as target.
After changing, I am unable to read string resources values from Windows Phone project. While executing below line,
string test = Test.String1;
It throws exception as,
An exception of type 'System.ArgumentNullException' occurred in mscorlib.ni.dll but was not handled in user code
Additional information: Value cannot be null.
Exception Trace:
System.ArgumentNullException was unhandled by user code
HResult=-2147467261
Message=Value cannot be null.
Parameter name: format
Source=mscorlib
ParamName=format
StackTrace:
at System.String.Format(IFormatProvider provider, String format, Object[] args)
at System.Environment.GetResourceString(String key, Object[] values)
at System.Resources.ResourceManager.GetString(String name, CultureInfo culture)
at App.Core.Resources.Test.get_String1()
at App.Forms.WindowsPhoneUI.MainPage..ctor()
at App.Forms.WindowsPhoneUI.App_Forms_WindowsPhoneUI_XamlTypeInfo.XamlTypeInfoProvider.Activate_4_MainPage()
at App.Forms.WindowsPhoneUI.App_Forms_WindowsPhoneUI_XamlTypeInfo.XamlUserType.ActivateInstance()
InnerException:
Screenshot:
What is going wrong here? Please someone help me to fix this.
This blog helped me to fix this issue. Although the exceptions were different, in the blog its mentioned as MissingManifestResourceException whereas I was getting ArgumentNull exception, but internal it was crashing in Getstring method in both the cases.
Code Referred from above blog:
I added below class in my project.
public class WindowsRuntimeResourceManager : ResourceManager
{
private readonly ResourceLoader resourceLoader;
private WindowsRuntimeResourceManager(string baseName, Assembly assembly) : base(baseName, assembly)
{
this.resourceLoader = ResourceLoader.GetForViewIndependentUse(baseName);
}
public static void InjectIntoResxGeneratedApplicationResourcesClass(Type resxGeneratedApplicationResourcesClass)
{
resxGeneratedApplicationResourcesClass.GetRuntimeFields()
.First(m => m.Name == "resourceMan")
.SetValue(null, new WindowsRuntimeResourceManager(resxGeneratedApplicationResourcesClass.FullName, resxGeneratedApplicationResourcesClass.GetTypeInfo().Assembly));
}
public override string GetString(string name, CultureInfo culture)
{
return this.resourceLoader.GetString(name);
}
}
And in Windows Phone project before calling resource file, just have to call below method.
WindowsRuntimeResourceManager.InjectIntoResxGeneratedApplicationResourcesClass(typeof(App.Resources.Account));
string test = App.Resources.Account.Error_CouldnotCreateUserProfile;

Creating instance of class accessor

I am currently writing a unit test framework which shall in the end run standard unit tests written in Visual Studio. The Framework is currently not working correctly with accessors. Consider the following test method:
[TestMethod()]
public void TestMethod()
{
ExampleMethods_Accessor target = null;
target = new ExampleMethods_Accessor();
target.SomeMethod();
}
In this example, the accessor has been generated by Visual Studio. The unit test works perfectly fine when run using the Unit Testing environment of Visual Studio. However, I would like to invoke the TestMethod() from within my Framework. At the line "target = new ExampleMethods_Accessor()", the following exception is thrown:
The type initializer for "Proband.ExampleMethods_Accessor" threw an excepition.
Inner exception:
Could not load file or assembly: Proband, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null...
Has anyone an idea of how the Microsoft Unit Testing Framework invokes unit tests? I was thinking it might be due to the missing TestContext object. This is "null" in my case. When starting the unit test in Visual Studio, the TestContext object contains a lot of information. Could it be, that I need to initialize it properly? How would it need to be initialized?
Thanks for all help,
Christian
EDIT:
I kept experimenting with the way accessors are working. I used ILSpy to see what code is being generated into the Proband_Accessor.dll. It turns out that the instruction causing the exception is:
SomeClass_Accessor.m_privateType = new PrivateType("Probant, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Probant.SomeClass");
I modified my unit test code to be like this (just for test):
[TestMethod()]
[DeploymentItem("Proband.dll")]
public void SomeMethodTest()
{
ExampleMethods_Accessor target = null;
ExampleMethods c = null;
try
{
Assembly.Load("Proband, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"); // this works fine
PrivateType tx = new PrivateType(typeof(ExampleMethods)); // this works fine as well (also without loading the assembly)
PrivateType t = new PrivateType("Proband, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "Proband.ExampleMethods"); // this causes the exception
c = new ExampleMethods(); // this works fine
target = new ExampleMethods_Accessor(); // this causes the exception as well
}
catch (Exception ex)
{
Console.WriteLine();
}
int actual;
actual = target.SomeMethod();
}
I do absolutely not understand, why "new PrivateType("Proband, Version...." does not work. Has anyone an idea?
I have managed to create a workaround for the issue.
To my AppDomain, I am adding an AssemblyResolveEventHandler:
AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(MyResolveEventHandler);
This event handler contains the following code:
private Assembly MyResolveEventHandler(object sender, ResolveEventArgs args)
{
if(args.Name == "Proband, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null")
{
// resolving correct assembly of type under test
return typeof(ExampleMethods).Assembly;
}
else
{
return null;
}
}
Now the line of code "target = new ExampleMethods_Accessor();" works fine and returns the correct accessor object.
I still do not understand, why the Assembly cannot be resolved automatically.
Even if it is very unlikely that anyone will have the same problem: I hope this answer helps someone :)
I am not doing anything nearly as complex, but I had:
web application project using .NET 3.5
Configuration project using .NET 3.5
Test project using .NET 3.5
I was getting the same BadImageFormat exception when trying to run a unit test using an accessor.
I found the following link:
http://connect.microsoft.com/VisualStudio/feedback/details/677203/even-after-installing-vs2010-sp1-unit-tests-targeting-3-5-framework-fail-if-they-are-using-private-accessor#details
The second work-around solved my problem. I changed the test project to target .NET 4.0 and it worked.
I just had this exact problem, and it was because I removed the DeploymentItem attribute from the test method. Once I added it again, I no longer got the error on the build machine.
[TestMethod]
[DeploymentItem("FedImportServer.dll")] // ** This is necessary for the build machine. **
public void SourceFileStillExistsAfterProcessingFails()
Note: I never got the error when running it locally.
This is the error:
Test method FedImportTests.FedImportServiceHostTest.FileNoLongerExistsAfterSucessfulProcessing threw exception:
System.TypeInitializationException: The type initializer for 'FedImportServer.Processing.FileProcessor_Accessor' threw an exception. ---> System.IO.FileNotFoundException: Could not load file or assembly 'FedImportServer, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

Categories