Commit 5c5827d3 authored by Krishna Reddy Tamatam's avatar Krishna Reddy Tamatam

HIMSScannerServices for Production Update

parents
{
"version": 1,
"isRoot": true,
"tools": {
"csharpier": {
"version": "0.28.2",
"commands": [
"dotnet-csharpier"
]
}
}
}
\ No newline at end of file
# These are some examples of commonly ignored file patterns.
# You should customize this list as applicable to your project.
# Learn more about .gitignore:
# https://www.atlassian.com/git/tutorials/saving-changes/gitignore
# Node artifact files
node_modules/
dist/
# Compiled Java class files
*.class
# Compiled Python bytecode
*.py[cod]
# Log files
*.log
# Package files
*.jar
# Maven
target/
dist/
# JetBrains IDE
.idea/
# Unit test reports
TEST*.xml
*.bak
# Generated by MacOS
.DS_Store
# Generated by Windows
Thumbs.db
# Applications
*.app
*.exe
*.war
# Large media files
*.mp4
*.tiff
*.avi
*.flv
*.mov
*.wmv
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
[Aa][Rr][Mm]/
[Aa][Rr][Mm]64/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
/publish
/appsettings.Development.json
{
"version": "0.2.0",
"configurations": [
{
// Use IntelliSense to find out which attributes exist for C# debugging
// Use hover for the description of the existing attributes
// For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
"name": ".NET Core Launch (web)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/bin/Debug/net6.0/FTPService.dll",
"args": [],
"cwd": "${workspaceFolder}",
"stopAtEntry": false,
// Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser
"serverReadyAction": {
"action": "openExternally",
"pattern": "\\bNow listening on:\\s+(https?://\\S+)"
},
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"sourceFileMap": {
"/Views": "${workspaceFolder}/Views"
}
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach"
}
]
}
\ No newline at end of file
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}/FTPService.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "publish",
"command": "dotnet",
"type": "process",
"args": [
"publish",
"${workspaceFolder}/FTPService.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "watch",
"command": "dotnet",
"type": "process",
"args": [
"watch",
"run",
"--project",
"${workspaceFolder}/FTPService.csproj"
],
"problemMatcher": "$msCompile"
}
]
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using FTP_Services.Core.Models;
using Microsoft.Extensions.Options;
namespace FTP_Services.Services.Controllers
{
public class BaseAPIController : ControllerBase
{
protected IConfiguration? _configuration;
protected readonly AppSettings _appSettings;
protected readonly log4net.ILog log = log4net.LogManager.GetLogger("BaseAPIController");
public BaseAPIController(AppSettings appSettings)
{
_appSettings=appSettings;
_configuration=null;
log.Debug("BaseAPIController constructor called");
}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Threading.Tasks;
using FTP_Services.Core.Models;
using FTP_Services.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
namespace FTP_Services.Services.Controllers
{
public class FTPManagementAPIController : BaseAPIController
{
private readonly AppSettings _appSettings;
private readonly Microsoft.AspNetCore.Hosting.IWebHostEnvironment _hostingEnvironment;
// public FTPManagementAPIController(
// IOptions<AppSettings> appSettings,
// IConfiguration configuration,
// Microsoft.AspNetCore.Hosting.IWebHostEnvironment hostingEnvironment
// )
// : base(appSettings.Value)
public FTPManagementAPIController(IOptions<AppSettings> appSettings)
: base(appSettings.Value)
{
log.Info("FTPManagementAPIController : Constractor");
_appSettings = appSettings.Value;
// _hostingEnvironment = hostingEnvironment;
}
[HttpPost("GetLoginDetails")]
public IActionResult GetLoginDetails([FromBody] LoginResponseModel model)
{
// _hostingEnvironment.log("GetLoginDetails ==> ");
try
{
FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
List<Login>? RequestsList = adapter.LoginData(model.UserName);
return Ok(RequestsList);
}
catch (Exception ex)
{
log.Error("Fail to get data for login - Error:" + ex.Message);
return NotFound("No results");
}
}
[HttpGet("GetSearchedPatients")]
public IActionResult GetSearchedPatients(string SearchText)
{
log.Debug("GetSearchedPatients ==> ");
try
{
FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
// List<SearchPatients>? RequestsList = adapter.SearchedPatientsData(SearchText);
List<object>? RequestsList = adapter.SearchedPatientsData(SearchText);
return Ok(RequestsList);
}
catch (Exception ex)
{
log.Error("Fail to get data for search patients - Error:" + ex.Message);
return NotFound("No results");
}
}
[HttpGet("LoadDocumentCategories")]
public IActionResult LoadDocumentCategories()
{
log.Debug("LoadDocumentCategories ==> ");
try
{
FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
List<DocumentCategories>? RequestsList = adapter.DocumentCategories();
return Ok(RequestsList);
}
catch (Exception ex)
{
log.Error("Fail to get data for load documents - Error:" + ex.Message);
return NotFound("No results");
}
}
[HttpGet("GetSpecialities")]
public IActionResult GetSpecialities()
{
log.Debug("GetSpecialities ==> ");
try
{
FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
List<Specialities>? RequestsList = adapter.Specialities();
return Ok(RequestsList);
}
catch (Exception ex)
{
log.Error("Fail to get data for specialities - Error:" + ex.Message);
return NotFound("No results");
}
}
[HttpGet("GetPatientDocuments")]
public IActionResult GetPatientDocuments(int SPatientID, int SDocID)
{
log.Debug("GetPatientDocuments ==> ");
try
{
FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
List<PatientDocuments>? RequestsList = adapter.PatientDocuments(SPatientID, SDocID);
return Ok(RequestsList);
}
catch (Exception ex)
{
log.Error("Fail to get data for patient documents - Error:" + ex.Message);
return NotFound("No results");
}
}
[HttpPost("SavePatientDocument")]
public int SavePatientDocument([FromBody] PatientDocumentDetailsModel model)
{
log.Debug("SavePatientDocument ==> ");
int SavePT = 0;
try
{
FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
SavePT = adapter.SavePatientDocumentData(model);
}
catch (Exception ex)
{
log.Error("Fail to get data for save patient documents - Error:" + ex.Message);
}
return SavePT;
}
// [HttpPost("DeletePatientDocument")]
// public int DeletePatientDocument(int DocumentID)
// {
// log.Debug("DeletePatientDocument ==> ");
// int DeletePT = 0;
// try
// {
// FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
// DeletePT = adapter.DeletePatientDocumentData(DocumentID);
// }
// catch (Exception ex)
// {
// log.Error("Fail to get data for delete patient documents - Error:" + ex.Message);
// }
// return DeletePT;
// }
[HttpPost("DeletePatientDocument")]
public string DeletePatientDocument(int DocumentID)
{
log.Debug("DeletePatientDocument ==> ");
string DeletePT = "";
try
{
FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
DeletePT = adapter.DeletePatientDocumentData(DocumentID);
}
catch (Exception ex)
{
log.Error("Fail to get data for delete patient documents - Error:" + ex.Message);
}
return DeletePT;
}
[HttpGet("IsValidUser")]
public bool IsValidUser(string SndUserName, string SndPassword)
{
log.Debug("IsValidUser ==> ");
bool _isValid = false;
try
{
FTPDataAdapter adapter = new FTPDataAdapter(_appSettings);
_isValid = adapter.IsValidUserData(SndUserName, SndPassword);
}
catch (Exception ex)
{
log.Error("Fail to get data for IsValidUser - Error:" + ex.Message);
}
return _isValid;
}
[HttpPost("DownloadBase64DataAsync")]
public async Task<string> DownloadBase64DataAsync(string fileNameWithPath)
{
bool isFTPMODE = _appSettings.FTPConfiguration.FTPMODE;
var base64 = string.Empty;
if (isFTPMODE == true)
{
int bytesRead;
// byte[] buffer = new byte[2048];
byte[] buffer = new byte[1048576]; // 1 MB buffer
byte[] fileData = null;
string FTPURL = _appSettings.FTPConfiguration.FtpURL.ToString();
string FTPUserName = _appSettings.FTPConfiguration.Username.ToString();
string FTPPassword = _appSettings.FTPConfiguration.Password.ToString();
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(FTPURL + fileNameWithPath);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(FTPUserName, FTPPassword);
try
{
Stream reader = request.GetResponse().GetResponseStream();
using (MemoryStream ms = new MemoryStream())
{
while (true)
{
bytesRead = await reader.ReadAsync(buffer, 0, buffer.Length);
if (bytesRead == 0)
break;
ms.Write(buffer, 0, bytesRead);
}
fileData = ms.ToArray();
}
reader.Close();
base64 = Convert.ToBase64String(fileData);
}
catch (WebException ex)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
response.Close();
}
return null;
}
}
else
{
string strDestinationPath = _appSettings
.FTPConfiguration.DestinationPath.ToString()
.Trim();
string strFullPath = Path.Combine(strDestinationPath, fileNameWithPath);
if (string.IsNullOrEmpty(strFullPath) || !System.IO.File.Exists(strFullPath))
{
return "File not found";
}
byte[] fileBytes = await System.IO.File.ReadAllBytesAsync(strFullPath);
base64 = Convert.ToBase64String(fileBytes);
}
return base64;
}
[HttpGet("GetPDFBase64")]
public async Task<string> GetPDFBase64(string remoteFilePath)
{
// string filePath = @"C:\Users\mohank\Desktop\FTP\9.pdf";
byte[] fileBytes = System.IO.File.ReadAllBytes(remoteFilePath);
string strbase64 = Convert.ToBase64String(fileBytes);
return strbase64;
}
[HttpPost("DownloadBase64LargeFileAsync")]
public async Task<string> DownloadBase64LargeFileAsync(string remoteFilePath)
{
// string filePath = @"C:\Users\mohank\Desktop\FTP\9.pdf";
// byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);
// string strbase64=Convert.ToBase64String(fileBytes);
// return strbase64;
try
{
string _ftpUrl = _appSettings.FTPConfiguration.FtpURL.ToString();
string _ftpUsername = _appSettings.FTPConfiguration.Username.ToString();
string _ftpPassword = _appSettings.FTPConfiguration.Password.ToString();
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_ftpUrl + remoteFilePath);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(_ftpUsername, _ftpPassword);
request.UseBinary = true;
request.UsePassive = true;
request.KeepAlive = true;
request.Timeout = 2400000; // Increased timeout for large files (40 minutes)
request.ReadWriteTimeout = 2400000; // Increased read/write timeout for large files
using (FtpWebResponse response = (FtpWebResponse)await request.GetResponseAsync())
{
using (Stream ftpStream = response.GetResponseStream())
{
// byte[] buffer = new byte[1024 * 8];
byte[] buffer = new byte[1048576]; // 1 MB buffer
int bytesRead;
using (MemoryStream memoryStream = new MemoryStream())
{
while (
(bytesRead = await ftpStream.ReadAsync(buffer, 0, buffer.Length))
> 0
)
{
await memoryStream.WriteAsync(buffer, 0, bytesRead);
}
byte[] fileData = memoryStream.ToArray();
string base64Encoded = Convert.ToBase64String(fileData);
return base64Encoded;
}
}
}
}
catch (WebException ex)
{
return ex.ToString();
}
catch (Exception ex)
{
return ex.ToString();
}
}
[HttpPost("RenameFtpFile")]
public async Task<bool> RenameFtpFile(string source, string destination)
{
string FTPURL = _appSettings.FTPConfiguration.FtpURL.ToString();
string FTPUserName = _appSettings.FTPConfiguration.Username.ToString();
string FTPPassword = _appSettings.FTPConfiguration.Password.ToString();
Uri serverFile = new Uri(FTPURL + source);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverFile);
request.Method = WebRequestMethods.Ftp.Rename;
request.UseBinary = true;
request.Credentials = new NetworkCredential(FTPUserName, FTPPassword);
request.RenameTo = "/" + destination;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
var success =
response.StatusCode == FtpStatusCode.CommandOK
|| response.StatusCode == FtpStatusCode.FileActionOK;
return success;
}
[HttpPost("UploadProfileImageAsync")]
public async Task<string> UploadProfileImageAsync(
[FromBody] FileResponseModel model,
string filePath
)
{
if (string.IsNullOrEmpty(filePath) && string.IsNullOrEmpty(model.Base64String))
{
return "Should not be empty filePath and file..";
}
var imageBytes = ToImageBytes(model.Base64String);
var imageStream = new MemoryStream(imageBytes);
bool isFTPMODE = _appSettings.FTPConfiguration.FTPMODE;
string uploadResponse = string.Empty;
if (isFTPMODE == true)
{
uploadResponse = await this.UploadFileWithStreamAsync(
filePath.ToString().Trim(),
imageStream
);
}
else
{
uploadResponse = await this.UploadFileWithStreamLocal(
filePath.ToString().Trim(),
imageStream
);
// uploadResponse = await this.UploadFileWithStreamToNetworkShare(
// filePath.ToString().Trim(),
// imageStream
// );
}
return uploadResponse;
}
public async Task<string> UploadFileWithStreamLocal(string fileName, Stream stream)
{
// WriteLog("UploadFileWithStreamLocal Start.");
if (stream == null)
{
throw new ArgumentNullException(nameof(stream), "Stream cannot be null.");
}
if (string.IsNullOrWhiteSpace(fileName))
{
throw new ArgumentNullException(
nameof(fileName),
"File name cannot be null or empty."
);
}
string strDestinationPath = _appSettings
.FTPConfiguration.DestinationPath.ToString()
.Trim();
string strMfN = fileName.Replace("/", "\\").TrimStart('\\');
string strFullPath = Path.Combine(strDestinationPath, strMfN);
string strDirectoryPath = Path.GetDirectoryName(strFullPath);
// WriteLog("DestinationPath: " + strDestinationPath);
// WriteLog("FullPath: " + strFullPath);
// WriteLog("DirectoryPath: " + strDirectoryPath);
if (!Directory.Exists(strDirectoryPath))
{
Directory.CreateDirectory(strDirectoryPath);
}
if (System.IO.File.Exists(strFullPath))
{
return "File already exists.";
}
string filePath = Path.Combine(strDirectoryPath, Path.GetFileName(strFullPath));
// WriteLog("filePath: " + filePath);
try
{
using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
await stream.CopyToAsync(fileStream);
}
return string.Empty; // Success
}
catch (Exception ex)
{
return ex.Message.ToString(); // Return error message if an exception occurs
}
}
public async Task<string> UploadFileWithStreamToNetworkShare(string fileName, Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream), "Stream cannot be null.");
}
if (string.IsNullOrWhiteSpace(fileName))
{
throw new ArgumentNullException(
nameof(fileName),
"File name cannot be null or empty."
);
}
// Network share path
string strDestinationPath = _appSettings
.FTPConfiguration.DestinationPath.ToString()
.Trim();
// Replace forward slashes with backslashes for network path
string strMfN = fileName.Replace("/", "\\").TrimStart('\\');
string strFullPath = Path.Combine(strDestinationPath, strMfN);
string strDirectoryPath = Path.GetDirectoryName(strFullPath);
// if (strDestinationPath.StartsWith(@"\\"))
if (true)
{
try
{
var networkPath = strDestinationPath;
var networkCredential = new NetworkCredential(
"krishna",
"Krishna@123",
"ICREATECH"
);
using (new NetworkConnection(networkPath, networkCredential))
{
if (!Directory.Exists(strDirectoryPath))
{
Directory.CreateDirectory(strDirectoryPath);
}
}
}
catch (UnauthorizedAccessException uaEx)
{
return "Access denied. Check permissions on the network share.";
}
catch (Exception ex)
{
return "Error creating directory: " + ex.Message;
}
}
else
{
if (!Directory.Exists(strDirectoryPath))
{
Directory.CreateDirectory(strDirectoryPath);
}
}
if (System.IO.File.Exists(strFullPath))
{
return "File already exists.";
}
string filePath = Path.Combine(strDirectoryPath, Path.GetFileName(strFullPath));
try
{
using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
await stream.CopyToAsync(fileStream);
}
return string.Empty; // Success
}
catch (Exception ex)
{
return "Error while uploading the file: " + ex.Message;
}
}
public static void CreateNetworkDirectory(
string networkPath,
string username,
string password
)
{
try
{
// Prepare the network credentials
NetworkCredential credentials = new NetworkCredential(
username,
password,
"WORKGROUP"
); // Use the appropriate domain
CredentialCache credentialCache = new CredentialCache();
credentialCache.Add(new Uri(networkPath), "Basic", credentials);
string testFilePath = Path.Combine(networkPath, "temp.txt");
if (!System.IO.File.Exists(networkPath))
{
System.IO.File.Create(testFilePath).Dispose();
}
if (!Directory.Exists(networkPath))
{
Directory.CreateDirectory(networkPath);
}
else { }
}
catch (UnauthorizedAccessException ex)
{
// Console.WriteLine("Access denied. Please check your network permissions.");
// Console.WriteLine($"Error: {ex.Message}");
}
catch (Exception ex)
{
// Console.WriteLine("An error occurred while creating the directory.");
// Console.WriteLine($"Error: {ex.Message}");
}
}
static string ConvertFtpUrlToLocalPath(string ftpUrl, string localRootPath)
{
Uri uri = new Uri(ftpUrl);
string ftpPath = uri.AbsolutePath;
if (!Directory.Exists(localRootPath))
{
Directory.CreateDirectory(localRootPath);
}
string localFilePath = Path.Combine(
localRootPath,
ftpPath.TrimStart('/').Replace('/', Path.DirectorySeparatorChar)
);
return localFilePath;
}
public async Task<string> UploadFileWithStreamAsync(string fileName, Stream stream)
{
if (stream == null)
{
throw new ArgumentNullException(nameof(stream), "Stream cannot be null.");
}
if (string.IsNullOrWhiteSpace(fileName))
{
throw new ArgumentNullException(
nameof(fileName),
"File name cannot be null or empty."
);
}
string ftpUrl = _appSettings.FTPConfiguration.FtpURL.ToString();
string ftpUserName = _appSettings.FTPConfiguration.Username.ToString();
string ftpPassword = _appSettings.FTPConfiguration.Password.ToString();
if (!ftpUrl.StartsWith("ftp://", StringComparison.OrdinalIgnoreCase))
{
throw new ArgumentException("FTP URL must start with ftp://", nameof(ftpUrl));
}
if (!ftpUrl.EndsWith("/"))
{
ftpUrl += "/";
}
string uploadUrl = ftpUrl + fileName;
try
{
Uri uri = new Uri(uploadUrl);
string strFolderPath = uri.AbsoluteUri.Substring(
0,
uri.AbsoluteUri.LastIndexOf('/')
);
if (CheckFolderExists(strFolderPath, ftpUserName, ftpPassword) == false)
CreateFolder(strFolderPath, ftpUserName, ftpPassword);
FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(uploadUrl);
ftp.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
ftp.KeepAlive = true;
ftp.UseBinary = true;
ftp.UsePassive = true;
ftp.Method = WebRequestMethods.Ftp.UploadFile;
ftp.Timeout = 2400000; // Increased timeout for large files (40 minutes)
ftp.ReadWriteTimeout = 2400000; // Increased read/write timeout for large files
//Console.WriteLine($"Requesting upload to {uploadUrl} with method {ftp.Method}");
using (Stream ftpStream = await ftp.GetRequestStreamAsync())
{
// byte[] buffer = new byte[2048];
byte[] buffer = new byte[1048576]; // 1 MB buffer
int bytesRead;
while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0)
{
await ftpStream.WriteAsync(buffer, 0, bytesRead);
}
}
using (FtpWebResponse response = (FtpWebResponse)await ftp.GetResponseAsync())
{
return "";
}
}
catch (WebException ex)
{
if (ex.Response is FtpWebResponse response)
{
response.Close();
}
return "Exception: " + ex.Message;
}
catch (Exception ex)
{
return "Exception: " + ex.Message;
}
}
// public async Task<string> UploadFileWithStreamAsync(string fileName, Stream stream)
// {
// if (stream == null)
// {
// throw new ArgumentNullException(nameof(stream), "Stream cannot be null.");
// }
// if (string.IsNullOrWhiteSpace(fileName))
// {
// throw new ArgumentNullException(
// nameof(fileName),
// "File name cannot be null or empty."
// );
// }
// string ftpUrl = _appSettings.FTPConfiguration.FtpURL.ToString();
// string ftpUserName = _appSettings.FTPConfiguration.Username.ToString();
// string ftpPassword = _appSettings.FTPConfiguration.Password.ToString();
// if (!ftpUrl.StartsWith("ftp://", StringComparison.OrdinalIgnoreCase))
// {
// throw new ArgumentException("FTP URL must start with ftp://", nameof(ftpUrl));
// }
// if (!ftpUrl.EndsWith("/"))
// {
// ftpUrl += "/";
// }
// string uploadUrl = ftpUrl + fileName;
// try
// {
// Uri uri = new Uri(uploadUrl);
// string strFolderPath = uri.AbsoluteUri.Substring(
// 0,
// uri.AbsoluteUri.LastIndexOf('/')
// );
// if (!CheckFolderExists(strFolderPath, ftpUserName, ftpPassword))
// {
// CreateFolder(strFolderPath, ftpUserName, ftpPassword);
// }
// FtpWebRequest ftp = (FtpWebRequest)WebRequest.Create(uploadUrl);
// ftp.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
// ftp.KeepAlive = true;
// ftp.UseBinary = true; // Ensure binary mode for PDFs
// ftp.UsePassive = true; // Use passive mode for better firewall compatibility
// ftp.Method = WebRequestMethods.Ftp.UploadFile;
// // Set high timeout values to ensure file upload completion
// ftp.Timeout = 2400000; // Increased timeout for large files (40 minutes)
// ftp.ReadWriteTimeout = 2400000; // Increased read/write timeout for large files
// // Choose an appropriate buffer size for large files (e.g., 512 KB buffer)
// byte[] buffer = new byte[1048576]; // 1 MB buffer
// int bytesRead;
// long totalBytesUploaded = 0;
// using (Stream ftpStream = await ftp.GetRequestStreamAsync())
// {
// while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) > 0)
// {
// await ftpStream.WriteAsync(buffer, 0, bytesRead);
// totalBytesUploaded += bytesRead;
// }
// }
// using (FtpWebResponse response = (FtpWebResponse)await ftp.GetResponseAsync())
// {
// // Console.WriteLine($"FTP Response: {response.StatusCode}");
// if (response.StatusCode == FtpStatusCode.ClosingData)
// {
// return ""; // Success
// }
// else
// {
// return response.StatusDescription; // Return status description if not successful
// }
// }
// }
// catch (WebException ex)
// {
// if (ex.Response is FtpWebResponse response)
// {
// using (response)
// {
// return "FTP Error: " + response.StatusDescription;
// }
// }
// return "WebException: " + ex.Message;
// }
// catch (Exception ex)
// {
// return "Exception: " + ex.Message;
// }
// }
// public static byte[] ToImageBytes(string image) =>
// !string.IsNullOrEmpty(image)
// ? Convert.FromBase64String(
// Regex.Replace(
// image,
// "data:image/(png|jpg|PNG|JPG|JPEG|jpeg|gif|GIF|bmp|BMP);base64,",
// string.Empty
// )
// )
// : null;
public static byte[] ToImageBytes(string image)
{
if (string.IsNullOrEmpty(image))
return null;
try
{
// Remove the data:image part (if it exists) using a regex
string base64String = Regex.Replace(
image,
@"^data:image\/(png|jpg|jpeg|gif|bmp);base64,",
string.Empty,
RegexOptions.IgnoreCase
);
// Decode the base64 string to bytes
return Convert.FromBase64String(base64String);
}
catch (FormatException ex)
{
// Catch any base64 errors
Console.WriteLine("Invalid base64 string: " + ex.Message);
return null;
}
}
[HttpPost("DeleteFTPFile")]
public async Task<int> DeleteFTPFile(string fileNameWithDestinationPath)
{
try
{
string FTPURL = _appSettings.FTPConfiguration.FtpURL.ToString();
string FTPUserName = _appSettings.FTPConfiguration.Username.ToString();
string FTPPassword = _appSettings.FTPConfiguration.Password.ToString();
FtpWebRequest ftp = (FtpWebRequest)
WebRequest.Create(FTPURL + fileNameWithDestinationPath);
ftp.Credentials = new NetworkCredential(FTPUserName, FTPPassword);
ftp.KeepAlive = true;
ftp.UseBinary = true;
ftp.UsePassive = true;
ftp.Method = WebRequestMethods.Ftp.DeleteFile;
FtpWebResponse response = (FtpWebResponse)await ftp.GetResponseAsync();
var statuscode = (int)response.StatusCode;
response.Close();
return statuscode;
}
catch (WebException ex)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
response.Close();
return 1;
}
else
{
response.Close();
return 0;
}
}
}
public bool CheckIfFileExistsOnServer(string fileName)
{
string FTPURL = _appSettings.FTPConfiguration.FtpURL.ToString();
string FTPUserName = _appSettings.FTPConfiguration.Username.ToString();
string FTPPassword = _appSettings.FTPConfiguration.Password.ToString();
var request = (FtpWebRequest)WebRequest.Create(FTPURL + fileName);
request.Credentials = new NetworkCredential(FTPUserName, FTPPassword);
request.Method = WebRequestMethods.Ftp.GetFileSize;
request.KeepAlive = true;
request.UseBinary = true;
request.UsePassive = true;
try
{
var response = (FtpWebResponse)request.GetResponse();
response.Close();
return true;
}
catch (WebException ex)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
response.Close();
return false;
}
response.Close();
}
return false;
}
public bool CheckFolderExists(string folderName, string username, string password)
{
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(folderName);
request.Credentials = new NetworkCredential(username, password);
request.Method = WebRequestMethods.Ftp.ListDirectory;
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
return true;
}
}
catch (WebException ex)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
return false;
}
else
{
return false;
}
}
}
public bool CreateFolder(string folderName, string username, string password)
{
try
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(folderName);
request.Credentials = new NetworkCredential(username, password);
request.Method = WebRequestMethods.Ftp.MakeDirectory;
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
return true;
}
}
catch (WebException ex)
{
return false;
}
}
// [HttpPost("UploadProfileImageAsyncLargeFiles")]
// public async Task<string> UploadProfileImageAsyncLargeFiles(
// [FromBody] FileResponseModel model,
// string filePath
// )
// {
// if (string.IsNullOrEmpty(filePath) && string.IsNullOrEmpty(model.Base64String))
// {
// return "Should not be empty filePath and file..";
// }
// var imageBytes = ToImageBytes(model.Base64String);
// var imageStream = new MemoryStream(imageBytes);
// var uploadResponse = await this.UploadFileWithStreamAsync_New(filePath, imageStream);
// return uploadResponse;
// }
// public async Task<string> UploadFileWithStreamAsync_New(string fileName, Stream stream)
// {
// if (stream == null)
// {
// throw new ArgumentNullException(nameof(stream), "Stream cannot be null.");
// }
// if (string.IsNullOrWhiteSpace(fileName))
// {
// throw new ArgumentNullException(
// nameof(fileName),
// "File name cannot be null or empty."
// );
// }
// string ftpUrl = _appSettings.FTPConfiguration.FtpURL.ToString();
// string ftpUserName = _appSettings.FTPConfiguration.Username.ToString();
// string ftpPassword = _appSettings.FTPConfiguration.Password.ToString();
// // Ensure the URL starts with "ftp://" and ends with a slash
// if (!ftpUrl.StartsWith("ftp://", StringComparison.OrdinalIgnoreCase))
// {
// throw new ArgumentException("FTP URL must start with ftp://", nameof(ftpUrl));
// }
// if (!ftpUrl.EndsWith("/"))
// {
// ftpUrl += "/";
// }
// string uploadUrl = ftpUrl + fileName;
// try
// {
// // Extract the FTP server host from the FTP URL
// Uri uri = new Uri(uploadUrl);
// string ftpHost = uri.Host;
// // Create an FTP client using FluentFTP
// using (
// FluentFTP.FtpClient ftpClient = new FluentFTP.FtpClient(
// ftpHost,
// new NetworkCredential(ftpUserName, ftpPassword)
// )
// )
// {
// // Connect to the FTP server asynchronously
// await ftpClient.ConnectAsync();
// // Extract the folder path (directory) from the URL (excluding the protocol part and file name)
// string remoteFolderPath = uri.AbsolutePath;
// // Normalize the path: replace backslashes with forward slashes
// remoteFolderPath = remoteFolderPath.Replace("\\", "/");
// // Remove the file name from the path, leaving only the directory portion
// remoteFolderPath = Path.GetDirectoryName(remoteFolderPath);
// // Ensure the folder path ends with a slash
// if (!remoteFolderPath.EndsWith("/"))
// {
// remoteFolderPath += "/";
// }
// // Log the path for debugging
// Console.WriteLine($"Checking if directory exists: {remoteFolderPath}");
// // Check if the directory exists
// bool directoryExists = await ftpClient.DirectoryExistsAsync(remoteFolderPath);
// if (directoryExists)
// {
// Console.WriteLine("Directory exists.");
// }
// else
// {
// Console.WriteLine("Directory does not exist.");
// }
// // If the directory does not exist, create it
// if (!directoryExists)
// {
// await ftpClient.CreateDirectoryAsync(remoteFolderPath);
// Console.WriteLine("Directory created.");
// }
// // Upload the file to the FTP server
// FtpStatus uploadStatus = await ftpClient.UploadAsync(
// stream,
// fileName,
// FtpRemoteExists.Overwrite
// );
// // Check if the upload was successful
// if (uploadStatus == FtpStatus.Success)
// {
// return "";
// }
// else
// {
// return "File upload failed. Status: " + uploadStatus.ToString();
// }
// }
// }
// catch (FtpException ex)
// {
// return "FTP Error: " + ex.Message;
// }
// catch (Exception ex)
// {
// return "Exception: " + ex.Message;
// }
// }
public void WriteLog(string SndException)
{
string strfname = Convert.ToString(DateTime.Today.ToString("yyyy-MM-dd"));
string strDirectory =
System
.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase
)
.Replace("file:\\", "") + "\\LOGDetails";
string strFile =
System
.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase
)
.Replace("file:\\", "")
+ "\\LOGDetails\\"
+ strfname
+ ".txt";
if (!System.IO.Directory.Exists(strDirectory))
{
System.IO.Directory.CreateDirectory(strDirectory);
}
StreamWriter objStreamWriter = default(StreamWriter);
if (!System.IO.File.Exists(strFile))
{
FileStream fs = new FileStream(strFile, FileMode.Create, FileAccess.Write);
objStreamWriter = new StreamWriter(fs);
objStreamWriter.BaseStream.Seek(0, SeekOrigin.End);
}
else
{
objStreamWriter = System.IO.File.AppendText(strFile);
}
objStreamWriter.WriteLine(SndException);
objStreamWriter.Close();
}
}
}
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>FTP_Services</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ExcelDataReader" Version="3.6.0" />
<PackageReference Include="ExcelDataReader.DataSet" Version="3.6.0" />
<PackageReference Include="log4net" Version="2.0.14" />
<PackageReference Include="Microsoft.Data.SqlClient" Version="4.1.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="PetaPoco.Compiled" Version="6.0.494-beta" />
<PackageReference Include="prometheus-net" Version="5.0.2" />
<PackageReference Include="prometheus-net.AspNetCore" Version="5.0.2" />
<PackageReference Include="prometheus-net.SystemMetrics" Version="2.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.0" />
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.15.0" />
<PackageReference Include="Npgsql" Version="8.0.3" />
<PackageReference Include="AspNetCore.HealthChecks.NpgSql" Version="8.0.1" />
</ItemGroup>
</Project>

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.002.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "FTPService", "FTPService.csproj", "{DB335205-331F-467D-ACB6-6A821F24F4CF}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{DB335205-331F-467D-ACB6-6A821F24F4CF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DB335205-331F-467D-ACB6-6A821F24F4CF}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DB335205-331F-467D-ACB6-6A821F24F4CF}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DB335205-331F-467D-ACB6-6A821F24F4CF}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {DB89F67C-13F5-4154-87BD-BE6BE23E6ADC}
EndGlobalSection
EndGlobal
namespace FTP_Services.Core.Models
{
public class AppSettings
{
public string ConnectionString { get; set; }
public AppSettings()
{
ConnectionString = "";
}
public FTPConfiguration FTPConfiguration { get; set; }
}
public class FTPConfiguration
{
public string Username { get; set; }
public string Password { get; set; }
public string FtpURL { get; set; }
public bool FTPMODE { get; set; }
public string DestinationPath { get; set; }
public FTPConfiguration()
{
Username = "";
Password = "";
FtpURL = "";
FTPMODE = false;
DestinationPath = "";
}
}
}
namespace FTP_Services.Core.Models
{
public class PatientDocumentDetailsModel
{
public string DocumentType { get; set; }
public string Description { get; set; }
public string DocumentName { get; set; }
public int UploadedBy { get; set; }
public int PatientId { get; set; }
public string ContentType { get; set; }
public string Size { get; set; }
public string DocumentUrl { get; set; }
public string ThumbnailUrl { get; set; }
public int SplID { get; set; }
public PatientDocumentDetailsModel()
{
DocumentType = "";
Description = "";
DocumentName = "";
UploadedBy = -1;
PatientId = -1;
ContentType = "";
Size = "";
DocumentUrl = "";
ThumbnailUrl = "";
SplID = -1;
}
}
// public class Login
// {
// public string ID { get; set; }
// public string Name { get; set; }
// public string Code { get; set; }
// public Login()
// {
// ID = "";
// Name = "";
// Code = "";
// }
// }
public class FileResponseModel
{
public string Base64String { get; set; }
public FileResponseModel()
{
Base64String = "";
}
}
public class LoginResponseModel
{
public string UserName { get; set; }
public LoginResponseModel()
{
UserName = "";
}
}
public class Login
{
public int UserID { get; set; }
public string UserName { get; set; }
public string FullName { get; set; }
public bool Active { get; set; }
public bool IsLocked { get; set; }
public string SaltKey { get; set; }
public string PasswordHash { get; set; }
public string GCClientID { get; set; }
public Login()
{
UserID = -1;
UserName = "";
FullName = "";
Active = false;
IsLocked = false;
SaltKey = "";
PasswordHash = "";
GCClientID = "";
}
}
public class SearchPatients
{
public int PatientID { get; set; }
public string UMRNo { get; set; }
public string FullName { get; set; }
public string DOB { get; set; }
public int Age { get; set; }
public string Mobile { get; set; }
public string RegNo { get; set; }
public string Guid { get; set; }
public int DocCount { get; set; }
public SearchPatients()
{
PatientID = -1;
UMRNo = "";
FullName = "";
DOB = "";
Age = -1;
Mobile = "";
RegNo = "";
Guid = "";
DocCount = -1;
}
}
public class DocumentCategories
{
public int ID { get; set; }
public string Name { get; set; }
public DocumentCategories()
{
ID = -1;
Name = "";
}
}
public class Specialities
{
public int ID { get; set; }
public string Name { get; set; }
public Specialities()
{
ID = -1;
Name = "";
}
}
public class PatientDocuments
{
public int PatientId { get; set; }
public string Guid { get; set; }
public string UMRNo { get; set; }
public int PatientDocumentId { get; set; }
public string DocumentType { get; set; }
public string DocumentName { get; set; }
public string Description { get; set; }
public string ContentType { get; set; }
public string Size { get; set; }
public string IsRead { get; set; }
public string UploadedDate { get; set; }
public int UploadedBy { get; set; }
public string UploadedByName { get; set; }
public string UploadedByRole { get; set; }
public string FullName { get; set; }
public string DocumentUrl { get; set; }
public PatientDocuments()
{
PatientId = -1;
Guid = "";
UMRNo = "";
PatientDocumentId = -1;
DocumentType = "";
DocumentName = "";
Description = "";
ContentType = "";
Size = "";
IsRead = "";
UploadedDate = "";
UploadedBy = -1;
UploadedByName = "";
UploadedByRole = "";
FullName = "";
DocumentUrl = "";
}
}
public class ValidUserCount
{
public int RecordCount { get; set; }
public ValidUserCount()
{
RecordCount = -1;
}
}
}
using Microsoft.AspNetCore.Hosting;
using System;
using System.IO;
public class LogService
{
private readonly IWebHostEnvironment _environment;
public LogService(IWebHostEnvironment environment)
{
_environment = environment;
}
public void WriteLog(string SndException)
{
string strBaseDirectory = _environment.ContentRootPath;
string strDirectory = Path.Combine(strBaseDirectory, "LOGDetails");
if (!Directory.Exists(strDirectory))
{
Directory.CreateDirectory(strDirectory);
}
string strFile = Path.Combine(strDirectory, DateTime.Today.ToString("yyyy-MM-dd") + ".txt");
using (StreamWriter objStreamWriter = new StreamWriter(strFile, true))
{
objStreamWriter.WriteLine(SndException);
}
}
}
using System;
using System.IO;
using System.Net;
using System.Runtime.InteropServices;
public class NetworkConnection : IDisposable
{
private string _networkName;
private NetworkCredential _credentials;
[DllImport("mpr.dll")]
private static extern int WNetAddConnection2(ref NetResource netResource, string password, string username, int flags);
[DllImport("mpr.dll")]
private static extern int WNetCancelConnection2(string name, int flags, bool force);
[StructLayout(LayoutKind.Sequential)]
public class NetResource
{
public int dwScope;
public int dwType;
public int dwDisplayType;
public int dwUsage;
public string lpLocalName;
public string lpRemoteName;
public string lpComment;
public string lpProvider;
}
public NetworkConnection(string networkName, NetworkCredential credentials)
{
_networkName = networkName;
_credentials = credentials;
Connect();
}
private void Connect()
{
NetResource networkResource = new NetResource
{
dwType = 1, // Disk
lpRemoteName = _networkName
};
int result = WNetAddConnection2(ref networkResource, _credentials.Password, _credentials.UserName, 0);
if (result != 0)
{
throw new UnauthorizedAccessException("Could not connect to network drive.");
}
}
public void Dispose()
{
WNetCancelConnection2(_networkName, 0, true);
}
}
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="nuget.org" value="https://api.nuget.org/v3/index.json" />
</packageSources>
</configuration>
// var builder = WebApplication.CreateBuilder(args);
// // Add services to the container.
// builder.Services.AddControllersWithViews();
// var app = builder.Build();
// // Configure the HTTP request pipeline.
// if (!app.Environment.IsDevelopment())
// {
// app.UseExceptionHandler("/Home/Error");
// // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
// app.UseHsts();
// }
// app.UseHttpsRedirection();
// app.UseStaticFiles();
// app.UseRouting();
// app.UseAuthorization();
// app.MapControllerRoute(
// name: "default",
// pattern: "{controller=Home}/{action=Index}/{id?}");
// app.Run();
using FTP_Services.Services;
using FTP_Services.Core.Models;
using Microsoft.AspNetCore.Http.Features;
using Prometheus;
using Prometheus.SystemMetrics;
//log4netConfig.Load(File.OpenRead("log4net.config"));
try
{
string? curPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
if (String.IsNullOrEmpty(curPath))
curPath = System.Environment.CurrentDirectory;
string confFile = Path.Combine(curPath, "log4net.config");
var repo = log4net.LogManager.CreateRepository(System.Reflection.Assembly.GetEntryAssembly(),
typeof(log4net.Repository.Hierarchy.Hierarchy));
//log4net.Config.XmlConfigurator.Configure(repo, log4netConfig["log4net"]);
log4net.Config.XmlConfigurator.Configure(new System.IO.FileInfo(confFile));
log4net.ILog log = log4net.LogManager.GetLogger("Progaram Main");
log.Info("************************ Starting the ADRCP Connect Services **************************************************************** ");
}
catch (Exception ex)
{
Console.WriteLine($"Fail to load log4net config file, log will be disabled {ex.Message}");
}
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSwaggerGen(c =>
{
//c.SwaggerDoc("v1", new OpenApiInfo { Title = "Sample.FileUpload.Api", Version = "v1" });
c.OperationFilter<SwaggerFileOperationFilter>();
});
// configure strongly typed settings object
builder.Services.Configure<AppSettings>(builder.Configuration.GetSection("AppSettings"));
builder.Services.Configure<FormOptions>(x =>
{
x.ValueLengthLimit = int.MaxValue;
x.MultipartBodyLengthLimit = int.MaxValue; // In case of multipart
});
// builder.Services.AddScoped<IUserService, UserService>();
builder.Services.AddControllersWithViews();
var app = builder.Build();
//check matrics at http://host/metrics
app.UseMetricServer();
app.UseHttpMetrics();
// global cors policy
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
//app.UseDeveloperExceptionPage();
//or
app.UseSwagger();
app.UseSwaggerUI();
}
//app.UseHttpsRedirection();
app.UseAuthorization();
// custom jwt auth middleware
// app.UseMiddleware<JwtMiddleware>();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.MapControllers();
app.UseRouting();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseEndpoints(endpoints =>
{endpoints.MapControllers();
});
// app.UseEndpoints(endpoints =>
// {
// endpoints.MapGet("/", async context =>
// {
// // await context.Response.WriteAsync("Hello World!");
// });
// });
if (app.Environment.IsDevelopment())
{
app.Run("http://localhost:5603");
}
else
{
app.Run();
}
{
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:57685",
"sslPort": 44313
}
},
"profiles": {
"FTP_Services": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7053;http://localhost:5178",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using PetaPoco;
using Microsoft.Extensions.Options;
using FTP_Services.Core.Models;
namespace FTP_Services.Services
{
public class BaseDataAdapter : IDisposable
{
#region Variables
protected PetaPoco.Database _repository;
//protected IConfiguration _configuration;
protected AppSettings _appSettings;
protected readonly log4net.ILog log = log4net.LogManager.GetLogger("BaseDataAdapter");
protected int _auth_user_id;
protected int _user_id;
#endregion
public BaseDataAdapter(AppSettings appSettings)
{
log.Debug("BaseDataAdapter() called");
//this._configuration=configuration;
//string constr = _configuration.GetSection("MySettings").GetSection("ConnectionString").Value;
this._appSettings=appSettings;
string constr = _appSettings.ConnectionString;
log.Debug("Connection String -" + constr);
// this._repository = new PetaPoco.Database(new Npgsql.NpgsqlConnection(constr));
_auth_user_id=0;
_user_id=0;
// this._repository = new PetaPoco.Database(constr,"Microsoft.Data.SqlClient");
_repository = new PetaPoco.Database(constr, "npgsql");
}
public void Dispose()
{
if(this._repository.Connection!=null)
this._repository.Connection.Close();
this._repository.Dispose();
}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using FTP_Services.Core.Models;
//using System.Web.Helpers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Npgsql;
using PetaPoco;
namespace FTP_Services.Services
{
public class FTPDataAdapter : BaseDataAdapter
{
public FTPDataAdapter(AppSettings appSettings)
: base(appSettings)
{
log.Debug("FTPDataAdapter() Called");
}
public List<Login>? LoginData(string sndUserName)
{
List<Login>? LoginData = null;
try
{
using (var tx = _repository.GetTransaction())
{
LoginData = _repository.Fetch<Login>(
"SELECT * FROM \"SPScanTool_GetLoginDetails\"(@Parm_UserName)",
new { Parm_UserName = sndUserName }
);
GC.Collect();
tx.Complete();
}
return LoginData;
}
catch (Exception ex)
{
log.Error("LoginData->Failed to get info from db - " + ex.Message);
return null;
}
}
// public List<SearchPatients>? SearchedPatientsData(string SearchText)
// {
// List<SearchPatients>? SearchPatientsData = null;
// try
// {
// using (var tx = _repository.GetTransaction())
// {
// // Check if SearchText is null or empty and set it to a wildcard if true
// string searchTextParam = string.IsNullOrEmpty(SearchText) ? "%" : SearchText.Replace("'", "''");
// // Build the SQL query string
// string sqlQuery = $"SELECT * FROM \"SPScanTool_GetSearchedPatients\"(@Parm_SearchText)";
// // Perform the fetch operation with the constructed SQL query and parameter
// SearchPatientsData = _repository.Fetch<SearchPatients>(
// sqlQuery,
// new { Parm_SearchText = searchTextParam }
// );
// GC.Collect();
// tx.Complete();
// }
// return SearchPatientsData;
// }
// catch (Exception ex)
// {
// log.Error("SearchedPatientsData->Failed to get info from db - " + ex.Message);
// return null;
// }
// }
public List<object>? SearchedPatientsData(string SearchText)
{
List<object>? SearchPatientsData = null;
try
{
using (var tx = _repository.GetTransaction())
{
string searchTextParam = string.IsNullOrEmpty(SearchText)
? "%"
: SearchText.Replace("'", "''");
string sqlQuery =
$"SELECT * FROM \"SPScanTool_GetSearchedPatients\"(@Parm_SearchText)";
SearchPatientsData = _repository.Fetch<object>(
sqlQuery,
new { Parm_SearchText = searchTextParam }
);
GC.Collect();
tx.Complete();
}
return SearchPatientsData;
}
catch (Exception ex)
{
log.Error("SearchedPatientsData->Failed to get info from db - " + ex.Message);
return null;
}
}
public List<DocumentCategories>? DocumentCategories()
{
List<DocumentCategories>? DocumentCategoriesData = null;
try
{
using (var tx = _repository.GetTransaction())
{
DocumentCategoriesData = _repository.Fetch<DocumentCategories>(
"SELECT * FROM \"SPScanTool_LoadDocumentCategories\"()"
);
GC.Collect();
tx.Complete();
}
return DocumentCategoriesData;
}
catch (Exception ex)
{
log.Error("DocumentCategories->Failed to get info from db - " + ex.Message);
return null;
}
}
public List<Specialities>? Specialities()
{
List<Specialities>? SpecialitiesData = null;
try
{
using (var tx = _repository.GetTransaction())
{
SpecialitiesData = _repository.Fetch<Specialities>(
"select \"SpecializationId\" as \"ID\", \"SpecializationName\" \"Name\" from \"Specialization\" WHERE \"Active\" = true ORDER BY \"Name\""
);
GC.Collect();
tx.Complete();
}
return SpecialitiesData;
}
catch (Exception ex)
{
log.Error("Specialities->Failed to get info from db - " + ex.Message);
return null;
}
}
public List<PatientDocuments>? PatientDocuments(int SPatientID, int SDocID)
{
List<PatientDocuments>? PatientDocumentsData = null;
try
{
using (var tx = _repository.GetTransaction())
{
PatientDocumentsData = _repository.Fetch<PatientDocuments>(
"SELECT * FROM \"SPScanTool_GetPatientDocuments\"("
+ SPatientID.ToString()
+ ","
+ SDocID.ToString()
+ ");"
);
GC.Collect();
tx.Complete();
}
return PatientDocumentsData;
}
catch (Exception ex)
{
log.Error("PatientDocuments->Failed to get info from db - " + ex.Message);
return null;
}
}
public int SavePatientDocumentData(PatientDocumentDetailsModel SndPatDocRec)
{
int _save = 0;
try
{
using (var tx = _repository.GetTransaction())
{
string SQLStr =
"SELECT * FROM \"SPScanTool_SavePatientDocument\"(0, "
+ SndPatDocRec.PatientId
+ ","
+ SndPatDocRec.UploadedBy
+ ",'"
+ SndPatDocRec.DocumentName
+ "','"
+ SndPatDocRec.DocumentType
+ "','"
+ SndPatDocRec.ContentType
+ "',"
+ SndPatDocRec.Size
+ ",'"
+ SndPatDocRec.Description
+ "','"
+ SndPatDocRec.DocumentUrl
+ "','"
+ SndPatDocRec.ThumbnailUrl
+ "',"
+ SndPatDocRec.SplID
+ ")";
_save = _repository.Single<int>(SQLStr);
GC.Collect();
tx.Complete();
}
}
catch (Exception ex)
{
log.Error("SavePatientDocumentData->Failed to get info from db - " + ex.Message);
}
return _save;
}
// public int DeletePatientDocumentData(int SndPatDocRecID)
// {
// int _Delete = 0;
// try
// {
// using (var tx = _repository.GetTransaction())
// {
// string SQLStr =
// "SELECT * FROM \"SPScanTool_DeletePatientDocument\"("
// + SndPatDocRecID
// + ");";
// _Delete = _repository.Single<int>(SQLStr);
// GC.Collect();
// tx.Complete();
// }
// }
// catch (Exception ex)
// {
// log.Error("DeletePatientDocumentData->Failed to get info from db - " + ex.Message);
// }
// return _Delete;
// }
public string DeletePatientDocumentData(int SndPatDocRecID)
{
string result = string.Empty;
try
{
using (var tx = _repository.GetTransaction())
{
string SQLStr =
"SELECT * FROM \"SPScanTool_DeletePatientDocument\"("
+ SndPatDocRecID
+ ");";
result = _repository.Single<string>(SQLStr);
result = "";
GC.Collect();
tx.Complete();
}
}
catch (Exception ex)
{
log.Error("DeletePatientDocumentData->Failed to get info from db - " + ex.Message);
result = "Error: " + ex.Message;
}
return result;
}
public bool IsValidUserData(string SndUserName, string SndPassword)
{
try
{
int count = 0;
using (var tx = _repository.GetTransaction())
{
count = _repository.Single<int>(
"SELECT COUNT(*) as \"RecordCount\" FROM \"Login\" WHERE \"Username\" = '"
+ SndUserName
+ "' AND \"Password\" = '"
+ SndPassword
+ "'"
);
GC.Collect();
tx.Complete();
}
if (count > 0)
return true;
else
return false;
}
catch (Exception ex)
{
log.Error("IsValidUserData->Failed to get info from db - " + ex.Message);
return false;
}
}
}
}
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.OpenApi.Any;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerGen;
using Swashbuckle.AspNetCore.Swagger;
using System;
public class SwaggerFileOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
var fileUploadMime = "multipart/form-data";
if (operation.RequestBody == null || !operation.RequestBody.Content.Any(x => x.Key.Equals(fileUploadMime, StringComparison.InvariantCultureIgnoreCase)))
return;
var fileParams = context.MethodInfo.GetParameters().Where(p => p.ParameterType == typeof(IFormFile));
operation.RequestBody.Content[fileUploadMime].Schema.Properties =
fileParams.ToDictionary(k => k.Name, v => new OpenApiSchema()
{
Type = "file",
Format = "binary" ,
});
}
}
\ No newline at end of file
@{
ViewData["Title"] = "Home Page";
}
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
</div>
@* <div>
<iframe src="IFramADRCPUri"></iframe>
</div> *@
\ No newline at end of file
@{
ViewData["Title"] = "Privacy Policy";
}
<h1>@ViewData["Title"]</h1>
<p>Use this page to detail your site's privacy policy.</p>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - FTP_Services</title>
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" asp-append-version="true" />
<link rel="stylesheet" href="~/FTP_Services.styles.css" asp-append-version="true" />
</head>
<body>
<header>
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3">
<div class="container-fluid">
<a class="navbar-brand" asp-area="" asp-controller="Home" asp-action="Index">FTP_Services</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Index">Home</a>
</li>
<li class="nav-item">
<a class="nav-link text-dark" asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</li>
</ul>
</div>
</div>
</nav>
</header>
<div class="container">
<main role="main" class="pb-3">
@RenderBody()
</main>
</div>
<footer class="border-top footer text-muted">
<div class="container">
&copy; 2023 - FTP_Services - <a asp-area="" asp-controller="Home" asp-action="Privacy">Privacy</a>
</div>
</footer>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>
/* Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification
for details on configuring this project to bundle and minify static web assets. */
a.navbar-brand {
white-space: normal;
text-align: center;
word-break: break-all;
}
a {
color: #0077cc;
}
.btn-primary {
color: #fff;
background-color: #1b6ec2;
border-color: #1861ac;
}
.nav-pills .nav-link.active, .nav-pills .show > .nav-link {
color: #fff;
background-color: #1b6ec2;
border-color: #1861ac;
}
.border-top {
border-top: 1px solid #e5e5e5;
}
.border-bottom {
border-bottom: 1px solid #e5e5e5;
}
.box-shadow {
box-shadow: 0 .25rem .75rem rgba(0, 0, 0, .05);
}
button.accept-policy {
font-size: 1rem;
line-height: inherit;
}
.footer {
position: absolute;
bottom: 0;
width: 100%;
white-space: nowrap;
line-height: 60px;
}
{
"AppSettings": {
"ConnectionString": "SERVER=192.168.7.207;PORT=5432;UID=ff4dbuser;PWD=dbuser4ff123!;Database=fernandez_uat_20240913;Timeout=1000",
"FTPConfiguration": {
"Username": "fernandez",
"Password": "fernandez123!",
"FtpURL": "ftp://192.168.7.104/",
"FTPMODE": false,
"DestinationPath": "D:\\FTPRoot\\Fernandez"
}
},
"https_port": 8001,
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
html {
font-size: 14px;
}
@media (min-width: 768px) {
html {
font-size: 16px;
}
}
html {
position: relative;
min-height: 100%;
}
body {
margin-bottom: 60px;
}
\ No newline at end of file
<html>
<head>
<title>FTP API</title>
</head>
<body>
<h1>Welcome to FTP API</h1>
</body>
</html>
\ No newline at end of file
// Please see documentation at https://docs.microsoft.com/aspnet/core/client-side/bundling-and-minification
// for details on configuring this project to bundle and minify static web assets.
// Write your JavaScript code.
The MIT License (MIT)
Copyright (c) 2011-2021 Twitter, Inc.
Copyright (c) 2011-2021 The Bootstrap Authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Copyright (c) .NET Foundation. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
these files except in compliance with the License. You may obtain a copy of the
License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
// Unobtrusive validation support library for jQuery and jQuery Validate
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// @version v3.2.11
/*jslint white: true, browser: true, onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: false */
/*global document: false, jQuery: false */
(function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define("jquery.validate.unobtrusive", ['jquery-validation'], factory);
} else if (typeof module === 'object' && module.exports) {
// CommonJS-like environments that support module.exports
module.exports = factory(require('jquery-validation'));
} else {
// Browser global
jQuery.validator.unobtrusive = factory(jQuery);
}
}(function ($) {
var $jQval = $.validator,
adapters,
data_validation = "unobtrusiveValidation";
function setValidationValues(options, ruleName, value) {
options.rules[ruleName] = value;
if (options.message) {
options.messages[ruleName] = options.message;
}
}
function splitAndTrim(value) {
return value.replace(/^\s+|\s+$/g, "").split(/\s*,\s*/g);
}
function escapeAttributeValue(value) {
// As mentioned on http://api.jquery.com/category/selectors/
return value.replace(/([!"#$%&'()*+,./:;<=>?@\[\\\]^`{|}~])/g, "\\$1");
}
function getModelPrefix(fieldName) {
return fieldName.substr(0, fieldName.lastIndexOf(".") + 1);
}
function appendModelPrefix(value, prefix) {
if (value.indexOf("*.") === 0) {
value = value.replace("*.", prefix);
}
return value;
}
function onError(error, inputElement) { // 'this' is the form element
var container = $(this).find("[data-valmsg-for='" + escapeAttributeValue(inputElement[0].name) + "']"),
replaceAttrValue = container.attr("data-valmsg-replace"),
replace = replaceAttrValue ? $.parseJSON(replaceAttrValue) !== false : null;
container.removeClass("field-validation-valid").addClass("field-validation-error");
error.data("unobtrusiveContainer", container);
if (replace) {
container.empty();
error.removeClass("input-validation-error").appendTo(container);
}
else {
error.hide();
}
}
function onErrors(event, validator) { // 'this' is the form element
var container = $(this).find("[data-valmsg-summary=true]"),
list = container.find("ul");
if (list && list.length && validator.errorList.length) {
list.empty();
container.addClass("validation-summary-errors").removeClass("validation-summary-valid");
$.each(validator.errorList, function () {
$("<li />").html(this.message).appendTo(list);
});
}
}
function onSuccess(error) { // 'this' is the form element
var container = error.data("unobtrusiveContainer");
if (container) {
var replaceAttrValue = container.attr("data-valmsg-replace"),
replace = replaceAttrValue ? $.parseJSON(replaceAttrValue) : null;
container.addClass("field-validation-valid").removeClass("field-validation-error");
error.removeData("unobtrusiveContainer");
if (replace) {
container.empty();
}
}
}
function onReset(event) { // 'this' is the form element
var $form = $(this),
key = '__jquery_unobtrusive_validation_form_reset';
if ($form.data(key)) {
return;
}
// Set a flag that indicates we're currently resetting the form.
$form.data(key, true);
try {
$form.data("validator").resetForm();
} finally {
$form.removeData(key);
}
$form.find(".validation-summary-errors")
.addClass("validation-summary-valid")
.removeClass("validation-summary-errors");
$form.find(".field-validation-error")
.addClass("field-validation-valid")
.removeClass("field-validation-error")
.removeData("unobtrusiveContainer")
.find(">*") // If we were using valmsg-replace, get the underlying error
.removeData("unobtrusiveContainer");
}
function validationInfo(form) {
var $form = $(form),
result = $form.data(data_validation),
onResetProxy = $.proxy(onReset, form),
defaultOptions = $jQval.unobtrusive.options || {},
execInContext = function (name, args) {
var func = defaultOptions[name];
func && $.isFunction(func) && func.apply(form, args);
};
if (!result) {
result = {
options: { // options structure passed to jQuery Validate's validate() method
errorClass: defaultOptions.errorClass || "input-validation-error",
errorElement: defaultOptions.errorElement || "span",
errorPlacement: function () {
onError.apply(form, arguments);
execInContext("errorPlacement", arguments);
},
invalidHandler: function () {
onErrors.apply(form, arguments);
execInContext("invalidHandler", arguments);
},
messages: {},
rules: {},
success: function () {
onSuccess.apply(form, arguments);
execInContext("success", arguments);
}
},
attachValidation: function () {
$form
.off("reset." + data_validation, onResetProxy)
.on("reset." + data_validation, onResetProxy)
.validate(this.options);
},
validate: function () { // a validation function that is called by unobtrusive Ajax
$form.validate();
return $form.valid();
}
};
$form.data(data_validation, result);
}
return result;
}
$jQval.unobtrusive = {
adapters: [],
parseElement: function (element, skipAttach) {
/// <summary>
/// Parses a single HTML element for unobtrusive validation attributes.
/// </summary>
/// <param name="element" domElement="true">The HTML element to be parsed.</param>
/// <param name="skipAttach" type="Boolean">[Optional] true to skip attaching the
/// validation to the form. If parsing just this single element, you should specify true.
/// If parsing several elements, you should specify false, and manually attach the validation
/// to the form when you are finished. The default is false.</param>
var $element = $(element),
form = $element.parents("form")[0],
valInfo, rules, messages;
if (!form) { // Cannot do client-side validation without a form
return;
}
valInfo = validationInfo(form);
valInfo.options.rules[element.name] = rules = {};
valInfo.options.messages[element.name] = messages = {};
$.each(this.adapters, function () {
var prefix = "data-val-" + this.name,
message = $element.attr(prefix),
paramValues = {};
if (message !== undefined) { // Compare against undefined, because an empty message is legal (and falsy)
prefix += "-";
$.each(this.params, function () {
paramValues[this] = $element.attr(prefix + this);
});
this.adapt({
element: element,
form: form,
message: message,
params: paramValues,
rules: rules,
messages: messages
});
}
});
$.extend(rules, { "__dummy__": true });
if (!skipAttach) {
valInfo.attachValidation();
}
},
parse: function (selector) {
/// <summary>
/// Parses all the HTML elements in the specified selector. It looks for input elements decorated
/// with the [data-val=true] attribute value and enables validation according to the data-val-*
/// attribute values.
/// </summary>
/// <param name="selector" type="String">Any valid jQuery selector.</param>
// $forms includes all forms in selector's DOM hierarchy (parent, children and self) that have at least one
// element with data-val=true
var $selector = $(selector),
$forms = $selector.parents()
.addBack()
.filter("form")
.add($selector.find("form"))
.has("[data-val=true]");
$selector.find("[data-val=true]").each(function () {
$jQval.unobtrusive.parseElement(this, true);
});
$forms.each(function () {
var info = validationInfo(this);
if (info) {
info.attachValidation();
}
});
}
};
adapters = $jQval.unobtrusive.adapters;
adapters.add = function (adapterName, params, fn) {
/// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation.</summary>
/// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
/// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
/// <param name="params" type="Array" optional="true">[Optional] An array of parameter names (strings) that will
/// be extracted from the data-val-nnnn-mmmm HTML attributes (where nnnn is the adapter name, and
/// mmmm is the parameter name).</param>
/// <param name="fn" type="Function">The function to call, which adapts the values from the HTML
/// attributes into jQuery Validate rules and/or messages.</param>
/// <returns type="jQuery.validator.unobtrusive.adapters" />
if (!fn) { // Called with no params, just a function
fn = params;
params = [];
}
this.push({ name: adapterName, params: params, adapt: fn });
return this;
};
adapters.addBool = function (adapterName, ruleName) {
/// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
/// the jQuery Validate validation rule has no parameter values.</summary>
/// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
/// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
/// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value
/// of adapterName will be used instead.</param>
/// <returns type="jQuery.validator.unobtrusive.adapters" />
return this.add(adapterName, function (options) {
setValidationValues(options, ruleName || adapterName, true);
});
};
adapters.addMinMax = function (adapterName, minRuleName, maxRuleName, minMaxRuleName, minAttribute, maxAttribute) {
/// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
/// the jQuery Validate validation has three potential rules (one for min-only, one for max-only, and
/// one for min-and-max). The HTML parameters are expected to be named -min and -max.</summary>
/// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
/// in the data-val-nnnn HTML attribute (where nnnn is the adapter name).</param>
/// <param name="minRuleName" type="String">The name of the jQuery Validate rule to be used when you only
/// have a minimum value.</param>
/// <param name="maxRuleName" type="String">The name of the jQuery Validate rule to be used when you only
/// have a maximum value.</param>
/// <param name="minMaxRuleName" type="String">The name of the jQuery Validate rule to be used when you
/// have both a minimum and maximum value.</param>
/// <param name="minAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that
/// contains the minimum value. The default is "min".</param>
/// <param name="maxAttribute" type="String" optional="true">[Optional] The name of the HTML attribute that
/// contains the maximum value. The default is "max".</param>
/// <returns type="jQuery.validator.unobtrusive.adapters" />
return this.add(adapterName, [minAttribute || "min", maxAttribute || "max"], function (options) {
var min = options.params.min,
max = options.params.max;
if (min && max) {
setValidationValues(options, minMaxRuleName, [min, max]);
}
else if (min) {
setValidationValues(options, minRuleName, min);
}
else if (max) {
setValidationValues(options, maxRuleName, max);
}
});
};
adapters.addSingleVal = function (adapterName, attribute, ruleName) {
/// <summary>Adds a new adapter to convert unobtrusive HTML into a jQuery Validate validation, where
/// the jQuery Validate validation rule has a single value.</summary>
/// <param name="adapterName" type="String">The name of the adapter to be added. This matches the name used
/// in the data-val-nnnn HTML attribute(where nnnn is the adapter name).</param>
/// <param name="attribute" type="String">[Optional] The name of the HTML attribute that contains the value.
/// The default is "val".</param>
/// <param name="ruleName" type="String" optional="true">[Optional] The name of the jQuery Validate rule. If not provided, the value
/// of adapterName will be used instead.</param>
/// <returns type="jQuery.validator.unobtrusive.adapters" />
return this.add(adapterName, [attribute || "val"], function (options) {
setValidationValues(options, ruleName || adapterName, options.params[attribute]);
});
};
$jQval.addMethod("__dummy__", function (value, element, params) {
return true;
});
$jQval.addMethod("regex", function (value, element, params) {
var match;
if (this.optional(element)) {
return true;
}
match = new RegExp(params).exec(value);
return (match && (match.index === 0) && (match[0].length === value.length));
});
$jQval.addMethod("nonalphamin", function (value, element, nonalphamin) {
var match;
if (nonalphamin) {
match = value.match(/\W/g);
match = match && match.length >= nonalphamin;
}
return match;
});
if ($jQval.methods.extension) {
adapters.addSingleVal("accept", "mimtype");
adapters.addSingleVal("extension", "extension");
} else {
// for backward compatibility, when the 'extension' validation method does not exist, such as with versions
// of JQuery Validation plugin prior to 1.10, we should use the 'accept' method for
// validating the extension, and ignore mime-type validations as they are not supported.
adapters.addSingleVal("extension", "extension", "accept");
}
adapters.addSingleVal("regex", "pattern");
adapters.addBool("creditcard").addBool("date").addBool("digits").addBool("email").addBool("number").addBool("url");
adapters.addMinMax("length", "minlength", "maxlength", "rangelength").addMinMax("range", "min", "max", "range");
adapters.addMinMax("minlength", "minlength").addMinMax("maxlength", "minlength", "maxlength");
adapters.add("equalto", ["other"], function (options) {
var prefix = getModelPrefix(options.element.name),
other = options.params.other,
fullOtherName = appendModelPrefix(other, prefix),
element = $(options.form).find(":input").filter("[name='" + escapeAttributeValue(fullOtherName) + "']")[0];
setValidationValues(options, "equalTo", element);
});
adapters.add("required", function (options) {
// jQuery Validate equates "required" with "mandatory" for checkbox elements
if (options.element.tagName.toUpperCase() !== "INPUT" || options.element.type.toUpperCase() !== "CHECKBOX") {
setValidationValues(options, "required", true);
}
});
adapters.add("remote", ["url", "type", "additionalfields"], function (options) {
var value = {
url: options.params.url,
type: options.params.type || "GET",
data: {}
},
prefix = getModelPrefix(options.element.name);
$.each(splitAndTrim(options.params.additionalfields || options.element.name), function (i, fieldName) {
var paramName = appendModelPrefix(fieldName, prefix);
value.data[paramName] = function () {
var field = $(options.form).find(":input").filter("[name='" + escapeAttributeValue(paramName) + "']");
// For checkboxes and radio buttons, only pick up values from checked fields.
if (field.is(":checkbox")) {
return field.filter(":checked").val() || field.filter(":hidden").val() || '';
}
else if (field.is(":radio")) {
return field.filter(":checked").val() || '';
}
return field.val();
};
});
setValidationValues(options, "remote", value);
});
adapters.add("password", ["min", "nonalphamin", "regex"], function (options) {
if (options.params.min) {
setValidationValues(options, "minlength", options.params.min);
}
if (options.params.nonalphamin) {
setValidationValues(options, "nonalphamin", options.params.nonalphamin);
}
if (options.params.regex) {
setValidationValues(options, "regex", options.params.regex);
}
});
adapters.add("fileextensions", ["extensions"], function (options) {
setValidationValues(options, "extension", options.params.extensions);
});
$(function () {
$jQval.unobtrusive.parse(document);
});
return $jQval.unobtrusive;
}));
// Unobtrusive validation support library for jQuery and jQuery Validate
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// @version v3.2.11
!function(a){"function"==typeof define&&define.amd?define("jquery.validate.unobtrusive",["jquery-validation"],a):"object"==typeof module&&module.exports?module.exports=a(require("jquery-validation")):jQuery.validator.unobtrusive=a(jQuery)}(function(a){function e(a,e,n){a.rules[e]=n,a.message&&(a.messages[e]=a.message)}function n(a){return a.replace(/^\s+|\s+$/g,"").split(/\s*,\s*/g)}function t(a){return a.replace(/([!"#$%&'()*+,.\/:;<=>?@\[\\\]^`{|}~])/g,"\\$1")}function r(a){return a.substr(0,a.lastIndexOf(".")+1)}function i(a,e){return 0===a.indexOf("*.")&&(a=a.replace("*.",e)),a}function o(e,n){var r=a(this).find("[data-valmsg-for='"+t(n[0].name)+"']"),i=r.attr("data-valmsg-replace"),o=i?a.parseJSON(i)!==!1:null;r.removeClass("field-validation-valid").addClass("field-validation-error"),e.data("unobtrusiveContainer",r),o?(r.empty(),e.removeClass("input-validation-error").appendTo(r)):e.hide()}function d(e,n){var t=a(this).find("[data-valmsg-summary=true]"),r=t.find("ul");r&&r.length&&n.errorList.length&&(r.empty(),t.addClass("validation-summary-errors").removeClass("validation-summary-valid"),a.each(n.errorList,function(){a("<li />").html(this.message).appendTo(r)}))}function s(e){var n=e.data("unobtrusiveContainer");if(n){var t=n.attr("data-valmsg-replace"),r=t?a.parseJSON(t):null;n.addClass("field-validation-valid").removeClass("field-validation-error"),e.removeData("unobtrusiveContainer"),r&&n.empty()}}function l(e){var n=a(this),t="__jquery_unobtrusive_validation_form_reset";if(!n.data(t)){n.data(t,!0);try{n.data("validator").resetForm()}finally{n.removeData(t)}n.find(".validation-summary-errors").addClass("validation-summary-valid").removeClass("validation-summary-errors"),n.find(".field-validation-error").addClass("field-validation-valid").removeClass("field-validation-error").removeData("unobtrusiveContainer").find(">*").removeData("unobtrusiveContainer")}}function u(e){var n=a(e),t=n.data(v),r=a.proxy(l,e),i=f.unobtrusive.options||{},u=function(n,t){var r=i[n];r&&a.isFunction(r)&&r.apply(e,t)};return t||(t={options:{errorClass:i.errorClass||"input-validation-error",errorElement:i.errorElement||"span",errorPlacement:function(){o.apply(e,arguments),u("errorPlacement",arguments)},invalidHandler:function(){d.apply(e,arguments),u("invalidHandler",arguments)},messages:{},rules:{},success:function(){s.apply(e,arguments),u("success",arguments)}},attachValidation:function(){n.off("reset."+v,r).on("reset."+v,r).validate(this.options)},validate:function(){return n.validate(),n.valid()}},n.data(v,t)),t}var m,f=a.validator,v="unobtrusiveValidation";return f.unobtrusive={adapters:[],parseElement:function(e,n){var t,r,i,o=a(e),d=o.parents("form")[0];d&&(t=u(d),t.options.rules[e.name]=r={},t.options.messages[e.name]=i={},a.each(this.adapters,function(){var n="data-val-"+this.name,t=o.attr(n),s={};void 0!==t&&(n+="-",a.each(this.params,function(){s[this]=o.attr(n+this)}),this.adapt({element:e,form:d,message:t,params:s,rules:r,messages:i}))}),a.extend(r,{__dummy__:!0}),n||t.attachValidation())},parse:function(e){var n=a(e),t=n.parents().addBack().filter("form").add(n.find("form")).has("[data-val=true]");n.find("[data-val=true]").each(function(){f.unobtrusive.parseElement(this,!0)}),t.each(function(){var a=u(this);a&&a.attachValidation()})}},m=f.unobtrusive.adapters,m.add=function(a,e,n){return n||(n=e,e=[]),this.push({name:a,params:e,adapt:n}),this},m.addBool=function(a,n){return this.add(a,function(t){e(t,n||a,!0)})},m.addMinMax=function(a,n,t,r,i,o){return this.add(a,[i||"min",o||"max"],function(a){var i=a.params.min,o=a.params.max;i&&o?e(a,r,[i,o]):i?e(a,n,i):o&&e(a,t,o)})},m.addSingleVal=function(a,n,t){return this.add(a,[n||"val"],function(r){e(r,t||a,r.params[n])})},f.addMethod("__dummy__",function(a,e,n){return!0}),f.addMethod("regex",function(a,e,n){var t;return!!this.optional(e)||(t=new RegExp(n).exec(a),t&&0===t.index&&t[0].length===a.length)}),f.addMethod("nonalphamin",function(a,e,n){var t;return n&&(t=a.match(/\W/g),t=t&&t.length>=n),t}),f.methods.extension?(m.addSingleVal("accept","mimtype"),m.addSingleVal("extension","extension")):m.addSingleVal("extension","extension","accept"),m.addSingleVal("regex","pattern"),m.addBool("creditcard").addBool("date").addBool("digits").addBool("email").addBool("number").addBool("url"),m.addMinMax("length","minlength","maxlength","rangelength").addMinMax("range","min","max","range"),m.addMinMax("minlength","minlength").addMinMax("maxlength","minlength","maxlength"),m.add("equalto",["other"],function(n){var o=r(n.element.name),d=n.params.other,s=i(d,o),l=a(n.form).find(":input").filter("[name='"+t(s)+"']")[0];e(n,"equalTo",l)}),m.add("required",function(a){"INPUT"===a.element.tagName.toUpperCase()&&"CHECKBOX"===a.element.type.toUpperCase()||e(a,"required",!0)}),m.add("remote",["url","type","additionalfields"],function(o){var d={url:o.params.url,type:o.params.type||"GET",data:{}},s=r(o.element.name);a.each(n(o.params.additionalfields||o.element.name),function(e,n){var r=i(n,s);d.data[r]=function(){var e=a(o.form).find(":input").filter("[name='"+t(r)+"']");return e.is(":checkbox")?e.filter(":checked").val()||e.filter(":hidden").val()||"":e.is(":radio")?e.filter(":checked").val()||"":e.val()}}),e(o,"remote",d)}),m.add("password",["min","nonalphamin","regex"],function(a){a.params.min&&e(a,"minlength",a.params.min),a.params.nonalphamin&&e(a,"nonalphamin",a.params.nonalphamin),a.params.regex&&e(a,"regex",a.params.regex)}),m.add("fileextensions",["extensions"],function(a){e(a,"extension",a.params.extensions)}),a(function(){f.unobtrusive.parse(document)}),f.unobtrusive});
The MIT License (MIT)
=====================
Copyright Jörn Zaefferer
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Copyright JS Foundation and other contributors, https://js.foundation/
This software consists of voluntary contributions made by many
individuals. For exact contribution history, see the revision history
available at https://github.com/jquery/jquery
The following license applies to all parts of this software except as
documented below:
====
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
====
All files located in the node_modules and external directories are
externally maintained libraries used by this software which have their
own licenses; we recommend you read them, as their terms may differ from
the terms above.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment