From f637478dca0dd5c5a58775bf9251cd89ff294e66 Mon Sep 17 00:00:00 2001 From: "Samuele E. Locatelli" Date: Sat, 3 Oct 2020 15:57:46 +0200 Subject: [PATCH] Riorganizzaizone classi logger in memLayer --- SteamWare.Logger/Logging.cs | 6 +- SteamWareLib/fileMover.cs | 2431 ++++++++++++++++++----------------- SteamWareLib/memLayer.cs | 218 ++-- 3 files changed, 1329 insertions(+), 1326 deletions(-) diff --git a/SteamWare.Logger/Logging.cs b/SteamWare.Logger/Logging.cs index 166ca9d..26cabc8 100644 --- a/SteamWare.Logger/Logging.cs +++ b/SteamWare.Logger/Logging.cs @@ -21,7 +21,7 @@ namespace SteamWare.Logger static Logging() { -#if DEBUG +#if false // Setup the logging view for Sentinel - http://sentinel.codeplex.com var sentinalTarget = new NLogViewerTarget() { @@ -42,8 +42,6 @@ namespace SteamWare.Logger #endregion Public Constructors - - #region Public Properties /// @@ -53,8 +51,6 @@ namespace SteamWare.Logger #endregion Public Properties - - #region Public Methods public static void LogError(string message) diff --git a/SteamWareLib/fileMover.cs b/SteamWareLib/fileMover.cs index a780a9e..cf35192 100644 --- a/SteamWareLib/fileMover.cs +++ b/SteamWareLib/fileMover.cs @@ -6,126 +6,126 @@ using System.Net; namespace SteamWare { - /// - /// Accesso in lettura e scrittura al filesystem per gestione files upload e download - /// - public class fileMover - { - - #region oggetti private - /// - /// path di lavoro dei metodi leggi/scrivi + /// Accesso in lettura e scrittura al filesystem per gestione files upload e download /// - protected string _workPath; - /// - /// verifica esistenza directory ed eventualmente crea restituendo nome completo di "/" finale - /// - /// - /// - protected string verDir(string _path) + public class fileMover { - DirectoryInfo di = getDirectoryInfo(_path, true); - if (!di.Exists) - { - di.Create(); - } - if (!_path.EndsWith("/") && !_path.EndsWith(@"\")) - { - _path += "/"; - } - return _path; - } - /// - /// restituisce una tab di files dato l'elenco dei files - /// - /// - /// - private static DataLayer_generic.filesDataTable tabellaFiles(FileInfo[] _files) - { - DataLayer_generic.filesDataTable _dsEF = new DataLayer_generic.filesDataTable(); - DataLayer_generic.filesRow _riga; - foreach (FileInfo _fi in _files) - { - _riga = _dsEF.NewfilesRow(); - _riga.dataCreaz = _fi.CreationTime; - _riga.dataMod = _fi.LastWriteTime; - _riga.Nome = _fi.Name; - _riga.size = _fi.Length / 1000; - _dsEF.AddfilesRow(_riga); - } - return _dsEF; - } - /// - /// setta le directory - /// - /// - private void setDirs(string _path) - { - _workPath = _path; - } - /// - /// oggetto WebClient - /// - public WebClient WebCli; - #endregion + #region oggetti private - #region inizializzazione + /// + /// path di lavoro dei metodi leggi/scrivi + /// + protected string _workPath; + /// + /// verifica esistenza directory ed eventualmente crea restituendo nome completo di "/" finale + /// + /// + /// + protected string verDir(string _path) + { + DirectoryInfo di = getDirectoryInfo(_path, true); + if (!di.Exists) + { + di.Create(); + } + if (!_path.EndsWith("/") && !_path.EndsWith(@"\")) + { + _path += "/"; + } + return _path; + } + /// + /// restituisce una tab di files dato l'elenco dei files + /// + /// + /// + private static DataLayer_generic.filesDataTable tabellaFiles(FileInfo[] _files) + { + DataLayer_generic.filesDataTable _dsEF = new DataLayer_generic.filesDataTable(); + DataLayer_generic.filesRow _riga; + foreach (FileInfo _fi in _files) + { + _riga = _dsEF.NewfilesRow(); + _riga.dataCreaz = _fi.CreationTime; + _riga.dataMod = _fi.LastWriteTime; + _riga.Nome = _fi.Name; + _riga.size = _fi.Length / 1000; + _dsEF.AddfilesRow(_riga); + } + return _dsEF; + } + /// + /// setta le directory + /// + /// + private void setDirs(string _path) + { + _workPath = _path; + } + /// + /// oggetto WebClient + /// + public WebClient WebCli; - /// - /// inizializza il metodo alla cartella indicata - /// - /// - /// non serve +... x retrocompatibilità... - public fileMover(string _path, string _log) - { - setDirs(_path); - WebCli = new WebClient(); - } - /// - /// metodo di avvio empty - /// - public fileMover() - { - WebCli = new WebClient(); - } + #endregion + + #region inizializzazione + + /// + /// inizializza il metodo alla cartella indicata + /// + /// + /// non serve +... x retrocompatibilità... + public fileMover(string _path, string _log) + { + setDirs(_path); + WebCli = new WebClient(); + } + /// + /// metodo di avvio empty + /// + public fileMover() + { + WebCli = new WebClient(); + } - #endregion + #endregion - /// - /// Recupera path correttamente (se fisico o virtuale - /// - /// - /// - protected string GetPath(string path) - { - if (Path.IsPathRooted(path)) - { - return path; - } - // altrimenti MapPath! - return System.Web.HttpContext.Current.Server.MapPath(path); - } + /// + /// Recupera path correttamente (se fisico o virtuale + /// + /// + /// + protected string GetPath(string path) + { + if (Path.IsPathRooted(path)) + { + return path; + } + // altrimenti MapPath! + return System.Web.HttpContext.Current.Server.MapPath(path); + } - /// - /// cerca di caricare il fileinfo o da httpcontext-application re-position o direttamente come workpath + nomefile - /// - /// - /// - private FileInfo getFileInfoByName(string _nomeFile) - { - FileInfo _fi; - try - { - _fi = new FileInfo(GetPath(_workPath + "\\" + _nomeFile)); - } - catch (Exception exc) - { - logger.lg.scriviLog($"Errore in recupero info file: {_nomeFile}{Environment.NewLine}{exc}", tipoLog.EXCEPTION); - _fi = new FileInfo(_workPath + "\\" + _nomeFile); - } + /// + /// cerca di caricare il fileinfo o da httpcontext-application re-position o direttamente come workpath + nomefile + /// + /// + /// + private FileInfo getFileInfoByName(string _nomeFile) + { + FileInfo _fi; + try + { + _fi = new FileInfo(GetPath(_workPath + "\\" + _nomeFile)); + } + catch (Exception exc) + { + logger.lg.scriviLog($"Errore in recupero info file: {_nomeFile}{Environment.NewLine}{exc}", tipoLog.EXCEPTION); + _fi = new FileInfo(_workPath + "\\" + _nomeFile); + } #if false // se nomefile contiene "/" --> faccio mappath altrimenti è percorso fisico... if (_nomeFile.IndexOf("/") < 0) @@ -153,27 +153,27 @@ namespace SteamWare } } #endif - return _fi; - } - /// - /// cerca di caricare il fileinfo o da httpcontext-application re-position o direttamente come workpath + nomefile - /// - /// The _path. - /// The _nome file. - /// - private FileInfo getFileInfoByName(string _path, string _nomeFile) - { - FileInfo _fi; - try - { - _fi = new FileInfo(GetPath(_path + _nomeFile)); + return _fi; + } + /// + /// cerca di caricare il fileinfo o da httpcontext-application re-position o direttamente come workpath + nomefile + /// + /// The _path. + /// The _nome file. + /// + private FileInfo getFileInfoByName(string _path, string _nomeFile) + { + FileInfo _fi; + try + { + _fi = new FileInfo(GetPath(_path + _nomeFile)); - } - catch (Exception exc) - { - logger.lg.scriviLog($"Errore in recupero info path: {_path} | file: {_nomeFile}{Environment.NewLine}{exc}", tipoLog.EXCEPTION); - _fi = new FileInfo(_path + "\\" + _nomeFile); - } + } + catch (Exception exc) + { + logger.lg.scriviLog($"Errore in recupero info path: {_path} | file: {_nomeFile}{Environment.NewLine}{exc}", tipoLog.EXCEPTION); + _fi = new FileInfo(_path + "\\" + _nomeFile); + } #if false try { @@ -185,1108 +185,1119 @@ namespace SteamWare _fi = new FileInfo(_path + "\\" + _nomeFile); } #endif - return _fi; - } - /// - /// cerca di caricare il fileinfo o da httpcontext-application re-position o direttamente come workpath + nomefile - /// - /// cartella file - /// nome file - /// indica se il path sia assoluto - /// - private FileInfo getFileInfoByName(string _path, string _nomeFile, bool absPath) - { - FileInfo _fi; - if (absPath) - { - _fi = new FileInfo(_path + "\\" + _nomeFile); - } - else - { - _fi = getFileInfoByName(_path, _nomeFile); - } - return _fi; - } - /// - /// cerca di caricare la directoryInfo o da httpcontext-application re-position o direttamente come workpath - /// - /// - private DirectoryInfo getDirectoryInfo() - { - DirectoryInfo _di; - try - { - _di = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath(_workPath)); - } - catch - { - _di = new DirectoryInfo(_workPath); - } - return _di; - } - /// - /// imposta la directory richiesta... - /// - /// - private DirectoryInfo getDirectoryInfo(string path, bool absPath) - { - DirectoryInfo _di; - if (absPath) - { - _di = new DirectoryInfo(path); - } - else - { - - try - { - _di = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath(path)); + return _fi; } - catch + /// + /// cerca di caricare il fileinfo o da httpcontext-application re-position o direttamente come workpath + nomefile + /// + /// cartella file + /// nome file + /// indica se il path sia assoluto + /// + private FileInfo getFileInfoByName(string _path, string _nomeFile, bool absPath) { - _di = new DirectoryInfo(path); - } - } - return _di; - } - - #region oggetti public - - /// - /// Legge i dati da uno stream fino a quando arriva alla fine. - /// I dati sono restituiti come un byte[] array. un eccezione IOException è - /// sollevata se una delle chiamate IO sottostanti fallisce. - /// - /// Lo stream da cui leggere - /// Lunghezza buffer iniziale (-1 = default 32k) - public static byte[] ReadFully(Stream stream, int initialLength) - { - // If we've been passed an unhelpful initial length, just - // use 32K. - if (initialLength < 1) - { - initialLength = 32768; - } - - byte[] buffer = new byte[initialLength]; - int read = 0; - - int chunk; - while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0) - { - read += chunk; - - // If we've reached the end of our buffer, check to see if there's - // any more information - if (read == buffer.Length) - { - int nextByte = stream.ReadByte(); - - // End of stream? If so, we're done - if (nextByte == -1) - { - return buffer; - } - - // Nope. Resize the buffer, put in the byte we've just - // read, and continue - byte[] newBuffer = new byte[buffer.Length * 2]; - Array.Copy(buffer, newBuffer, buffer.Length); - newBuffer[read] = (byte)nextByte; - buffer = newBuffer; - read++; - } - } - // Buffer is now too big. Shrink it. - byte[] ret = new byte[read]; - Array.Copy(buffer, ret, read); - return ret; - } - - /// - /// verifica esistenza directory, eventualmente crea e restituisce controllo DirectoryInfo - /// - /// - public DirectoryInfo checkDir() - { - DirectoryInfo _di = getDirectoryInfo(); - if (!_di.Exists) - { - _di.Create(); - } - return _di; - } - - /// - /// ottiene il dataset dei files presenti nella directory indicata esplicitamente - /// - /// dir da indicizzare... già mappata! ( es SteamwareStrings.getFilePath(...) ) - /// - public DataLayer_generic.filesDataTable elencoFilesDir(string directory) - { - _workPath = directory; - return elencoFiles(); - } - - /// - /// ottiene il dataset dei files presenti nella directory indicata all'istanziazione dell'oggetto - /// - /// - public DataLayer_generic.filesDataTable elencoFiles() - { - DirectoryInfo _di = checkDir(); - FileInfo[] _files = _di.GetFiles(); - DataLayer_generic.filesDataTable _dsEF = tabellaFiles(_files); - return _dsEF; - } - /// - /// ottiene il dataset dei files DEL TIPO "like {param}" presenti nella directory indicata all'istanziazione dell'oggetto - /// - /// - public DataLayer_generic.filesDataTable elencoFiles(string _param) - { - DirectoryInfo _di = checkDir(); - FileInfo[] _files = _di.GetFiles(_param); - DataLayer_generic.filesDataTable _dsEF = tabellaFiles(_files); - return _dsEF; - } - /// - /// elenco dei files come array di oggetti FileInfo - /// - /// - public FileInfo[] elencoFiles_FI() - { - DirectoryInfo _di = checkDir(); - return _di.GetFiles(); - } - /// - /// elenco dei files come array di oggetti FileInfo filtrati per parametro - /// - /// - /// - public FileInfo[] elencoFiles_FI(string _param) - { - DirectoryInfo _di = checkDir(); - return _di.GetFiles(_param); - } - /// - /// elenco sub-directory array di oggetti FileInfo filtrati per parametro - /// - /// - public DirectoryInfo[] elencoSubdir_DI() - { - DirectoryInfo _di = checkDir(); - return _di.GetDirectories(); - } - /// - /// elenco sub-directory array di oggetti FileInfo filtrati per parametro - /// - /// - /// - public DirectoryInfo[] elencoSubdir_DI(string _param) - { - DirectoryInfo _di = checkDir(); - return _di.GetDirectories(_param); - } - /// - /// elimina la directory di lavoro se è dir virtuale mappata - /// - /// - public bool eliminaDir() - { - DirectoryInfo _di = checkDir(); - bool fatto = false; - try - { - _di.Delete(true); - fatto = true; - } - catch - { - } - return fatto; - } - - /// - /// elimina tutti i files con la regexp indicata da una directory, true se cancellato almeno uno - /// - /// regexp selezione files in dir (* = tutti!!!) - /// - public bool svuotaDir(string nomeCercato) - { - bool answ = false; - FileInfo[] _fis = elencoFiles_FI(nomeCercato); - foreach (FileInfo _file in _fis) - { - eliminaFile(_file.Name); - answ = true; - } - return answ; - } - - /// - /// verifica se il file indicato esista in workDir - /// - /// - /// - public bool fileExist(string _nomeFile) - { - bool answ = false; - FileInfo _fi = getFileInfoByName(_nomeFile); - answ = _fi.Exists; - if (!answ) - { - // registro che non ho trovaot il file: path e nome file! - logger.lg.scriviLog(string.Format("Attenzione: non e' stato possibile trovare il file!{0}wrkDir:{1}{0}file:{2}", Environment.NewLine, _workPath, _nomeFile), tipoLog.INFO); - } - return answ; - } - /// - /// verifica se il file indicato esista in _path - /// - /// - /// - /// - public bool fileExist(string _path, string _nomeFile) - { - bool answ = false; - FileInfo _fi = getFileInfoByName(_path, _nomeFile); - answ = _fi.Exists; - if (!answ) - { - // registro che non ho trovaot il file: path e nome file! - logger.lg.scriviLog(string.Format("Attenzione: non e' stato possibile trovare il file!{0}path:{1}{0}file:{2}", Environment.NewLine, _path, _nomeFile), tipoLog.INFO); - } - return answ; - } - /// - /// elimina il file indicato dalla directory di lavoro - /// - /// - /// - public bool eliminaFile(string _nomeFile) - { - FileInfo _fi = getFileInfoByName(_nomeFile); - bool fatto = false; - try - { - _fi.Delete(); - fatto = true; - } - catch - { } - if (fatto) - { - logger.lg.scriviLog($"Eliminazione file {_nomeFile} eseguita"); - } - else - { - logger.lg.scriviLog($"impossibile Eliminare il file {_nomeFile}"); - } - return fatto; - } - /// - /// elimina il file indicato dalla directory di lavoro - /// - /// The _fi. - /// - public bool eliminaFile(FileInfo _fi) - { - bool fatto = false; - try - { - _fi.Delete(); - fatto = true; - } - catch - { - } - return fatto; - } - /// - /// restituisce lo stream del file richiesto - /// - /// - /// - public byte[] scaricaFile(string _nomeFile) - { - FileInfo _fi = getFileInfoByName(_nomeFile); - // verifica ci siano attach... - if (_fi.Exists) - { - Stream _stream = _fi.OpenRead(); - byte[] _risposta = ReadFully(_stream, -1); - _stream.Close(); - return _risposta; - } - else - { - return null; - } - } - /// - /// restituisce la stringa letta dal file richiesto - /// - /// - /// - public string scaricaFileString(string _nomeFile) - { - return byteToStr(scaricaFile(_nomeFile)); - } - /// - /// scrive il file dallo stream byte[] inviato - /// - /// - /// - /// - /// - public bool salvaFileBuffer(string _path, string _nomeFile, byte[] _fileBuffer) - { - _workPath = _path; - DirectoryInfo _di = getDirectoryInfo(_path, true); - if (!_di.Exists) - { - _di.Create(); - } - FileInfo _fi = getFileInfoByName(_path, _nomeFile); - Stream _stream; - if (!_fi.Exists) - { - _stream = _fi.Create(); - } - else - { - _stream = _fi.OpenWrite(); - } - _stream.Write(_fileBuffer, 0, _fileBuffer.Length); - _stream.Flush(); - _stream.Close(); - - return true; - } - /// - /// scrive il file dallo stream byte[] inviato - /// - /// - /// - /// - public bool salvaFileBuffer(string _nomeFile, byte[] _fileBuffer) - { - DirectoryInfo _di = getDirectoryInfo(); - if (!_di.Exists) - { - _di.Create(); - } - FileInfo _fi = getFileInfoByName(_nomeFile); - Stream _stream; - if (!_fi.Exists) - { - _stream = _fi.Create(); - } - else - { - _stream = _fi.OpenWrite(); - } - _stream.Write(_fileBuffer, 0, _fileBuffer.Length); - _stream.Flush(); - _stream.Close(); - - return true; - } - /// - /// scrive il file dalla stringa inviata - /// - /// - /// - /// - /// - public bool salvaFileString(string _path, string _nomeFile, string _fileString) - { - return salvaFileBuffer(_path, _nomeFile, strToByte(_fileString)); - } - /// - /// scrive il file dalla stringa inviata - /// - /// - /// - /// - public bool salvaFileString(string _nomeFile, string _fileString) - { - return salvaFileBuffer(_nomeFile, strToByte(_fileString)); - } - /// - /// converte una string in un byte[] - /// - /// - /// - protected byte[] strToByte(string _val) - { - System.Text.ASCIIEncoding encod = new System.Text.ASCIIEncoding(); - return encod.GetBytes(_val); - } - /// - /// converte un byte[] in una string - /// - /// - /// - protected string byteToStr(byte[] _array) - { - System.Text.ASCIIEncoding encod = new System.Text.ASCIIEncoding(); - return encod.GetString(_array); - } - - /// - /// sposta il file da From a To... - /// - /// - /// - /// - /// - public bool muoviFile(string _pathFrom, string _pathTo, string _nomeFile) - { - bool fatto = false; - // verifica directory - _pathTo = verDir(_pathTo); - _pathFrom = verDir(_pathFrom); - FileInfo _fi = getFileInfoByName(_pathFrom, _nomeFile, true); - try - { - _fi.CopyTo(_pathTo + _nomeFile, true); - _fi.Delete(); - fatto = true; - } - catch (Exception e) - { - Console.WriteLine("{0} Exception caught.", e); - } - return fatto; - } - /// - /// Copia il contenuto directory da From a To (opzionalmente in modo ricorsivo)... - /// - /// Nome dir sorgente - /// Nome dir destinazione - /// Indica se copiare ricorsivamente - /// Indica se sovrascrivere i dati (default = true) - /// - public static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs, bool overwrite = true) - { - // Get the subdirectories for the specified directory. - DirectoryInfo dir = new DirectoryInfo(sourceDirName); - - if (!dir.Exists) - { - throw new DirectoryNotFoundException( - "Source directory does not exist or could not be found: " - + sourceDirName); - } - - DirectoryInfo[] dirs = dir.GetDirectories(); - // If the destination directory doesn't exist, create it. - if (!Directory.Exists(destDirName)) - { - Directory.CreateDirectory(destDirName); - } - - // Get the files in the directory and copy them to the new location. - FileInfo[] files = dir.GetFiles(); - foreach (FileInfo file in files) - { - string temppath = Path.Combine(destDirName, file.Name); - file.CopyTo(temppath, overwrite); - } - - // If copying subdirectories, copy them and their contents to new location. - if (copySubDirs) - { - foreach (DirectoryInfo subdir in dirs) - { - string temppath = Path.Combine(destDirName, subdir.Name); - DirectoryCopy(subdir.FullName, temppath, copySubDirs); - } - } - } - - /// - /// copia il file da From a To... - /// - /// - /// - /// - /// - public bool copiaFile(string _pathFrom, string _pathTo, string _nomeFile) - { - bool fatto = false; - // verifica directory - _pathFrom = verDir(_pathFrom); - _pathTo = verDir(_pathTo); - FileInfo _fi = getFileInfoByName(_pathFrom, _nomeFile); - try - { - _fi.CopyTo(_pathTo + _nomeFile, true); - fatto = true; - } - catch (Exception e) - { - Console.WriteLine("{0} Exception caught.", e); - } - return fatto; - } - /// - /// copia il file da From a To... - /// - /// - /// - /// - /// - /// - public bool copiaFile(string _pathFrom, string _pathTo, string _nomeFileOrig, string _nomeFileDest) - { - bool fatto = false; - // verifica directory - _pathFrom = verDir(_pathFrom); - _pathTo = verDir(_pathTo); - FileInfo _fi = getFileInfoByName(_pathFrom, _nomeFileOrig); - try - { - _fi.CopyTo(System.Web.HttpContext.Current.Server.MapPath(_pathTo) + _nomeFileDest, true); - fatto = true; - } - catch (Exception e) - { - Console.WriteLine("{0} Exception caught.", e); - _fi.CopyTo(_pathTo + _nomeFileDest, true); - fatto = true; - } - return fatto; - } - /// - /// Effettua copia files da locale a rete con auth (Local 2 Network)... - /// - /// - /// - /// - /// - /// - /// - /// - public static bool copiaFileL2N(string pathSource, string pathDest, NetworkCredential credentialsDest, string fileSource, string fileDest) - { - bool fatto = false; - logger.lg.scriviLog($"Richiesta trasferimento files: {pathSource}\\{fileSource} --> {pathDest}\\{fileDest}", tipoLog.INFO); - try - { - using (new NetworkConnection(pathDest, credentialsDest)) - { - File.Copy($"{pathSource}\\{fileSource}", $"{pathDest}\\{fileDest}"); - fatto = true; - } - } - catch (Exception exc) - { - logger.lg.scriviLog($"Eccezione durante trasferimento files: {pathSource}\\{fileSource} --> {pathDest}\\{fileDest}{Environment.NewLine}{exc}", tipoLog.EXCEPTION); - } - return fatto; - } - /// - /// Effettua copia files via rete con auth (Net 2 Net)... - /// - /// - /// - /// - /// - /// - /// - /// - public static bool copiaFileN2N(string pathSource, string pathDest, NetworkCredential credentialsSource, NetworkCredential credentialsDest, string fileSource, string fileDest) - { - bool fatto = false; - logger.lg.scriviLog($"Richiesta trasferimento files: {pathSource}\\{fileSource} --> {pathDest}\\{fileDest}", tipoLog.INFO); - try - { - using (new NetworkConnection(pathSource, credentialsSource)) - using (new NetworkConnection(pathDest, credentialsDest)) - { - File.Copy($"{pathSource}\\{fileSource}", $"{pathDest}\\{fileDest}"); - fatto = true; - } - } - catch (Exception exc) - { - logger.lg.scriviLog($"Eccezione durante trasferimento files: {pathSource}\\{fileSource} --> {pathDest}\\{fileDest}{Environment.NewLine}{exc}", tipoLog.EXCEPTION); - } - return fatto; - } - - /// - /// imposta la dir di lavoro - /// - /// - public void setDirectory(string _path) - { - setDirs(_path); - } - /// - /// imposta la dir di lavoro - /// - /// - /// non serve +... x retrocompatibilità... - public void setDirectory(string _path, string _log) - { - setDirs(_path); - } - /// - /// imposta la dir di lavoro impostandola dal mapPath corretto della web app... (come subfolder della web app) - /// - /// - public void setDirectoryMapPath(string _path) - { - setDirs(System.Web.HttpContext.Current.Server.MapPath(_path)); - } - /// - /// restituisce la stringa completa e corretta del filepath del server (anche con vDir) - /// - /// path relativo alla cartella iis dell'applicativo - /// path fisico tradotto - public static string getFilePath(string pathRel) - { - string answ = ""; - try - { - answ = System.Web.HttpContext.Current.Server.MapPath(pathRel); - } - catch - { } - return answ; - } - /// - /// esegue un comando in shell - /// - /// - /// - /// - /// - public static int ExecuteCommand(string workDir, string Command, int Timeout) - { - int ExitCode; - ProcessStartInfo ProcessInfo; - Process Process; - - ProcessInfo = new ProcessStartInfo(Command); - ProcessInfo.CreateNoWindow = false; - ProcessInfo.UseShellExecute = true; - ProcessInfo.WorkingDirectory = workDir; - //ProcessInfo.RedirectStandardError = true; - //ProcessInfo.RedirectStandardInput = true; - //ProcessInfo.RedirectStandardOutput = true; - Process = Process.Start(ProcessInfo); - Process.WaitForExit(Timeout); - ExitCode = Process.ExitCode; - Process.Close(); - - return ExitCode; - } - /// - /// esegue un comando in shell - /// - /// - /// - /// - /// - public static void LaunchCommand(string workDir, string Command, int Timeout) - { - //int ExitCode; - ProcessStartInfo ProcessInfo; - Process Process; - - ProcessInfo = new ProcessStartInfo(Command); - ProcessInfo.CreateNoWindow = false; - ProcessInfo.UseShellExecute = true; - ProcessInfo.WorkingDirectory = workDir; - //ProcessInfo.RedirectStandardError = true; - //ProcessInfo.RedirectStandardInput = true; - //ProcessInfo.RedirectStandardOutput = true; - Process = Process.Start(ProcessInfo); - //Process.WaitForExit(Timeout); - //ExitCode = Process.ExitCode; - //Process.Close(); - } - /// - /// Scarica un file dall'url fornito nella directory indicata x il filemover col nome richiesto - /// - /// url del file - /// nome con cui salvare il file - /// - public void scaricaFileFromWeb(string urlFile, string nomeDest) - { - // utilizzo l'oggetto webCli... - - WebCli.Credentials = System.Net.CredentialCache.DefaultCredentials; - WebCli.DownloadFile(urlFile, string.Format("{0}\\{1}", _workPath, nomeDest)); - } - /// - /// comprime zip il file indicato - /// - /// - /// - public bool zippaSingoloFile(string _nomeFile) - { - bool fatto = false; - FileInfo _fi = getFileInfoByName(_nomeFile); - // calcolo il nome del file zip... - string nomeZip = string.Format("{0}.zip", _fi.FullName); - try - { - using (ZipOutputStream s = new ZipOutputStream(File.Create(nomeZip))) - { - s.SetLevel(5); - byte[] buffer = new byte[4096]; - ZipEntry entry = new ZipEntry(Path.GetFileName(_fi.FullName)); - // Could also use the last write time or similar for the file. - entry.DateTime = DateTime.Now; - s.PutNextEntry(entry); - using (FileStream fs = File.OpenRead(_fi.FullName)) - { - // Using a fixed size buffer here makes no noticeable difference for output - // but keeps a lid on memory usage. - int sourceBytes; - do + FileInfo _fi; + if (absPath) { - sourceBytes = fs.Read(buffer, 0, buffer.Length); - s.Write(buffer, 0, sourceBytes); - } while (sourceBytes > 0); - } - s.Finish(); - s.Close(); - } - fatto = true; - } - catch - { - } - return fatto; - } - - /// - /// comprime zip il file indicato - /// - /// File in formato FileInfo - /// - public bool zippaSingoloFile(FileInfo _fi) - { - bool fatto = false; - // calcolo il nome del file zip... - string nomeZip = string.Format("{0}.zip", _fi.FullName); - try - { - using (ZipOutputStream s = new ZipOutputStream(File.Create(nomeZip))) - { - s.SetLevel(5); - byte[] buffer = new byte[4096]; - ZipEntry entry = new ZipEntry(Path.GetFileName(_fi.FullName)); - // Could also use the last write time or similar for the file. - entry.DateTime = DateTime.Now; - s.PutNextEntry(entry); - using (FileStream fs = File.OpenRead(_fi.FullName)) - { - // Using a fixed size buffer here makes no noticeable difference for output - // but keeps a lid on memory usage. - int sourceBytes; - do - { - sourceBytes = fs.Read(buffer, 0, buffer.Length); - s.Write(buffer, 0, sourceBytes); - } while (sourceBytes > 0); - } - s.Finish(); - s.Close(); - } - fatto = true; - } - catch - { - } - return fatto; - } - /// - /// comprime zip i files corrispondenti alla RegExp indicata nella dir corrente - /// - /// Espressione ricerca, come *.txt - /// Nome del file zip da creare - /// - public bool zippaFilesByRegExp(string regExp, string outZipFileName) - { - bool fatto = false; - // inizializzo il file zip... - DirectoryInfo _di = checkDir(); - // calcolo il nome del file zip... - string nomeZip = string.Format("{0}/{1}.zip", _di.FullName, outZipFileName.Replace(".zip", "")); - // inizio a inserire dati - try - { - using (ZipOutputStream s = new ZipOutputStream(File.Create(nomeZip))) - { - s.SetLevel(5); - byte[] buffer = new byte[4096]; - // effettuo una ricerca dei files corrispondenti al criterio regexp, e per ognuno effettuo inserimento in zipfile... - FileInfo[] filesTrovati = elencoFiles_FI(regExp); - ZipEntry entry; - foreach (FileInfo _fi in filesTrovati) - { - // calcolo la nuova entry nel file zip... - entry = new ZipEntry(Path.GetFileName(_fi.FullName)); - // Could also use the last write time or similar for the file. - entry.DateTime = DateTime.Now; - s.PutNextEntry(entry); - using (FileStream fs = File.OpenRead(_fi.FullName)) - { - // Using a fixed size buffer here makes no noticeable difference for output but keeps a lid on memory usage. - int sourceBytes; - do - { - sourceBytes = fs.Read(buffer, 0, buffer.Length); - s.Write(buffer, 0, sourceBytes); - } while (sourceBytes > 0); + _fi = new FileInfo(_path + "\\" + _nomeFile); } - } - s.Finish(); - s.Close(); - } - fatto = true; - } - catch (Exception e) - { - logger.lg.scriviLog(string.Format("Errore in creazione file zip con parametri {0} e {1}: {2}", regExp, outZipFileName, e)); - } - return fatto; - } - /// - /// scompatta tutto il contenuto di un file zip - /// - /// - /// - public static bool UnZipFile(string InputPathOfZipFile) - { - bool ret = true; - try - { - if (File.Exists(InputPathOfZipFile)) - { - string baseDirectory = Path.GetDirectoryName(InputPathOfZipFile); - - using (ZipInputStream ZipStream = new - -ZipInputStream(File.OpenRead(InputPathOfZipFile))) - { - ZipEntry theEntry; - while ((theEntry = ZipStream.GetNextEntry()) != null) + else { - if (theEntry.IsFile) - { - if (theEntry.Name != "") + _fi = getFileInfoByName(_path, _nomeFile); + } + return _fi; + } + /// + /// cerca di caricare la directoryInfo o da httpcontext-application re-position o direttamente come workpath + /// + /// + private DirectoryInfo getDirectoryInfo() + { + DirectoryInfo _di; + try + { + _di = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath(_workPath)); + } + catch + { + _di = new DirectoryInfo(_workPath); + } + return _di; + } + /// + /// imposta la directory richiesta... + /// + /// + private DirectoryInfo getDirectoryInfo(string path, bool absPath) + { + DirectoryInfo _di; + if (absPath) + { + _di = new DirectoryInfo(path); + } + else + { + + try { - string strNewFile = @"" + baseDirectory + @"\" + + _di = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath(path)); + } + catch + { + _di = new DirectoryInfo(path); + } + } + return _di; + } -theEntry.Name; - if (File.Exists(strNewFile)) - { - continue; - } + #region oggetti public - using (FileStream streamWriter = File.Create(strNewFile)) - { - int size = 4096; - byte[] data = new byte[4096]; - while (true) + /// + /// Legge i dati da uno stream fino a quando arriva alla fine. + /// I dati sono restituiti come un byte[] array. un eccezione IOException è + /// sollevata se una delle chiamate IO sottostanti fallisce. + /// + /// Lo stream da cui leggere + /// Lunghezza buffer iniziale (-1 = default 32k) + public static byte[] ReadFully(Stream stream, int initialLength) + { + // If we've been passed an unhelpful initial length, just + // use 32K. + if (initialLength < 1) + { + initialLength = 32768; + } + + byte[] buffer = new byte[initialLength]; + int read = 0; + + int chunk; + while ((chunk = stream.Read(buffer, read, buffer.Length - read)) > 0) + { + read += chunk; + + // If we've reached the end of our buffer, check to see if there's + // any more information + if (read == buffer.Length) + { + int nextByte = stream.ReadByte(); + + // End of stream? If so, we're done + if (nextByte == -1) { - size = ZipStream.Read(data, 0, data.Length); - if (size > 0) - streamWriter.Write(data, 0, size); - else - break; + return buffer; } - streamWriter.Close(); - } + + // Nope. Resize the buffer, put in the byte we've just + // read, and continue + byte[] newBuffer = new byte[buffer.Length * 2]; + Array.Copy(buffer, newBuffer, buffer.Length); + newBuffer[read] = (byte)nextByte; + buffer = newBuffer; + read++; } - } - else if (theEntry.IsDirectory) - { - string strNewDirectory = @"" + baseDirectory + @"\" + theEntry.Name; - if (!Directory.Exists(strNewDirectory)) - { - Directory.CreateDirectory(strNewDirectory); - } - } } - ZipStream.Close(); - } + // Buffer is now too big. Shrink it. + byte[] ret = new byte[read]; + Array.Copy(buffer, ret, read); + return ret; } - } - catch (Exception ex) - { - ret = false; - logger.lg.scriviLog(string.Format("Non sono riuscito ad unzippare: eccezione {0}", ex), tipoLog.EXCEPTION); - } - return ret; - } - /// - /// scompatta uno specifico file contenuto in un file zip - /// - /// The input path of zip file. - /// The file2unzip. - /// - public static bool UnZipSingleFile(string InputPathOfZipFile, string file2unzip) - { - bool ret = true; - try - { - if (File.Exists(InputPathOfZipFile)) + + /// + /// verifica esistenza directory, eventualmente crea e restituisce controllo DirectoryInfo + /// + /// + public DirectoryInfo checkDir() { - string baseDirectory = Path.GetDirectoryName(InputPathOfZipFile); - - using (ZipInputStream ZipStream = new - -ZipInputStream(File.OpenRead(InputPathOfZipFile))) - { - ZipEntry theEntry; - while ((theEntry = ZipStream.GetNextEntry()) != null) + DirectoryInfo _di = getDirectoryInfo(); + if (!_di.Exists) { - if (theEntry.IsFile) - { - if (theEntry.Name == file2unzip) - { - string strNewFile = @"" + baseDirectory + @"\" + theEntry.Name; - if (File.Exists(strNewFile)) - { - continue; - } - - using (FileStream streamWriter = File.Create(strNewFile)) - { - int size = 4096; - byte[] data = new byte[4096]; - while (true) - { - size = ZipStream.Read(data, 0, data.Length); - if (size > 0) - streamWriter.Write(data, 0, size); - else - break; - } - streamWriter.Close(); - } - } - } - else if (theEntry.IsDirectory) - { - string strNewDirectory = @"" + baseDirectory + @"\" + - -theEntry.Name; - if (!Directory.Exists(strNewDirectory)) - { - Directory.CreateDirectory(strNewDirectory); - } - } + _di.Create(); } - ZipStream.Close(); - } + return _di; } - } - catch (Exception ex) - { - ret = false; - logger.lg.scriviLog(string.Format("Non sono riuscito ad unzippare: eccezione {0}", ex), tipoLog.EXCEPTION); - } - return ret; - } - /// - /// elimina il file indicato - /// - /// - /// - public static bool deleteFile(string PathOfFile2Delete) - { - bool ret = true; - try - { - if (File.Exists(PathOfFile2Delete)) + + /// + /// ottiene il dataset dei files presenti nella directory indicata esplicitamente + /// + /// dir da indicizzare... già mappata! ( es SteamwareStrings.getFilePath(...) ) + /// + public DataLayer_generic.filesDataTable elencoFilesDir(string directory) { - File.Delete(PathOfFile2Delete); + _workPath = directory; + return elencoFiles(); } - } - catch (Exception ex) - { - ret = false; - logger.lg.scriviLog(string.Format("Non sono riuscito ad eliminare file: eccezione {0}", ex), tipoLog.EXCEPTION); - } - return ret; - } - /// - /// elimina la folder indicata - /// - /// Path della fodler da eliminare - /// Indica se cancellare in modo ricorsivo - /// - public static bool deleteDir(string PathOfDir2Delete, bool recursive = true) - { - bool ret = true; - try - { - if (Directory.Exists(PathOfDir2Delete)) + + /// + /// ottiene il dataset dei files presenti nella directory indicata all'istanziazione dell'oggetto + /// + /// + public DataLayer_generic.filesDataTable elencoFiles() { - Directory.Delete(PathOfDir2Delete, recursive); + DirectoryInfo _di = checkDir(); + FileInfo[] _files = _di.GetFiles(); + DataLayer_generic.filesDataTable _dsEF = tabellaFiles(_files); + return _dsEF; } - } - catch (Exception ex) - { - ret = false; - logger.lg.scriviLog($"Non sono riuscito ad eliminare la directory {PathOfDir2Delete} richiesta: eccezione {ex}", tipoLog.EXCEPTION); - } - return ret; - } - - - /// - /// calcola la dim della directory corrente... - /// - /// - public float totalMb() - { - DirectoryInfo _di = checkDir(); - FileInfo[] _fis = _di.GetFiles(); - float _byte = 0; - foreach (FileInfo _file in _fis) - { - _byte += _file.Length; - } - return _byte / 1000000; - } - /// - /// elimina il file + vecchio - /// - /// - public void deleteOldest() - { - DirectoryInfo _di = checkDir(); - FileInfo[] _fis = _di.GetFiles(); - DateTime _oldest = DateTime.Now; - string _nome = ""; - foreach (FileInfo _file in _fis) - { - if (_file.CreationTime < _oldest) + /// + /// ottiene il dataset dei files DEL TIPO "like {param}" presenti nella directory indicata all'istanziazione dell'oggetto + /// + /// + public DataLayer_generic.filesDataTable elencoFiles(string _param) { - _nome = _file.Name; + DirectoryInfo _di = checkDir(); + FileInfo[] _files = _di.GetFiles(_param); + DataLayer_generic.filesDataTable _dsEF = tabellaFiles(_files); + return _dsEF; } - } - eliminaFile(_nome); + /// + /// elenco dei files come array di oggetti FileInfo + /// + /// + public FileInfo[] elencoFiles_FI() + { + DirectoryInfo _di = checkDir(); + return _di.GetFiles(); + } + /// + /// elenco dei files come array di oggetti FileInfo filtrati per parametro + /// + /// + /// + public FileInfo[] elencoFiles_FI(string _param) + { + DirectoryInfo _di = checkDir(); + return _di.GetFiles(_param); + } + /// + /// elenco sub-directory array di oggetti FileInfo filtrati per parametro + /// + /// + public DirectoryInfo[] elencoSubdir_DI() + { + DirectoryInfo _di = checkDir(); + return _di.GetDirectories(); + } + /// + /// elenco sub-directory array di oggetti FileInfo filtrati per parametro + /// + /// + /// + public DirectoryInfo[] elencoSubdir_DI(string _param) + { + DirectoryInfo _di = checkDir(); + return _di.GetDirectories(_param); + } + /// + /// elimina la directory di lavoro se è dir virtuale mappata + /// + /// + public bool eliminaDir() + { + DirectoryInfo _di = checkDir(); + bool fatto = false; + try + { + _di.Delete(true); + fatto = true; + } + catch + { + } + return fatto; + } + + /// + /// elimina tutti i files con la regexp indicata da una directory, true se cancellato almeno uno + /// + /// regexp selezione files in dir (* = tutti!!!) + /// + public bool svuotaDir(string nomeCercato) + { + bool answ = false; + FileInfo[] _fis = elencoFiles_FI(nomeCercato); + foreach (FileInfo _file in _fis) + { + eliminaFile(_file.Name); + answ = true; + } + return answ; + } + + /// + /// verifica se il file indicato esista in workDir + /// + /// + /// + public bool fileExist(string _nomeFile) + { + bool answ = false; + FileInfo _fi = getFileInfoByName(_nomeFile); + answ = _fi.Exists; + if (!answ) + { + // registro che non ho trovaot il file: path e nome file! + logger.lg.scriviLog(string.Format("Attenzione: non e' stato possibile trovare il file!{0}wrkDir:{1}{0}file:{2}", Environment.NewLine, _workPath, _nomeFile), tipoLog.INFO); + } + return answ; + } + /// + /// verifica se il file indicato esista in _path + /// + /// + /// + /// + public bool fileExist(string _path, string _nomeFile) + { + bool answ = false; + FileInfo _fi = getFileInfoByName(_path, _nomeFile); + answ = _fi.Exists; + if (!answ) + { + // registro che non ho trovaot il file: path e nome file! + logger.lg.scriviLog(string.Format("Attenzione: non e' stato possibile trovare il file!{0}path:{1}{0}file:{2}", Environment.NewLine, _path, _nomeFile), tipoLog.INFO); + } + return answ; + } + /// + /// elimina il file indicato dalla directory di lavoro + /// + /// + /// + public bool eliminaFile(string _nomeFile) + { + FileInfo _fi = getFileInfoByName(_nomeFile); + bool fatto = false; + try + { + _fi.Delete(); + fatto = true; + } + catch + { } + if (fatto) + { + logger.lg.scriviLog($"Eliminazione file {_nomeFile} eseguita"); + } + else + { + logger.lg.scriviLog($"impossibile Eliminare il file {_nomeFile}"); + } + return fatto; + } + /// + /// elimina il file indicato dalla directory di lavoro + /// + /// The _fi. + /// + public bool eliminaFile(FileInfo _fi) + { + bool fatto = false; + try + { + _fi.Delete(); + fatto = true; + } + catch + { + } + return fatto; + } + /// + /// restituisce lo stream del file richiesto + /// + /// + /// + public byte[] scaricaFile(string _nomeFile) + { + FileInfo _fi = getFileInfoByName(_nomeFile); + // verifica ci siano attach... + if (_fi.Exists) + { + Stream _stream = _fi.OpenRead(); + byte[] _risposta = ReadFully(_stream, -1); + _stream.Close(); + return _risposta; + } + else + { + return null; + } + } + /// + /// restituisce la stringa letta dal file richiesto + /// + /// + /// + public string scaricaFileString(string _nomeFile) + { + return byteToStr(scaricaFile(_nomeFile)); + } + /// + /// scrive il file dallo stream byte[] inviato + /// + /// + /// + /// + /// + public bool salvaFileBuffer(string _path, string _nomeFile, byte[] _fileBuffer) + { + _workPath = _path; + DirectoryInfo _di = getDirectoryInfo(_path, true); + if (!_di.Exists) + { + _di.Create(); + } + FileInfo _fi = getFileInfoByName(_path, _nomeFile); + Stream _stream; + if (!_fi.Exists) + { + _stream = _fi.Create(); + } + else + { + _stream = _fi.OpenWrite(); + } + _stream.Write(_fileBuffer, 0, _fileBuffer.Length); + _stream.Flush(); + _stream.Close(); + + return true; + } + /// + /// scrive il file dallo stream byte[] inviato + /// + /// + /// + /// + public bool salvaFileBuffer(string _nomeFile, byte[] _fileBuffer) + { + DirectoryInfo _di = getDirectoryInfo(); + if (!_di.Exists) + { + _di.Create(); + } + FileInfo _fi = getFileInfoByName(_nomeFile); + Stream _stream; + if (!_fi.Exists) + { + _stream = _fi.Create(); + } + else + { + _stream = _fi.OpenWrite(); + } + _stream.Write(_fileBuffer, 0, _fileBuffer.Length); + _stream.Flush(); + _stream.Close(); + + return true; + } + /// + /// scrive il file dalla stringa inviata + /// + /// + /// + /// + /// + public bool salvaFileString(string _path, string _nomeFile, string _fileString) + { + return salvaFileBuffer(_path, _nomeFile, strToByte(_fileString)); + } + /// + /// scrive il file dalla stringa inviata + /// + /// + /// + /// + public bool salvaFileString(string _nomeFile, string _fileString) + { + return salvaFileBuffer(_nomeFile, strToByte(_fileString)); + } + /// + /// converte una string in un byte[] + /// + /// + /// + protected byte[] strToByte(string _val) + { + System.Text.ASCIIEncoding encod = new System.Text.ASCIIEncoding(); + return encod.GetBytes(_val); + } + /// + /// converte un byte[] in una string + /// + /// + /// + protected string byteToStr(byte[] _array) + { + System.Text.ASCIIEncoding encod = new System.Text.ASCIIEncoding(); + return encod.GetString(_array); + } + + /// + /// sposta il file da From a To... + /// + /// + /// + /// + /// + public bool muoviFile(string _pathFrom, string _pathTo, string _nomeFile) + { + bool fatto = false; + // verifica directory + _pathTo = verDir(_pathTo); + _pathFrom = verDir(_pathFrom); + FileInfo _fi = getFileInfoByName(_pathFrom, _nomeFile, true); + try + { + _fi.CopyTo(_pathTo + _nomeFile, true); + _fi.Delete(); + fatto = true; + } + catch (Exception e) + { + Console.WriteLine("{0} Exception caught.", e); + } + return fatto; + } + /// + /// Copia il contenuto directory da From a To (opzionalmente in modo ricorsivo)... + /// + /// Nome dir sorgente + /// Nome dir destinazione + /// Indica se copiare ricorsivamente + /// Indica se sovrascrivere i dati (default = true) + /// + public static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs, bool overwrite = true) + { + // Get the subdirectories for the specified directory. + DirectoryInfo dir = new DirectoryInfo(sourceDirName); + + if (!dir.Exists) + { + throw new DirectoryNotFoundException( + "Source directory does not exist or could not be found: " + + sourceDirName); + } + + DirectoryInfo[] dirs = dir.GetDirectories(); + // If the destination directory doesn't exist, create it. + if (!Directory.Exists(destDirName)) + { + Directory.CreateDirectory(destDirName); + } + + // Get the files in the directory and copy them to the new location. + FileInfo[] files = dir.GetFiles(); + foreach (FileInfo file in files) + { + string temppath = Path.Combine(destDirName, file.Name); + file.CopyTo(temppath, overwrite); + } + + // If copying subdirectories, copy them and their contents to new location. + if (copySubDirs) + { + foreach (DirectoryInfo subdir in dirs) + { + string temppath = Path.Combine(destDirName, subdir.Name); + DirectoryCopy(subdir.FullName, temppath, copySubDirs); + } + } + } + + /// + /// copia il file da From a To... + /// + /// + /// + /// + /// + public bool copiaFile(string _pathFrom, string _pathTo, string _nomeFile) + { + bool fatto = false; + // verifica directory + _pathFrom = verDir(_pathFrom); + _pathTo = verDir(_pathTo); + FileInfo _fi = getFileInfoByName(_pathFrom, _nomeFile); + try + { + _fi.CopyTo(_pathTo + _nomeFile, true); + fatto = true; + } + catch (Exception e) + { + Console.WriteLine("{0} Exception caught.", e); + } + return fatto; + } + /// + /// copia il file da From a To... + /// + /// + /// + /// + /// + /// + public bool copiaFile(string _pathFrom, string _pathTo, string _nomeFileOrig, string _nomeFileDest) + { + bool fatto = false; + // verifica directory + _pathFrom = verDir(_pathFrom); + _pathTo = verDir(_pathTo); + FileInfo _fi = getFileInfoByName(_pathFrom, _nomeFileOrig); + try + { + _fi.CopyTo(System.Web.HttpContext.Current.Server.MapPath(_pathTo) + _nomeFileDest, true); + fatto = true; + } + catch (Exception e) + { + Console.WriteLine("{0} Exception caught.", e); + _fi.CopyTo(_pathTo + _nomeFileDest, true); + fatto = true; + } + return fatto; + } + /// + /// Effettua copia files da locale a rete con auth (Local 2 Network)... + /// + /// + /// + /// + /// + /// + /// + /// + public static bool copiaFileL2N(string pathSource, string pathDest, NetworkCredential credentialsDest, string fileSource, string fileDest) + { + bool fatto = false; + logger.lg.scriviLog($"Richiesta trasferimento files: {pathSource}\\{fileSource} --> {pathDest}\\{fileDest}", tipoLog.INFO); + try + { + using (new NetworkConnection(pathDest, credentialsDest)) + { + File.Copy($"{pathSource}\\{fileSource}", $"{pathDest}\\{fileDest}"); + fatto = true; + } + } + catch (Exception exc) + { + logger.lg.scriviLog($"Eccezione durante trasferimento files: {pathSource}\\{fileSource} --> {pathDest}\\{fileDest}{Environment.NewLine}{exc}", tipoLog.EXCEPTION); + } + return fatto; + } + /// + /// Effettua copia files via rete con auth (Net 2 Net)... + /// + /// + /// + /// + /// + /// + /// + /// + public static bool copiaFileN2N(string pathSource, string pathDest, NetworkCredential credentialsSource, NetworkCredential credentialsDest, string fileSource, string fileDest) + { + bool fatto = false; + logger.lg.scriviLog($"Richiesta trasferimento files: {pathSource}\\{fileSource} --> {pathDest}\\{fileDest}", tipoLog.INFO); + try + { + using (new NetworkConnection(pathSource, credentialsSource)) + using (new NetworkConnection(pathDest, credentialsDest)) + { + File.Copy($"{pathSource}\\{fileSource}", $"{pathDest}\\{fileDest}"); + fatto = true; + } + } + catch (Exception exc) + { + logger.lg.scriviLog($"Eccezione durante trasferimento files: {pathSource}\\{fileSource} --> {pathDest}\\{fileDest}{Environment.NewLine}{exc}", tipoLog.EXCEPTION); + } + return fatto; + } + + /// + /// imposta la dir di lavoro + /// + /// + public void setDirectory(string _path) + { + setDirs(_path); + } + /// + /// imposta la dir di lavoro + /// + /// + /// non serve +... x retrocompatibilità... + public void setDirectory(string _path, string _log) + { + setDirs(_path); + } + /// + /// imposta la dir di lavoro impostandola dal mapPath corretto della web app... (come subfolder della web app) + /// + /// + public void setDirectoryMapPath(string _path) + { + setDirs(System.Web.HttpContext.Current.Server.MapPath(_path)); + } + /// + /// restituisce la stringa completa e corretta del filepath del server (anche con vDir) + /// + /// path relativo alla cartella iis dell'applicativo + /// path fisico tradotto + public static string getFilePath(string pathRel) + { + string answ = ""; + if (System.Web.HttpContext.Current != null) + { + try + { + answ = System.Web.HttpContext.Current.Server.MapPath(pathRel); + } + catch + { } + } + else if(Path.IsPathRooted(pathRel)) + { + answ = pathRel; + } + else + { + answ = Path.GetFullPath(pathRel); + } + return answ; + } + /// + /// esegue un comando in shell + /// + /// + /// + /// + /// + public static int ExecuteCommand(string workDir, string Command, int Timeout) + { + int ExitCode; + ProcessStartInfo ProcessInfo; + Process Process; + + ProcessInfo = new ProcessStartInfo(Command); + ProcessInfo.CreateNoWindow = false; + ProcessInfo.UseShellExecute = true; + ProcessInfo.WorkingDirectory = workDir; + //ProcessInfo.RedirectStandardError = true; + //ProcessInfo.RedirectStandardInput = true; + //ProcessInfo.RedirectStandardOutput = true; + Process = Process.Start(ProcessInfo); + Process.WaitForExit(Timeout); + ExitCode = Process.ExitCode; + Process.Close(); + + return ExitCode; + } + /// + /// esegue un comando in shell + /// + /// + /// + /// + /// + public static void LaunchCommand(string workDir, string Command, int Timeout) + { + //int ExitCode; + ProcessStartInfo ProcessInfo; + Process Process; + + ProcessInfo = new ProcessStartInfo(Command); + ProcessInfo.CreateNoWindow = false; + ProcessInfo.UseShellExecute = true; + ProcessInfo.WorkingDirectory = workDir; + //ProcessInfo.RedirectStandardError = true; + //ProcessInfo.RedirectStandardInput = true; + //ProcessInfo.RedirectStandardOutput = true; + Process = Process.Start(ProcessInfo); + //Process.WaitForExit(Timeout); + //ExitCode = Process.ExitCode; + //Process.Close(); + } + /// + /// Scarica un file dall'url fornito nella directory indicata x il filemover col nome richiesto + /// + /// url del file + /// nome con cui salvare il file + /// + public void scaricaFileFromWeb(string urlFile, string nomeDest) + { + // utilizzo l'oggetto webCli... + + WebCli.Credentials = System.Net.CredentialCache.DefaultCredentials; + WebCli.DownloadFile(urlFile, string.Format("{0}\\{1}", _workPath, nomeDest)); + } + /// + /// comprime zip il file indicato + /// + /// + /// + public bool zippaSingoloFile(string _nomeFile) + { + bool fatto = false; + FileInfo _fi = getFileInfoByName(_nomeFile); + // calcolo il nome del file zip... + string nomeZip = string.Format("{0}.zip", _fi.FullName); + try + { + using (ZipOutputStream s = new ZipOutputStream(File.Create(nomeZip))) + { + s.SetLevel(5); + byte[] buffer = new byte[4096]; + ZipEntry entry = new ZipEntry(Path.GetFileName(_fi.FullName)); + // Could also use the last write time or similar for the file. + entry.DateTime = DateTime.Now; + s.PutNextEntry(entry); + using (FileStream fs = File.OpenRead(_fi.FullName)) + { + // Using a fixed size buffer here makes no noticeable difference for output + // but keeps a lid on memory usage. + int sourceBytes; + do + { + sourceBytes = fs.Read(buffer, 0, buffer.Length); + s.Write(buffer, 0, sourceBytes); + } while (sourceBytes > 0); + } + s.Finish(); + s.Close(); + } + fatto = true; + } + catch + { + } + return fatto; + } + + /// + /// comprime zip il file indicato + /// + /// File in formato FileInfo + /// + public bool zippaSingoloFile(FileInfo _fi) + { + bool fatto = false; + // calcolo il nome del file zip... + string nomeZip = string.Format("{0}.zip", _fi.FullName); + try + { + using (ZipOutputStream s = new ZipOutputStream(File.Create(nomeZip))) + { + s.SetLevel(5); + byte[] buffer = new byte[4096]; + ZipEntry entry = new ZipEntry(Path.GetFileName(_fi.FullName)); + // Could also use the last write time or similar for the file. + entry.DateTime = DateTime.Now; + s.PutNextEntry(entry); + using (FileStream fs = File.OpenRead(_fi.FullName)) + { + // Using a fixed size buffer here makes no noticeable difference for output + // but keeps a lid on memory usage. + int sourceBytes; + do + { + sourceBytes = fs.Read(buffer, 0, buffer.Length); + s.Write(buffer, 0, sourceBytes); + } while (sourceBytes > 0); + } + s.Finish(); + s.Close(); + } + fatto = true; + } + catch + { + } + return fatto; + } + /// + /// comprime zip i files corrispondenti alla RegExp indicata nella dir corrente + /// + /// Espressione ricerca, come *.txt + /// Nome del file zip da creare + /// + public bool zippaFilesByRegExp(string regExp, string outZipFileName) + { + bool fatto = false; + // inizializzo il file zip... + DirectoryInfo _di = checkDir(); + // calcolo il nome del file zip... + string nomeZip = string.Format("{0}/{1}.zip", _di.FullName, outZipFileName.Replace(".zip", "")); + // inizio a inserire dati + try + { + using (ZipOutputStream s = new ZipOutputStream(File.Create(nomeZip))) + { + s.SetLevel(5); + byte[] buffer = new byte[4096]; + // effettuo una ricerca dei files corrispondenti al criterio regexp, e per ognuno effettuo inserimento in zipfile... + FileInfo[] filesTrovati = elencoFiles_FI(regExp); + ZipEntry entry; + foreach (FileInfo _fi in filesTrovati) + { + // calcolo la nuova entry nel file zip... + entry = new ZipEntry(Path.GetFileName(_fi.FullName)); + // Could also use the last write time or similar for the file. + entry.DateTime = DateTime.Now; + s.PutNextEntry(entry); + using (FileStream fs = File.OpenRead(_fi.FullName)) + { + // Using a fixed size buffer here makes no noticeable difference for output but keeps a lid on memory usage. + int sourceBytes; + do + { + sourceBytes = fs.Read(buffer, 0, buffer.Length); + s.Write(buffer, 0, sourceBytes); + } while (sourceBytes > 0); + } + } + s.Finish(); + s.Close(); + } + fatto = true; + } + catch (Exception e) + { + logger.lg.scriviLog(string.Format("Errore in creazione file zip con parametri {0} e {1}: {2}", regExp, outZipFileName, e)); + } + return fatto; + } + /// + /// scompatta tutto il contenuto di un file zip + /// + /// + /// + public static bool UnZipFile(string InputPathOfZipFile) + { + bool ret = true; + try + { + if (File.Exists(InputPathOfZipFile)) + { + string baseDirectory = Path.GetDirectoryName(InputPathOfZipFile); + + using (ZipInputStream ZipStream = new + + ZipInputStream(File.OpenRead(InputPathOfZipFile))) + { + ZipEntry theEntry; + while ((theEntry = ZipStream.GetNextEntry()) != null) + { + if (theEntry.IsFile) + { + if (theEntry.Name != "") + { + string strNewFile = @"" + baseDirectory + @"\" + + + theEntry.Name; + if (File.Exists(strNewFile)) + { + continue; + } + + using (FileStream streamWriter = File.Create(strNewFile)) + { + int size = 4096; + byte[] data = new byte[4096]; + while (true) + { + size = ZipStream.Read(data, 0, data.Length); + if (size > 0) + streamWriter.Write(data, 0, size); + else + break; + } + streamWriter.Close(); + } + } + } + else if (theEntry.IsDirectory) + { + string strNewDirectory = @"" + baseDirectory + @"\" + theEntry.Name; + if (!Directory.Exists(strNewDirectory)) + { + Directory.CreateDirectory(strNewDirectory); + } + } + } + ZipStream.Close(); + } + } + } + catch (Exception ex) + { + ret = false; + logger.lg.scriviLog(string.Format("Non sono riuscito ad unzippare: eccezione {0}", ex), tipoLog.EXCEPTION); + } + return ret; + } + /// + /// scompatta uno specifico file contenuto in un file zip + /// + /// The input path of zip file. + /// The file2unzip. + /// + public static bool UnZipSingleFile(string InputPathOfZipFile, string file2unzip) + { + bool ret = true; + try + { + if (File.Exists(InputPathOfZipFile)) + { + string baseDirectory = Path.GetDirectoryName(InputPathOfZipFile); + + using (ZipInputStream ZipStream = new + + ZipInputStream(File.OpenRead(InputPathOfZipFile))) + { + ZipEntry theEntry; + while ((theEntry = ZipStream.GetNextEntry()) != null) + { + if (theEntry.IsFile) + { + if (theEntry.Name == file2unzip) + { + string strNewFile = @"" + baseDirectory + @"\" + theEntry.Name; + if (File.Exists(strNewFile)) + { + continue; + } + + using (FileStream streamWriter = File.Create(strNewFile)) + { + int size = 4096; + byte[] data = new byte[4096]; + while (true) + { + size = ZipStream.Read(data, 0, data.Length); + if (size > 0) + streamWriter.Write(data, 0, size); + else + break; + } + streamWriter.Close(); + } + } + } + else if (theEntry.IsDirectory) + { + string strNewDirectory = @"" + baseDirectory + @"\" + + + theEntry.Name; + if (!Directory.Exists(strNewDirectory)) + { + Directory.CreateDirectory(strNewDirectory); + } + } + } + ZipStream.Close(); + } + } + } + catch (Exception ex) + { + ret = false; + logger.lg.scriviLog(string.Format("Non sono riuscito ad unzippare: eccezione {0}", ex), tipoLog.EXCEPTION); + } + return ret; + } + /// + /// elimina il file indicato + /// + /// + /// + public static bool deleteFile(string PathOfFile2Delete) + { + bool ret = true; + try + { + if (File.Exists(PathOfFile2Delete)) + { + File.Delete(PathOfFile2Delete); + } + } + catch (Exception ex) + { + ret = false; + logger.lg.scriviLog(string.Format("Non sono riuscito ad eliminare file: eccezione {0}", ex), tipoLog.EXCEPTION); + } + return ret; + } + /// + /// elimina la folder indicata + /// + /// Path della fodler da eliminare + /// Indica se cancellare in modo ricorsivo + /// + public static bool deleteDir(string PathOfDir2Delete, bool recursive = true) + { + bool ret = true; + try + { + if (Directory.Exists(PathOfDir2Delete)) + { + Directory.Delete(PathOfDir2Delete, recursive); + } + } + catch (Exception ex) + { + ret = false; + logger.lg.scriviLog($"Non sono riuscito ad eliminare la directory {PathOfDir2Delete} richiesta: eccezione {ex}", tipoLog.EXCEPTION); + } + return ret; + } + + + /// + /// calcola la dim della directory corrente... + /// + /// + public float totalMb() + { + DirectoryInfo _di = checkDir(); + FileInfo[] _fis = _di.GetFiles(); + float _byte = 0; + foreach (FileInfo _file in _fis) + { + _byte += _file.Length; + } + return _byte / 1000000; + } + /// + /// elimina il file + vecchio + /// + /// + public void deleteOldest() + { + DirectoryInfo _di = checkDir(); + FileInfo[] _fis = _di.GetFiles(); + DateTime _oldest = DateTime.Now; + string _nome = ""; + foreach (FileInfo _file in _fis) + { + if (_file.CreationTime < _oldest) + { + _nome = _file.Name; + } + } + eliminaFile(_nome); + } + + #endregion + + /// + /// versione statica (singleton) del'oggetto fileMover + /// + public static fileMover obj = new fileMover(); + } - - #endregion - - /// - /// versione statica (singleton) del'oggetto fileMover - /// - public static fileMover obj = new fileMover(); - - } } diff --git a/SteamWareLib/memLayer.cs b/SteamWareLib/memLayer.cs index 6fe3302..9d88563 100644 --- a/SteamWareLib/memLayer.cs +++ b/SteamWareLib/memLayer.cs @@ -43,8 +43,6 @@ namespace SteamWare #endregion Public Fields - - #region Protected Constructors /// @@ -62,8 +60,6 @@ namespace SteamWare #endregion Protected Constructors - - #region Protected Properties /// @@ -185,80 +181,6 @@ namespace SteamWare } } - /// - /// carica in ram oggetto AppConf - /// - /// - protected Dictionary ricaricaAppConf() - { - Dictionary answ = new Dictionary(); - // istanzio un NUOVO oggetto x evitare problemi init contestuali - memLayer nML = new memLayer(); - var tabDati = nML.taConfig.GetData(); - // carico - foreach (DS_Utility.ConfigRow riga in tabDati) - { - try - { - answ.Add(riga.chiave, riga.valore); - } - catch (Exception exc) - { - logger.lg.scriviLog(string.Format("Errore procedura ricaricaAppConf per kvp: {0} / {1}{2}{3}", riga.chiave, riga.valore, Environment.NewLine, exc), tipoLog.EXCEPTION); - } - } - // log ricarica - logger.lg.scriviLog(string.Format("Effettuata procedura ricaricaAppConf per {0} records", answ.Count), tipoLog.INFO); - return answ; - } - - /// - /// avvio oggetto AppConf in ram - /// - protected void startupAppConf() - { - // SOLO SE ho la chiave x abilitare config su DB... - if (confReadString("DbConfConnectionString") != "") - { - try - { - if (redKeyPresent(ACBH)) - { - AppConf = new Dictionary(); - foreach (var item in redGetHash(ACBH)) - { - if (AppConf.ContainsKey(item.Key)) - { - AppConf[item.Key] = item.Value; - } - else - { - AppConf.Add(item.Key, item.Value); - } - } - } - else - { - AppConf = ricaricaAppConf(); - KeyValuePair[] valori = new KeyValuePair[AppConf.Count]; - int i = 0; - foreach (var item in AppConf) - { - valori[i] = new KeyValuePair(item.Key, item.Value); - i++; - } - // salvo in redis valori (con TTL) - redSaveHash(ACBH, valori, maxAgeAppConf); - logger.lg.scriviLog("Completato procedura startupAppConf ", tipoLog.INFO); - } - } - catch (Exception exc) - { - logger.lg.scriviLog(string.Format("Errore in startupAppConf:{0}{1}", Environment.NewLine, exc), tipoLog.EXCEPTION); - } - } - } - /// /// Configurations da tabella DB Config (short form wrapper) /// @@ -379,6 +301,80 @@ namespace SteamWare startupAppConf(); } + /// + /// carica in ram oggetto AppConf + /// + /// + protected Dictionary ricaricaAppConf() + { + Dictionary answ = new Dictionary(); + // istanzio un NUOVO oggetto x evitare problemi init contestuali + memLayer nML = new memLayer(); + var tabDati = nML.taConfig.GetData(); + // carico + foreach (DS_Utility.ConfigRow riga in tabDati) + { + try + { + answ.Add(riga.chiave, riga.valore); + } + catch (Exception exc) + { + logger.lg.scriviLog(string.Format("Errore procedura ricaricaAppConf per kvp: {0} / {1}{2}{3}", riga.chiave, riga.valore, Environment.NewLine, exc), tipoLog.EXCEPTION); + } + } + // log ricarica + Logger.Logging.Instance.Info($"Effettuata procedura ricaricaAppConf per {answ.Count} records"); + return answ; + } + + /// + /// avvio oggetto AppConf in ram + /// + protected void startupAppConf() + { + // SOLO SE ho la chiave x abilitare config su DB... + if (confReadString("DbConfConnectionString") != "") + { + try + { + if (redKeyPresent(ACBH)) + { + AppConf = new Dictionary(); + foreach (var item in redGetHash(ACBH)) + { + if (AppConf.ContainsKey(item.Key)) + { + AppConf[item.Key] = item.Value; + } + else + { + AppConf.Add(item.Key, item.Value); + } + } + } + else + { + AppConf = ricaricaAppConf(); + KeyValuePair[] valori = new KeyValuePair[AppConf.Count]; + int i = 0; + foreach (var item in AppConf) + { + valori[i] = new KeyValuePair(item.Key, item.Value); + i++; + } + // salvo in redis valori (con TTL) + redSaveHash(ACBH, valori, maxAgeAppConf); + Logger.Logging.Instance.Info("Completato procedura startupAppConf"); + } + } + catch (Exception exc) + { + Logger.Logging.Instance.Error($"Errore in startupAppConf:{Environment.NewLine}{exc}"); + } + } + } + #endregion area gestione config su DB #region utility gestione conf settings @@ -1424,11 +1420,6 @@ namespace SteamWare ValDesc } - /// - /// Oggetto currentDb locale - /// - private IDatabase _currDB { get; set; } - /// /// Oggetto DB REDIS corrente /// @@ -1504,26 +1495,9 @@ namespace SteamWare } /// - /// Effettua comaprazione x CHIAVE in KVP ASC + /// Oggetto currentDb locale /// - /// - /// - /// - private int CompareKey(KeyValuePair x, KeyValuePair y) - { - return x.Key.CompareTo(y.Key); - } - - /// - /// Effettua comaprazione x CHIAVE in KVP DESC - /// - /// - /// - /// - private int CompareKeyDesc(KeyValuePair x, KeyValuePair y) - { - return y.Key.CompareTo(x.Key); - } + private IDatabase _currDB { get; set; } /// /// Effettua comaprazione x VALORE in KVP ASC @@ -1890,7 +1864,7 @@ namespace SteamWare } catch (Exception exc) { - SteamWare.Logger.Logging.LogException(exc, Logger.Constants.ERROR_LEVEL.Error); + Logger.Logging.LogException(exc, Logger.Constants.ERROR_LEVEL.Error); } return answ; } @@ -2289,6 +2263,28 @@ namespace SteamWare return answ; } + /// + /// Effettua comaprazione x CHIAVE in KVP ASC + /// + /// + /// + /// + private int CompareKey(KeyValuePair x, KeyValuePair y) + { + return x.Key.CompareTo(y.Key); + } + + /// + /// Effettua comaprazione x CHIAVE in KVP DESC + /// + /// + /// + /// + private int CompareKeyDesc(KeyValuePair x, KeyValuePair y) + { + return y.Key.CompareTo(x.Key); + } + #endregion gestione valori in RedisCache #region URL corretti immagini @@ -2329,14 +2325,6 @@ namespace SteamWare } } - /// - /// Init accesso MongoDb - /// - private void setupMongo() - { - currMongoClient = new MongoClient(mongoConnString); - } - /// /// Restituisce oggetto DB richiesto /// @@ -2348,6 +2336,14 @@ namespace SteamWare return answ; } + /// + /// Init accesso MongoDb + /// + private void setupMongo() + { + currMongoClient = new MongoClient(mongoConnString); + } + #endregion gestione mongoDb } } \ No newline at end of file