I'm developing in C#, and using Dotnetzip's Source code to get the application in one file.
But when running, i get the exception:
System.OverflowException: Arithmetic operation resulted in an overflow.
at Ionic.Crc.CRC32..ctor(Int32 polynomial, Boolean reverseBits) in DotNetZip\CRC32.cs:line 452
at Ionic.Crc.CRC32..ctor(Boolean reverseBits) in DotNetZip\CRC32.cs:line 418
at Ionic.Crc.CRC32..ctor() in DotNetZip\CRC32.cs:line 398
at Ionic.Crc.CrcCalculatorStream..ctor(Boolean leaveOpen, Int64 length, Stream stream, CRC32 crc32) in DotNetZip\CRC32.cs:line 622
at Ionic.Crc.CrcCalculatorStream..ctor(Stream stream) in DotNetZip\CRC32.cs:line 519
at Ionic.Zip.ZipEntry.ExtractOne(Stream output) in DotNetZip\ZipEntry.Extract.cs:line 1043
at Ionic.Zip.ZipEntry.InternalExtract(String baseDir, Stream outstream, String password) in DotNetZip\ZipEntry.Extract.cs:line 870
at Ionic.Zip.ZipEntry.Extract(String baseDirectory, ExtractExistingFileAction extractExistingFile) in DotNetZip\ZipEntry.Extract.cs:line 240
at ItxInstaller.Package.GetData(String instFilePath) in Package.cs:line 32
at ItxInstaller.Install..ctor() in Install.cs:line 26
at ItxInstaller.Program.Main(String[] args) in Program.cs:line 54
The Install.cs is like this:
public Install()
{
// The InitializeComponent() call is required for Windows Forms designer support.
this.InitializeComponent();
Package pack = Package.GetData(Program.args[1]);
this.Title.Text = pack.AppName;
this.PathBox.Text = pack.GeneratePath();
}
The Package.cs contains the GetData():
class Package
{
public string AppName;
public string ExePath;
private string FilePath;
public Package(string filePath)
{
this.ValueInit(filePath);
this.FilePath = filePath;
}
public static Package GetData(string instFilePath)
{
using (ZipFile Package = ZipFile.Read(instFilePath))
{
Package["app.itx"].Extract(Path.GetTempPath(), ExtractExistingFileAction.OverwriteSilently);
}
return new Package(Path.Combine(Path.GetTempPath(), "app.itx"));
}
}
How to solve this exception?
I can reproduce this problem with Mono when using "-checked+" as parameter, i.e. with enabled arithmetic checks. Omitting this parameter results in a working executable.
There is also a project setting for it in Visual Studio.
I've extracted the relevant code into this working program so you can test it yourself:
using System;
namespace Test {
public class Program {
public static void Main(string[] args) {
CRC32 test = new CRC32();
Console.Out.WriteLine(test.dwPolynomial);
}
}
public class CRC32 {
public UInt32 dwPolynomial;
public CRC32() : this(false) {
}
public CRC32(bool reverseBits) :
this(unchecked((int)0xEDB88320), reverseBits) {
}
public CRC32(int polynomial, bool reverseBits) {
this.dwPolynomial = (uint) polynomial; // this is line 452
}
}
}
Using dcms test.cs && mono test.exe runs fine.
Using dcms -checked+ test.cs && mono test.exe results in a
Unhandled Exception: System.OverflowException: Number overflow.
at Test.Program.Main (System.String[] args) [0x00000] in <filename unknown>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.OverflowException: Number overflow.
at Test.Program.Main (System.String[] args) [0x00000] in <filename unknown>:0
Update: if you can't or don't want to disable arithmetic checks then you could modify the source code of like 452 to
this.dwPolynomial = unchecked((uint) polynomial);
This turns off arithmetic checks for the expression.
Related
I am practising on an online compiler. I have to write the factorial program that, given a number n from STDIN, it prints out the factorial of n to STDOUT:
I have written this
using System;
using System.Collections.Generic;
using System.IO;
class Solution {
static void Main(String[] args) {
int result=1;
int fact = int.Parse(args[0]);
if(fact==0)
{
Console.WriteLine(result);
}
else
{
for(int i=fact;i>=1;i--)
result = i*result;
}
Console.WriteLine(result);
}
}
I know in C, we use atoi. I also tried using simple Console.ReadLine() but it simply fails the test case.
Currently, I am getting the following error -
Unhandled Exception:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at Solution.Main (System.String[] args) [0x00002] in <31af8dc2b3da4d24a38e31199d9b8949>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.IndexOutOfRangeException: Index was outside the bounds of the array.
at Solution.Main (System.String[] args) [0x00002] in <31af8dc2b3da4d24a38e31199d9b8949>:0
I made a very simple program with C# VS2017 and Matlab 2012b:
namespace TestConMatlab
{
class Program
{
static void Main(string[] args)
{
try
{
var matlab = new MatlabFunction();
double[] data = { 1, 2, 3 };
double[,] r = (double[,])matlab.doMedian(data.ToArray());
Console.Out.Write("OK: " + r.ToString());
} catch( Exception ex )
{
Console.Out.Write(ex.ToString());
}
Console.ReadLine();
}
}
}
This program run on mulitple PC, but on one computer I have :
System.Exception:
... MWMCR::EvaluateFunction error ...
Undefined function 'doMedian' for input arguments of type 'double'..
at MathWorks.MATLAB.NET.Utility.MWMCR.EvaluateFunction(String functionName, Int32 numArgsOut, Int32 numArgsIn, MWArray[] argsIn)
at MathWorks.MATLAB.NET.Utility.MWMCR.EvaluateFunction(String functionName, Object[] argsIn)
at MatlabFunctionNative.MatlabFunction.doMedian(Object input)
at TestConMatlab.Program.Main(String[] args) in C:\Users\User\source\repos\TestConMatlab\Program.cs:line 18
Of course I have installed the same Matlab MCR v8.0. I have trace some API call with procmon but I did not find solution.
I have deleted the folder C:\Users\%USER%\AppData\Local\Temp\%USER%\mcrCache8.0
Remove MCR and delete manualy C:\Program Files (x86)\MATLAB, and after restart, program work !
I'm trying to run a transaction with realtime database to change an object, with the following code :
void tryBeHost()
{
string path = "weeks/" + week + "/games/" + gameId + "/gameInfo";
_dbRef.Child(path).RunTransaction(mutableData =>
{
GameInfo gameInfo = mutableData.Value as GameInfo;
if (gameInfo == null)
{
gameInfo = new GameInfo();
}
else if (gameInfo.host != null && gameInfo.host != myId)
{
return TransactionResult.Success(mutableData);
}
gameInfo.host = myId;
mutableData.Value = gameInfo;
return TransactionResult.Success(mutableData);
});
}
so I'm getting this weird error :
Exception in transaction delegate, aborting transaction
Firebase.Database.DatabaseException: Failed to parse object Serializables.GameInfo ---> System.ArgumentException: Invalid type Serializables.GameInfo for conversion to Variant
at Firebase.Variant.FromObject (System.Object o) [0x001df] in Z:\tmp\tmp.EaS8iXpRBh\firebase\app\client\unity\proxy\Variant.cs:117
at Firebase.Database.Internal.Utilities.MakeVariant (System.Object value) [0x00000] in Z:\tmp\tmp.sZ8vrpcx53\firebase\database\client\unity\proxy\Utilities.cs:25
--- End of inner exception stack trace ---
at Firebase.Database.Internal.Utilities.MakeVariant (System.Object value) [0x0000d] in Z:\tmp\tmp.sZ8vrpcx53\firebase\database\client\unity\proxy\Utilities.cs:27
at Firebase.Database.MutableData.set_Value (System.Object value) [0x00000] in Z:\tmp\tmp.sZ8vrpcx53\firebase\database\client\unity\proxy\MutableData.cs:136
at InternetShit.b__10_0 (Firebase.Database.MutableData mutableData) [0x00045] in /Users/sandukhan/Unity/projects/Ronda/Assets/Scripts/InternetShit.cs:73
at Firebase.Database.Internal.InternalTransactionHandler.DoTransaction (System.Int32 callbackId, System.IntPtr mutableData) [0x00022] in
Z:\tmp\tmp.sZ8vrpcx53\firebase\database\client\unity\proxy\InternalTransactionHandler.cs:49
UnityEngine.Debug:LogWarning(Object)
Firebase.Platform.FirebaseLogger:LogMessage(PlatformLogLevel, String) (at Z:/tmp/tmp.BbQyA8B710/firebase/app/client/unity/src/Unity/FirebaseLogger.cs:92)
Firebase.LogUtil:LogMessage(LogLevel, String) (at Z:/tmp/tmp.EaS8iXpRBh/firebase/app/client/unity/proxy/LogUtil.cs:68)
Firebase.Database.Internal.InternalTransactionHandler:DoTransaction(Int32, IntPtr) (at Z:/tmp/tmp.sZ8vrpcx53/firebase/database/client/unity/proxy/InternalTransactionHandler.cs:51)
Firebase.AppUtilPINVOKE:PollCallbacks()
Firebase.AppUtil:PollCallbacks() (at Z:/tmp/tmp.EaS8iXpRBh/firebase/app/client/unity/proxy/AppUtil.cs:32)
Firebase.Platform.FirebaseAppUtils:PollCallbacks() (at Z:/tmp/tmp.EaS8iXpRBh/firebase/app/client/unity/proxy/FirebaseAppUtils.cs:33)
Firebase.Platform.FirebaseHandler:Update() (at Z:/tmp/tmp.BbQyA8B710/firebase/app/client/unity/src/Unity/FirebaseHandler.cs:205)
Firebase.Platform.FirebaseMonoBehaviour:Update() (at Z:/tmp/tmp.BbQyA8B710/firebase/app/client/unity/src/Unity/FirebaseMonoBehaviour.cs:45)
my GameInfo Class is the following :
using System;
using Serializables;
namespace Serializables
{
[Serializable]
public class GameInfo
{
public string gameId;
public string host;
public string[] playersIds;
public string[] playersPics;
public string[] playersNames;
}
}
if anyone has an idea to solve this I will be grateful
I think you figured out the basics: You can only submit bool, string, long, double, IDictionary, and List<Object> to Value.
There's some interesting notes that I'd like to layer on top of this though! I like to use Unity's JsonUtility in conjunction with SetRawJsonValueAsync and GetRawJsonValue from GetValueAsync. Your code will look a bit like this:
async void SendGameInfo(string path, GameInfo info) {
try {
await _database
.GetReference(path)
.SetRawJsonValueAsync(JsonUtility.ToJson(info));
Debug.Log($"Successfully wrote {info}");
} catch (AggregateException e) {
Debug.LogWarning($"Failed with {e}");
}
}
async Task<GameInfo> ReadGameInfo(string path) {
try {
var dataSnapshot = await _database
.GetReference(path)
.GetValueAsync();
return JsonUtility.FromJson<GameInfo>(info);
} catch (AggregateException e) {
Debug.LogWarning($"Failed with {e}");
return null;
}
}
Also, if you can, having spent time digging through the library I like to consider IDictionary<string, object> the "basic primitive" of Realtime Database. This will be used as an intermediary format when you set RawJson if you step through the disassembly. Also, since Transactions don't provide access to raw json, this will give you a more uniform interface to RTDB (unless your data looks like an array, then your primitive is List<object> - "looks like" meaning that your keys are numbers and the range of numbers RTDB is aware of is about half full).
Of course, the team actively monitors the quickstart github page and you can use the new "feature request" template to request a change to any of this if it will help 😃.
I think RTFM always works, I found out that there are specific types that are accepted for mutableData.Value : bool, string, long, double, IDictionary and List{Object} where Object is one of previously listed types. So I got this error because my class GameInfo is not accepted and I have to convert my object to an IDictionary.
source : https://firebase.google.com/docs/reference/unity/class/firebase/database/mutable-data#class_firebase_1_1_database_1_1_mutable_data_1a4833f23246b3079078332d57c5649254
I am developing a Kinect based gesture recognizing application on Unity3D. I have to utilize an algorithm that has been written in Matlab. Thus I decided to generate a .Net DLL with Matlab deploytool and I successfully did so. Then I tested the DLL in a standalone .Net application project(in Visual Studio 2017) where it worked perfectly. BUT, when I turned to Unity3D, that DLL never worked...... What I got is shown as below:
enter image description here
System.TypeInitializationException: An exception was thrown by the type initializer for Untitled1.ADD ---> System.NotImplementedException: The requested feature is not implemented.
at System.Security.Principal.WindowsIdentity.GetCurrent (Boolean ifImpersonating) [0x00000] in /Users/builduser/buildslave/mono/build/mcs/class/corlib/System.Security.Principal/WindowsIdentity.cs:166
at MathWorks.MATLAB.NET.Utility.MWMCR.EvaluateFunction (System.String functionName, Int32 numArgsOut, Int32 numArgsIn, MathWorks.MATLAB.NET.Arrays.MWArray[] argsIn) [0x00000] in <filename unknown>:0
at MathWorks.MATLAB.NET.Utility.MWMCR.EvaluateFunction (Int32 numArgsOut, System.String functionName, MathWorks.MATLAB.NET.Arrays.MWArray[] argsIn) [0x00000] in <filename unknown>:0
at MathWorks.MATLAB.NET.Utility.MWMCR.setBuilderUserData () [0x00000] in <filename unknown>:0
at MathWorks.MATLAB.NET.Utility.MWMCR..ctor (System.String componentId, System.String componentPath, System.IO.Stream embeddedCtfStream, Boolean isLibrary) [0x00000] in <filename unknown>:0
at Untitled1.ADD..cctor () [0x00000] in <filename unknown>:0
--- End of inner exception stack trace ---
at dlltest.Start () [0x00000] in E:\Unity\mPrj\Assets\dlltest.cs:40
UnityEngine.Debug:Log(Object)
dlltest:Start() (at Assets/dlltest.cs:46)
From the Log, it seemed that the initializing of MCR was failed, but I just can not find why after viewing the C# source code generated by Matlab(who ever has done this job before must know what I am talking about).
Is there someone who is experienced in this kind of work and can explain to me this happened and how to solve? Thank you so much!
The namespace of the DLL is Untitled1(got no time to give it a name...) and the name of the class in the DLL is ADD.
Followings are the related code in this process(test samples):
Matlab source code add.m:
function y = add(n,m)
y = n+m;
The C# Code, which is generated by Matlab during building the M file into DLL, is too long to paste here, so I just show the code that defines the constructor, at which the error in Unity3D happen according to the Log:
static ADD()
{
if (MWMCR.MCRAppInitialized)
{
Assembly assembly= Assembly.GetExecutingAssembly();
string ctfFilePath= assembly.Location;
int lastDelimiter= ctfFilePath.LastIndexOf(#"\");
ctfFilePath= ctfFilePath.Remove(lastDelimiter, (ctfFilePath.Length - lastDelimiter));
string ctfFileName = "Untitled1.ctf";
Stream embeddedCtfStream = null;
String[] resourceStrings = assembly.GetManifestResourceNames();
foreach (String name in resourceStrings)
{
if (name.Contains(ctfFileName))
{
embeddedCtfStream = assembly.GetManifestResourceStream(name);
break;
}
}
mcr= new MWMCR("",
ctfFilePath, embeddedCtfStream, true);
}
else
{
throw new ApplicationException("MWArray assembly could not be initialized");
}
}
The code that successfully used the DLL in a standalone .Net Application:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MathWorks.MATLAB.NET.Utility;
using MathWorks.MATLAB.NET.Arrays;
using Untitled1;
namespace AddDllTest
{
class Program
{
static void Main(string[] args)
{
ADD myAdd = new ADD();
Console.WriteLine(myAdd.add((MWArray)1, (MWArray)1));
}
}
}
And the code, which is a Unity3D script, that failed to use the DLL in Unity3D(some comments have been deleted):
using UnityEngine;
using System.Collections;
using System.Runtime.InteropServices;
using RootSystem = System;
using System;
using System.Reflection;
using System.IO;
using Untitled1;
using MathWorks.MATLAB.NET.Arrays;
using MathWorks.MATLAB.NET.Utility;
public class dlltest : MonoBehaviour {
MWArray test1 = 1;
MWArray ref0 = 2;
MWArray result;
ADD myADD;
//Use this for initializations
void Start () {
try
{
myADD = new ADD();
}
catch (Exception e)
{
Debug.Log("EXCEPTION");
Debug.Log(e.ToString());
}
}
// Update is called once per frame
void Update () {
result = myADD.add(test1,ref0);
Debug.Log(result);
}
}
Looks like the static ctor of MWMCR class is calling into an unsupported method in Mono classlib:
(https://github.com/Unity-Technologies/mono/blob/uniy-trunk/mcs/class/corlib/System.Security.Principal/WindowsIdentity.cs#L166)
The reason your test worked as a standalone .Net is that you probably is running it on CLR.
When you try to run your Unity project it uses Mono (in most cases) and then you get this error.
It should work if you build your Unity project as a "Windows Store App" (because in this case your "game" will run using CLR)
I'm having some trouble with setting up my application to mono, it gives me a GetConsoleWindow Exception. I thought this would open a new window when you run it on windows, but in Mono, on CentOS 6 with Gnome it gives me this exception.
error code:
Unhandled Exception:
System.EntryPointNotFoundException: GetConsoleWindow
at (wrapper managed-to-native) Silverwave.Program:GetConsoleWindow ()
at Silverwave.Program.Main (System.String[] Args) [0x00000] in <filename unkno wn>:0
[ERROR] FATAL UNHANDLED EXCEPTION: System.EntryPointNotFoundException: GetConsol eWindow
at (wrapper managed-to-native) Silverwave.Program:GetConsoleWindow ()
at Silverwave.Program.Main (System.String[] Args) [0x00000] in <filename unkno wn>:0
[root#h2297404 Debug]# Unhandled Exception:
-bash: Unhandled: opdracht niet gevonden
[root#h2297404 Debug]# System.EntryPointNotFoundException: GetConsoleWindow
-bash: System.EntryPointNotFoundException:: opdracht niet gevonden
thanks in advance
Console windows are specific to Windows systems (that's why GetConsoleWindow() does not exist in .NET proper and you had to p/invoke it).
Linux systems do not expose this API, so you cannot invoke it on Linux, and there is no replacement.
Short answer - use Console.WindowWidth
Long answer:
https://unix.stackexchange.com/questions/215584/whats-the-name-of-the-environment-variable-with-current-terminal-width
$COLUMNS is one such variable.
Also there's stty -a or more specifically stty size
stty uses
get_terminal_width_height(STDIN_FILENO, &width, &height)
which in turn calls
ioctl(fd, TIOCGWINSZ, &winsize);
TIOCGWINSZ
Fill in the winsize structure pointed to by the third argument with the screen width and height.
The winsize structure is defined in `sys/ioctl.h' as follows:
struct winsize
{
unsigned short ws_row; /* rows, in characters */
unsigned short ws_col; /* columns, in characters */
unsigned short ws_xpixel; /* horizontal size, pixels */
unsigned short ws_ypixel; /* vertical size, pixels */
};
Here it is called in mono
https://github.com/mono/mono/blob/90972a343b81489e333a379e13f3e0018738e705/mono/metadata/console-unix.c#L177
exported as "TtySetup"
https://github.com/mono/mono/blob/92a0ac52a7018199f39f01625eb1025baf564743/mono/metadata/icall-def.h#L130
which is imported here to C# code
https://github.com/mono/mono/blob/88d2b9da2a87b4e5c82abaea4e5110188d49601d/mcs/class/corlib/System/ConsoleDriver.cs#L286
namespace System {
static class ConsoleDriver {
...
[MethodImplAttribute(MethodImplOptions.InternalCall)]
unsafe internal static extern bool TtySetup (
string keypadXmit, string teardown,
out byte [] control_characters, out int *address);
Here it is called -
https://github.com/mono/mono/blob/88d2b9da2a87b4e5c82abaea4e5110188d49601d/mcs/class/corlib/System/TermInfoDriver.cs#L227
unsafe void CheckWindowDimensions ()
https://github.com/mono/mono/blob/88d2b9da2a87b4e5c82abaea4e5110188d49601d/mcs/class/corlib/System/TermInfoDriver.cs#L688
And this is available through property WindowWidth:
namespace System {
class TermInfoDriver : IConsoleDriver {
public int WindowWidth {
of interface IConsoleDriver
https://github.com/mono/mono/blob/88d2b9da2a87b4e5c82abaea4e5110188d49601d/mcs/class/corlib/System/IConsoleDriver.cs#L50
Ultimately it should be available through
https://github.com/mono/mono/blob/92a0ac52a7018199f39f01625eb1025baf564743/mcs/class/corlib/System/Console.cs#L660
I checked, this works (as of mono 4.0.2.5 at least).
using System;
class mainclass {
public static int Main(string[] args) {
Console.WriteLine(Console.WindowWidth);
return 0; } }
sabayon aa $ mcs test.cs -r:System.dll
sabayon aa $ mono test.exe
239