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
Related
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.
I am creating a Nancy Module that will eventually be hosted inside of a Windows Service. To start the Nancy hosting, I am using Nancy.Hosting.Self. Below is the code to start Nancy host.
string strHostProtocol = Convert.ToString(ConfigurationManager.AppSettings["HostProtocol"]);
string strHostIP = Convert.ToString(ConfigurationManager.AppSettings["HostIP"]);
string strHostPort = Convert.ToString(ConfigurationManager.AppSettings["HostPort"]);
//Here strHostProtocol="https", strHostIP = "192.168.100.88" i.e. System IPv4, strHostPort = "9003"
var url = strHostProtocol + "://" + strHostIP + ":" + strHostPort;
//url ="https://192.168.100.88:9003"
this.host = new NancyHost(new Uri(url));
this.host.Start();
Now once the windows service starts, it will start the above host and I could see this in netstat -a command. When I browse this in browser using https://192.168.100.88:9003 I will get proper response.
The problem arises when the same is browsed using its external IP. Say this system has been assigned with external IP of 208.91.158.66 and when I try browsing this as https://208.91.158.66:9003 I will just get a browser default loading progress continuosly which does not stop and without any error thrown. I have also added the below command and reserved URL successfully.
netsh http add urlacl url=https://192.168.100.88:9003/ user=everyone
But even after this the host cannot be browsed using external IP assigned to that system. Is there any restricting Nancy is putting up? Firewalls are turned off, defenders are turned off. Anyone has any idea on this?
UPDATE
The duplicate linked question talks about LAN but here I am trying through external IP and I've tried answer mentioned over there and also specified the same in question
Alright. This issue was also posted to GitHub Nancy Repo and below is what #Khellang had to say.
When you bind to https://192.168.100.88:9003, the
TcpListener/HttpListener won't listen on other interfaces. You either
have to bind to https://208.91.158.66:9003 or https://localhost:9003
and set RewriteLocalhost = true (default).
Further he also said that
If you also want to listen to requests coming to the external IP, yes.
Or you could use a wildcard, like https://+:9003/, https://*:9003/ or
https://localhost:9003/ (with RewriteLocalhost = true, this will
result in https://+:9003/). You can read more about them in the link I
posted.
and thanks to #TimBourguignon as he suggested the same in his comments. Hope this helps someone in future.
He has also suggested to read this link to know more about the Strong Wildcard and Weak Wildcard
I am using C# .net and I am trying to upload a file to my server. I am not using asp .net.
I followed This Question and it doesn't seem to work for me. On a sidenote, this question was written back in 2008.
I am using this code as shown in the question above:
File.Copy("zQn69PZUx.png", "\\\\198.57.247.152\\~shiro\\public_html\\new");
//tried this also
File.Copy("zQn69PZUx.png", "\\\\198.57.247.152\\~shiro\\new");
The error I get:
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
Additional information: The network path was not found.
I also tried using my domain name and use the path like it shows up in the browser, without http:// because it complained about the format, saying its not accepted, like this: domain-name.com\\new, and still got the same error as a result.
Any ideas what I could be doing wrong, or have a better solution on how to upload a file to a server ? You can see here that the http://198.57.247.152/~shiro/new/ path exists.
The path \\198.57.247.152\~shiro\new is what Microsoft calls Uniform Naming Convention (UNC). This type of resource is only available on networks with NetBIOS enabled; essentially local network. The problem is that File.Copy only works if you have access to it in your network - since this is a remote server, it won't be able to find that server, leading to the The network path was not found exception.
http://198.57.247.152/~shiro/new/ follows the syntax of <scheme name> : <hierarchical part> [ ? <query> ] [ # <fragment> ] which is call Uniform resource locator (URL). Hypertext Transfer Protocol (http) resource is typical accessed by a browsers.
You can resolve this by instead using FTP to upload your file to the server:
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
client.UploadFile("ftp://ftpserver.com/targetpath", "localfilepath");
}
A valid target path would be something like: ftp://localhost/samplefile.txt
and the local filepath should be the fully qualified filepath.
You can upload file using code from Peter Luu's answer. But first you should have access to it.
For uploading a file to a remote server, you should be a user of it and should have a password. It is not the password you use for logging in to your Hostgator control panel. After logging into your Hostgator account, there will be an option like FTP in it, where you can setup FTP user accounts. There you can assign a user name and password and that have to be applied to the code for uploading..
And for checking whether the UserName and Password works, Open MyComputer, and in the addressbar type the FTP path (which will be something starting "ftp://"). There pops up a Dialog asking for UserName and Password (If the path is valid). If you enter into, See and copy files into the explorer window from there, then the uploading code will work
If you want to get the applicable path, Open windows explorer and type ftp://your_domain_name. Apply UserName and Password, browse through the path you need, copy it from the address bar and add it to the code.
I have been struggling with this problem for hours now. I have an web app that works with Active Directory Authentication. Only certain people are allowed to upload files to the server. When I test from my localhost everything works fine and I can upload files to the correct path on the server. When I publish my solution to the server and I run it from there, it gives me the error "Logon failure: unknown user name or bad password". I have set the permissions on the folder for myself to Full Control and Allow All. The server is running IIS 6. Can some one please advise on what to do. I have tried literally almost everything.
Server is on a different machine.
Local is on my PC.;
if (this.flUpload.HasFile)
{
flUpload.SaveAs(#"SERVERPATH\" + flUpload.FileName);
}
Please try below.
NetworkCredential myCred = new NetworkCredential(GlobalVariablesBO.UserID, GlobalVariablesBO.Password, GlobalVariablesBO.Domain);
WebClient webclient = new WebClient();
webclient.Credentials = myCred;
string tempFileForStorage = Path.Combine(Path.GetTempPath(), Path.GetFileName(dBO.SPFileName));
sharepointUpload.SaveAs(tempFileForStorage);
webclient.UploadFile("ServerPath", "PUT", tempFileForStorage);
webclient.Dispose();
File.Delete(tempFileForStorage);
It looks like more of configuration issue . Make sure that Website hosting server IIS User should have read/write permission to the server where you are uploading files .
Please try below code and see if the file is geeting sabed in tempFileForStorage location. This path is C://Temp
if (this.flUpload.HasFile)
{
string tempFileForStorage = Path.Combine(Path.GetTempPath(), flUpload.FileName
flUpload.SaveAs(tempFileForStorage);
}
First question!
Environment
MVC, C#, AppHarbor.
Problem
I am calling an openid provider, and generating an absolute callback url based on the domain.
On my local machine, this works fine if I hit http://localhost:12345/login
Request.Url; //gives me `http://localhost:12345/callback`
However, on AppHarbor where I'm deploying, because they are using non-standard ports, even if I'm hitting it at "http://sub.example.com/login"
Request.Url; //gives me http://sub.example.com:15232/callback
And this screws up my callback, because the port number wasn't in the original source url!
I've tried
Request.Url
Request.Url.OriginalString
Request.RawUrl
All gives me "http://sub.example.com:15232/callback".
Also to clear up that this isn't a Realm issue, the error message I am getting from DotNetOpenAuth is
'http://sub.example.com:14107/accounts/openidcallback' not under realm 'http://*.example.com/'.
I don't think I've stuffed that up?
Now, I'm about to consider some hacky stuff like
preprocessor commands (#IF DEBUG THEN PUT PORT)
string replace (Request.URL.Contains("localhost"))
All of these are not 100% solutions, but I'm sick of mulling over what could be a simple property that I am missing. I have also read this but that doesn't seem to have an accepted answer (and is more about the path rather than the authority). So I'm putting it towards you guys.
Summary
So if I had http://localhost:12345/login, I need to get http://localhost:12345/callback from the Request context.
And if I had "http://sub.example.com/login", I should get "http://sub.example.com/callback", regardless of what port it is on.
Thanks! (Sleep time, will answer any questions in the morning)
This is a common problem in load balanced setups like AppHarbor's - we've provided an example workaround.
Update: A more desirable solution for many ASP.NET applications may be to set the aspnet:UseHostHeaderForRequestUrl appSetting to true. We (AppHarbor) have seen several customers experience issues using it with their WCF apps, which is why we haven't enabled it by default and stil recommend the above solution for those situations. You can configure it using AppHarbor's "Configuration Variables" to inject the appsettings when deployed. More information can be found in this article.
I recently ran into an issue where I compared a URL to the current URL, and then highlighted navigation based on that. It worked locally, but not in production.
I had http://example.com/path/to/file.aspx as my file, but when viewing that file and running Request.Url.ToString() it produced https://example.com:81/path/to/file.aspx in a load balanced production environment.
Now I am using Request.Url.AbsolutePath to just give me /path/to/file.aspx, thus ignoring the schema, hostname, and port numbers.
When I need to compare it to the URL on each navigation item I used:
New Uri(theLink.Href).AbsolutePath
My initial thoughts are get the referrer variable and check if that includes a port, if so use it otherwise don't.
If that’s not an option because a proxy might remove the referrer header variable then you might need to use some client side script to get the location and pass it back to the server.
I'm guessing that AppHarbor use port forwarding to the IIS server so even though publicly the site is on port 80 IIS has it hosted on another port so it can't know what port the client connected on.
Something like
String port = Request.ServerVariables["SERVER_PORT"] == "80" ? "" : ":" + Request.ServerVariables["SERVER_PORT"];
String virtualRoot = Url.Content("~/");
destinationUrl = String.Format("http://{0}{1}{2}", Request.ServerVariables["SERVER_NAME"], port + virtualRoot, "/callback");
If you use the UrlBuilder class in the framework you can easly get around this. On the builder class if you set the port to -1 then the port number will be removed:
new UriBuilder("http://sub.example.com:15232/callback"){ Port = -1}
returns : http://sub.example.com/callback
To keep the port number on a local machine just check Request.IsLocal and don't apply -1 to the port.
I would wrap this into a extension method to keep it clean.
I see that this is an old thread. I had this issue running MVC5, on IIS 7.5, with an Apache proxy in front. Outside of the server, I would get "Empty Response", since the asp.net app gets the Url from apache with the custom port.
In order to have the app redirect to a subpath without including the "custom" port, forget the Response/Request objects, and use the Transfer method. For instance, if I want that users are automatically redirected to the login page in case they are not logged already:
if (!User.Identity.IsAuthenticated)
Server.TransferRequest("Account/Login");