Errors fix, removed old library, Added logging

This commit is contained in:
Marco 2025-07-23 15:08:25 +02:00
commit d8d8b152bd
6 changed files with 179 additions and 89 deletions

View file

@ -148,39 +148,36 @@ public class ImageCreatorSharp
private void ExtractExif() private void ExtractExif()
{ {
using (var img = SixLabors.ImageSharp.Image.Load(_workFile.FullName)) using var img = SixLabors.ImageSharp.Image.Load(_workFile.FullName);
_orientation = ExifReader.Orientations.TopLeft;
IExifValue<ushort> rotation = null;
var found = img.Metadata?.ExifProfile?.TryGetValue(ExifTag.Orientation, out rotation) ?? false;
if (found )
{ {
_orientation = ExifReader.Orientations.TopLeft; var intOrientation = rotation.Value.ToInt32();
_orientation = (ExifReader.Orientations)intOrientation;
}
IExifValue<ushort> rotation = null; IExifValue<string> date = null;
var creationFound = img.Metadata?.ExifProfile?.TryGetValue(ExifTag.DateTime, out date) ?? false;
var found = img.Metadata?.ExifProfile?.TryGetValue(ExifTag.Orientation, out rotation) ?? false; if (creationFound)
{
if (found) var succ = DateTime.TryParse(date.ToString(), out var crDate);
if (succ)
{ {
_orientation = (ExifReader.Orientations)rotation.ToInt32(); _creationDate = crDate;
}
IExifValue<string> date = null;
var creationFound = img.Metadata?.ExifProfile?.TryGetValue(ExifTag.DateTime, out date) ?? false;
if (creationFound)
{
var succ = DateTime.TryParse(date.ToString(), out var crDate);
if (succ)
{
_creationDate = crDate;
}
else
{
_creationDate = null;
}
} }
else else
{ {
_creationDate = null; _creationDate = null;
} }
}
else
{
_creationDate = null;
} }
} }

BIN
imagecatalog/Icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 317 B

View file

@ -10,6 +10,9 @@
<FileVersion>3.0.0.0</FileVersion> <FileVersion>3.0.0.0</FileVersion>
<InformationalVersion>3.0.0-alpha.63+Branch.develop.Sha.39a9baf5c618d8d79c75b89e2d5c4020939697f2</InformationalVersion> <InformationalVersion>3.0.0-alpha.63+Branch.develop.Sha.39a9baf5c618d8d79c75b89e2d5c4020939697f2</InformationalVersion>
<Version>3.0.0-alpha0063</Version> <Version>3.0.0-alpha0063</Version>
<AssemblyName>ImageCatalog2025</AssemblyName>
<LangVersion>default</LangVersion>
<ApplicationIcon>Logo.ico</ApplicationIcon>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<UpdateVersionProperties>true</UpdateVersionProperties> <UpdateVersionProperties>true</UpdateVersionProperties>
@ -34,10 +37,10 @@
<ProjectReference Include="..\MaddoShared\MaddoShared.csproj" /> <ProjectReference Include="..\MaddoShared\MaddoShared.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.1" /> <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="9.0.7" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="9.0.7" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="9.0.7" />
<PackageReference Include="Microsoft.VisualBasic" Version="10.3.0" /> <PackageReference Include="Microsoft.VisualBasic" Version="10.3.0" />
<PackageReference Include="Microsoft.WindowsAPICodePack-Core" Version="1.1.0.2" />
<PackageReference Include="Microsoft.WindowsAPICodePack-Shell" Version="1.1.0.0" />
<PackageReference Include="Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers" Version="0.4.421302"> <PackageReference Include="Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers" Version="0.4.421302">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
</PackageReference> </PackageReference>

BIN
imagecatalog/Logo.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 894 B

View file

@ -8,6 +8,7 @@ using System.IO;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Text;
using System.Threading; using System.Threading;
using System.Threading.Tasks; using System.Threading.Tasks;
using System.Windows.Forms; using System.Windows.Forms;
@ -15,9 +16,9 @@ using CatalogVbLib;
using ImageCatalog_2; using ImageCatalog_2;
using ImageCatalog_2.Services; using ImageCatalog_2.Services;
using MaddoShared; using MaddoShared;
using Microsoft.Extensions.Logging;
using Microsoft.VisualBasic; using Microsoft.VisualBasic;
using Microsoft.VisualBasic.CompilerServices; using Microsoft.VisualBasic.CompilerServices;
using Microsoft.WindowsAPICodePack.Dialogs;
namespace ImageCatalog namespace ImageCatalog
{ {
@ -25,22 +26,23 @@ namespace ImageCatalog
public partial class MainForm public partial class MainForm
{ {
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public DataModel Model { get; set; } public DataModel Model { get; set; }
private readonly ITestService _service; private readonly ITestService _service;
private readonly ILogger<MainForm> _logger;
public MainForm(ITestService testService) public MainForm(ITestService testService, ILogger<MainForm> logger)
{ {
_service = testService; _service = testService;
_logger = logger;
_logger.LogDebug("Start");
InitializeComponent(); InitializeComponent();
BindControls(); BindControls();
_Button3.Name = "Button3"; _Button3.Name = "Button3";
_Button2.Name = "Button2"; _Button2.Name = "Button2";
_Button8.Name = "Button8"; _Button8.Name = "Button8";
@ -57,11 +59,10 @@ namespace ImageCatalog
_btnCreaCatalogoAsync.Name = "btnCreaCatalogoAsync"; _btnCreaCatalogoAsync.Name = "btnCreaCatalogoAsync";
var version = Assembly.GetExecutingAssembly().GetName().Version; var version = Assembly.GetExecutingAssembly().GetName().Version;
_Label27.Text = $"Version: {version.Major}.{version.Minor}.{version.Build}.{version.Revision}"; _Label27.Text = $"Version: {version.Major}.{version.Minor}.{version.Build}.{version.Revision}";
_results = new ConcurrentBag<string>(); _results = new ConcurrentBag<string>();
UiUpdateEvent += OnUiUpdateEvent; UiUpdateEvent += OnUiUpdateEvent;
} }
protected void BindControls() protected void BindControls()
@ -75,7 +76,6 @@ namespace ImageCatalog
private void SetText(Label target, string text) private void SetText(Label target, string text)
{ {
if (InvokeRequired) if (InvokeRequired)
{ {
SetTextCallback d = new SetTextCallback(SetText); SetTextCallback d = new SetTextCallback(SetText);
@ -86,7 +86,9 @@ namespace ImageCatalog
target.Text = text; target.Text = text;
} }
} }
delegate void SetProgressCallback(ProgressBar target, int amount, int maximum); delegate void SetProgressCallback(ProgressBar target, int amount, int maximum);
private void SetProgress(ProgressBar target, int amount, int maximum) private void SetProgress(ProgressBar target, int amount, int maximum)
{ {
if (InvokeRequired) if (InvokeRequired)
@ -100,6 +102,7 @@ namespace ImageCatalog
target.Value = amount; target.Value = amount;
} }
} }
private void OnUiUpdateEvent(object sender, Tuple<string, int> args) private void OnUiUpdateEvent(object sender, Tuple<string, int> args)
{ {
SetProgress(ProgressBar1, _results.Count, args.Item2); SetProgress(ProgressBar1, _results.Count, args.Item2);
@ -194,31 +197,43 @@ namespace ImageCatalog
ComboBox5.SelectedIndex = 2; ComboBox5.SelectedIndex = 2;
} }
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool AllocConsole();
private void Form1_Load(object sender, EventArgs e) private void Form1_Load(object sender, EventArgs e)
{ {
bindingSource1.DataSource = Model; bindingSource1.DataSource = Model;
Application.EnableVisualStyles(); Application.EnableVisualStyles();
setDefaults(); setDefaults();
/* TODO ERROR: Skipped IfDirectiveTrivia */ // /* TODO ERROR: Skipped IfDirectiveTrivia */
AllocConsole(); // AllocConsole();
/* TODO ERROR: Skipped EndIfDirectiveTrivia */ // /* TODO ERROR: Skipped EndIfDirectiveTrivia */
Console.WriteLine("Programma avviato"); _logger.LogInformation("Programma Avviato");
//Console.WriteLine("Programma avviato");
} }
private void FixPaths() private void FixPaths()
{ {
if (Model.SourcePath.EndsWith(@"\") == false) Model.SourcePath = FixPath(Model.SourcePath);
Model.DestinationPath = FixPath(Model.DestinationPath);
}
private string FixPath(string path)
{
if (string.IsNullOrWhiteSpace(path))
{ {
Model.SourcePath += @"\"; return string.Empty;
} }
if (Model.DestinationPath.EndsWith(@"\") == false) // Trim leading/trailing quotes
{ path = path.Trim().Trim('"');
Model.DestinationPath += @"\";
} // Normalize directory separators
path = path.Replace('/', Path.DirectorySeparatorChar)
.Replace('\\', Path.DirectorySeparatorChar);
// Remove trailing separators then add one back
path = path.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar;
return path;
} }
private void lockUI() private void lockUI()
@ -241,6 +256,7 @@ namespace ImageCatalog
private void btnCreaCatalogo_Click(object sender, EventArgs e) private void btnCreaCatalogo_Click(object sender, EventArgs e)
{ {
_logger.LogInformation("Avvio elaborazione...");
lockUI(); lockUI();
DateTime timeStart; DateTime timeStart;
var timeStop = default(DateTime); var timeStop = default(DateTime);
@ -277,7 +293,7 @@ namespace ImageCatalog
ContaImmaginiThread = 0; ContaImmaginiThread = 0;
// creaImmaginiWithThreadMod(txtSorgente.Text, txtDestinazione.Text) // creaImmaginiWithThreadMod(txtSorgente.Text, txtDestinazione.Text)
creaimmaginiWithThreadDict(Model.SourcePath, Model.DestinationPath); CreaimmaginiWithThreadDict(Model.SourcePath, Model.DestinationPath);
ThreadPoolWorkItem ThAttivo = null; ThreadPoolWorkItem ThAttivo = null;
int i = 0; int i = 0;
/* TODO ERROR: Skipped DefineDirectiveTrivia */ /* TODO ERROR: Skipped DefineDirectiveTrivia */
@ -354,26 +370,32 @@ namespace ImageCatalog
double fotoSec = numFoto / (double)timediffS; double fotoSec = numFoto / (double)timediffS;
double fotoMin = numFoto / (double)timediffM; double fotoMin = numFoto / (double)timediffM;
double fotoOra = numFoto / (double)timediffH; double fotoOra = numFoto / (double)timediffH;
string s = "S: " + timediffS.ToString() + "; F/s: " + fotoSec.ToString("0.000"); // + " F/m: " + fotoMin.ToString("0.00") + " F/h: " + fotoOra.ToString("0.00") string s = "S: " + timediffS.ToString() + "; F/s: " +
fotoSec.ToString(
"0.000"); // + " F/m: " + fotoMin.ToString("0.00") + " F/h: " + fotoOra.ToString("0.00")
return s; return s;
} }
private string SelectFolder(string startingFolder) private string SelectFolder(string startingFolder)
{ {
CommonOpenFileDialog dialog = new CommonOpenFileDialog var dialog = new FolderBrowserDialog();
{ dialog.InitialDirectory = startingFolder;
InitialDirectory = startingFolder, if (dialog.ShowDialog() != DialogResult.OK) return string.Empty;
IsFolderPicker = true
}; // CommonOpenFileDialog dialog = new CommonOpenFileDialog
if (dialog.ShowDialog() != CommonFileDialogResult.Ok) return null; // {
var directoryScelta = dialog.FileName; // InitialDirectory = startingFolder,
if (directoryScelta.EndsWith(@"\") == false) // IsFolderPicker = true
{ // };
directoryScelta += @"\"; // if (dialog.ShowDialog() != CommonFileDialogResult.Ok) return null;
} var directoryScelta = FixPath(dialog.SelectedPath); // dialog.FileName;
// if (directoryScelta.EndsWith(@"\") == false)
// {
// directoryScelta += @"\";
// }
return directoryScelta; return directoryScelta;
} }
private void Button2_Click(object sender, EventArgs e) private void Button2_Click(object sender, EventArgs e)
@ -624,12 +646,14 @@ namespace ImageCatalog
if (PictureBox1.Image.Height >= PictureBox1.Image.Width) if (PictureBox1.Image.Height >= PictureBox1.Image.Width)
{ {
PictureBox1.Height = 160; PictureBox1.Height = 160;
PictureBox1.Width = Conversions.ToInteger(160 * PictureBox1.Image.Width / (double)PictureBox1.Image.Height); PictureBox1.Width =
Conversions.ToInteger(160 * PictureBox1.Image.Width / (double)PictureBox1.Image.Height);
} }
else else
{ {
PictureBox1.Width = 224; PictureBox1.Width = 224;
PictureBox1.Height = Conversions.ToInteger(224 * PictureBox1.Image.Height / (double)PictureBox1.Image.Width); PictureBox1.Height =
Conversions.ToInteger(224 * PictureBox1.Image.Height / (double)PictureBox1.Image.Width);
} }
} }
@ -638,7 +662,6 @@ namespace ImageCatalog
// 2021 // 2021
TextBox8.Text = Module1.SetupIni.LeggiParametroString("ChunkSize"); TextBox8.Text = Module1.SetupIni.LeggiParametroString("ChunkSize");
TextBox7.Text = Module1.SetupIni.LeggiParametroString("ThreadsCount"); TextBox7.Text = Module1.SetupIni.LeggiParametroString("ThreadsCount");
} }
} }
@ -860,7 +883,9 @@ namespace ImageCatalog
TestoTemp = (ContaDirXDir * NumFileXDir).ToString(); TestoTemp = (ContaDirXDir * NumFileXDir).ToString();
} }
for (int ContaTemp = 1, loopTo = NumCifreDir - TestoTemp.Length; ContaTemp <= loopTo; ContaTemp++) for (int ContaTemp = 1, loopTo = NumCifreDir - TestoTemp.Length;
ContaTemp <= loopTo;
ContaTemp++)
TestoTemp = "0" + TestoTemp; TestoTemp = "0" + TestoTemp;
DestDir = new DirectoryInfo(Path.Combine(DestDirStart.FullName, SuffixDir, TestoTemp)); DestDir = new DirectoryInfo(Path.Combine(DestDirStart.FullName, SuffixDir, TestoTemp));
// DestDir = New DirectoryInfo(DestDirStart.FullName & IIf(Not DestDirStart.FullName.EndsWith("\"), "\", String.Empty).ToString & SuffixDir & TestoTemp) // DestDir = New DirectoryInfo(DestDirStart.FullName & IIf(Not DestDirStart.FullName.EndsWith("\"), "\", String.Empty).ToString & SuffixDir & TestoTemp)
@ -1065,7 +1090,6 @@ namespace ImageCatalog
// Application.DoEvents() // Application.DoEvents()
var ClsCreaImmagine = new ImageCreatorSharp(childFile.Name, SourceDir, DestDir, DestDirStart); var ClsCreaImmagine = new ImageCreatorSharp(childFile.Name, SourceDir, DestDir, DestDirStart);
// ClsCreaImmagine.NomeFileChild = childFile.Name // ClsCreaImmagine.NomeFileChild = childFile.Name
// ClsCreaImmagine.DestDir = DestDir // ClsCreaImmagine.DestDir = DestDir
@ -1075,6 +1099,7 @@ namespace ImageCatalog
ContaImmaginiThread += 1; ContaImmaginiThread += 1;
//MyPool.InsertWorkItem(childFile.Name, new XyThreadAdd((_) => ClsCreaImmagine.CreaImmagineThread()), new object[1] { childFile.Name }, true); //MyPool.InsertWorkItem(childFile.Name, new XyThreadAdd((_) => ClsCreaImmagine.CreaImmagineThread()), new object[1] { childFile.Name }, true);
} }
// copy all the sub-directories by recursively calling this same routine // copy all the sub-directories by recursively calling this same routine
if (chkAggiornaSottodirectory.Checked == true) if (chkAggiornaSottodirectory.Checked == true)
{ {
@ -1114,20 +1139,20 @@ namespace ImageCatalog
return numerazioneType; return numerazioneType;
} }
private void creaimmaginiWithThreadDict(string SourcePath, string DestPath) private void CreaimmaginiWithThreadDict(string SourcePath, string DestPath)
{ {
var dirSourceDest = new Dictionary<FileInfo, DirectoryInfo>(); var dirSourceDest = new Dictionary<FileInfo, DirectoryInfo>();
if (chkAggiornaSottodirectory.Checked & chkCreaSottocartelle.Checked) if (chkAggiornaSottodirectory.Checked & chkCreaSottocartelle.Checked)
{ {
var helper = new FileHelper(Conversions.ToInteger(txtFilePerCartella.Text), txtSuffissoCartelle.Text, Conversions.ToInteger(txtCifreContatore.Text), getNumerazione()); var helper = new FileHelper(Conversions.ToInteger(txtFilePerCartella.Text), txtSuffissoCartelle.Text,
Conversions.ToInteger(txtCifreContatore.Text), getNumerazione());
// getfilesrecursive // getfilesrecursive
dirSourceDest = helper.GetFilesRecursive(new DirectoryInfo(SourcePath), new DirectoryInfo(DestPath), "*.jpg"); dirSourceDest =
helper.GetFilesRecursive(new DirectoryInfo(SourcePath), new DirectoryInfo(DestPath), "*.jpg");
} }
else if (chkAggiornaSottodirectory.Checked & !chkCreaSottocartelle.Checked) else if (chkAggiornaSottodirectory.Checked & !chkCreaSottocartelle.Checked)
{ {
// = getDirsDict(SourcePath, DestPath) // = getDirsDict(SourcePath, DestPath)
} }
foreach (var pair in dirSourceDest) foreach (var pair in dirSourceDest)
@ -1307,8 +1332,10 @@ namespace ImageCatalog
ClsCreaImmagine.jpegQuality = Conversions.ToLong(TextBox32.Text); ClsCreaImmagine.jpegQuality = Conversions.ToLong(TextBox32.Text);
ClsCreaImmagine.jpegQualityMin = Conversions.ToLong(TextBox33.Text); ClsCreaImmagine.jpegQualityMin = Conversions.ToLong(TextBox33.Text);
ContaImmaginiThread += 1; ContaImmaginiThread += 1;
MyPool.InsertWorkItem(childFile.Name, new XyThreadAdd(ClsCreaImmagine.CreaImmagineThread), new object[1] { childFile.Name }, true); MyPool.InsertWorkItem(childFile.Name, new XyThreadAdd(ClsCreaImmagine.CreaImmagineThread),
new object[1] { childFile.Name }, true);
} }
// copy all the sub-directories by recursively calling this same routine // copy all the sub-directories by recursively calling this same routine
if (chkAggiornaSottodirectory.Checked == true) if (chkAggiornaSottodirectory.Checked == true)
{ {
@ -1374,7 +1401,8 @@ namespace ImageCatalog
tempMultiplier = MaxPixel / (double)currentwidth; tempMultiplier = MaxPixel / (double)currentwidth;
} }
var NewSize = new Size((int)Math.Round(currentwidth * tempMultiplier), (int)Math.Round(currentheight * tempMultiplier)); var NewSize = new Size((int)Math.Round(currentwidth * tempMultiplier),
(int)Math.Round(currentheight * tempMultiplier));
return NewSize; return NewSize;
} }
@ -1382,10 +1410,16 @@ namespace ImageCatalog
{ {
StopAttivo = true; StopAttivo = true;
//MyPool.StopThreadPool(); //MyPool.StopThreadPool();
try
if (_mainToken != null)
{ {
_mainToken.Cancel(); _mainToken?.Cancel();
}
catch (Exception exception)
{
_logger.LogError(exception.Message);
_logger.LogInformation("Ignora questo errore");
// Console.WriteLine(exception);
// Console.WriteLine("Ignora questo errore");
} }
unlockUI(); unlockUI();
@ -1411,12 +1445,14 @@ namespace ImageCatalog
if (PictureBox1.Image.Height >= PictureBox1.Image.Width) if (PictureBox1.Image.Height >= PictureBox1.Image.Width)
{ {
PictureBox1.Height = 160; PictureBox1.Height = 160;
PictureBox1.Width = Conversions.ToInteger(160 * PictureBox1.Image.Width / (double)PictureBox1.Image.Height); PictureBox1.Width =
Conversions.ToInteger(160 * PictureBox1.Image.Width / (double)PictureBox1.Image.Height);
} }
else else
{ {
PictureBox1.Width = 224; PictureBox1.Width = 224;
PictureBox1.Height = Conversions.ToInteger(224 * PictureBox1.Image.Height / (double)PictureBox1.Image.Width); PictureBox1.Height =
Conversions.ToInteger(224 * PictureBox1.Image.Height / (double)PictureBox1.Image.Width);
} }
} }
} }
@ -1438,7 +1474,6 @@ namespace ImageCatalog
{ {
// GetColor() // GetColor()
// GetPixelColor(PictureBox1.PointToScreen(e.Location)).ToArgb.ToString("X8") // GetPixelColor(PictureBox1.PointToScreen(e.Location)).ToArgb.ToString("X8")
} }
private void PictureBox1_MouseUp(object sender, MouseEventArgs e) private void PictureBox1_MouseUp(object sender, MouseEventArgs e)
@ -1534,14 +1569,14 @@ namespace ImageCatalog
{ {
} }
private CancellationTokenSource _mainToken; private CancellationTokenSource? _mainToken;
private async void Button1_Click(object sender, EventArgs e) private async void Button1_Click(object sender, EventArgs e)
{ {
lockUI(); lockUI();
// Dim timeStart As Date // Dim timeStart As Date
// Dim timeStop As Date // Dim timeStop As Date
_mainToken?.Dispose();
_mainToken = new CancellationTokenSource(); _mainToken = new CancellationTokenSource();
var token = _mainToken.Token; var token = _mainToken.Token;
@ -1572,7 +1607,6 @@ namespace ImageCatalog
imageCreationOptions.ChunksSize = Conversions.ToInteger(TextBox8.Text); imageCreationOptions.ChunksSize = Conversions.ToInteger(TextBox8.Text);
imageCreationOptions.LinearExecution = rdbVecchioMetodo.Checked; imageCreationOptions.LinearExecution = rdbVecchioMetodo.Checked;
try try
{ {
@ -1590,20 +1624,24 @@ namespace ImageCatalog
} }
catch (OperationCanceledException operationCanceledException) catch (OperationCanceledException operationCanceledException)
{ {
Console.WriteLine("Operazione cancellata"); _logger.LogInformation("Operazione Cancellata");
//Console.WriteLine("Operazione cancellata");
} }
finally finally
{ {
_mainToken.Dispose(); _mainToken?.Dispose();
_mainToken = null;
timer1.Tick -= Timer1OnTick; timer1.Tick -= Timer1OnTick;
} }
Label10.Text = "Finito"; Label10.Text = "Finito";
unlockUI(); unlockUI();
} }
private int _currentAmount = 0; private int _currentAmount = 0;
private int _previousAmount = 0; private int _previousAmount = 0;
private void Timer1OnTick(object sender, EventArgs e) private void Timer1OnTick(object sender, EventArgs e)
{ {
_previousAmount = _currentAmount; _previousAmount = _currentAmount;
@ -1618,7 +1656,6 @@ namespace ImageCatalog
} }
private async Task CreaCatalogoParallel() private async Task CreaCatalogoParallel()
{ {
var timeStart = DateAndTime.TimeOfDay; var timeStart = DateAndTime.TimeOfDay;
@ -1723,7 +1760,8 @@ namespace ImageCatalog
public DirectoryInfo DirSource, DirDest, DirDestStart; public DirectoryInfo DirSource, DirDest, DirDestStart;
public string NomeImmagine; public string NomeImmagine;
public PicInfo(DirectoryInfo Dir_Source, DirectoryInfo Dir_Dest, DirectoryInfo Dir_DestStart, string Nome_Immagine) public PicInfo(DirectoryInfo Dir_Source, DirectoryInfo Dir_Dest, DirectoryInfo Dir_DestStart,
string Nome_Immagine)
{ {
DirSource = Dir_Source; DirSource = Dir_Source;
DirDest = Dir_Dest; DirDest = Dir_Dest;

View file

@ -1,11 +1,54 @@
using ImageCatalog; using System.Runtime.InteropServices;
using ImageCatalog;
using ImageCatalog_2.Services; using ImageCatalog_2.Services;
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
namespace ImageCatalog_2 namespace ImageCatalog_2
{ {
static class Program static class Program
{ {
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool AllocConsole();
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr GetStdHandle(int nStdHandle);
private const int STD_OUTPUT_HANDLE = -11;
private const int STD_ERROR_HANDLE = -12;
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool SetStdHandle(int nStdHandle, IntPtr handle);
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr GetConsoleWindow();
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool AttachConsole(int dwProcessId);
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr CreateFile(
string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
IntPtr lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
IntPtr hTemplateFile);
private const uint GENERIC_WRITE = 0x40000000;
private const uint OPEN_EXISTING = 3;
private static void RedirectConsoleOutput()
{
var stdOutHandle = CreateFile("CONOUT$", GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero);
var safeFileHandle = new Microsoft.Win32.SafeHandles.SafeFileHandle(stdOutHandle, true);
var fileStream = new FileStream(safeFileHandle, FileAccess.Write);
var standardOutput = new StreamWriter(fileStream) { AutoFlush = true };
Console.SetOut(standardOutput);
Console.SetError(standardOutput);
}
public static IServiceProvider ServiceProvider { get; private set; } public static IServiceProvider ServiceProvider { get; private set; }
[STAThread] [STAThread]
static void Main() static void Main()
@ -14,6 +57,9 @@ namespace ImageCatalog_2
Application.EnableVisualStyles(); Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false); Application.SetCompatibleTextRenderingDefault(false);
AllocConsole();
RedirectConsoleOutput();
var serviceCollection = new ServiceCollection(); var serviceCollection = new ServiceCollection();
ConfigureServices(serviceCollection); ConfigureServices(serviceCollection);
@ -36,6 +82,12 @@ namespace ImageCatalog_2
// Register your forms // Register your forms
services.AddTransient<MainForm>(); services.AddTransient<MainForm>();
services.AddLogging(configure =>
{
configure.AddConsole();
configure.SetMinimumLevel(LogLevel.Debug);
});
} }
} }
} }