How can i upload text to my own website automatically? - c#

In general i want that every 5 minutes my application will upload a text to my website. So if the current page in my website is empty after uploading the text i will see on the page the text.
This is my example website:
http://rhodan.wix.com/chocolade#!blank/c1236
Empty page.
This is the code I'm trying to use to upload the text to the site:
private void SaveTToWeb()
{
try
{
WebClient client = new WebClient();
string myFile = #"C:\Temp\file.txt";
client.Credentials = CredentialCache.DefaultCredentials;
client.UploadFile(#"http://rhodan.wix.com/chocolade#!blank/c1236", "PUT", myFile);
client.Dispose();
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
}
I don't get any exceptions or errors but i don't see the text in the text file on my page.

When uploading a file to remote server, one must ask himself couple of question.
Does the remote server support it ?
How do you communicate with the remote host (HTTP, FTP, REST API) ?
I see that you write "PUT", does wix support what you are trying to do ?
In addition, you would probably need credentials (username/password/key) in order to upload a file to a specific remote server.
From quick reading, I see you should upload the files via FTP.
http://www.wix.com/support/forum/flash/other/other/accessing-my-server-for-upload-of-files
And here's a link might be useful
FTP client in C#

Related

Downloading a file with a type 'application/octet-stream' and saving it download folder to install

I'm currently doing a proof of concept for my application to check for updates and if their is a new version then download that version and install it (prompt the user to install?).
I'm stuck on implementing the download part of the problem, I have an AJAX call with PHP that just returns a file but the type is "application/octet-stream".
<?php #session_start();
$filename = "\\xxx\x\Application\ka-v1.0.0.0.txt";
header("X-Sendfile: $filename");
header("Content-type: application/octet-stream");
header('Content-Disposition: attachment; filename="' . basename($filename) . '"');
?>
The idea is to expand this and check the database what is the latest version and based on that it will form the filename. Originally the plan is to do a scandir on the directory to get all filenames and check for the latest and compare that to the application.
On the Xamarin.Form my code is
_client = new HttpClient();
public async void GetUpdate(string uri)
{
var bytesme = await DownloadFile("https://10.0.2.2:8080/apps/x/ajax/ajax.get_download.php");
File.WriteAllBytes(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), bytesme);
}
public static Task<byte[]> DownloadFile(string url)
{
if (!url.Trim().StartsWith("https", StringComparison.OrdinalIgnoreCase))
throw new Exception("iOS and Android Require Https");
return _client.GetByteArrayAsync(url);
}
So the idea is that when the user starts the application then it will call GetUpdates. For now GetUpdate is tied to a button click event. So the idea on the code is that it will download the file via HTTPClient then write it on a Downloads folder.
In this state that code doesn't work
The next step that I haven't research is automatically opening the file to prompt the user to install the new update
Since doing byte download with content-type 'application/octet-stream' is unreliable on Xamarin.Forms I came up with an alternative way of downloading and installing a apk file.
Instead of capturing the data, storing it locally then running it afterwards, I changed that sequence to the API call to a default browser
try
{
await Browser.OpenAsync("https://10.0.2.2/apps/x/ajax/ajax.get_download.php", BrowserLaunchMode.SystemPreferred);
}
catch (Exception ex)
{
// An unexpected error occured. No browser may be installed on the device.
}
So the idea is that the application will get downloaded in the browser and will give the user to open it and install the update.

Stream file from FTP server using FluentFTP to web client in ASP.NET Core

I have a shared webhosting service which my ASP.NET Core app runs, and an FTP server. I want to serve the files that clients need to download from the site.
I want the files not to be accessible to everyone, so this is what I do (I use FluentFTP):
var cred = new NetworkCredential(_config.UserName, _config.Password);
FtpClient client = new FtpClient(_config.Host, int.Parse(_config.Port), cred);
await client.ConnectAsync();
var remotePath = $"{_config.Folder}{FILE_DIR}/{filename}";
var result = await client.DownloadAsync(remotePath: remotePath, 0L);
await client.DisconnectAsync();
if (result != null)
{
return File(result, "application/force-download", filename)
}
else
{
throw new Exception("Failed");
}
The problem is, the server tries to download the file from the FTP server, then sends it to client. And there is the same problem for upload too, the client needs to upload file to the server, and then server uploads it to the FTP server. I think this can be very time-consuming with large files.
Is there any better way to achieve this goal? Or is it possible to write the file being downloaded from FTP simultaneously to the client response so the client downloads any bit of file downloaded in server and doesn't have to wait for the download to server to finish to start the download?
Thanks in advance.
Download the file directly to the HTTP output stream with use of FtpClient.Download (to be renamed FtpClient.DownloadStream in upcoming versions) and HttpResponse.OutputStream:
Response.AddHeader("Content-Disposition", $"attachment; filename={filename}");
client.Download(Response.OutputStream, remotePath);
(where Response is ASP.NET HttpResponse).
A similar question for native .NET FtpWebRequest/WebClient:
Download file from FTP and how prompt user to save/open file in ASP.NET C#
Also note that the application/force-download seems like a hack.
Use Content-Disposition: attachment to force the download.

Firewall blocking uploading a file in my filezilla server

I am trying to setup a filezilla server. I have followed the instructions from here. I have write a simple c# script in order to upload data to server. My code is the following:
static void UploadFile(string filepath)
{
string m_FtpHost = "ftp://ip:port/";
string m_FtpUsername = "user";
string m_FtpPassword = "pass";
// Get an instance of WebClient
WebClient client = new System.Net.WebClient();
// parse the ftp host and file into a uri path for the upload
Uri uri = new Uri(m_FtpHost + new FileInfo(filepath).Name);
// set the username and password for the FTP server
client.Credentials = new System.Net.NetworkCredential(m_FtpUsername, m_FtpPassword);
// upload the file asynchronously, non-blocking.
client.UploadFileAsync(uri, "STOR", filepath);
}
When I am running that script from the same computer everything is working fine. When I trid to run the same script from another computer of the same lan I got issues. The file doesnt sent it properly. When I turn off the firewall however the upload is happerning normally. Any idea how to get over the firewall?
Usually the Windows asks the user to give permission to a program when it tries to use any port (the Windows get's a pop out asking to allow or disallow the program from using the port ) ...
I'm not sure how to do it but I found a link ...
I'm not sure what conditions need to be met to expose this dialog, I
would assume an application that attempts to open a listening port on
a vanilla Windows instance should always display this dialog. Why
don't you try adding your application to the 'authorized applications'
list, or opening the port manually using the Windows Firewall COM
interop (NetFwTypeLib)?
http://blogs.msdn.com/b/securitytools/archive/2009/08/21/automating-windows-firewall-settings-with-c.aspx
quoted from alexw

FTP transfer via ASP.net page

I'm rather new to development and I have a problem which I haven't sound a solution for. I can't seem to find if it is possible or not to solve, anyway..
I want to create an asp page which would allow a user to download a whole folder from an ftp server. The ftp server itself is not on the same physical server as the asp site. To further complicate the issue is that I want to use either explicit or implicit transfer which I can't seem to work in a browser.
The webpage acts as an intermediary between the client and the ftp server, and is meant to be as user friendly as possible. eg. the user just have to press download and it automatically downloads from the ftp server without the use of an installed local client.
client -> asp page -> ftp server
client <- ftp server
My problem is that the asp page does not have the permission to create files on the client system. I have managed to connect to the ftp and try to download all files in a folder but the files do not appear on the client in the target folder.
I might just be searching for the wrong terms but I would appreciate any feedback.
when you say "client" I assume you are referring to the asp.net server. In that case you need to check what user the app pool for your website is running under. Then you need to make sure that user has write permissions to the folder you are storing the ftp files in.
The user is most likely network service.
Your ASP site will not be able to write directly to the end user's system. Just think, would you want any website to have direct access to your file system?
You could download the files to a temporary folder on the Web Server, and then use write it in a response to prompt the user to download it.
Here is a SO question regarding downloading files in ASP.NET
From our question's comment discussion, looks like you are looking to provide user with a option to download file which you have collected on server side from ftp server
//Connect to your file
FileStream sourceFile = new FileStream(Server.MapPath(#"FileName"), FileMode.Open);
float FileSize= sourceFile.Length;
//Write the file content to a byte Array
byte[] getContent = new byte[(int)FileSize];
sourceFile.Read(getContent, 0, (int)sourceFile.Length);
sourceFile.Close();
//Build HTTP Response object
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Length", getContent.Length.ToString());
Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName);
Response.BinaryWrite(getContent);
Response.Flush();
Response.End();
Please see if the above code helps.
Also, check out HTTP Response file Attachment Discussion

If I create a file in Codebehind where does the physical file acually exist?

protected void Page_Load(object sender, EventArgs e)
{
System.IO.File.WriteAllText(#"C:\CallInformation.txt", "Some data");
}
is CallInformation.txt on the Server? Or the client? If it's the server, other than specifying a computer name (#"\Workstation\c$\CallInformation.txt") how can I get it to save the file client side?
It is built on the server. It would be a major security vulnerability if you could create a file on a client without them physically accepting it. You could always send the data to them as a stream and allow them to choose where to save it.
It's on the server. The code behind executes in the context of the web server.
To get a file to download, there are a few ways. One way is to do something along these lines:
Response.ContentType = "image/jpeg";
Response.AppendHeader("Content-Disposition","attachment; filename=SailBig.jpg");
Response.TransmitFile( Server.MapPath("~/images/sailbig.jpg") );
Response.End();
If you are writing a web application, you should understand that the code runs on the server.
So the file is saved on the server.
To send it to the client, you have to write the contents of the file to the response stream.
The file would be create on the server. To write it locally, you would need a client framework other than just the W3C DOM compliant browser, such as Silverlight and (maybe) Flash - and even then the user would be prompted to allow it to happen.
Here's a post that explains how it can be done:
http://www.c-sharpcorner.com/uploadfile/dpatra/read-and-write-file-to-local-file-system-in-silverlight-4/
Hope it helps.

Categories