how to check if file exist in a folder on ftp in c# - winforms

i want to check if some files exists in a folder on ftp then do specific task
i have the following methos for files check
public static bool CheckFileExistOnFTP(string ServerUri, string FTPUserName, string FTPPassword)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ServerUri);
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
request.Credentials = new NetworkCredential(FTPUserName, FTPPassword);
//request.Method = WebRequestMethods.Ftp.GetFileSize;
// request.Method = WebRequestMethods.Ftp.GetDateTimestamp;
try
{
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
return true;
}
catch (WebException ex)
{
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
return false;
}
}
return true;
}
and i call that method on formload
if (FTPUtility.CheckFileExistOnFTP("ftp://ip address/Requests/", "edexcrawler", "edexcrawler123"))
{
btnUploadRequest.Visible = true;
btnUploadRequest.BackColor = System.Drawing.Color.LightGreen;
btnUploadRequest.ForeColor = System.Drawing.Color.Blue;
}

Based on your other question to get a list of files from ftp, you can check if the file you want to check is in that list:
Var fileNameToCkeck = "myfile.txt";
var utility= new FtpUtility();
utility.UserName = "...";
utility.Password = "...";
utility.Path = "...";
If (utility.ListFiles().Contains(fileNameToCkeck))
{
//The file exists
}
Or if you want to know if that path has any file:
If (utility.ListFiles().Count() > 0)
{
//The folder contains files
}
And here is the code for FtpUtility
public class FtpUtility
{
public string UserName { get; set; }
public string Password { get; set; }
public string Path { get; set; }
public List<string> ListFiles()
{
var request = (FtpWebRequest)WebRequest.Create(Path);
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
request.Credentials = new NetworkCredential(UserName, Password);
List<string> files = new List<string>();
using (var response = (FtpWebResponse)request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
var reader = new StreamReader(responseStream);
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (string.IsNullOrWhiteSpace(line) == false)
{
var fileName = line.Split(new[] { ' ', '\t' }).Last();
if (!fileName.StartsWith("."))
files.Add(fileName);
}
}
return files;
}
}
}
}

Related

jwt value is null but cookie have value how can I check?

this controller login
[EnableCors("AllowOrigin")]
[HttpPost("login")]
public IActionResult Login(string aimUserMail, string aimUserPassword)
{
var user = _sql.AimUsers.SingleOrDefault(x => x.AimUserMail == aimUserMail && x.AimUserPassword == aimUserPassword);
return BadRequest(error: new { message = "UserEmail or password is not correct" });
//}
if (user == null)
{
return BadRequest(error: new { message = "UserEmail or password is not correct ...." });
}
var jwt = this.jwt.Generete(user.AimUserId);
Response.Cookies.Append("jwt",jwt, new CookieOptions
{
HttpOnly = true,
SameSite = SameSiteMode.None,
Secure = true
});
return Ok(user);
}
this is controller check auth :
[HttpGet("user")]
public IActionResult User()
{
try
{
var jwt = Request.Cookies["jwt"];
var token = this.jwt.Verify(jwt);
int aimUserId = int.Parse(token.Issuer);
var user = _sql.AimUsers.SingleOrDefault(x => x.AimUserId == aimUserId);
return Ok(user);
}
catch (Exception e)
{
return Unauthorized();
}
}
Your jwt is null, seems you have add return method in your login function.
If you want get all cookie, you can try below code. Then you can check what you want.
[HttpGet("GetAllCookie")]
public IActionResult GetCookie()
{
int count = Request.Cookies.Count;
var CookiesArray = Request.Cookies.Keys.ToArray();
List<CookieObj> list = new List<CookieObj>();
CookieObj o;
for (int i = 0; i < count; i++)
{
o = new CookieObj();
string cookieKey = CookiesArray[i];
o.cookiename = cookieKey;
o.cookievalue = Request.Cookies[cookieKey];
list.Add(o);
}
return Ok(list);
}
public class CookieObj {
public string cookiename { get; set; }
public string cookievalue { get; set; }
}

WPF Binding not working unless used with async code

I have a Label with the Content property bound to a string on a ViewModel (Prism/MVVM). When I run this method, assigning "pending" to that string, the value changes, but the view never updates. It does update on the second assignment ("success") though.
I fiddled around trying to force an update with RaisePropertyChanged with no success then tried running parts of the code async. That worked!?! - but I have no clue why. Any Idieas on this problem? Any remedy without the async workaround?
XAML:
<Label
Content="{Binding DbaseCreateSuccess, UpdateSourceTrigger=PropertyChanged}">
</Label>
Method sync:
private void DbaseCreate()
{
DbaseCreateSuccess = "pending";
string[] files = Directory.GetFiles("Scripts", "*.*", SearchOption.AllDirectories);
String databaseName = "testbase";
String databaseScript = "testbase.sql";
int fileCount = 0;
foreach (String file in files)
{
if (file.Contains(databaseScript))
{
DataService.Runscript(file);
}
}
foreach (String file in files)
{
FileInfo info = new FileInfo(file);
Trace.WriteLine("FileExtension: " + info.Extension);
if (info.Extension == ".sql" && !file.Contains(databaseScript))
{
++fileCount;
DataService.Runscript(file, databaseName);
}
}
if (DataService.GetTableNames(databaseName).Count == fileCount)
{
DbaseCreateSuccess = "success";
}
Method async:
private async void DbaseCreate()
{
DbaseCreateSuccess = "pending";
string[] files = Directory.GetFiles("Scripts", "*.*", SearchOption.AllDirectories);
String databaseName = "testbase";
String databaseScript = "testbase.sql";
int fileCount = 0;
await Task.Factory.StartNew(() =>
{
foreach (String file in files)
{
if (file.Contains(databaseScript))
{
DataService.Runscript(file);
}
}
foreach (String file in files)
{
FileInfo info = new FileInfo(file);
Trace.WriteLine("FileExtension: " + info.Extension);
if (info.Extension == ".sql" && !file.Contains(databaseScript))
{
++fileCount;
DataService.Runscript(file, databaseName);
}
}
});
if (DataService.GetTableNames(databaseName).Count == fileCount)
{
DbaseCreateSuccess = "success";
}
}
ViewModel:
public class DatabaseAdminViewModel : BindableBase
{
private readonly IUnityContainer _container;
private readonly IRegionManager _regionManager;
private String _DbaseCreateSuccess;
public String DbaseCreateSuccess { get { return _DbaseCreateSuccess; } set { SetProperty(ref _DbaseCreateSuccess, value, "DbaseCreateSuccess"); } }
public DelegateCommand DbaseCreateCommand { get; set; }
public DatabaseAdminViewModel(IUnityContainer container, IRegionManager regionManager)
{
_regionManager = regionManager;
_container = container;
DbaseCreateSuccess = "idle";
DbaseCreateCommand = new DelegateCommand(DbaseCreate);
}
private async void DbaseCreate()
{
DbaseCreateSuccess = "pending";
string[] files = Directory.GetFiles("Scripts", "*.*", SearchOption.AllDirectories);
String databaseName = "testbase";
String databaseScript = "testbase.sql";
int fileCount = 0;
await Task.Factory.StartNew(() =>
{
foreach (String file in files)
{
if (file.Contains(databaseScript))
{
DataService.Runscript(file);
}
}
foreach (String file in files)
{
FileInfo info = new FileInfo(file);
Trace.WriteLine("FileExtension: " + info.Extension);
if (info.Extension == ".sql" && !file.Contains(databaseScript))
{
++fileCount;
DataService.Runscript(file, databaseName);
}
}
});
if (DataService.GetTableNames(databaseName).Count == fileCount)
{
DbaseCreateSuccess = "success";
}
}
}

Error inserting data from many method return lists to a database in c#

I need help here with part of my code so here it is:
I have 6 methods as you can see below that parse incoming data and then returns it as a list, so my issue is to send that list data to my database table SerialNumber, each method of the lists is a separate field that will fill a database column.
So for example the parse material will fill the database materiallookupcode column and the same for the others.
Here is an image of the database table
Here is the code of all 5 methods that reads the data and then returns it and I need this data send to my database
private List<string> ParseMaterial()
{
var materialList = new List<string>();
foreach (var material in _connection.GetBarcodeList())
{
materialList.Add(material.Substring(10, 5));
}
return materialList;
}
private List<string> ParseLot()
{
var lotList = new List<string>();
var establishmentList = GetEstablishmentCode();
foreach (var lot in _connection.GetBarcodeList())
{
if (establishmentList.Contains("038"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.LoganSport038Property);
}
if (establishmentList.Contains("072"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.LouisaCounty072Property);
}
if (establishmentList.Contains("086"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.Madison086Property);
}
if (establishmentList.Contains("089"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.Perry089Property);
}
if (establishmentList.Contains("069"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.StormLake069Property);
}
if (establishmentList.Contains("088"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.Waterloo088Property);
}
if (establishmentList.Contains("265"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.GoodLetsVille265Property);
}
if (establishmentList.Contains("087"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.CouncilBluffs087Property);
}
if (establishmentList.Contains("064"))
{
lotList.Add(lot.Substring(28, 6) + _lotEstablishment.Sherman064Property);
}
}
return lotList;
}
private List<string> ParseSerialNumber()
{
var serialNumberList = new List<string>();
foreach (var serialNumber in _connection.GetBarcodeList())
{
serialNumberList.Add(serialNumber.Substring(36, 10));
}
return serialNumberList;
}
public List<string> ParseNetWeight()
{
var netWeightList = new List<string>();
foreach (var netWeight in _connection.GetBarcodeList())
{
netWeightList.Add(netWeight.Substring(22, 4));
}
return netWeightList;
}
public List<string> ParseGrossWeight()
{
var grossWeightList = new List<string>();
foreach (var grossWeight in _connection.GetBarcodeList())
{
grossWeightList.Add(grossWeight.Substring(22, 4));
}
return grossWeightList;
}
public List<string> FullBarcode()
{
var receiveFullBarcodeList = new List<string>();
foreach (var fullBarcode in _connection.GetBarcodeList())
{
receiveFullBarcodeList.Add(fullBarcode);
}
return receiveFullBarcodeList;
}
public List<string> GetEstablishmentCode()
{
var establishmentList = new List<string>();
foreach (var establishmentCode in _connection.GetBarcodeList())
{
establishmentList.Add(establishmentCode.Substring(36, 3));
}
return establishmentList;
}
The issue is here the button when clicking will read all 5 methods and send it to the database, I am sure the part where I making the list of variables to a string and the separator part is wrong so I need how is the correct way to add those list to each column of the database
private async void btn_SubmitData_Click(object sender, EventArgs e)
{
// parse list methodss
var materialList = ParseMaterial();
var lotList = ParseLot();
var netWeightList = ParseNetWeight();
var grossWeightList = ParseGrossWeight();
var serialNumberList = ParseSerialNumber();
var fullSerialNumberList = FullBarcode();
var material = "";
var lot = "";
var net = "";
var gross = "";
var serial = "";
var fullSerial = "";
var currentUser = _currentUser.GetCurrentUsernameOnApp();
var licensePlateId = GetLicensePlateIds();
for (var i = 0; i < _connection.GetBarcodeList().Count; i++)
{
material = materialList[i];
lot = lotList[i];
net = netWeightList[i];
gross = grossWeightList[i];
serial = serialNumberList[i];
fullSerial = fullSerialNumberList[i];
}
// database table and columns
var serialNumbersInsert = new List<SerialNumber>
{
new SerialNumber
{
SerialNumberLookupCode = serial,
NetWeight = Convert.ToDecimal(net) / 100,
GrossWeight = Convert.ToDecimal(gross) / 100,
LotLookupCode = lot,
MaterialLookupCode = material,
FullSerialNumberLookupCode = fullSerial,
CreatedSysDateTime = DateTime.Now,
ModifiedSysDateTime = DateTime.Now,
CreatedSysUser = currentUser,
ModifiedSysUser = currentUser,
LicensePlateId = licensePlateId
}
};
// insert to the database
foreach (var list in serialNumbersInsert)
{
_unitOfWork.SerialNumbers.Add(list);
}
await _unitOfWork.Complete();
}
Here is the SerialNumber domain class that represents a database table using a code first migration
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BarcodeReceivingApp.Core.Domain
{
// domain class, represents a database table in sql server using code
// first migration
public class SerialNumber
{
public int Id { get; set; }
public int LicensePlateId { get; set; }
public string FullSerialNumberLookupCode { get; set; }
public string SerialNumberLookupCode { get; set; }
public decimal NetWeight { get; set; }
public decimal GrossWeight { get; set; }
public string LotLookupCode { get; set; }
public string MaterialLookupCode { get; set; }
public DateTime CreatedSysDateTime { get; set; }
public DateTime ModifiedSysDateTime { get; set; }
public string CreatedSysUser { get; set; }
public string ModifiedSysUser { get; set; }
}
}
I search other places but could not find a good solution so far, so any help is appreciate it.
I was able to resolve my question, what I did is to assign all lists in a loop and then assign them to each column in the database.
But I am still searching for a better and more clean way to this solution
private async void btn_SubmitData_Click(object sender, EventArgs e)
{
// parse list methods - represents each field of the database column
var materialList = ParseMaterial();
var lotList = ParseLot();
var netWeightList = ParseNetWeight();
var grossWeightList = ParseGrossWeight();
var serialNumberList = ParseSerialNumber();
var fullSerialNumberList = FullBarcode();
var currentUser = _currentUser.GetCurrentUsernameOnApp();
var licensePlateId = GetLicensePlateIds();
for (var i = 0; i < _connection.GetBarcodeList().Count; i++)
{
var serialNumbersInsert = new List<SerialNumber>
{
new SerialNumber
{
SerialNumberLookupCode = materialList[i],
NetWeight = Convert.ToDecimal(netWeightList[i]) / 100,
GrossWeight = Convert.ToDecimal(grossWeightList[i]) / 100,
LotLookupCode = lotList[i],
MaterialLookupCode = materialList[i],
FullSerialNumberLookupCode = fullSerialNumberList[i],
CreatedSysDateTime = DateTime.Now,
ModifiedSysDateTime = DateTime.Now,
CreatedSysUser = currentUser,
ModifiedSysUser = currentUser,
LicensePlateId = licensePlateId
}
};
foreach (var list in serialNumbersInsert)
{
_unitOfWork.SerialNumbers.Add(list);
}
await _unitOfWork.Complete();
}
}

how to display files from ftp server to a local windows application gridview

i have uploaded my files to ftb server, now i want to display that files in my local windows application gridview
i want to display that files in datagridview.
public List<string> ListFiles()
{
// Get the object used to communicate with the server.
var request = (FtpWebRequest)WebRequest.Create("ftp://ipaddress/Requests/");
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
request.Credentials = new NetworkCredential("username", "password");
List<string> files = new List<string>();
using (var response = (FtpWebResponse)request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
var reader = new StreamReader(responseStream);
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (string.IsNullOrWhiteSpace(line) == false)
{
files.Add(line.Split(new[] { ' ', '\t' }).Last());
}
}
return files;
}
}
}
following is the code on my load form.
FTPItility is my class in which listfiles is a method
FTPUtility obj = new FTPUtility();
List<string> strings = new List<string>();
dataGridViewRequest.DataSource = obj.ListFiles();
Here is the code you can use.
Here is code of FtpUtility:
public class FtpUtility
{
public string UserName { get; set; }
public string Password { get; set; }
public string Path { get; set; }
public List<string> ListFiles()
{
var request = (FtpWebRequest)WebRequest.Create(Path);
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
request.Credentials = new NetworkCredential(UserName, Password);
List<string> files = new List<string>();
using (var response = (FtpWebResponse)request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
var reader = new StreamReader(responseStream);
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (string.IsNullOrWhiteSpace(line) == false)
{
var fileName = line.Split(new[] { ' ', '\t' }).Last();
if (!fileName.StartsWith("."))
files.Add(fileName);
}
}
return files;
}
}
}
}
And here is the code of form:
I have created an instance of FtpUtility and passed requiered parameters to it, then get the files and put it in a friendly list(Name, Path) and bind to grid:
private void Form1_Load(object sender, EventArgs e)
{
this.LoadFiles();
}
public void LoadFiles()
{
var ftp = new FtpUtility();
ftp.UserName = "username";
ftp.Password = "password";
ftp.Path = "ftp://address";
this.dataGridView1.DataSource = ftp.ListFiles()
.Select(x => new
{
Name = x, //Name Column
Path = ftp.Path + x //Path Column
}).ToList();
}

ng-flow file upload in web api

I have seen many examples with ng-flow having the php side server to upload the files. But as I am not an expert in php and I need some help in the webapi, can someone please help me to find a working example or tutorial of ng-flow with webapi files upload.
Thanks everyone.
below is my web-api code to do this
[HttpPost]
public async Task<HttpResponseMessage> SaveFile()
{
if (!Request.Content.IsMimeMultipartContent())
Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
var provider = FileSaver.GetMultipartProvider();
var result = await Request.Content.ReadAsMultipartAsync(provider);
var fileInfo = FileSaver.MoveToTemp(result);
return Request.CreateResponse(HttpStatusCode.OK, fileInfo);
}
it uses the custom FileSaver class
public class FileSaver
{
public static MultipartFormDataStreamProvider GetMultipartProvider()
{
var uploadFolder = //your upload path;
return new MultipartFormDataStreamProvider(uploadFolder);
}
private static string GetDeserializedFileName(MultipartFileData fileData)
{
var fileName = GetFileName(fileData);
return JsonConvert.DeserializeObject(fileName).ToString();
}
private static string GetFileName(MultipartFileData fileData)
{
return fileData.Headers.ContentDisposition.FileName;
}
public static FileInfo MoveToTemp(MultipartFormDataStreamProvider result)
{
var originalFileName = GetDeserializedFileName(result.FileData.First());
var uploadedFileInfo = new FileInfo(result.FileData.First().LocalFileName);
string timestamp = DateTime.UtcNow.ToString("yyyyMMddHHmmssfff", CultureInfo.InvariantCulture);
var folder = Directory.CreateDirectory(**); //your upload path
if (!folder.Exists) folder.Create();
var filename = folder.FullName + #"\" + originalFileName;
MoveFile(uploadedFileInfo, filename);
return uploadedFileInfo;
}
private static void MoveFile(FileInfo fileInfo, string filename)
{
var count = 0;
do
{
try
{
fileInfo.MoveTo(filename);
return;
}
catch (Exception)
{
if (count == 4)
{
throw;
}
count++;
Thread.Sleep(1 * 1000);
}
} while (true);
}
}

Resources