277 lines
9.3 KiB
C#
277 lines
9.3 KiB
C#
using Sarand.BusinessMgr.Net.Core.Procs.Procs;
|
|
using Sarand.Net.Standard.Base.App;
|
|
using Sarand.Net.Standard.Base.Core;
|
|
using Sarand.Net.Standard.Base.Utils;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.IO;
|
|
using System.Linq;
|
|
using System.Net;
|
|
using System.Text;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Sarand.BusinessMgr.Net.Core.Procs.Procs
|
|
{
|
|
//=======================================================================
|
|
// F T P
|
|
//=======================================================================
|
|
partial class SbmProcess_Base
|
|
{
|
|
//-------------------------------------------------------------------
|
|
// Definitions.
|
|
public class FtpConfig
|
|
{
|
|
public String Host { get; set; }
|
|
public String Username { get; set; }
|
|
public String Password { get; set; }
|
|
}
|
|
|
|
//-------------------------------------------------------------------
|
|
// F T P U t i l i t i e s
|
|
//-------------------------------------------------------------------
|
|
private String GetFtpUrl (FtpConfig ftpConfig, String path)
|
|
{
|
|
return "ftp://" + ftpConfig.Host + "/" + FtpUtil.CleansePath(path);
|
|
}
|
|
private FtpWebRequest CreateFtpRequest (FtpConfig ftpConfig, String path, bool keepAlive = true)
|
|
{
|
|
FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(GetFtpUrl(ftpConfig, path));
|
|
// Credentials.
|
|
if (!StringUtil.IsEmpty(ftpConfig.Username) || StringUtil.IsEmpty(ftpConfig.Password))
|
|
ftpRequest.Credentials = new NetworkCredential(ftpConfig.Username, ftpConfig.Password);
|
|
ftpRequest.UseBinary = true;
|
|
// Keep alive = true will reuse the connection (behind the scenes) even though
|
|
// a new FTP Web Request is created for each request. Don't know how!
|
|
// Ref. https://stackoverflow.com/questions/7132246/how-to-reuse-ftpwebrequest-connection/7132428#7132428
|
|
// Network tracing: https://stackoverflow.com/questions/9664650/output-log-using-ftpwebrequest/9666598#9666598
|
|
ftpRequest.KeepAlive = keepAlive;
|
|
ftpRequest.Timeout = 5000;
|
|
ftpRequest.UsePassive = true;
|
|
return ftpRequest;
|
|
}
|
|
private WebClient CreateFtpWebClient (FtpConfig ftpConfig)
|
|
{
|
|
WebClient webClient = new WebClient();
|
|
// Credentials.
|
|
if (!StringUtil.IsEmpty(ftpConfig.Username) || StringUtil.IsEmpty(ftpConfig.Password))
|
|
webClient.Credentials = new NetworkCredential(ftpConfig.Username, ftpConfig.Password);
|
|
return webClient;
|
|
}
|
|
|
|
//-------------------------------------------------------------------
|
|
// Test connection.
|
|
protected bool TestFtpConnection (FtpConfig ftpConfig)
|
|
{
|
|
String fn = GetType().Name + ".TestFtpConnection";
|
|
WebResponse response = null;
|
|
try
|
|
{
|
|
// FTP request.
|
|
FtpWebRequest ftpRequest = CreateFtpRequest(ftpConfig, "");
|
|
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
|
|
// Send request.
|
|
response = ftpRequest.GetResponse();
|
|
using (Stream responseStream = response.GetResponseStream())
|
|
using (StreamReader reader = new StreamReader(responseStream))
|
|
{
|
|
String responseData = reader.ReadToEnd();
|
|
SaLogger.Debug(fn + ": Items in root: " + responseData.ReplaceAll("\r\n", ", "));
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
SaLogger.Warn(fn + " " + exc.GetType().Name + ": " + exc.Message, true);
|
|
return AddErrorMessage("Unable to connect to FTP host");
|
|
}
|
|
finally
|
|
{
|
|
if (response != null) response.Dispose();
|
|
}
|
|
return true;
|
|
}
|
|
protected bool CloseFtpConnection (FtpConfig ftpConfig)
|
|
{
|
|
WebResponse response = null;
|
|
try
|
|
{
|
|
// FTP request with KeepAlive=false to close connection.
|
|
FtpWebRequest ftpRequest = CreateFtpRequest(ftpConfig, "", false);
|
|
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
|
|
response = ftpRequest.GetResponse();
|
|
}
|
|
catch { }
|
|
finally
|
|
{
|
|
if (response != null) response.Dispose();
|
|
}
|
|
return true;
|
|
}
|
|
|
|
//-------------------------------------------------------------------
|
|
protected bool FtpFolderExists (FtpConfig ftpConfig, String folder)
|
|
{
|
|
String fn = GetType().Name + ".FtpFolderExists";
|
|
WebResponse response = null;
|
|
try
|
|
{
|
|
String parentFolder = FtpUtil.GetParentFolder(folder);
|
|
String itemName = FtpUtil.GetItemName(folder);
|
|
// FTP request.
|
|
FtpWebRequest ftpRequest = CreateFtpRequest(ftpConfig, parentFolder);
|
|
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
|
|
// Send request.
|
|
String data = "";
|
|
response = ftpRequest.GetResponse();
|
|
using (Stream responseStream = response.GetResponseStream())
|
|
using (StreamReader reader = new StreamReader(responseStream))
|
|
{
|
|
data = reader.ReadToEnd().Replace("\r", "");
|
|
}
|
|
String[] directoryItems = data.Split(new String[] { "\n" }, StringSplitOptions.None);
|
|
foreach (String directoryItemData in directoryItems)
|
|
{
|
|
FtpUtil.FtpDirectoryItem directoryItem = FtpUtil.GetDirectoryItem(directoryItemData);
|
|
if (directoryItem != null && directoryItem.Name.EqualsCI(itemName))
|
|
return directoryItem.IsDirectory;
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
SaLogger.Warn(fn + " " + exc.GetType().Name + ": " + exc.Message, true);
|
|
return false;
|
|
}
|
|
finally
|
|
{
|
|
if (response != null) response.Dispose();
|
|
}
|
|
return false;
|
|
}
|
|
|
|
//-------------------------------------------------------------------
|
|
/// <summary>Get list of items in remote FTP folder.</summary>
|
|
protected List<FtpUtil.FtpDirectoryItem> GetFtpFileItems (FtpConfig ftpConfig, String folder)
|
|
{
|
|
return GetFtpItems(ftpConfig, folder).FindAll(item => !item.IsDirectory);
|
|
}
|
|
/// <summary>Get list of items in remote FTP folder.</summary>
|
|
protected List<FtpUtil.FtpDirectoryItem> GetFtpItems (FtpConfig ftpConfig, String folder)
|
|
{
|
|
String fn = this.GetType().Name + ".GetFtpItems";
|
|
List<FtpUtil.FtpDirectoryItem> files = new List<FtpUtil.FtpDirectoryItem>();
|
|
WebResponse response = null;
|
|
try
|
|
{
|
|
// FTP request.
|
|
FtpWebRequest ftpRequest = CreateFtpRequest(ftpConfig, folder);
|
|
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
|
|
// Send request.
|
|
// Send request.
|
|
response = ftpRequest.GetResponse();
|
|
String data = "";
|
|
using (Stream responseStream = response.GetResponseStream())
|
|
using (StreamReader reader = new StreamReader(responseStream))
|
|
{
|
|
data = reader.ReadToEnd().Replace("\r", "");
|
|
}
|
|
String[] directoryItems = data.Split(new String[] { "\n" }, StringSplitOptions.None);
|
|
foreach (String directoryItemData in directoryItems)
|
|
{
|
|
FtpUtil.FtpDirectoryItem directoryItem = FtpUtil.GetDirectoryItem(directoryItemData);
|
|
if (directoryItem != null)
|
|
files.Add(directoryItem);
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
SaLogger.Warn(fn + " " + exc.GetType().Name + ": " + exc.Message, true);
|
|
}
|
|
finally
|
|
{
|
|
if (response != null) response.Dispose();
|
|
}
|
|
return files;
|
|
}
|
|
|
|
//-------------------------------------------------------------------
|
|
protected String GetFtpFileData (FtpConfig ftpConfig, String folder, String filename)
|
|
{
|
|
String fn = GetType() + ".GetFtpFileData";
|
|
WebClient ftpClient = null;
|
|
try
|
|
{
|
|
ftpClient = CreateFtpWebClient(ftpConfig);
|
|
String ftpUrl = GetFtpUrl(ftpConfig, folder + "/" + filename);
|
|
byte[] fileData = ftpClient.DownloadData(ftpUrl);
|
|
return System.Text.Encoding.UTF8.GetString(fileData);
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
SaLogger.Warn(fn + " " + exc.GetType().Name + ": " + exc.Message, true);
|
|
}
|
|
finally
|
|
{
|
|
if (ftpClient != null) ftpClient.Dispose();
|
|
}
|
|
return "";
|
|
}
|
|
|
|
//-------------------------------------------------------------------
|
|
protected bool WriteDataToFtpFile (FtpConfig ftpConfig, String folder, String filename, String data)
|
|
{
|
|
String fn = GetType() + ".WriteDataToFtpFile";
|
|
bool dataWrittenToFile = false;
|
|
FtpWebResponse response = null;
|
|
try
|
|
{
|
|
FtpWebRequest ftpRequest = CreateFtpRequest(ftpConfig, folder + Path.DirectorySeparatorChar + filename);
|
|
ftpRequest.Method = WebRequestMethods.Ftp.UploadFile;
|
|
ftpRequest.ContentLength = data.Length;
|
|
using (Stream request_stream = ftpRequest.GetRequestStream())
|
|
{
|
|
byte[] bytes = Encoding.UTF8.GetBytes(data);
|
|
request_stream.Write(bytes, 0, data.Length);
|
|
request_stream.Close();
|
|
}
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
SaLogger.Warn(fn + " " + exc.GetType().Name + ": " + exc.Message, true);
|
|
}
|
|
finally
|
|
{
|
|
if (response != null) response.Dispose();
|
|
}
|
|
return dataWrittenToFile;
|
|
}
|
|
|
|
//-------------------------------------------------------------------
|
|
protected bool DeleteFtpFile (FtpConfig ftpConfig, String folder, String filename)
|
|
{
|
|
String fn = GetType() + ".DeleteFtpData";
|
|
bool fileDeleted = false;
|
|
FtpWebResponse response = null;
|
|
try
|
|
{
|
|
// FTP request.
|
|
FtpWebRequest ftpRequest = CreateFtpRequest(ftpConfig, folder + Path.DirectorySeparatorChar + filename);
|
|
ftpRequest.Method = WebRequestMethods.Ftp.DeleteFile;
|
|
response = (FtpWebResponse)ftpRequest.GetResponse();
|
|
if (EnhancedLogging) SaLogger.Info(ProcessDescription + " - Delete FTP file: Response: " + response.StatusDescription, true);
|
|
fileDeleted = true;
|
|
}
|
|
catch (Exception exc)
|
|
{
|
|
SaLogger.Warn(fn + " " + exc.GetType().Name + ": " + exc.Message, true);
|
|
}
|
|
finally
|
|
{
|
|
if (response != null) response.Dispose();
|
|
}
|
|
return fileDeleted;
|
|
}
|
|
|
|
//-------------------------------------------------------------------
|
|
}
|
|
//=======================================================================
|
|
}
|