To upload any content on server...what to use? - c#

i am making one application,
what to use if i want to upload data on server in C# based application.
i know this names in web services [ i don't know How to use it? ]
1. SOAP,
2. REST,
3. AWS
So my question is,
How many ways i can upload my data file to server?
Do i have to use web service or is their any other way to upload data file?
btw... i am just beginner in C# and web service...so may be u will find this question simple.
thanks in advance,
nitz.
EDIT :
my app. is on windows based.....
and the files which will be generated from my app. , that i want to store at server.....

You don't need to use any fancy "web service" technology to upload data from a client application to a server. You can create a simple ASP.NET Web handler and save the input file from the request body:
public class FileUploader : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
string fileName = context.Request.QueryString["FileName"];
byte[] fileData = context.Request.BinaryRead(context.Request.ContentLength);
string path = ...; // decide where you want to save the file
File.WriteAllBytes(path, fileData);
}
public bool IsReusable
{
get { return false; }
}
}
From the client app, you'd use WebClient.UploadFile method:
using (var client = new WebClient()) {
client.QueryString["FileName"] = fileName;
client.UploadData(url, inputFileData);
}
This approach eliminates the overhead of protocols like SOAP and posts the file directly in the HTTP request body.

If you really want to up-/download **files* you should maybe take the File Transfer Protocol (FTP).
FtpWebRequest

Related

C# MVC Download SSRS Report as PDF File passing Parameter data as Post Request

I've set up a short test for creating a SSRS report and Downloading it as PDF via an MVC Website.
private static string _report = #"http://myServer/ReportServer?/Test&s:Command=Render&rs:Format=pdf&Param1={0}&Param2={1}";
public FileResult DownloadReport() {
using (var client = new WebClient()) {
client.Credentials = CredentialCache.DefaultCredentials;
var data = client.DownloadData(String.Format(_report, "MyParam1Value", "MyParam2Value");
return File(data, "application/pdf", "YourReport.pdf");
}
}
This is working fine so far.
But for the Report im planning to do i will have a lot of Parameters with large data.
So im worried that im reaching the maximum lenght of the URL.
Is there a way to pass the Parameter data as POST request, so that its not in the URL?
Thank you all
I have found a Solution, or workaround.. :-)
I will store all the data in a Db an just pass the id of the created record to the report.
It was for my usecase not neccessary to store the data in a Db, but its also not a problem.
If someone still would know how to pass the parameters via Post Request, then feel free to answer. Maybe someone else needs it.
Thank you all

Why does WebClient.UploadValues overwrites my html web page?

I'm familiar with Winform and WPF, but new to web developing. One day saw WebClient.UploadValues and decided to try it.
static void Main(string[] args)
{
using (var client = new WebClient())
{
var values = new NameValueCollection();
values["thing1"] = "hello";
values["thing2"] = "world";
//A single file that contains plain html
var response = client.UploadValues("D:\\page.html", values);
var responseString = Encoding.Default.GetString(response);
Console.WriteLine(responseString);
}
Console.ReadLine();
}
After run, nothing printed, and the html file content becomes like this:
thing1=hello&thing2=world
Could anyone explain it, thanks!
The UploadValues method is intended to be used with the HTTP protocol. This means that you need to host your html on a web server and make the request like that:
var response = client.UploadValues("http://some_server/page.html", values);
In this case the method will send the values to the server by using application/x-www-form-urlencoded encoding and it will return the response from the HTTP request.
I have never used the UploadValues with a local file and the documentation doesn't seem to mention anything about it. They only mention HTTP or FTP protocols. So I suppose that this is some side effect when using it with a local file -> it simply overwrites the contents of this file with the payload that is being sent.
You are using WebClient not as it was intended.
The purpose of WebClient.UploadValues is to upload the specified name/value collection to the resource identified by the specified URI.
But it should not be some local file on your disk, but instead it should be some web-service listening for requests and issuing responces.

How do I send a file on a self hosted web API and process it on the server?

I have a self hosted web api using Owin and Katana. I would like to send files (can be pretty large, a few hundred MB) from a sample client, and would like to save these files on the server's disk. Currently just testing the server on my local machine.
I have the following on the test client's machine (it says image here, but it's not always going to be an image):
using System;
using System.IO;
using System.Net.Http;
class Program
{
string port = "1234";
string fileName = "whatever file I choose will be here";
static void Main(string[] args)
{
string baseAddress = "http://localhost:" + port;
InitiateClient(baseAddress);
}
static void InitiateClient(string serverBase)
{
Uri serverUri = new Uri(serverBase);
using(HttpClient client = new HttpClient())
{
client.BaseAddress = serverUri;
HttpResponseMessage response = SendImage(client, fileName);
Console.WriteLine(response);
Console.ReadLine();
}
}
private static HttpResponseMessage SendImage(HttpClient client, string imageName)
{
using (var content = new MultipartFormDataContent())
{
byte[] imageBytes = System.IO.File.ReadAllBytes(imageName);
content.Add(new StreamContent(new MemoryStream(imageBytes)), "File", "samplepic.png");
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("multipart/form-data"));
return client.PostAsync("api/ServiceA", content).Result;
}
}
First, is this the right way of sending a file using POST?
And now here is where I'm really lost. I am not sure how to save the file I receive in the Post method of my ServiceAController which inherits ApiController. I saw some other examples which used HttpContext.Current, but since it's self hosted, it seems to be null.
I would split files into chunks before uploading. 100 Mb is a bit large for single HTTP POST request. Most of web servers also have certain limit on HTTP request size.
By using chunks you won't need to resend all data again if connection times out.
It should not matter whether you use self hosting or IIS, and whether it is an image file or any type of file.
You can check my answer that will give you simple code to do so
https://stackoverflow.com/a/10765972/71924
Regarding size, it is definitely better to chunk if possible but this gives more work for your clients (unless you also own the API client code) and for you on the server as you must rebuild the file.
It will depend if all files will be over 100MB or if only few. If they are consistently large, I would suggest to look for http byte range support. This is part of the http standard and I am sure you can find somebody who implemented it using WebAPI

Using JSON and HTTP Request in C#

I'm currently developing an Android app and I'm using Connect Android to MS SQL Server Tutorial to link my MSSQL server to the code.
And the first part is good though the second part is using a third party program to code which I don't want to. I want to write the whole code in C# (I'm using Xamarin).
I found out Json.NET / Json.NET for Xamarin website.
Though how am I supposed to use the HTTPUtils and requests in C# ? An example would be great.
Also, I have kind of a newbie question, I'm trying to get to the root of the code I sent, the .aspx file, and I don't quite understand where the web method is, I am used to a seperate .asmx file containing [Web Method]s that define them and then I can use them freely by creating a web reference on an .aspx file, so, where is the web method in the code I sent ?
public static String getJsonData(String webServiceName,String parameter)
{
try
{
String urlFinal=SERVICE_URI+"/"+webServiceName+"?parameter=";
HttpPost postMethod = new HttpPost(urlFinal.trim()+""+URLEncoder.encode(parameter,"UTF-8"));
postMethod.setHeader("Accept", "application/json");
postMethod.setHeader("Content-type", "application/json");
HttpClient hc = new DefaultHttpClient();
HttpResponse response = hc.execute(postMethod);
Log.i("response", ""+response.toString());
HttpEntity entity = response.getEntity();
String responseText = EntityUtils.toString(entity);
string=responseText;
Log.i("Output", ""+responseText);
}
catch (Exception e) {
// TODO: handle exception
}
return string;
}

Design - Log user downloads

I have to log the download requests for each file that is grabbed off of a website. This log has to have the Employee ID, Solution ID, IP Address. I've used quite a few methods -
First, I was using a model where I was putting the path of the file
in an anchor tag . Whenever the user clicked on this anchor tag, I
was generating an AJAX request to log the file download.
But the huge drawback of this is that the user can just copy the file and paste it in a seperate window to get the file. That would ensure that the download was not logged.
Second,
When I was processing the ajax request in the web method in a page. I tried transmitting the file through HttpResponse, but that didn't work either.
HttpContext.Current.Response.TransmitFile("filename");
jQuery ajax call kept failing, and I never got the file on the client side.
The key thing is, I have to do the whole thing without refreshing the page.
I'm wondering if this is possible at all...
You could implement a IHttpHandler that logs the request, retrieves the file and serves it. This way, even if the link is copied and pasted directly, it would still log it.
public class SimpleHandler : IHttpHandler
{
public bool IsReusable
{
get { return false; }
}
public void ProcessRequest(HttpContext context)
{
string fileToServe = context.Request.QueryString["file"];
if (!string.IsNullOrEmpty(fileToServe))
{
//Log request here...
context.Response.ContentType = "content type for your file here";
context.Response.WriteFile("~/path/" + fileToServe);
}
}
}
You could use the AJAX method, with an identifier in the link to be used as a parameter value to refer to the file - rather than storing the full path - and have your web method return the serialized data of the file.
So, your web method might look something like this:
[WebMethod]
public static string GetDownload(string someIdentifier) {
// get the contents of your file, then...
// do your logging, and...
var serializer = new JavaScriptSerializer();
return serializer.Serialize(fileByteArrayOrSuch);
}
Then handle the file contents on the client side. There will doubtless be some more trifling elements to add to your function for the sake of logging; but the bottom line is, your AJAX can both handle logging and then process the download request.
This is very much possible – you need to return a file as a response to an action (Mvc) or to an aspx page (webforms). So when the action or aspx page is hit you can log the request and write the file to the response.
Edit: for webforms example, see this SO question
For mvc:
public ActionResult DownloadFile(string fileHint)
{
// log what you want here.
string filePath = "determine the path of the file to download maybe using fileHint";
return File(filePath, "application/octet-stream"); // second argument represents file type; in this case, it's a binary file.
}

Categories