C# How do I send a video over HTTP with partial content? - c#

I'm currently building a "video server", it has to be able to send videos over HTTP to the client which is using an HTML( tag) website.
I have this video tag on the website:
<video src="http://<?php echo $_SERVER['SERVER_ADDR']; ?>:8080/stream/0c73f95521d163257379e8ed37839e34" autoplay controls muted></video>
And this code on my server: (ctx is my HttpListenerContext)
string file = Directory.GetFiles(
contentDirectory,
ctx.Request.RawUrl.Substring(("/stream/").Length) + ".*",
SearchOption.AllDirectories)[0];
//Console.Log(ctx.Request.Headers.GetValues("Range")[0]);
byte[] data = File.ReadAllBytes(file);
ctx.Response.OutputStream.Write(data, 0, data.Length);
ctx.Response.OutputStream.Flush();
ctx.Response.OutputStream.Close();
I have been looking for a method that works but I haven't found any.
Basically what I'm trying to do is send video over HTTP from my C# program to my website (which is hosted on another web server).
Update:
I found this answer yesterday but didn't think I worked because I used an HttpListener, when I read it a bit closer I found that he used a TcpListener.
Handle range requests with HttpListener
I hope this might help someone else!
Thank you!

Related

Android HttpListener using SSL?

I'm developing a android app that hosts a web server using the HttpListener class.
But i need to host it using a SSL certificate, I have read somewhere that you need to place the certificate in a special directory on the android device.
But i have lost the link that specified exactly where.
So does any one know how to get HTTPS to work on Xamarin Android with the HttpListener class?
Edit:
I have tired to store a .cer and .pvk file under Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), ".mono", "httplistener") as suggested in HttpListener with HTTPS on MonoTouch but when i try to access the url i get no answer, if i change to http i at least get a answer.
I found the following source code on github, https://github.com/mono/mono/blob/3f779475e3fc982e312212d5dbbd86515eddfc0c/mcs/class/System/System.Net/HttpListener.Mono.cs#L73
But it just eats any exception that occures so there is no way to figure out if anything goes wrong!
You've not indicated what you're calling the file itself, looking at the mono code for System.Net.HttpListener the file itself must be {port number}.cer, i.e. 443.cer if you were to listen on 443.
string dirname = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string path = Path.Combine(dirname, ".mono");
path = Path.Combine(path, "httplistener");
string cert_file = Path.Combine(path, String.Format("{0}.cer", port));
https://github.com/mono/mono/blob/3f779475e3fc982e312212d5dbbd86515eddfc0c/mcs/class/System/System.Net/HttpListener.Mono.cs#L64

Is it possible to use NSUrlSession to upload files to an FTP server?

I've been scouring the web for a few hours looking for a solution to a problem that I need to resolve with a Xamarin.iOS app that I've been developing. Most, if not all, of our customers in the field need to upload pictures that they attach to work orders (tickets), which go to an FTP on our backend. My coworker developed the Android app and from him I took the current method, based off of an FtpRequest casted to an FtpWebRequest. It works 90% of the time and uploads to the server reasonably quick if the user has a decent connection.
The problem? I need 100% of the time, and I need it to be in the background. I found that NSUrlSession seems to be my best bet for solving this issue, as it's native to iOS and has support for backgrounding. My only issue is that when I try to create the UploadTask with session.CreateUploadTask, it says "cannot read file at (path)" where path is: file://var/mobile/Containers/Data/Application/850CB1FE-9C2D-456C-8B5F-921DC8D5CEF5/Documents/PolarisPictures2/VUPSXOUTA722002799CMC5022017103109544681088_1.jpeg. I've already confirmed that the file does exist on that path via printing out the file name using foreach( var file in Directory.EnumerateFiles(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "PolarisPictures2") ) Without using the file:// protocol, the error returns with "...is not a valid file:// url." So is it that I'm not accessing the file properly, or is it that there's simply no way to do what I'm trying to do?
And if there is no way, could anyone provide a solution that would best achieve the backgrounding capabilities that I require?
Appreciate it, guys.
Thanks.
Here's my code:
NSUrlSession session = null;
NSUrlSessionConfiguration config = NSUrlSessionConfiguration.CreateBackgroundSessionConfiguration("com.PolarisFTPUpload.BackgroundSession");
session = NSUrlSession.FromConfiguration(config, (NSUrlSessionDelegate)new MySessionDelegate(), new NSOperationQueue());
string docs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
docs = docs.Replace("/var", "file://var");
string filepath = System.IO.Path.Combine(docs, "PolarisPictures2/VUPSXOUTA722002799CMC5022017103109544681088_1.jpeg");
Console.WriteLine(filepath);
string UploadURLString = "ftp://myftpUser:myftpPass#myftpIP:Port/Pictures/Database" + "/" + DateTime.Today.Year + "/" + DateTime.Today.Month + "/" + DateTime.Today.Day + "/";
NSUrlSessionUploadTask uploadTask;
NSUrl uploadURL = NSUrl.FromString(UploadURLString);
NSUrlRequest req = NSUrlRequest.FromUrl(uploadURL);
uploadTask = session.CreateUploadTask(req, NSUrl.FromString(filepath));
Neither NSURLSession nor its predecessor, NSURLConnection, support the FTP PUT command. The only Apple API that supports FTP uploads is CFFTPStream, which is ancient, deprecated, and strongly discouraged for new development.
Either way, you should not under any circumstances use FTP. Period. It is fundamentally impossible to make FTP secure, because passwords are sent in cleartext across the network.
Instead, you should write a simple bit of PHP code on your web server that accepts file uploads, and use HTTPS uploads. Not only is that approach more secure, it is also supported with NSURLSession.
See Secure PHP File Upload Script for more information on the web site of things, and see Apple's NSURLSession Programming Guide for help with the uploads on the iOS side.
There should be three / with file prefix. The prefix should be file:///, not file://.
You can just use NSUrl.FromFilename(filepath) to get this url without replacing the prefix.

C# Download Data using Web Client

I'm having an issue downloading a file. I'm running this website on my local IIS. The BaseUrl correctly has the address of my local IIS site. The moduleImgPath is a Sitecore media item: "/sitecore/shell/~/media/Racking/module-image.png". The BaseUrl has the structure "http://local-$company.com".
The code used for the download is essentiall shown below. The method errors on Image.FromStream() with a System.ArguementException - "Parameter is not valid."
Stream stream = new MemoryStream(new WebClient().DownloadData(RackingConfigHelper.BaseUrl + moduleImgPath));
Image objImage = Image.FromStream(stream);
My question essentially revolves around - can you use a WebClient this way, to download data from what essentially a local source? Or will I need to deploy this code to my test environment to test it out? If I can, do I need to worry about ports?
It looks like your image data is not a jpg (I think this is typically what is expected for Image).
You can see why the error happens on this msdn link
and you can see the docs for Image on this msdn link
I would hazard a guess you are either trying to use a non-jpg OR perhaps the jpg you have may be unusually formed.

How to download big video files using WebClient class

I'm a newbie and I'm developing a windows application. I need to download a video file from my site and that's my issue here. I had designed a custom down-loader, through which I can download images, text files from my site. But I wasn't able download videos from my site. Could anyone please help me out..?
WebClient client = new WebClient();
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged);
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted);
client.DownloadFileAsync(new Uri("http://mysitename.com/Videos/vid.mp4"), "c:\\movie.mp4");
I don't want to download by means of response content dispatch because my client wants me to download through custom browser.. so please let me know solutions from you experts.. thank you
I have tried to download a video file with WebClient and it works. My setup is as below:
I have a virtualdirectory(Video) in defaultwebsite (IIS) which has this video file.
I just use the below code to download the video file to C drive:
var client = new WebClient();
Uri address = new Uri("http://localhost/Video/wildlife.wmv");
client.DownloadFileAsync(address, #"c:\video.wmv");
Also note since you are downloading in Async fashion, wait for about a min for the operation to complete for the full file to be downloaded. Initially it shows 0 bytes but based on the size it takes some time to complete it.
UPDATE: If your server doesnt have the file mime type specified then just add to the collection of mime types that IIS can serve and you can download the file without any problem.
When adding MIME type the following values to be used are (for your scenario):
File Extension: .mp4
MIME Type: video/mp4
To add mime types in IIS follow these links:
For IIS 4,5
For IIS 6
For IIS 7
This sounds more like a server issue, but if you are doubting your code, you may want to try download sync (I have had some issues in the past downloading async). Another way is to use the WebRequest class. If this server is very remote, try pinging beforehand. I think that you should also check to make sure the file is on the server, and if the file is really big, you should check to see if the file finished uploading.

C# upload file to server - both client and server side

I'm a C# game programmer with little web development experience.
I need to upload a small file (25-100 or so bytes, depending on it's content) to a server. This is on the Windows Phone 7 using XNA. The target server is fairly limited and only supports PHP and classic ASP.
Since the CF on the WP7 only has access to a limited subset of networking commands, it's looking like an HttpWebRequest GET aimed at a script that saves the file will be the best option. The data I'm sending is small in size, and should be able to be passed as a parameter in the url.
I've been searching but have yet to find a complete example of this, which handles both the client and server side script (mainly the latter). This is close to what I'm looking for, except it has no mention of the server side script: Upload files with HTTPWebrequest (multipart/form-data)
The closest that I got was this: http://www.johny.org/2007/08/upload-using-c-as-client-and-php-as-server/
But when attempting to use it I get an unhandled exception: "The remote server returned an error: (405) Method Not Allowed". This method seems the most promising so far, but I've yet to be able to debug this.
Unfortunately, I have a short amount of time to implement this, and as I said only a passing familiarity with web development. I'm not worried about maximum security or scalability as this is a temporary measure to collect feedback internally. Basically, I just need the quickest thing that works. ;)
Any help would be fantastic!
I've solved it. First off, PHP wasn't supported on my server (just now learning that PHP and ASP are can't be used on the same server, depending on whether it's on Linux or Windows - like I said, web development noob here!). I switched to ASP and, after digging through the docs, wrote this script:
<%
dim theData, theFileName
set theData=Request("data")
set theFileName=Request("filename")
dim fs,tfile
set fs=Server.CreateObject("Scripting.FileSystemObject")
set tfile=fs.CreateTextFile(Server.MapPath(theFileName+".txt"))
tfile.WriteLine(theData)
tfile.Close
set fname=nothing
set fs=nothing
set theData=nothing
set theFileName=nothing
%>
This C# code uploads the file:
const string cAddress = "http://site.com/folder/upload.asp";
string fileName = foo;
string data = bar;
string address = cAddress + "?filename=" + fileName + "&data=" + data;
uploadRequest = (HttpWebRequest) HttpWebRequest.Create(address);
uploadRequest.Method = "GET";
uploadRequest.GetResponse();
Hope this helps someone else looking for an example of how to do this!
But you have the METHOD as GET instead of POST. You can't upload a file to a website by passing the file path to the Query String.

Categories

Resources