Aggiunta test FileWatcher

This commit is contained in:
Samuele Locatelli
2021-12-01 16:48:17 +01:00
parent 6c13590778
commit bd2b801918
9 changed files with 341 additions and 0 deletions
+25
View File
@@ -0,0 +1,25 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30413.136
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Test-FileWatcher", "Test-FileWatcher\Test-FileWatcher.csproj", "{41CED9A1-A4F8-4F8D-97EC-CBEFC2B3F2EB}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{41CED9A1-A4F8-4F8D-97EC-CBEFC2B3F2EB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{41CED9A1-A4F8-4F8D-97EC-CBEFC2B3F2EB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{41CED9A1-A4F8-4F8D-97EC-CBEFC2B3F2EB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{41CED9A1-A4F8-4F8D-97EC-CBEFC2B3F2EB}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {D37298AA-67AF-432E-B3BB-12C51CD28F92}
EndGlobalSection
EndGlobal
+109
View File
@@ -0,0 +1,109 @@
using System;
using System.IO;
using System.Security.Permissions;
namespace TestApp
{
/**************************************************
* Classe gestione verifica cambio files in directory
*
* links:
* https://docs.microsoft.com/it-it/dotnet/api/system.io.filesystemwatcher?view=netframework-4.0
* https://www.c-sharpcorner.com/UploadFile/puranindia/filesystemwatcher-in-C-Sharp/
*
*
* ***********************************************/
public static class FSWatch
{
/// <summary>
/// Metodo principale esecuzione check filesystem
/// </summary>
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public static void Run()
{
//string[] args = Environment.GetCommandLineArgs();
//// If a directory is not specified, exit program.
//if (args.Length != 2)
//{
// // Display the proper way to call the program.
// Console.WriteLine("Usage: Watcher.exe (directory)");
// return;
//}
try
{
// Create a new FileSystemWatcher and set its properties.
using (FileSystemWatcher watcher = new FileSystemWatcher())
{
//watcher.Path = args[1];
watcher.Path = Directory.GetCurrentDirectory();
// NO guardo le subdirs
watcher.IncludeSubdirectories = false;
// Watch for changes in LastAccess and LastWrite times, and
// the renaming of files or directories.
//watcher.NotifyFilter = NotifyFilters.DirectoryName
// | NotifyFilters.FileName
// | NotifyFilters.LastAccess
// | NotifyFilters.LastWrite
// | NotifyFilters.Size;
watcher.NotifyFilter = NotifyFilters.Attributes
| NotifyFilters.CreationTime
| NotifyFilters.DirectoryName
| NotifyFilters.FileName
| NotifyFilters.LastAccess
| NotifyFilters.LastWrite
| NotifyFilters.Security
| NotifyFilters.Size;
// Only watch text files.
watcher.Filter = "*.*";
// Add event handlers.
watcher.Changed += OnChanged;
watcher.Created += OnChanged;
watcher.Error += OnError;
watcher.Deleted += OnChanged;
watcher.Renamed += OnRenamed;
// Begin watching.
watcher.EnableRaisingEvents = true;
// Wait for the user to quit the program.
Console.WriteLine("Press 'q' to quit the sample.");
while (Console.Read() != 'q') ;
}
}
catch (IOException e)
{
//Console.WriteLine("A Exception Occurred :" + e);
Utils.Log.Error("A Exception Occurred :" + e);
}
catch (Exception oe)
{
//Console.WriteLine("An Exception Occurred :" + oe);
Utils.Log.Error("An Exception Occurred :" + oe);
}
}
private static void OnError(object sender, ErrorEventArgs e) =>
// Specify what is done when a file is changed, created, or deleted.
Console.WriteLine($"{DateTime.Now} | Error: {e.GetException()}");
// Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e) =>
Utils.Log.Info($"File: {e.Name} {e.ChangeType}");
// Specify what is done when a file is changed, created, or deleted.
//Console.WriteLine($"{DateTime.Now} | File: {e.Name} {e.ChangeType} ({e.FullPath})");
private static void OnRenamed(object source, RenamedEventArgs e) =>
Utils.Log.Info($"File: {e.OldName} renamed to {e.Name}");
// Specify what is done when a file is renamed.
//Console.WriteLine($"{DateTime.Now} | File: {e.OldName} renamed to {e.Name} ({e.OldFullPath} --> {e.FullPath})");
}
}
+54
View File
@@ -0,0 +1,54 @@
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="false"
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
<!-- optional, add some variables
https://github.com/nlog/NLog/wiki/Configuration-file#variables
-->
<variable name="logDir" value="${basedir}/logs"/>
<!--
See https://github.com/nlog/nlog/wiki/Configuration-file
for information on customizing logging rules and outputs.
-->
<targets>
<target xsi:type="File"
name="f_base"
fileName="${logDir}/${shortdate}.log"
layout="${longdate} [${uppercase:${level}}] ${logger:shortName=true}|${message}"
archiveFileName="${logDir}/${shortdate}.{###}.log"
archiveNumbering="Sequence"
archiveAboveSize="10240000"
maxArchiveFiles="60"
enableArchiveFileCompression="false"
keepFileOpen="false"
/>
<target xsi:type="File"
name="f_error"
fileName="${logDir}/${shortdate}.log"
layout="${longdate} [${uppercase:${level}}] ${logger:shortName=true}|${message}${newline}${exception:format=tostring}"
archiveFileName="${logDir}/${shortdate}.{###}.log"
archiveNumbering="Sequence"
archiveAboveSize="10240000"
maxArchiveFiles="60"
enableArchiveFileCompression="false"
keepFileOpen="false"
/>
</targets>
<rules>
<!-- add your logging rules here -->
<!--
Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace) to "f"
<logger name="*" minlevel="Debug" writeTo="f" />
-->
<logger name="*" minlevel="Debug" maxlevel="Warn" final="true" writeTo="f_base" />
<logger name="*" minlevel="Error" writeTo="f_error" />
</rules>
</nlog>
+16
View File
@@ -0,0 +1,16 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestApp
{
internal class Program
{
private static void Main(string[] args)
{
// eseguo test FS Watcher
FSWatch.Run();
}
}
}
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// Le informazioni generali relative a un assembly sono controllate dal seguente
// set di attributi. Modificare i valori di questi attributi per modificare le informazioni
// associate a un assembly.
[assembly: AssemblyTitle("TestApp")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TestApp")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Se si imposta ComVisible su false, i tipi in questo assembly non saranno visibili
// ai componenti COM. Se è necessario accedere a un tipo in questo assembly da
// COM, impostare su true l'attributo ComVisible per tale tipo.
[assembly: ComVisible(false)]
// Se il progetto viene esposto a COM, il GUID seguente verrà utilizzato come ID della libreria dei tipi
[assembly: Guid("41ced9a1-a4f8-4f8d-97ec-cbefc2b3f2eb")]
// Le informazioni sulla versione di un assembly sono costituite dai seguenti quattro valori:
//
// Versione principale
// Versione secondaria
// Numero di build
// Revisione
//
// È possibile specificare tutti i valori oppure impostare valori predefiniti per i numeri relativi alla revisione e alla build
// usando l'asterisco '*' come illustrato di seguito:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
+73
View File
@@ -0,0 +1,73 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{41CED9A1-A4F8-4F8D-97EC-CBEFC2B3F2EB}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>TestApp</RootNamespace>
<AssemblyName>TestApp</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="NLog, Version=4.0.0.0, Culture=neutral, PublicKeyToken=5120e14c03d0593c, processorArchitecture=MSIL">
<HintPath>..\packages\NLog.4.7.5\lib\net40-client\NLog.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.ServiceModel" />
<Reference Include="System.Transactions" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="FSWatch.cs" />
<Compile Include="Utils.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="logs\.placeholder">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="NLog.config">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Include="packages.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="AfterBuild">
<ItemGroup>
<MoveToLibFolder Include="$(OutputPath)*.dll ; $(OutputPath)*.pdb ; $(OutputPath)*.xml" />
</ItemGroup>
</Target>
</Project>
+23
View File
@@ -0,0 +1,23 @@
using NLog;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestApp
{
public class Utils
{
/// <summary>
/// S
/// </summary>
public static Logger Log { get; private set; }
static Utils()
{
LogManager.ReconfigExistingLoggers();
Log = LogManager.GetCurrentClassLogger();
}
}
}
+1
View File
@@ -0,0 +1 @@

+4
View File
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="NLog" version="4.7.5" targetFramework="net40" />
</packages>