DownloadFile stopped downloading file - c#

I have an updater application that is being started when an update is available. This application is simply downloading a new exe to a specified path, but suddenly it is not working anymore. The updater downloads the file with a size of 0kb and does not give any error.
I had uploaded the new exe to the server 2 months ago and many clients downloaded the file successfully. Yesterday, one of my clients noticed when he started working with the application and the update failed. The updater is running on many clients and worked always. Could it be a server issue?
Here is the updater code in C#:
public void StartUpdate()
{
WebClient webclient = new WebClient();
try
{
//webclient.DownloadFile("http://www.example.nl/folder/example.exe", #"C:\example\example.exe");
webclient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webclient_DownloadProgressChanged);
webclient.DownloadFileCompleted += new AsyncCompletedEventHandler(webclient_DownloadFileCompleted);
webclient.DownloadFileAsync(new Uri("http://www.example.nl/folder/example.exe"), #"C:\example\example.exe");
}
catch (Exception)
{
MessageBox.Show("Download Failed.\n\nPlease contact your system administrator");
Application.Exit();
}
}
void webclient_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
label1.Text = "Download successfully!";
label3.Text = "Download complete!";
timer2.Enabled = true; //here some other magic happens like start the program and exit this updater.
}
void webclient_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
progressBar1.Maximum = (int)e.TotalBytesToReceive / 100;
progressBar1.Value = (int)e.BytesReceived / 100;
}
I am running Apache on CentOS where the exe file is stored. Folder/file permission are okay. When I open the exe URL in any browser, the file is being downloaded successfully.
I never change the exe file within the past 2 months nor any other settings on the webserver. This method worked for 2 years and now it automatically stopped working.
UPDATE:
System.Net.WebException: The request has been aborted: Cannot create a secure SSL / TLS channel.
at System.Net.HttpWebRequest.EndGetResponse (IAsyncResult asyncResult)
at System.Net.WebClient.GetWebResponse (WebRequest request, IAsyncResult result)
at System.Net.WebClient.DownloadBitsResponseCallback (IAsyncResult result) A first chance exception or type 'System.ComponentModel.Win32Exception' occurred in System.dll

It seems like your server SSL certifcate is broken. It is possible expired. If you are using a self signed certificate make sure you imported the the CA certiface you used to self sign your servers certificate. An other possibility is that your server (or client) has an invalid system clock. So the client thinks your certificate expired.

The program could not handle secured uri's. I added the following line
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
below this line
webclient.DownloadFileCompleted += new AsyncCompletedEventHandler(webclient_DownloadFileCompleted);
which fixed my problem.

Related

Copy to clipboard in ASP.NET

This copy button functionality is working in localhost. But when deploy it into server it's not working on server side.
protected void btnCopy_Click(object sender, EventArgs e)
{
try
{
Thread myth;
myth = new Thread(new System.Threading.ThreadStart(CallSaveDialog));
myth.ApartmentState = ApartmentState.STA;
myth.Start();
lblok.Text = "URL Copied to Clipboard, Use CTRL+V to Paste";
}
catch (Exception ex)
{
Class_login abc = new Class_login();
abc.writeerrorlog(ex.Message);
}
}
void CallSaveDialog() { System.Windows.Forms.Clipboard.SetText(TxtUrl.Text); }
This code:
System.Windows.Forms.Clipboard.SetText(TxtUrl.Text);
Runs on the web server. It sets the text to the clipboard of the user executing your web application, which usually is someone named IIS AppPool\Sitename. This user is not the visitor of your website, it is the server process that is running your .NET code.
It works on your development machine ("localhost"), because IIS Express runs as your user.
The solution is to do this using JavaScript: How do I copy to the clipboard in JavaScript?

FileSystemWatcher does not inform about events on Samba share [duplicate]

This question already has answers here:
C# FileSystemWatcher Serious Problem?
(4 answers)
FileSystemWatcher with Samba on Linux
(3 answers)
Closed 2 years ago.
I use the FileSystemWatcher in my C# application and this application runs as a Windows Service on my server. The watchers path is a Samba share from another network.
The application works totally fine when the folder path of the watcher is a folder on the Server, but with the shared folder no events are raised - I need to be informed when a file is created in the folder, then I move it to another one, rename it, read it and so on. (I also tried the watcher.Changed event but nothing is happening there either)
I found a similar question here:
FileSystemWatcher with Samba on Linux
Does anybody know if the FSW has still problems with Samba-shared folders?
I already tried to use a StreamReader and StreamWriter to test if I even have access to the shared folder - this works without any problems. I also thought about resetting the EnableRaisingEvents to true if the FSW "breaks" (like it is mentioned in the question above) but I am a bit confused how to even find out if it broke - because I don't get an error, it just does nothing at all.
This is a part of my watcher class, it runs as a BackgroundService:
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
Initialize();
TestAccessability();
RunFileWatcher();
return Task.CompletedTask;
}
private void TestAccessability()
{
// Get the directories currently on the shared drive.
DirectoryInfo[] sDirs = new DirectoryInfo(#"\\10.18.249.8\halit4ind$").GetDirectories();
// Write each directory name to a file.
using (StreamWriter sw = new StreamWriter(importPath + "\\SDriveDirs.txt"))
{
foreach (DirectoryInfo dir in sDirs)
{
sw.WriteLine(dir.Name);
}
}
// Read and show each line from the file.
string line = "";
using (StreamReader sr = new StreamReader(importPath + "\\SDriveDirs.txt"))
{
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
private void RunFileWatcher()
{
logger.LogInformation($"RunFileWatcher watching path {importPath}");
watcher = new FileSystemWatcher
{
Path = #importPath,
Filter = "*.csv"
};
watcher.Created += OnCreated;
watcher.Changed += OnCreated;
watcher.EnableRaisingEvents = true;
}
private void OnCreated(object source, FileSystemEventArgs e)
{
logger.LogInformation($"File {e.FullPath} created/changed - Type: {e.ChangeType}");
if (e.ChangeType == WatcherChangeTypes.Created)
{
var newFilename = TryMoveFileToWork(e.Name);
MoveFileToArchiv(newFilename);
}
}
This is the output I get in the console (I tried creating a file in \10.18.249.8\halit4ind$\Outbox but nothing happens):
pers
Inbox
Outbox
Work
Archiv
[07:19:57 INF] RunFileWatcher watching path \\10.18.249.8\halit4ind$\Outbox
[07:19:57 DBG] Failed to locate the development https certificate at 'null'.
[07:19:57 DBG] Hosting started
[07:19:57 DBG] Loaded hosting startup assembly InfoniqaServiceHali
Hosting environment: Production
Content root path: D:\Services\InfoniqaServiceHali
Now listening on: http://0.0.0.0:7040
Application started. Press Ctrl+C to shut down.
This is the output I get if I use another path:
pers
Inbox
Outbox
Work
Archiv
[08:49:35 INF] RunFileWatcher watching path D:\temp\Outbox
[08:49:35 DBG] Failed to locate the development https certificate at 'null'.
[08:49:35 DBG] Hosting started
[08:49:35 DBG] Loaded hosting startup assembly InfoniqaServiceHali
Hosting environment: Production
Content root path: D:\Services\InfoniqaServiceHali
Now listening on: http://0.0.0.0:7040
Application started. Press Ctrl+C to shut down.
[08:49:44 INF] File D:\temp\Outbox\Personal.csv created/changed - Type: Created
[08:49:44 INF] TryMoveFileToWork Personal.csv

DCOM Object Reference C#

I am trying to add a reference of the remote computer in a local network (computer name or IP address) to a DCOM object. Just for example:
When I do the following it works on the local machine:
private void btnOpnDWSFT_Click(object sender, EventArgs e)
{
DEWEsoft.IApp x = new
DEWEsoft.App();
x.Init();
x.Width = 1000;
x.Height = 800;
x.Visible = true;
}
But where shall I add the reference to the Remote Machine? BTW: The DCOM server is running and is registered on the remote machine and I got it working in LabView somehow (with ActiveX ObjectRef) but I couldn't get it work in C#.
I would like to remote controll SW called DEWEsoft on a different Machine.
Thank you!

Windows Service "Timeout" instantly on startup

I'm currently running in to an issue where a Windows Service I wrote is "timing out" instantly on start up. The message I get is Error 1053: The service did not respond to the start or control request in a timely fashion. I checked Event Viewer and I see that message and another A timeout was reached (30000 milliseconds) while waiting for the X service to connect. Only problem is that it's not waiting 30 seconds to time out, it's more like half a second.
My service's OnStart()
private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private string version = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion;
private string incomingProdFileLocation = ConfigurationManager.AppSettings["ProdIncomingFileLocation"];
private string incomingCertFileLocation = ConfigurationManager.AppSettings["CertIncomingFileLocation"];
//private string incomingCombFileLocation = ConfigurationManager.AppSettings["CombIncomingFileLocation"];
private string processedFileLocation = ConfigurationManager.AppSettings["ProcessedFileLocation"];
private string errorFileLocation = ConfigurationManager.AppSettings["ErrorFileLocation"];
FileSystemWatcher prodWatcher = new FileSystemWatcher();
FileSystemWatcher certWatcher = new FileSystemWatcher();
//FileSystemWatcher combWatcher = new FileSystemWatcher();
protected override void OnStart(string[] args) {
log.InfoFormat("Starting up Merchant Bulk Load Service v{0}", version);
if (verifyDirectories()) {
log.InfoFormat("Initialize Prod FileSystemWatcher() at {0}", incomingProdFileLocation);
prodWatcher.Path = incomingProdFileLocation;
prodWatcher.Filter = "*.csv";
prodWatcher.Created += ProdBulkLoadFileReceived;
prodWatcher.EnableRaisingEvents = true;
log.InfoFormat("Initialize Cert FileSystemWatcher() at {0}", incomingCertFileLocation);
certWatcher.Path = incomingCertFileLocation;
certWatcher.Filter = "*.csv";
certWatcher.Created += CertBulkLoadFileReceived;
certWatcher.EnableRaisingEvents = true;
/*log.InfoFormat("Initialize Comb FileSystemWatcher() at {0}", incomingCombFileLocation);
combWatcher.Path = incomingCombFileLocation;
combWatcher.Filter = "*.csv";
combWatcher.Created += CombBulkLoadFileReceived;
combWatcher.EnableRaisingEvents = true;*/
} else {
log.ErrorFormat("verifyDirectories() returned false. Service stopping");
this.Stop();
}
}
private bool verifyDirectories() {
// verify each of the necessary directories exists before setting up any FileSystemWatcher()s
if (!Directory.Exists(incomingProdFileLocation)) {
log.ErrorFormat("Incoming production file location {0} does not exist. Please create the directory or edit the configuration file.",
incomingProdFileLocation);
return false;
}
if (!Directory.Exists(incomingCertFileLocation)) {
log.ErrorFormat("Incoming cert file location {0} does not exist. Please create the directory or edit the configuration file.",
incomingCertFileLocation);
return false;
}
/*if (!Directory.Exists(incomingCombFileLocation)) {
log.ErrorFormat("Incoming combined file location {0} does not exist. Please create the directory or edit the configuration file.",
incomingCombFileLocation);
return false;
}*/
if (!Directory.Exists(processedFileLocation)) {
log.ErrorFormat("Processed file location {0} does not exist. Please create the directory or edit the configuration file.",
processedFileLocation);
return false;
}
if (!Directory.Exists(errorFileLocation)) {
log.ErrorFormat("Error file location {0} does not exist. Please create the directory or edit the configuration file.",
errorFileLocation);
return false;
}
return true;
}
My entire service works splendidly in our development and certification environments, but won't start in our production environment, it doesn't seem like it's even getting to the OnStart() because a log is never made. Things I've checked:
Made sure service had correct permissions in the necessary directories, it does
Made sure the correct version of .NET framework that my service is targeting (4) is installed, it is
Made sure Event Viewer wasn't throwing any other types of errors that might give me a hint to what's happening, there's nothing
All of the directories for the FileSystemWatcher actually exist, they do
The directory for the log4net file exists, it does
I'm at a loss at the moment; any help would be awesome.
edit
After double checking the .NET framework again I realize I checked the wrong server for the versions. A good way to be certain is to double-click on the actual exe file for the service and see what it says. In my case it literally said "Make sure 4.0 is installed" which prompted me to check again and there I saw that 4.0 wasn't installed.
Are you sure that your .net is up to date. This could happen if for instance 3.5 is on the machine and you're using 4.0.
This is an old ticket, but I just saw the same error (albeit with "90000 milliseconds" rather than 30000) on all of the Windows services we've created as part of our application (about 10 of them). .Net framework was installed and functional.
I examined the registry setting where this 90000 ms (90 second) limit was set.
In the node, HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control
The value of ServicesPipeTimeout was 90000 (Decimal).
I didn't need it to be 90000 and I don't know why it was set thus, but it certainly wasn't waiting 90 seconds -- it was failing instantly.
So I modified the value to 30000 and rebooted the server.
All services begin starting or restarting successfully.

SSH / SFTP connection issue using Tamir.SharpSsh

This is my code to connect and send a file to a remote SFTP server.
public static void SendDocument(string fileName, string host, string remoteFile, string user, string password)
{
Scp scp = new Scp();
scp.OnConnecting += new FileTansferEvent(scp_OnConnecting);
scp.OnStart += new FileTansferEvent(scp_OnProgress);
scp.OnEnd += new FileTansferEvent(scp_OnEnd);
scp.OnProgress += new FileTansferEvent(scp_OnProgress);
try
{
scp.To(fileName, host, remoteFile, user, password);
}
catch (Exception e)
{
throw e;
}
}
I can successfully connect, send and receive files using CoreFTP. Thus, the issue is not with the server. When I run the above code, the process seems to stop at the scp.To method. It just hangs indefinitely.
Anyone know what might my problem be? Maybe it has something to do with adding the key to the a SSH Cache? If so, how would I go about this?
EDIT: I inspected the packets using wireshark and discovered that my computer is not executing the Diffie-Hellman Key Exchange Init. This must be the issue.
EDIT: I ended up using the following code. Note, the StrictHostKeyChecking was turned off to make things easier.
JSch jsch = new JSch();
jsch.setKnownHosts(host);
Session session = jsch.getSession(user, host, 22);
session.setPassword(password);
System.Collections.Hashtable hashConfig = new System.Collections.Hashtable();
hashConfig.Add("StrictHostKeyChecking", "no");
session.setConfig(hashConfig);
try
{
session.connect();
Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp c = (ChannelSftp)channel;
c.put(fileName, remoteFile);
c.exit();
}
catch (Exception e)
{
throw e;
}
Thanks.
I use Tamir.SharpSSH - latest version 1.1.1.13
This has a class SFTP. You can use this class directly to do SFTP instead of using JSch, Session class.
Quick Sample here:
127.0.0.1 - Server IP
/SFTPFolder1/SFTPFolder2 - Server Location Where I want my files to go
Sftp sftpClient = new Sftp("127.0.0.1", "myuserName", "MyPassword");
sftpClient.Connect();
sftpClient.Put(#"C:\Local\LocalFile.txt", "/SFTPFolder1/SFTPFolder2");
Let me know if you have any issues.
Without looking at your log files it is hard to tell what the issue is.
However keep in mind that SCP is not SFTP - they are completely different protocols that run over SSH. It is possible that your SFTP does not actually support SCP - not all SFTP servers do. CoreFTP may be using SFTP.
Our commercial package, edtFTPnet/PRO, might also be worth trying, if only as an alternative to try to get a different client working against your server.

Categories

Resources