Micro blog about Answer to the Ultimate Question of Life, the Universe, and Everything
  • Home
    • List all categories
    • Sitemap
  • Downloads
    • WebSphere
    • Hitachi902
    • Hospital
    • Kryptonite
    • OCR
    • APK
  • About me
    • Gallery
      • Italy2022
      • Côte d'Azur 2024
    • Curriculum vitae
      • Resume
      • Lebenslauf
    • Social networks
      • Facebook
      • Twitter
      • LinkedIn
      • Xing
      • GitHub
      • Google Maps
      • Sports tracker
    • Adventures planning
  1. You are here:  
  2. Home

Logger wrapper for Windows Forms

Details
Written by: Stanko Milosev
Category: C#
Published: 21 November 2024
Last Updated: 24 November 2024
Hits: 505
This is my example of logger wrapper from Steven van Deursen.

The part available in the Stack Overflow article will not be repeated here; instead, I will focus on the WinForms-specific implementation.

Since I often build different tools using Windows Forms, I aim to have a central place to display information or errors in a TextBox that is immediately visible. The problem is that I want to have constructor injection in Program.cs, which happens before any components in a form are created. To solve this, I added a TextBox property to my TextBoxLogger class:

namespace LoggerWrapper.Logger;

public class TextBoxLogger : ILogger
{
    public TextBox? TextBox { get; set; }
    public void Log(LogEntry entry)
    {
        TextBox?.AppendText(
            $@"[{entry.Severity}] {DateTime.Now} {entry.Message} {entry.Exception}");
        TextBox?.AppendText(Environment.NewLine);
    }
}
Notice:
public TextBox? TextBox { get; set; }

Later, I will connect this property to the actual TextBox in Form1. Here’s what my Program.cs looks like:

using LoggerWrapper.Logger;

namespace LoggerWrapper
{
    internal static class Program
    {
        [STAThread]
        static void Main()
        {
            ApplicationConfiguration.Initialize();

            var textBoxLogger = new TextBoxLogger();
            var someDiClassHandler = new SomeDiClassHandler(textBoxLogger);

            Form1 form1 = new Form1(someDiClassHandler);
            textBoxLogger.TextBox = form1.TbLogger;

            Application.Run(form1);
        }
    }
}
Notice:
textBoxLogger.TextBox = form1.TbLogger;
In Form1, I introduced a property named TbLogger:
namespace LoggerWrapper;

public partial class Form1 : Form
{
    public TextBox? TbLogger { get; }

    private readonly SomeDiClassHandler _someDiClassHandler;

    public Form1(SomeDiClassHandler someDiClassHandler)
    {
        InitializeComponent();

        TbLogger = tbLogger;

        _someDiClassHandler = someDiClassHandler;
    }

    private void btnStart_Click(object sender, EventArgs e)
    {
        SomeDiClassCommand someDiClassCommand = new SomeDiClassCommand();
        _someDiClassHandler.Execute(someDiClassCommand);
    }
}
After creating Form1 I will assign TextBox to my TextBoxLogger, and in Form1 constructor I will assign TbLogger to real TextBox, in my case tbLogger:
        TbLogger = tbLogger;
Example download from here

Validating XML with XSL in .Net Core

Details
Written by: Stanko Milosev
Category: C#
Published: 16 October 2024
Last Updated: 17 November 2024
Hits: 616
  • xml
  • xslt 2.0
Here I already explained once how it can be done in .Net Framework, with Saxon-Se, and now here is experimental example in .Net Core.

Install NuGet package SaxonHE12s9apiExtensions.

In .csproj add something like:

<ItemGroup>
	<PackageReference Include="IKVM.Maven.Sdk" Version="1.8.2"/>
	<MavenReference Include="net.sf.saxon:Saxon-HE" version="12.5"/>
	<PackageReference Include="SaxonHE12s9apiExtensions" Version="12.5.9.4"/>
</ItemGroup>
Use this method to return result as a string which later you can convert to XML as I already explained here:
using net.sf.saxon.s9api;
using net.liberty_development.SaxonHE12s9apiExtensions;
...
string ValidateXmlFile(string xmlFile, string xslFile)
{
    Processor processor = new Processor();
    DocumentBuilder builder = processor.newDocumentBuilder();

    XsltTransformer xsltTransformer = processor.newXsltCompiler().Compile(new Uri(xslFile)).load();
    var inputNode = builder.Build(new Uri(xmlFile));
    xsltTransformer.setInitialContextNode(inputNode);
    using var stringWriter = new StringWriter();
    Serializer serializer = processor.NewSerializer(stringWriter);
    xsltTransformer.setDestination(serializer);
    xsltTransformer.transform();
    return stringWriter.ToString();
}
Example download from here.

Validating XML with Schematron

Details
Written by: Stanko Milosev
Category: C#
Published: 12 October 2024
Last Updated: 17 November 2024
Hits: 630
  • xml
  • xslt 2.0
For this example I was using this answer on Stack Overflow, and example I also downloaded from here.

This example will also not work in .NET Core.

My example you can download from here.

Validating XML with XSL

Details
Written by: Stanko Milosev
Category: C#
Published: 11 October 2024
Last Updated: 19 November 2024
Hits: 640
  • xml
  • xslt 2.0
First install Saxon-HE, it looks like that it Saxon Home Edition does not support .NET core, which is why test project has to be .NET Framework.

Example method:

private static string ValidateXmlFile(string inputFile, string transformFile)
{
	try
	{
		if (string.IsNullOrWhiteSpace(inputFile))
		{
			throw new FileNotFoundException("Filename is empty");
		}

		inputFile = Path.GetFullPath(inputFile);
		if (!File.Exists(inputFile))
		{
			throw new FileNotFoundException($"File: {inputFile} not found");
		}

		transformFile = Path.GetFullPath(transformFile);
		if (!File.Exists(transformFile))
		{
			throw new FileNotFoundException($"File: {transformFile} not found");
		}

		Processor processor = new Processor();

		DocumentBuilder builder = processor.NewDocumentBuilder();
		builder.BaseUri = new Uri(inputFile);

		XdmNode inputNode;
		using (var inputStream = File.OpenRead(inputFile))
		{
			inputNode = builder.Build(inputStream);
		}

		XsltCompiler compiler = processor.NewXsltCompiler();
		XsltExecutable executable;
		using (var xsltStream = File.OpenRead(transformFile))
		{
			executable = compiler.Compile(xsltStream);
			if (compiler.GetErrorList().Count != 0)
				throw new Exception("Exception loading xsl!");
		}

		XsltTransformer transformer = executable.Load();

		transformer.InitialContextNode = inputNode;

		Serializer serializer = processor.NewSerializer();
		using (var stringWriter = new StringWriter())
		{
			serializer.SetOutputWriter(stringWriter);
			transformer.Run(serializer);
			string result = stringWriter.ToString();
			return result;
		}
	}
	catch (Exception e)
	{
	   return e.Message;
	}
}
Since validation result is XML, we can parse failed validations like:
IEnumerable<FailedAssert> failedAsserts = doc.Descendants(svrl + "failed-assert")
	.Select(fa => new FailedAssert
	{
		Flag = fa.Attribute("flag")?.Value,
		Id = fa.Attribute("id")?.Value,
		Test = fa.Attribute("test")?.Value,
		Location = fa.Attribute("location")?.Value,
		Text = fa.Element(svrl + "text")?.Value
	});
SVRL is an abbreviation for 'Schematron Validation Report Language.'

FailedAssert class looks like:

public class FailedAssert
{
	public string Flag { get; set; }
	public string Id { get; set; }
	public string Test { get; set; }
	public string Location { get; set; }
	public string ExceptionMessage { get; set; }
	public string Text { get; set; }
}
Example download from here. For this example I used file 01.03a-INVOICE_uncefact.xml which I downloaded from here where I manipulated with DateTimeField. Instead of a date I wrote "test", in order to trigger a failed assertion. I also downloaded XSL file EN16931-CII-validation.xsl from "Koordinierungsstelle für IT-Standards" (KoSIT) GitHub repository.
  1. Master - Detail with DataGridView and DataTables example
  2. Simple MVVM example in Windows Forms
  3. Post image and additional data to WebAPI
  4. FluentFTP async example

Subcategories

C#

Azure

ASP.NET

JavaScript

Software Development Philosophy

MS SQL

IBM WebSphere MQ

MySQL

Joomla

Delphi

PHP

Windows

Life

Lazarus

Downloads

Android

CSS

Chrome

HTML

Linux

Eclipse

Page 4 of 164

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10