Laden...

Forenbeiträge von BlackPhoenix Ingesamt 1 Beiträge

06.11.2016 - 15:09 Uhr

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


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;
        }
    }

}


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);
        }
    }
}


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);
        }
    }
}


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 = "";
            }
        }
    }

}