2 Temmuz 2018

WPF Logger Screen

Proje TreeView


  • Models
    • Log.cs
  • ViewModels
    • DelegateCommand.cs
    • LoggerConsoleViewModel.cs
    • MainWindowViewModel.cs
  • Views
    • LoggerConsoleView
    • MainWindow.xaml

Log.cs


using System;
using System.Collections.ObjectModel;
using System.Windows.Media;

namespace ConsoleLoggerDemo
{

    public class Logger
    {
        public static int Limit => 100;    
        public ObservableCollection Logs { get; private set; }
        public Logger()
        {
            Logs = new ObservableCollection();
        }
        public void Clear() => Logs.Clear();
        public void Add(ILoggable log)
        {
            if (Logs.Count == Limit)
                Logs.RemoveAt(0);
            Logs.Add(log);
        }
        public void Log(params string[] logs) => Add(new Log(logs));
        public void Error(params string[] logs) => Add(new Error(logs));
        public void Info(params string[] logs) => Add(new Info(logs));
        public void Success(params string[] logs) => Add(new Success(logs));
        public void Warning(params string[] logs) => Add(new Warning(logs));
    }

    public interface ILoggable
    {
        string Text { get; }
        SolidColorBrush Background { get; }
        SolidColorBrush Foreground { get; }
    }
    public class Log : ILoggable
    {
        public SolidColorBrush Background => Brushes.White;

        public SolidColorBrush Foreground => Brushes.Black;
        public string Text { get; private set; }
        public Log(params string[] logs)
        {
            string logText = $"Log({DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")}): ";
            logText = logText + string.Join(",", logs);
            Text = logText;
        }

    }
    public class Error : ILoggable
    {
        public SolidColorBrush Background => Brushes.Red;

        public SolidColorBrush Foreground => Brushes.White;
        public string Text { get; private set; }
        public Error(params string[] logs)
        {
            string logText = $"Error({DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")}): ";
            logText = logText + string.Join(",", logs);
            Text = logText;
        }
    }
    public class Info : ILoggable
    {

        public string Text { get; private set; }
        public Info(params string[] logs)
        {
            string logText = $"Info({DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")}): ";
            logText = logText + string.Join(",", logs);
            Text = logText;
        }
        public SolidColorBrush Background => Brushes.White;

        public SolidColorBrush Foreground => Brushes.Blue;
    }
    public class Success : ILoggable
    {
        public string Text { get; private set; }
        public Success(params string[] logs)
        {
            string logText = $"Success({DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")}): ";
            logText = logText + string.Join(",", logs);
            Text = logText;
        }
        public SolidColorBrush Background => Brushes.Green;

        public SolidColorBrush Foreground => Brushes.White;
    }

    public class Warning : ILoggable
    {
        public string Text { get; private set; }
        public Warning(params string[] logs)
        {
            string logText = $"Warning({DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss")}): ";
            logText = logText + string.Join(",", logs);
            Text = logText;
        }
        public SolidColorBrush Background => Brushes.Orange;

        public SolidColorBrush Foreground => Brushes.White;
    }
}


DelegateCommand.cs
using System;
using System.Windows.Input;

namespace ConsoleLoggerDemo.ViewModels
{
    public class DelegateCommand : ICommand
    {
        private readonly Action _action;

        public DelegateCommand(Action action)
        {
            _action = action;
        }

        public void Execute(object parameter)
        {
            _action();
        }

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

        public event EventHandler CanExecuteChanged { add { } remove { } }
    }

}

LoggerConsoleViewModel
using System.Windows.Input;

namespace ConsoleLoggerDemo.ViewModels
{
    public class LoggerConsoleViewModel
    {
        public Logger Logger { get; private set; }
        public LoggerConsoleViewModel(Logger logger)
        {
            Logger = logger;
        }


        public ICommand ClearCommand {
            get {
                return new DelegateCommand(() =>
                {
                    Logger.Clear();
                });
            }
        }
    }
}

MainWindowViewModel.cs
using ConsoleLoggerDemo.Views;
using System;
using System.Windows.Input;

namespace ConsoleLoggerDemo.ViewModels
{
    public class MainWindowViewModel
    {
        public Logger logger { get; set; }
        public LoggerConsoleView Logger { get; private set; }

        public MainWindowViewModel()
        {
            logger = new Logger();
            Logger =

             new LoggerConsoleView(
                new LoggerConsoleViewModel(logger));
            logger.Log("Kayıt");
            logger.Info(Environment.MachineName);
            logger.Error("Hata");
            logger.Success("Basari");
            logger.Warning("Uyari");

            logger.Log("Kayıt");
            logger.Info("Bilgi");
            logger.Error("Hata");
            logger.Success("Basari");
            logger.Warning("Uyari");
        }
        public ICommand ErrorCommand {
            get {
                return new DelegateCommand(() =>
                {
                    try
                    {
                        int x = 0;
                        var z = 1 / x;

                    }
                    catch (Exception ex)
                    {

                        logger.Error(ex.ToString());
                    }
                });
            }
        }
        public ICommand InfoCommand {
            get {
                return new DelegateCommand(() =>
                {
                    logger.Info("some info text");
                });
            }
        }
        public ICommand WarningCommand {
            get {
                return new DelegateCommand(() =>
                {
                    logger.Warning("some warning text");
                });
            }
        }
        public ICommand LogCommand {
            get {
                return new DelegateCommand(() =>
                {
                    logger.Log("some log text");
                });
            }
        }
        public ICommand SuccessCommand {
            get {
                return new DelegateCommand(() =>
                {
                    logger.Success("some success text");
                });
            }
        }
    }
}

LoggerConsoleView.xaml

<Page x:Class="ConsoleLoggerDemo.Views.LoggerConsoleView"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
      xmlns:local="clr-namespace:ConsoleLoggerDemo"
      mc:Ignorable="d"
      d:DesignHeight="300" d:DesignWidth="300"
      Title="LoggerConsole">
    <Border BorderThickness="1" BorderBrush="Black" Padding="4">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="auto"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            <StackPanel Orientation="Horizontal" Background="LightGray">
                <Button Content="Clear" Margin="4" Padding="4"
Command="{Binding ClearCommand}"/>
            </StackPanel>
            <ScrollViewer Margin="0" Background="White" Grid.Row="1" Name="Scroll">
                <StackPanel>
                    <ItemsControl  ItemsSource="{Binding Logger.Logs,Mode=OneWay}">
                        <ItemsControl.ItemTemplate>
                            <DataTemplate>
                                <TextBox Text="{Binding Text,Mode=OneWay}"
Foreground="{Binding Foreground}" FontFamily="Consolas"
Background="{Binding Background}" Margin="2"
TextWrapping="Wrap" Padding="4" BorderThickness="0"/>
                            </DataTemplate>
                        </ItemsControl.ItemTemplate>
                    </ItemsControl>
                </StackPanel>
            </ScrollViewer>
        </Grid>
    </Border>
</Page>


LoggerConsoleView.xaml.cs
using ConsoleLoggerDemo.ViewModels;
using System.Windows.Controls;

namespace ConsoleLoggerDemo.Views
{
    public partial class LoggerConsoleView : Page
    {
        public LoggerConsoleView(LoggerConsoleViewModel loggerConsoleViewModel)
        {
            InitializeComponent();
            DataContext = loggerConsoleViewModel;
            loggerConsoleViewModel.Logger.Logs.CollectionChanged += (se, ev) =>
            {
                Scroll.ScrollToBottom();
            };
        }
    }
}

MainWindow.xaml
<Window x:Class="ConsoleLoggerDemo.Views.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ConsoleLoggerDemo"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="600">
    <Window.Resources>
        <Style TargetType="Button">
            <Setter Property="Width" Value="100"/>
            <Setter Property="Margin" Value="4"/>
            <Setter Property="Padding" Value="4"/>
            <Setter Property="FontWeight" Value="Bold"/>
        </Style>
    </Window.Resources>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <StackPanel Orientation="Horizontal">
            <Button Content="Error" Background="Red"
Command="{Binding ErrorCommand}"/>
            <Button Content="Info" Background="SkyBlue"
Command="{Binding InfoCommand}"/>
            <Button Content="Success" Background="DarkSeaGreen"
Command="{Binding SuccessCommand}"/>
            <Button Content="Warning" Background="Orange"
Command="{Binding WarningCommand}"/>
            <Button Content="Log" Background="White"
Command="{Binding LogCommand}"/>
        </StackPanel>
        <Frame Content="{Binding Logger}" Grid.Row="1"/>

    </Grid>
</Window>

MainWindow.xaml
using ConsoleLoggerDemo.ViewModels;
using System.Windows;

namespace ConsoleLoggerDemo.Views
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        MainWindowViewModel model { get; set; }
        public MainWindow()
        {
            InitializeComponent();
            model = new MainWindowViewModel();
            DataContext = model;
        }       
    }
}