Factorial of a number using Command Line Arguments in C# - c#

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

Related

Matlab MWMCR::EvaluateFunction error in C# on one system

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 !

Having trouble in initializing Matlab MCR when using a DLL, generated by matlab, in Unity3D

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)

C# to Mono GetConsoleWindow Exception

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

Dotnetzip OverflowException

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.

Getting the Exception object in a try..catch to include full stacktrace, currently it's truncated

I am trying to get the full stack trace when within a catch of try..catch. Currently its truncated to include only the current method where the error is.
Let me explain. Currently my stack trace includes the method "Third" where the error happens but First and Second isn't included, I believe this is by design.
private void First()
{
this.Second();
}
private void Second()
{
this.Third();
}
private void Third()
{
try
{
throw new SystemException("ERROR HERE!");
}
catch (Exception ex)
{
// I WILL LOG THE EXCEPTION object "EX" here ! but ex.StackTrace is truncated!
}
}
I have seen a number of tricks to get the full stack trace in a STRING but problem is my logging framework expects a object of type "Exception", but my variable (ex) which has my exception is valid but the property StackTrace is truncated.
Is there anyway I can receive a FULL exception with a FULL stack trace so I am able to still send along my "EX" but this time it will have an Untruncated stack trace.
UnhandledErrror event seems to work as if I arrive here the Exception has a stack trace and is fully populated.
string fullStackTrace = exception.StackTrace + Environment.StackTrace;
The current method may be added two times, if so, remove one line from one of the properties.
class Program
{
static void Main(string[] args)
{
try
{
First();
}
catch (Exception ex)
{
Console.WriteLine(ex.StackTrace);
}
Console.ReadLine();
}
private static void First()
{
Second();
}
private static void Second()
{
Third();
}
private static void Third()
{
throw new SystemException("ERROR HERE!");
}
}
The output in this case is:
at stack.Program.Third() in C:\Temp\customers\stack\Program.cs:line 37
at stack.Program.Second() in C:\Temp\customers\stack\Program.cs:line 31
at stack.Program.First() in C:\Temp\customers\stack\Program.cs:line 25
at stack.Program.Main(String[] args) in C:\Temp\customers\stack\Program.cs:li
ne 14
Update: I suddenly had doubts, and ran through all the solutions presented thus far. They all work, though Environment.StackTrace is the easiest. Here's what the output looks like:
==ex.StackTrace==
at stack.Program.Third() in C:\Temp\customers\stack\Program.cs:line 35
==Environment.StackTrace per Guillaume/Jorge Córdoba==
at stack.Program.Third() in C:\Temp\customers\stack\Program.cs:line 35 at S
ystem.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
at System.Environment.get_StackTrace()
at stack.Program.Third() in C:\Temp\customers\stack\Program.cs:line 44
at stack.Program.Second() in C:\Temp\customers\stack\Program.cs:line 27
at stack.Program.First() in C:\Temp\customers\stack\Program.cs:line 21
at stack.Program.Main(String[] args) in C:\Temp\customers\stack\Program.cs:li
ne 15
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySec
urity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, C
ontextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
==ex.ToString() per danyolgiax==
System.SystemException: ERROR HERE!
at stack.Program.Third() in C:\Temp\customers\stack\Program.cs:line 35
==GetFrame(i) per MBen==
Void Third(): (line 52)
Void Second(): (line 27)
Void First(): (line 21)
Void Main(System.String[]): (line 15)
Int32 _nExecuteAssembly(System.Reflection.Assembly, System.String[]): (line 0)
Int32 ExecuteAssembly(System.String, System.Security.Policy.Evidence, System.Str
ing[]): (line 0)
Void RunUsersAssembly(): (line 0)
Void ThreadStart_Context(System.Object): (line 0)
Void Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, Sy
stem.Object): (line 0)
Void ThreadStart(): (line 0)
You need something like this :
private static void Third()
{
try
{
throw new SystemException("ERROR HERE!");
}
catch (Exception ex)
{
// I WILL LOG THE EXCEPTION object "EX" here ! but ex.StackTrace is truncated!
StackTrace st = new StackTrace(true);
for (int i = 0; i < st.FrameCount; i++)
{
// Note that high up the call stack, there is only
// one stack frame.
StackFrame sf = st.GetFrame(i);
Console.WriteLine();
Console.WriteLine("High up the call stack, Method: {0}",
sf.GetMethod());
Console.WriteLine("High up the call stack, Line Number: {0}",
sf.GetFileLineNumber());
}
}
}
Check this article for more info :
StackStace class
Hope this helps.
You don't understand how stack trace work. What is included in an exception trace is the "route" short to speak that the exception has traveled to reach the point where you're handling it.
Thus, on your example, it hasn't traveled at all yet, it's still in the "Third" method. If it would bubble up to "Second", then it would have gone across Third, to Second, and you'll be getting that on the stack trace.
I think what you actually want is the CallStack. Is the same concept, but the trace that's included in the exception is actually included "backwards" sort to speak, as the exception travels "up" to the place where it is handled.
Try logging the CallStack where you handle the exception.

Categories

Resources