0

I'm trying to write my own GUI for a Program in C#, which translate Morsecode to text. My IDE doesn't show any errors and the GUI works so far. But when I push the button, for the translation of the text, the whole program crashes. I already reviewed my code, but I can't find any issues, because the IDE can build the program, without showing errors.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Morse.Annotations;
using Morse.Command;

namespace Morse.ViewModel
{
    public class MorseViewModel: INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        public MorseViewModel()
        {

            @UComm = new MorseCommand(this);
        }

        public Dictionary<char, string> MorseCode { get; set; }

        private string _meinTextWert;

        private string _meinErgebnisWert;

        public string MeinTextWert
        {
            get { return _meinTextWert;}
            set
            {
                if(value == _meinTextWert) return;
                _meinTextWert = value;
                OnPropertyChanged();
            }
        }

        public string MeinErgebnisWert
        {
            get { return _meinErgebnisWert; }
            set
            {
                if(value == _meinErgebnisWert) return;
                _meinErgebnisWert = value;
                OnPropertyChanged();
            }
        }

        public MorseCommand UComm { get; set; }

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

This is my .xaml code for the GUI:

<TextBox Grid.Column="1" Grid.Row="1" Text="{Binding MeinTextWert}"
                MinWidth="250" HorizontalAlignment="Left" TextWrapping="NoWrap" AcceptsReturn="True" VerticalScrollBarVisibility="Auto"/>
        <TextBox Grid.Column="3" Grid.Row="1" Text="{Binding MeinErgebnisWert, UpdateSourceTrigger=PropertyChanged}"
                 MinWidth="250" HorizontalAlignment="Left" TextWrapping="NoWrap" AcceptsReturn="True" VerticalScrollBarVisibility="Auto"/>

<Button Grid.Column="1" Grid.Row="3" MinWidth="250" Command="{Binding UComm}"
                HorizontalAlignment="Center" Content="Übersetzen ins Morse" Padding="0.5"/>

And this is my Code for my ButtonCommand:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Input;
using Morse.ViewModel;

namespace Morse.Command
{
    public class MorseCommand: ICommand
    {
        private readonly MorseViewModel _morseViewModel;
        public MorseCommand(MorseViewModel morseViewModel)
        {
            _morseViewModel = morseViewModel;
        }

        public bool CanExecute(object parameter)
        {
            return true;
        }




        public void Execute(object parameter)
        {

            /*_morseViewModel.MeinTextWert = "test";*/

            Dictionary<char, string> MorseCode = new Dictionary<char, string>() {

                {'a', ".-"}, {'b', "-..."}, {'c', "-.-."}, {'d', "-.."}, {'e', "."},

                {'f', "..-."}, {'g', "--."}, {'h', "...."}, {'i', ".."}, {'j', ".---"},

                {'k', "-.-"}, {'l', ".-.."}, {'m', "--"}, {'n', "-."}, {'o', "---"},

                {'p', ".--."}, {'q', "--.-"}, {'r', ".-."}, {'s', "..."}, {'t', "-"},

                {'u', "..-"}, {'v', "...-"}, {'w', ".--"}, {'x', "-..-"}, {'y', "-.--"},

                {'z', "--.."}, {'0', "-----"}, {'1', ".----"}, {'2', "..---"},

                {'3', "...--"}, {'4', "....-"}, {'5', "....."}, {'6', "-...."},

                {'7', "--..."}, {'8', "---.."}, {'9', "----."}, {'à', ".--.-"},

                {'å', ".--.-"}, {'ä', ".-.-"}, {'è', ".-..-"}, {'é', "..-.."},

                {'ö', "---."}, {'ü', "..--"}, {'ß', "...--.."}, {'ñ', "--.--"},

                {'.', ".-.-.-"}, {',', "--..--"}, {':', "---..."}, {';', "-.-.-."},

                {'?', "..--.."}, {'-', "-....-"}, {'_', "..--.-"}, {'(', "-.--."},

                {')', "-.--.-"}, {'\'', ".----."}, {'=', "-...-"}, {'+', ".-.-."},

                {'/', "-..-."}, {'@', ".--.-."}, {' ', "   "}

            };

            StringBuilder Ausgabe  =new StringBuilder();

            char EingabeTextBox;

            EingabeTextBox = Convert.ToChar(_morseViewModel.MeinTextWert.ToLower().ToCharArray());


            for (int i = 0; i < _morseViewModel.MeinTextWert.Length ; i++)
            {
                if (i % 20 == 0)
                    Ausgabe.Append('\n');
                try
                {
                    Ausgabe.Append(MorseCode[_morseViewModel.MeinTextWert[i]]).Append(' ');
                }
                catch (KeyNotFoundException)
                {

                }

                _morseViewModel.MeinErgebnisWert = "\n Morse" + Ausgabe;

            }
        }

        public event EventHandler CanExecuteChanged;
    }
}```



I don't really get any errors in my EventLog. These are alle the logs I got:

23.03.2020 15:09 Build succeeded with warnings at 15:09:27

15:48 Build succeeded with warnings at 15:48:05

15:58 Build succeeded with warnings at 15:58:07

15:58 Build succeeded at 15:58:25

15:59 Build succeeded at 15:59:19

16:04 Build succeeded at 16:04:33```

These are the warnings in Errors In Solution.

enter image description here

I also debugged the program, and this is the Error I finally got:




System.InvalidCastException: Das Objekt des Typs "System.Char[]" kann nicht in Typ "System.IConvertible" umgewandelt werden.
   bei System.Convert.ToChar(Object value)
   bei Morse.Command.MorseCommand.Execute(Object parameter) in D:\Schule_Ordner\13. Klasse\Morse\Morse\Command\MorseCommand.cs:Zeile 66.
   bei MS.Internal.Commands.CommandHelpers.CriticalExecuteCommandSource(ICommandSource commandSource, Boolean userInitiated)
   bei MS.Internal.Commands.CommandHelpers.ExecuteCommandSource(ICommandSource commandSource)
   bei System.Windows.Controls.Primitives.ButtonBase.OnClick()
   bei System.Windows.Controls.Button.OnClick()
   bei System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
   bei System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e)
   bei System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
   bei System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
   bei System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   bei System.Windows.RouteItem.InvokeHandler(RoutedEventArgs routedEventArgs)
   bei System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   bei System.Windows.EventRoute.ReInvokeHandlers(Object source, RoutedEventArgs args)
   bei System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
   bei System.Windows.UIElement.CrackMouseButtonEventAndReRaiseEvent(DependencyObject sender, MouseButtonEventArgs e)
   bei System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)
   bei System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
   bei System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
   bei System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
   bei System.Windows.RouteItem.InvokeHandler(RoutedEventArgs routedEventArgs)
   bei System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
   bei System.Windows.EventRoute.InvokeHandlers(Object source, RoutedEventArgs args)
   bei System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
   bei System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
   bei System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
   bei System.Windows.Input.InputManager.ProcessStagingArea()
   bei System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
   bei System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
   bei System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
   bei System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   bei System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   bei MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
   bei MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
   bei System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
   bei System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   bei System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
   bei System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
   bei System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)
   bei MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
   bei MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
   bei System.Windows.Threading.Dispatcher.TranslateAndDispatchMessage(MSG& msg)
   bei System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
   bei System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
   bei System.Windows.Threading.Dispatcher.Run()
   bei System.Windows.Application.RunDispatcher(Object ignore)
   bei System.Windows.Application.RunInternal(Window window)
   bei System.Windows.Application.Run(Window window)
   bei System.Windows.Application.Run()
   bei Morse.App.Main()
  • 2
    We usually need to know which line is throwing the exception, and post your error message, stack trace, ect. – LarsTech Mar 23 '20 at 14:38
  • 1
    I assume there's a crash message. In addition to what @LarsTech says, the message gives details on the crash (like whether it's a null pointer exception, etc). – lurker Mar 23 '20 at 14:43
  • The term "keeps crashing" is too broad, try editing your question and describing better the behaviour, error messages, etc... – Cleptus Mar 23 '20 at 14:45
  • _"I already reviewed my code, but I can't find any issues, because the IDE can build the program, without showing errors"_ - if there were never any errors because the code compiles then SO would not exist. Have you tried debugging your code - put a breakpoint in the button event & step through. – PaulF Mar 23 '20 at 14:48
  • Not sure this line is making a whole lot of sense: `char EingabeTextBox = Convert.ToChar(_morseViewModel.MeinTextWert.ToLower().ToCharArray());` – LarsTech Mar 23 '20 at 14:55
  • 2
    My goto tool for things like this is "[break on exception](https://www.jetbrains.com/help/rider/Debugging_Exceptions.html#)" feature. This stops execution when the failure occurs, and allows you to inspect variables etc so you can discover why the error occured – JonasH Mar 23 '20 at 15:01
  • @LarsTech I wanted to convert the string to a List of chars, which then are translated to dots and dashes for my output in the second TextBox. – Emanuel Avadani Mar 23 '20 at 15:29
  • But you can't just convert a CharArray to a char. You can select the first index of the CharArray, if that's what you are trying to do. – LarsTech Mar 23 '20 at 15:32
  • As the compiler warnings show, you only assign EingabeTextBox end never use that value. But here you are trying to convert a char-array (result of the .ToArray) to a single char. What do you expect from that line? Remove it and check the results – Hans Kesting Mar 23 '20 at 15:35
  • OT instead of `Ausgabe.Append('\n')` you can also use `Ausgabe.AppendLine()`, which uses a "windows-style" end-of-line (or rather, an OS-specific EOL) – Hans Kesting Mar 23 '20 at 15:37
  • @PaulF thanks for the tipp. I've done it and now I got a System.InvalidCastException. – Emanuel Avadani Mar 23 '20 at 15:38
  • OT instead of catching an exception, use [ContainsKey()](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.containskey?view=netframework-4.8#System_Collections_Generic_Dictionary_2_ContainsKey__0_) to prevent it – Hans Kesting Mar 23 '20 at 15:40
  • And on what line did you get that exception? – Hans Kesting Mar 23 '20 at 15:41
  • @HansKesting I removed the line and changed to Ausgabe.AppendLine( ) and now it works. Thank you :-) – Emanuel Avadani Mar 23 '20 at 15:43
  • @HansKesting the exception was because of this line: ```EingabeTextBox = Convert.ToChar(_morseViewModel.MeinTextWert.ToLower().ToCharArray()); ``` I just deleted it and now it works... thank you very much :-) – Emanuel Avadani Mar 24 '20 at 16:21

0 Answers0