From 43466c85e618c62f1b5e36bb4ef245d69f498f04 Mon Sep 17 00:00:00 2001 From: misya Date: Thu, 8 May 2025 12:15:36 +0800 Subject: [PATCH] fix --- Areas/MMS/Controllers/MarineController.cs | 104 +++++++++++++--------- Areas/MMS/Models/NetworkAccessService.cs | 104 ++++++++++++++-------- Program.cs | 5 +- 3 files changed, 133 insertions(+), 80 deletions(-) diff --git a/Areas/MMS/Controllers/MarineController.cs b/Areas/MMS/Controllers/MarineController.cs index 9a49ca2..2170dc4 100644 --- a/Areas/MMS/Controllers/MarineController.cs +++ b/Areas/MMS/Controllers/MarineController.cs @@ -12,43 +12,15 @@ namespace PSTW_CentralSystem.Areas.MMS.Controllers public class MarineController : Controller { private readonly MMSSystemContext _context; - private readonly NetworkAccessService _networkAccessService; - private const string PhotoBasePath = @"\\192.168.12.42\images\marine\manual_tarball"; + private readonly NetworkShareAccess _networkAccessService; + private const string PhotoBasePath = "\\192.168.12.42\\images\\marine\\manual_tarball"; - public MarineController(MMSSystemContext context, NetworkAccessService networkAccessService) + public MarineController(MMSSystemContext context, NetworkShareAccess networkAccessService) { _context = context; _networkAccessService = networkAccessService; } - private bool TryAccessNetworkPath() //check if the path is accessible - { - try - { - _networkAccessService.ConnectToNetworkShare(PhotoBasePath); - - if (_networkAccessService.DirectoryExists(PhotoBasePath)) - { - Console.WriteLine("Network path is accessible."); - return true; - } - else - { - Console.WriteLine("Network path does not exist."); - } - } - catch (Exception ex) - { - Console.WriteLine($"Error accessing network path: {ex.Message}"); - } - finally - { - _networkAccessService.DisconnectFromNetworkShare(PhotoBasePath); - } - - return false; - } - public IActionResult Index() { return View(); @@ -56,23 +28,58 @@ namespace PSTW_CentralSystem.Areas.MMS.Controllers public IActionResult TarBallForm() { - if (!TryAccessNetworkPath()) + try { - return StatusCode(500, "Unable to access network path."); + var marineTarballs = _context.MarineTarballs + .Where(t => t.StationID != "1") // To remove unusable data with invalid stationID + .Select(t => new + { + t.Id, + Date = t.DateSample.ToString("yyyy/MM/dd"), + Station = t.StationID + }) + .ToList(); + + Console.WriteLine($"Marine Tarballs Count: {marineTarballs.Count}"); + return View(marineTarballs); } + catch (Exception ex) + { + Console.WriteLine($"Error: {ex.Message}"); + return StatusCode(500, "An error occurred while loading the data."); + } + } - var marineTarballs = _context.MarineTarballs - .Where(t => t.StationID != "1") // Remove unusable data - .Select(t => new + + public IActionResult GetImage(string fileName) + { + try + { + // Connect to the network path + _networkAccessService.ConnectToNetworkPath(); + + string imagePath = Path.Combine(PhotoBasePath, fileName); + + if (System.IO.File.Exists(imagePath)) { - t.Id, - Date = t.DateSample.ToString("yyyy/MM/dd"), - Station = t.StationID - }) - .ToList(); - - Console.WriteLine($"Marine Tarballs Count: {marineTarballs.Count}"); - return View(marineTarballs); + byte[] imageBytes = System.IO.File.ReadAllBytes(imagePath); + return File(imageBytes, "image/jpeg"); + } + else + { + return NotFound("Image not found."); + } + } + catch (Exception ex) + { + Console.WriteLine($"Error retrieving image: {ex.Message}"); + return StatusCode(500, "Error retrieving image."); + } + finally + { + // Disconnect from the network path + _networkAccessService.DisconnectFromNetworkShare(); + } } public IActionResult GenerateReport(int id) @@ -91,6 +98,9 @@ namespace PSTW_CentralSystem.Areas.MMS.Controllers try { + // Connect to the network path + _networkAccessService.ConnectToNetworkPath(); + // 1. Fetch core data from database var tarballData = (from marine in _context.MarineTarballs join station in _context.MarineStations on marine.StationID equals station.StationID @@ -225,8 +235,14 @@ namespace PSTW_CentralSystem.Areas.MMS.Controllers Console.WriteLine($"Error: {ex.Message}"); return StatusCode(500, $"PDF generation failed: {ex.Message}"); } + finally + { + // Disconnect from the network path + _networkAccessService.DisconnectFromNetworkShare(); + } } + private bool IsImageValid(string imagePath) { try diff --git a/Areas/MMS/Models/NetworkAccessService.cs b/Areas/MMS/Models/NetworkAccessService.cs index df8f425..a20b14b 100644 --- a/Areas/MMS/Models/NetworkAccessService.cs +++ b/Areas/MMS/Models/NetworkAccessService.cs @@ -1,51 +1,85 @@ using System; using System.IO; using System.Runtime.InteropServices; +using System.Text; -public class NetworkAccessService : IDisposable +public class NetworkShareAccess : IDisposable { - private readonly IConfiguration _config; + private readonly string _networkPath; + private readonly string _username; + private readonly string _password; - public NetworkAccessService(IConfiguration config) + // Constructor to initialize the network path, username, and password + public NetworkShareAccess(string networkPath, string username, string password) { - _config = config; + _networkPath = networkPath; + _username = username; + _password = password; } - public void ConnectToNetworkShare(string networkPath) + // Public method to connect to the network path + public void ConnectToNetworkPath() { - var username = _config["NetworkCredentials:ImageServer:Username"]; - var password = _config["NetworkCredentials:ImageServer:Password"]; - var domain = _config["NetworkCredentials:ImageServer:Domain"] ?? "."; - var netResource = new NetResource { Scope = ResourceScope.GlobalNetwork, ResourceType = ResourceType.Disk, - RemoteName = networkPath + DisplayType = ResourceDisplayType.Share, + RemoteName = _networkPath }; - var result = WNetAddConnection2(netResource, password, username, 0); + var result = WNetAddConnection2(netResource, _password, _username, 0); + if (result != 0) { - throw new Exception($"Failed to connect to {networkPath}. Error code: {result}"); + Console.WriteLine($"Error connecting to network path: {result}"); + throw new IOException($"Error connecting to network path: {result}"); + } + + } + + // Public method to disconnect from the network share + public void DisconnectFromNetworkShare() + { + // Check if the network path is connected + var buffer = new StringBuilder(512); + int bufferSize = buffer.Capacity; + int connectionStatus = WNetGetConnection(_networkPath, buffer, ref bufferSize); + + if (connectionStatus != 0) + { + Console.WriteLine($"Network path {_networkPath} is not connected. Skipping disconnection."); + return; // Exit if the connection does not exist + } + + // Proceed with disconnection + var result = WNetCancelConnection2(_networkPath, 0, true); + + if (result != 0) + { + throw new IOException($"Error disconnecting from network path: {result}"); } } - public void DisconnectFromNetworkShare(string networkPath) - { - WNetCancelConnection2(networkPath, 0, true); - } - - public bool DirectoryExists(string path) - { - return Directory.Exists(path); - } - + // Dispose method to ensure proper cleanup public void Dispose() { - // No impersonation context to clean up, but you can add cleanup logic here if needed. + DisconnectFromNetworkShare(); } + // P/Invoke for adding a network connection + [DllImport("mpr.dll")] + private static extern int WNetAddConnection2(NetResource netResource, string password, string username, int flags); + + // P/Invoke for canceling a network connection + [DllImport("mpr.dll")] + private static extern int WNetCancelConnection2(string name, int flags, bool force); + + // P/Invoke for checking if a network connection exists + [DllImport("mpr.dll")] + private static extern int WNetGetConnection(string localName, StringBuilder remoteName, ref int length); + + // Struct for network resource [StructLayout(LayoutKind.Sequential)] private class NetResource { @@ -59,33 +93,33 @@ public class NetworkAccessService : IDisposable public string Provider; } - private enum ResourceScope : int + // Enum for resource scope + private enum ResourceScope { Connected = 1, - GlobalNetwork = 2, - Remembered = 3, + GlobalNetwork, + Remembered, + Recent, + Context } - private enum ResourceType : int + // Enum for resource type + private enum ResourceType { Any = 0, Disk = 1, Print = 2, + Reserved = 8 } - private enum ResourceDisplayType : int + // Enum for resource display type + private enum ResourceDisplayType { Generic = 0x0, Domain = 0x01, Server = 0x02, Share = 0x03, File = 0x04, - Group = 0x05, + Group = 0x05 } - - [DllImport("mpr.dll")] - private static extern int WNetAddConnection2(NetResource netResource, string password, string username, int flags); - - [DllImport("mpr.dll")] - private static extern int WNetCancelConnection2(string name, int flags, bool force); } diff --git a/Program.cs b/Program.cs index 88bafcf..47c788f 100644 --- a/Program.cs +++ b/Program.cs @@ -22,7 +22,9 @@ internal class Program // Add services to the container. builder.Services.AddControllersWithViews(); builder.Services.AddRazorPages(); - builder.Services.AddScoped(); + builder.Services.AddScoped(provider => + new NetworkShareAccess("\\192.168.12.42\\images\\marine\\manual_tarball", "installer", "mms@pstw")); + Log.Logger = new LoggerConfiguration() .ReadFrom.Configuration(builder.Configuration) @@ -80,6 +82,7 @@ internal class Program // Add scope builder.Services.AddScoped(); + var app = builder.Build(); // Configure the HTTP request pipeline.