myCSharp.de - DIE C# und .NET Community
Willkommen auf myCSharp.de! Anmelden | kostenlos registrieren
 
 | Suche | FAQ

» Hauptmenü
myCSharp.de
» Startseite
» Forum
» FAQ
» Artikel
» C#-Snippets
» Jobbörse
» Suche
» Regeln
» Wie poste ich richtig?
» Forum-FAQ

Mitglieder
» Liste / Suche
» Wer ist wo online?

Ressourcen
» openbook: Visual C#
» openbook: OO
» Microsoft Docs

Team
» Kontakt
» Übersicht
» Wir über uns

» myCSharp.de Diskussionsforum
Du befindest Dich hier: Community-Index » Diskussionsforum » Entwicklung » Code-Reviews » Exceptionhandling beim AUsgeben von Exceptions in Textbox - Ist dieses Handling richtig?
Letzter Beitrag | Erster ungelesener Beitrag Druckvorschau | Thema zu Favoriten hinzufügen

Antwort erstellen
Zum Ende der Seite springen  

Exceptionhandling beim AUsgeben von Exceptions in Textbox - Ist dieses Handling richtig?

 
Autor
Beitrag « Vorheriges Thema | Nächstes Thema »
BlackPhoenix
myCSharp.de-Mitglied

Dabei seit: 06.11.2016
Beiträge: 1
Entwicklungsumgebung: C#, Java


BlackPhoenix ist offline

Exceptionhandling beim AUsgeben von Exceptions in Textbox - Ist dieses Handling richtig?

Beitrag: beantworten | zitieren | editieren | melden/löschen       | Top

Hallo liebe C-Sharpler,

Ich arbeite seit längerem an einem Projekt namens "Code Watcher". Die Aufgabe besteht darin, ein Directory zu wählen, dieses in einem Tree abbilden, in gültigen HTML Code verwandeln und Files mit der Endung ".cs" auslesen und deren Code abbilden. Anschließend in einem Web Browser (WPF) und alternativ in ein HTML File ausgeben/speichern.
Exceptions werden in einem TextBlock ausgegeben.

Mich interessiert eure Meinung zu meinem Exception handling (Habe noch nicht sehr oft damit gearbeitet.),
zu meiner Kommunikation zwischen Code und WPF
und wie ich meine GUIManager Klasse optimieren könnte.

Ich bedanke mich für eure Zeit.

MFG Fabian

C#-Code:
namespace CodeWatcher
{
    static class Watcher
    {
        static string _HTMLTemplateDirectory = @"../../../HTMLTemplate.html";

        //click event from button Generate
        public static void StartHTMLGeneration()
        {
            List<string> extensions = new List<string>();
            string directoryForOutput = GUIManager.TextBlockDirectoryToSearchPath.Text;
            string currentPlaceholder = "{placeholder:HTMLOutput}";
            extensions = GetItemsAsStringFromList(GUIManager.ListBoxExtensions);

            try
            {
                SendOutput("Loading Template...");
                string htmlTemplateText  = GetTextFromFile(_HTMLTemplateDirectory);
                SendOutput("Template loaded");


                TreeNode tree = DirectoryExplorer.GetDirectoryAsTree(directoryForOutput, extensions);
                string nestedPaths = GenerateHTMLFromTree(tree);

                SendOutput("Creating directory...");
                SendOutput("Directory created");

                SendOutput("Replacing placeholder...");
                string htmlOutputText = StringReplace(htmlTemplateText, currentPlaceholder, nestedPaths);
                SendOutput("Placeholder replaced");



                //WIP: css may not work here
                //ToDo implement better
                SendOutput("Setting Webbrowser text...");
                SetWebBrowserText(htmlOutputText);
                SendOutput("Webbrowser text set");

                if ((bool)GUIManager.CheckBoxGenerateHTMLFile.IsChecked)
                {

                    string path = GUIManager.TextBlockHTMLGenerateDirectory.Text + @"/" + GUIManager.TextBoxHTMLOutputFileName.Text + ".html";

                    SendOutput("Creating and write to file...");
                    WriteToFile(path, htmlOutputText);
                    SendOutput("File created");
                }

                SendOutput("Finished" + "\n");
            }
            catch (Exception ex)
            {
                SendOutput("Error: " + ex.Message + "\n");
            }
            //finally
            //{
            //    //releasing data
            //}
        }

        static void AddListBoxItem(string value)
        {
            bool dublicate = false;

            foreach (ListBoxItem item in GUIManager.ListBoxExtensions.Items)
            {
                if (item.ToString() == value)
                {
                    dublicate = true;
                    //ToDo: Send dublicate to error box
                }

            }

            if (!dublicate)
            {
                GUIManager.ListBoxExtensions.Items.Add(value);
                GUIManager.ListBoxExtensions.Items.Refresh();
            }

        }

        static void RemoveListBoxItem(int idx)
        {
            GUIManager.ListBoxExtensions.Items.RemoveAt(idx);
            GUIManager.ListBoxExtensions.Items.Refresh();
        }

        static void SetWebBrowserText(string text)
        {
            GUIManager.WebBrowser.NavigateToString(text);
        }

        static string GenerateHTMLFromTree(TreeNode rootNode)
        {
            string output = "<ul>";

            GenerateHTMLRekursive(rootNode, ref output);

            output += "</ul>";

            return output;

        }

        static void GenerateHTMLRekursive(TreeNode currentNode, ref string output)
        {
            //if it contains a dot, its a file.
            if (currentNode.Value.Contains("."))
            {
                output += "<li>" + currentNode.Value + "</li>";

                if (currentNode.Value.Contains(".cs"))
                {
                    output += "<ul>" + "{CODE GOES HERE}" + "</ul>";
                }
            }
            else
            {
                output += "<li>" + currentNode.Value + "</li> <ul>";

                foreach (TreeNode node in currentNode.ChildNodes)
                {
                    GenerateHTMLRekursive(node, ref output);
                }

                output += "</ul>";
            }
        }

        static string GetTextFromFile(string path)
        {
            string ret = "";

            ret = File.ReadAllText(path);

            return ret;
        }

        static void WriteToFile(string fullDirectory, string text)
        {
            File.WriteAllText(fullDirectory, text);
        }

        static List<string> GetItemsAsStringFromList(ListBox listBox)
        {
            List<string> ret = new List<string>();

            foreach (string item in GUIManager.ListBoxExtensions.Items)
            {
                ret.Add(item);
            }

            return ret;
        }

        public static void RemoveExtension()
        {
            GUIManager.ListBoxExtensions.Items.RemoveAt(GUIManager.ListBoxExtensions.SelectedIndex);
            GUIManager.ListBoxExtensions.Items.Refresh();
        }

        public static void AddExtension(string itemName)
        {
            //ToDo Better way to check which error occurred
            bool isValid = IsValidExtension(itemName);
            bool isDublicate = IsDublicateInList(itemName, GUIManager.ListBoxExtensions);

            if(isValid && !isDublicate)
            {
                GUIManager.ListBoxExtensions.Items.Add(itemName);
                GUIManager.ListBoxExtensions.Items.Refresh();
            }
            else
            {
                if (!isValid)
                    SendOutput("Extension has not a valid lenght.");
                if (isDublicate)
                    SendOutput("Extension alredy in list.");
            }
        }

        static bool IsValidExtension(string extension)
        {
            bool isValid = false;

            //ToDo more to check
            if(extension.Length > 2 && extension.Contains("."))
                isValid = true;

            return isValid;
        }

        //ToDo implement generic for other programs use
        static bool IsDublicateInList(string checkableItem, ListBox listBoxExtensions)
        {
            bool isDublicate = false;

            foreach (string item in listBoxExtensions.Items)
            {
                if(item == checkableItem)
                {
                    isDublicate = true;
                }
            }

            return isDublicate;
        }

        //to change output later
        static void SendOutput(string message)
        {
            GUIManager.SendOutput(message);
        }

        static string StringReplace(string currentText, string replaceThat, string replaceWith)
        {
            string ret = "";

            if (currentText.Contains(replaceThat))
                ret = currentText.Replace(replaceThat, replaceWith);
            else
                throw new Exception("Current text does not contain '" + replaceThat + "'");

            return ret;
        }
    }

}

C#-Code:
namespace CodeWatcherLib
{
    public static class DirectoryExplorer
    {
        //for every and specific file extension
        public static TreeNode GetDirectoryAsTree(string path, List<string> extensions)
        {
            TreeNode result = new TreeNode(GetRelativePath(path));

            foreach(string dirName in Directory.GetDirectories(path))
            {
                result.Append(GetDirectoryAsTree(dirName, extensions));
            }

            foreach (string fileName in Directory.GetFiles(path))
            {
                if (extensions.Count == 0)
                    result.Append(GetRelativePath(fileName));
                else
                {
                    foreach (string extension in extensions)
                    {
                        if (Path.GetExtension(fileName) == extension)
                        {
                            result.Append(GetRelativePath(fileName));
                            break;
                        }
                    }
                }
            }

            return result;
        }

        //for every file extension
        public static TreeNode GetDirectoryAsTree(string path)
        {
            List<string> list = new List<string>();
            TreeNode ret = GetDirectoryAsTree(path, list);
            return ret;
        }

        static string GetRelativePath(string path)
        {
            int lastIndex = path.LastIndexOf(@"\");
            return path.Substring(lastIndex, path.Length - lastIndex);
        }
    }
}

C#-Code:
namespace CodeWatcherLib
{
    public class TreeNode
    {
        List<TreeNode> _ChildNodes = new List<TreeNode>();

        public string Value { private set; get; }
        public IList<TreeNode> ChildNodes { get { return _ChildNodes.AsReadOnly(); } }

        public TreeNode(string newValue)
        {
            Value = newValue;
        }

        public TreeNode Append(TreeNode newNode)
        {
            //ToDo: implement checks here .. if null, if alredy in childnodes, if alredy in tree?
            if (newNode == null)
                throw new Exception("new node is null");


            _ChildNodes.Add(newNode);
            return newNode;
        }

        public TreeNode Append(string newValue)
        {
            TreeNode newNode = new TreeNode(newValue);
            return Append(newNode);
        }
    }
}

C#-Code:
namespace CodeWatcher
{
    static class GUIManager
    {
        //ToDo: handle multiple different gui objects right
       /*
       list objects add TextBlock, Button,...
       if object is TextBlock...
       if object is Button...
       */


        private static TextBlock _TextBlockOutput;

        public static WebBrowser WebBrowser { private set; get; }

        public static TextBlock TextBlockDirectoryToSearchPath { private set; get; }
        public static Button ButtonGenerateHTML { private set; get; }

        public static TextBlock TextBlockHTMLGenerateDirectory { private set; get; }
        public static Button ButtonSelectDirectoryForHTMLOutput { private set; get; }

        public static CheckBox CheckBoxGenerateHTMLFile { private set; get; }
        public static TextBox TextBoxHTMLOutputFileName { private set; get; }

        public static ListBox ListBoxExtensions { private set; get; }

        public static void Init(TextBlock textBlockOutput, TextBlock textBlockDirectoryToSearchPath, Button buttonGenerateHTML, TextBlock textBlockHTMLGenerateDirectory,
            Button buttonSelectDirectoryForHTMLOutput, WebBrowser webBrowser, CheckBox checkBoxGenerateHTMLFile, TextBox textBoxHTMLOutputFileName,
            ListBox listBoxExtensions)
        {
            _TextBlockOutput = textBlockOutput;
            TextBlockDirectoryToSearchPath = textBlockDirectoryToSearchPath;
            ButtonGenerateHTML = buttonGenerateHTML;
            TextBlockHTMLGenerateDirectory = textBlockHTMLGenerateDirectory;
            ButtonSelectDirectoryForHTMLOutput = buttonSelectDirectoryForHTMLOutput;
            WebBrowser = webBrowser;
            CheckBoxGenerateHTMLFile = checkBoxGenerateHTMLFile;
            TextBoxHTMLOutputFileName = textBoxHTMLOutputFileName;
            ListBoxExtensions = listBoxExtensions;

            _TextBlockOutput.Text = "";

        }

        public static void SendOutput(string errorName)
        {
            DateTime currentDate = DateTime.Now;

            if (_TextBlockOutput == null)
                MessageBox.Show("TextBlockErrorOuput is null");
            else
            {
                _TextBlockOutput.Text += currentDate.ToString("H:mm:ss") + " " + errorName + "\n";
            }
        }

        public static void ClearOutputBox()
        {
            if (_TextBlockOutput == null)
                MessageBox.Show("TextBlockErrorOuput is null");
            else
            {
                _TextBlockOutput.Text = "";
            }
        }
    }

}


Dateianhang:
unknown CodeWatcher_V2_ReleaseReady_07Nov2016.rar (122,43 KB, 49 mal heruntergeladen)
06.11.2016 15:09 E-Mail | Beiträge des Benutzers | zu Buddylist hinzufügen
MrSparkle MrSparkle ist männlich
myCSharp.de-Team

avatar-2159.gif


Dabei seit: 16.05.2006
Beiträge: 5.561
Herkunft: Leipzig


MrSparkle ist offline

Beitrag: beantworten | zitieren | editieren | melden/löschen       | Top

Hi BlackPhoenix,

wenn du mit WPF arbeitest, solltest du MVVM und DataBinding verwenden. Dann kannst du deine Listen und Texte via ViewModel direkt an die GUI-Elemente binden. Damit kannst du dir den gesamten Code sparen, daher gehe ich da jetzt auch nicht näher darauf ein. Was deine Watcher- und GuiManager-Klassen machen, geht mit DataBinding viel einfacher und zuverlässiger.
06.11.2016 22:37 Beiträge des Benutzers | zu Buddylist hinzufügen
Baumstruktur | Brettstruktur       | Top 
myCSharp.de | Forum Der Startbeitrag ist älter als 4 Jahre.
Der letzte Beitrag ist älter als 4 Jahre.
Antwort erstellen


© Copyright 2003-2020 myCSharp.de-Team | Impressum | Datenschutz | Alle Rechte vorbehalten. | Dieses Portal verwendet zum korrekten Betrieb Cookies. 24.11.2020 07:50