I am trying to send an XML via web client on Monotouch. Although everything is working on the iOS simulator I get an exception when the app is running on the device. Here is the code.
try
{
Byte[] sendData = System.Text.Encoding.UTF8.GetBytes(someXML) ;
WebClient client = new WebClient();
Byte[] forResp;
client.Headers.Add("Content-Type","text/xml");
bresp = wc.UploadData(URL, sendData);
string resp = System.Text.Encoding.ASCII.GetString(forResp);
XmlDocument xresp = new XmlDocument();
xresp.LoadXml(resp);
return xresp;
}
catch
{
// error
}
I tried the WebClient because I had the same issue with the HttpWebRequest.
Exception:
The request timed out
System.Net.WebException: The request timed out
at System.Net.HttpWebRequest.EndGetResponse (IAsyncResult asyncResult) [0x00065] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/HttpWebRequest.cs:830
at System.Net.HttpWebRequest.GetResponse () [0x0000e] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/HttpWebRequest.cs:836
at System.Net.WebClient.GetWebResponse (System.Net.WebRequest request) [0x00000] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/WebClient.cs:1433
at System.Net.WebClient.ReadAll (System.Net.WebRequest request, System.Object userToken) [0x00000] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/WebClient.cs:866
at System.Net.WebClient.UploadDataCore (System.Uri address, System.String method, System.Byte[] data, System.Object userToken) [0x00038] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/WebClient.cs:462
at System.Net.WebClient.UploadData (System.Uri address, System.String method, System.Byte[] data) [0x00035] in /Developer/MonoTouch/Source/mono/mcs/class/System/System.Net/WebClient.cs:441
The stacktrace tells us that the timeout occurs when WebClient tries to get a response from the server (and not when uploading the data to the server). That means access to the server is not the issue (and why stacktraces are very useful ;-)
The next steps depends if you have control, or not, of the server. If you control the server then check it's logs to find the request and see how it was handled. If possible also ensure you received/decoded the data identically between the simulator and device.
If you do not control the server then it's harder to know what's going on inside it. E.g. maybe it did not like the request (i.e. the server code can decide not to answer based on any condition, including the user-agent).
In such case using a tool, like wireshark, is often your best bet. Compare the session from the iOS simulator and from the device.
Is the request identical ? e.g. the data you uploaded could be different due to something else;
Is the server answering for the device ? with the same status code ? in the same time frame ?
If everything is identical then you might have found a bug. Please report it (along with the above informations and files) to http://bugzilla.xamarin.com
Otherwise you should have more precise clues to debug the issue and/or update the question to be more specific :-)
Related
I am running the following code from Scott Allen's ASP.Net Fundamentals course
using System;
using Microsoft.Owin.Hosting;
using Owin;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string uri = "http://localhost:8080";
using (WebApp.Start<Startup>(uri))
{
Console.WriteLine("Started!");
Console.ReadKey();
Console.WriteLine("Stopping!");
}
}
}
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseWelcomePage();
//app.Run(
// ctx => ctx.Response.WriteAsync("Hello Owin!"));
}
}
}
However when I run the console app I get a message
Unhandled Exception: System.Reflection.TargetInvocationException: Exception has
been thrown by the target of an invocation. ---> System.Net.HttpListenerExceptio
n: Failed to listen on prefix 'http://localhost:8080/' because it conflicts with
an existing registration on the machine.
at System.Net.HttpListener.AddAllPrefixes()
at System.Net.HttpListener.Start()
at Microsoft.Owin.Host.HttpListener.OwinHttpListener.Start(HttpListener liste
ner, Func`2 appFunc, IList`1 addresses, IDictionary`2 capabilities, Func`2 logge
rFactory)
at Microsoft.Owin.Host.HttpListener.OwinServerFactory.Create(Func`2 app, IDic
tionary`2 properties)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments,
Signature sig, Boolean constructor)
at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Objec
t[] parameters, Object[] arguments)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invoke
Attr, Binder binder, Object[] parameters, CultureInfo culture)
at Microsoft.Owin.Hosting.ServerFactory.ServerFactoryAdapter.Create(IAppBuild
er builder)
at Microsoft.Owin.Hosting.Engine.HostingEngine.StartServer(StartContext conte
xt)
at Microsoft.Owin.Hosting.Engine.HostingEngine.Start(StartContext context)
at Microsoft.Owin.Hosting.Starter.DirectHostingStarter.Start(StartOptions opt
ions)
at Microsoft.Owin.Hosting.Starter.HostingStarter.Start(StartOptions options)
at Microsoft.Owin.Hosting.WebApp.StartImplementation(IServiceProvider service
s, StartOptions options)
at Microsoft.Owin.Hosting.WebApp.Start(StartOptions options)
at Microsoft.Owin.Hosting.WebApp.Start[TStartup](StartOptions options)
at Microsoft.Owin.Hosting.WebApp.Start[TStartup](String url)
at ConsoleApplication1.Program.Main(String[] args) in e:\EShared\Dev2015\WebA
ppScottAllen\ConsoleApplication1\ConsoleApplication1\Program.cs:line 12
Press any key to continue . . .
I ran the Resource Monitor from the Task Manager Performance Tab and can see that there are 2 entries on Listening Ports for 8080.
Both have Image=System, PID=4, IPv6 unspecified, Protocol TCP, Firewall Status Not allowed, not restricted
I am new to Listening Ports, how do I get the code working?
When faced with error: "Failed to listen on prefix 'http://someURL:somePortNo/' because it conflicts with an existing registration on the machine." It is not really necessary that there is an application actively listening on that port - thus output of Netstat -abno may not always help. If the already registered application is running it can help you narrow down to which application is causing the issue by looking at the info Netstat provides.
However, you will get this error even after the application in question is stopped since the error indicates a registration. The correct diagnostic command therefore is:
netsh http show urlacl
We need to examine the output and check whether any of the listed reserved URLs is configured to listen on the specific port your application is trying to use. You need to note the value of the "Reserved URL" field for that specific application. You will need it later for deleting the registration which is causing the error.
Uninstalling that specific application - assuming their uninstall procedure does include an un-registration - may resolve the problem. Alternatively you could take a more direct and precise approach of using the command for deleting a URL reservation:
(Note that if the conflict is legitimate, it may be better to reconfigure your application to listen on a different port instead.)
netsh http delete urlacl url=<value of "Reserved URL" in the output of netsh http show urlacl>
When the command works you will see output: URL reservation successfully deleted.
Upon running netsh http show urlacl a second time you will now see that the url registration is indeed gone. And now running your application should not result in the error you were seeing earlier.
I was able to solve the problem by uninstalling several programs.
Unfortunately I did not test after each, so I don't know which one it was.
They included Dropbox, Goto Assist, Goto Meeting and a winforms application
I had the same issue, and it was a silly fix. I had other console apps open that was using the same port number, so after I have closed all the console apps, I was able to run and did not get this error.
I had the same error in Visual Studio which was kind enough to tell me which port was wrong. I then ran this command in an Administrator Command Prompt:
netsh http delete urlacl url=http://+:44308/
Note : It is important to remember to final slash. Otherwise you will get an error.
I have an iOS application that developed by Xamarin Studio.
When I try to get a string from server I got the following exception.
Exception in Class: WebClient
Line : 271
and Method:DownloadDataCore
with message Error: SendFailure (Error writing headers)
Stack Trace: at System.Net.HttpWebRequest.EndGetResponse (IAsyncResult asyncResult) [0x00065] in ///Library/Frameworks/Xamarin.iOS.framework/Versions/8.2.0.207/src/mono/mcs/class/System/System.Net/HttpWebRequest.cs:971
at System.Net.HttpWebRequest.GetResponse () [0x0000e] in ///Library/Frameworks/Xamarin.iOS.framework/Versions/8.2.0.207/src/mono/mcs/class/System/System.Net/HttpWebRequest.cs:985
at System.Net.WebClient.GetWebResponse (System.Net.WebRequest request) [0x00000] in ///Library/Frameworks/Xamarin.iOS.framework/Versions/8.2.0.207/src/mono/mcs/class/System/System.Net/WebClient.cs:1563
at System.Net.WebClient.ReadAll (System.Net.WebRequest request, System.Object userToken) [0x00000] in ///Library/Frameworks/Xamarin.iOS.framework/Versions/8.2.0.207/src/mono/mcs/class/System/System.Net/WebClient.cs:972
at System.Net.WebClient.DownloadDataCore (System.Uri address, System.Object userToken) [0x0000a] in ///Library/Frameworks/Xamarin.iOS.framework/Versions/8.2.0.207/src/mono/mcs/class/System/System.Net/WebClient.cs:271
When I try to download the string from a none-SSL website it is ok and loads the string without any problem.
The website certificate is completely valid and It doesn't refused by Safari both in simulator and OSX.
I am runing the application on simulator.
I will be so thankful if you can help me fix the issue.
The code that I used for getting string from server is :
System.Net.ServicePointManager.ServerCertificateValidationCallback += (o, certificate, chain, errors) => true;
WebClient wc = new WebClient ();
wc.CachePolicy = new System.Net.Cache.RequestCachePolicy (System.Net.Cache.RequestCacheLevel.NoCacheNoStore );
result = wc.DownloadString (Url);
Regards
Before accessing SSL site with mono, you have to run mozroots --import --sync to import list of mozilla trusted certificates.
Also, there is mono security FAQ which can help to resolve SSL issues.
I am scratching my head over a peculiar problem that seems to work on IE and Chrome.
We have a custom passive STS which serves a RP. All is well till i authenticate via my custom authentication service and then STS returns token which i can see in my temp folder. The POST operation which then sends the SAML 1.0 token hangs and silently dies instead of getting back the FedAuth cookie which would normally redirect me the RP
Note : RP and IP are hosted on web server that is behind a reverse proxy server (Nginx). Reverse proxy is hosted over SSL and all traffic to and fro proxy server and webserver is non SSL
The following get logged on the webserver
Event code: 3005
Event message: An unhandled exception has occurred.
Event time: 12/11/2013 5:16:33 PM
Event time (UTC): 12/11/2013 5:16:33 PM
Event ID: eef80ad2bffe425780dd46e5f28c0306
Event sequence: 2
Event occurrence: 1
Event detail code: 0
Exception information:
Exception type: XmlException
Exception message: **Unexpected end of file. Following elements are not closed: RequestedUnattachedReference, RequestSecurityTokenResponse,** RequestSecurityTokenResponseCollection. Line 1, position 5852.
at System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader reader, String res, String arg1, String arg2, String arg3)
at System.Xml.XmlExceptionHelper.ThrowUnexpectedEndOfFile(XmlDictionaryReader reader)
at System.Xml.XmlBufferReader.GetByteHard()
at System.Xml.XmlBufferReader.GetByte()
at System.Xml.XmlUTF8TextReader.ReadStartElement()
at System.Xml.XmlUTF8TextReader.Read()
at System.Xml.XmlBaseReader.ReadEndElement()
at Microsoft.IdentityModel.Protocols.WSTrust.WSTrustSerializationHelper.ReadRSTRXml(XmlReader reader, RequestSecurityTokenResponse rstr, WSTrustSerializationContext context, WSTrustConstantsAdapter trustConstants)
at Microsoft.IdentityModel.Protocols.WSTrust.WSTrust13ResponseSerializer.ReadXmlElement(XmlReader reader, RequestSecurityTokenResponse rstr, WSTrustSerializationContext context)
at Microsoft.IdentityModel.Protocols.WSTrust.WSTrustSerializationHelper.CreateResponse(XmlReader reader, WSTrustSerializationContext context, WSTrustResponseSerializer responseSerializer, WSTrustConstantsAdapter trustConstants)
at Microsoft.IdentityModel.Protocols.WSTrust.WSTrust13ResponseSerializer.ReadXml(XmlReader reader, WSTrustSerializationContext context)
at Microsoft.IdentityModel.Protocols.WSFederation.WSFederationSerializer.CreateResponse(WSFederationMessage message, WSTrustSerializationContext context)
at Microsoft.IdentityModel.Web.WSFederationAuthenticationModule.GetXmlTokenFromMessage(SignInResponseMessage message, WSFederationSerializer federationSerializer)
at Microsoft.IdentityModel.Web.WSFederationAuthenticationModule.GetXmlTokenFromMessage(SignInResponseMessage message)
at Microsoft.IdentityModel.Web.WSFederationAuthenticationModule.GetXmlTokenFromMessage(SignInResponseMessage message, WSFederationSerializer federationSerializer)
at Microsoft.IdentityModel.Web.WSFederationAuthenticationModule.GetSecurityToken(SignInResponseMessage message)
at Microsoft.IdentityModel.Web.WSFederationAuthenticationModule.GetSecurityToken(HttpRequest request)
at Microsoft.IdentityModel.Web.WSFederationAuthenticationModule.SignInWithResponseMessage(HttpRequest request)
at Microsoft.IdentityModel.Web.WSFederationAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs args)
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
I dont understand why just for FF i get this problem. Is there a limitation on the size of the content that is sent in the header for FF?
Another question is : I have installed two different certificates one at proxy server (SSL)and one at webserver(STS) to signing the token. Can i use the same certificate? Should i?
According to the top voted answer on the question Can HTTP headers be too big for a browser, Firefox does have the lowest individual header-size (or at least did back in FF3.6). The accepted answer may help you though as you've mentioned you're behind a proxy.
I'm using OAuthWebSecurity to login with facebook and it is working on localhost. However then deployed to the live server I get the following error message:
The remote server returned an error: (400) Bad Request.
I have checked domain details are correct on facebook.
The sandbox mode is disabled.
I have disabled windows firewall - still get same error.
Responses from facebook have the identical format whether in live or localhost environments.
The date and time of live server is correct.
I've test locally also changing the host file to the live domain - still works locally.
Here's the stack trace:
[WebException: The remote server returned an error: (400) Bad Request.]
System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request) +3291120
System.Net.WebClient.DownloadString(Uri address) +207
DotNetOpenAuth.AspNet.Clients.FacebookClient.QueryAccessToken(Uri returnUrl, String authorizationCode) +293
DotNetOpenAuth.AspNet.Clients.OAuth2Client.VerifyAuthentication(HttpContextBase context, Uri returnPageUrl) +167
DotNetOpenAuth.AspNet.OpenAuthSecurityManager.VerifyAuthentication(String returnUrl) +502
Microsoft.Web.WebPages.OAuth.OAuthWebSecurity.VerifyAuthenticationCore(HttpContextBase context, String returnUrl) +231
Any suggestions?
There was a defect open related to this:
https://github.com/DotNetOpenAuth/DotNetOpenAuth/issues/203
but that library is apparently no longer being maintained:
https://github.com/DotNetOpenAuth/DotNetOpenAuth/issues/317#issuecomment-29580565
... although it is still referenced in many Microsoft documents. Investigating that related to another defect.
See also: The remote server returned an error: (400) Bad Request Microsoft.AspNet.Membership.OpenAuth
This is an old one, but I hit a 400 error from Facebook login using dotnetopenoath as it is integrated into MVC 4 and went on a wild goose chase thinking that it was not working because it was no longer supported, when all I needed to do was catch and log the exception which pointed me to the problem for my particular case (app secret proof setting):
catch (WebException exception)
{
using (WebResponse response = exception.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse) response;
m_log.Debug("Error code: " + httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
{
if (data != null)
{
using (var reader = new StreamReader(data))
{
string text = reader.ReadToEnd();
m_log.Debug(text);
}
}
}
}
}
I need to provide a file-download feature where the web server retrieves the file from another source (via HTTP) and simultaneously streams it to the browser. I am guessing that using MVC's Controller.File ActionResult will not work, but I wrote a prototype like this anyway:
public ActionResult Download()
{
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create("http://somewhere/somefile.pdf");
HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse();
Stream stream = webResponse.GetResponseStream();
var mimeType = "application/pdf";
var fileName = "somefile.pdf";
return File(stream, mimeType, fileName);
}
This works fine, but there is no way to call Close() on the HttpWebResponse and Stream after the return statement. The help on the HttpWebResponse.GetResponseStream method says, "You must call either the Stream.Close or the HttpWebResponse.Close method to close the stream and release the connection for reuse. It is not necessary to call both Stream.Close and HttpWebResponse.Close, but doing so does not cause an error. Failure to close the stream will cause your application to run out of connections."
Should I create an HttpHandler and manually read bytes from the source stream and write them out to the response, along the lines of this or this? Is there another approach I'm not aware of?
While I'm not directly familiar with trying something like this, my first though was to do what you suggested in regards to reading in the stream, closing the connection, then returning the bytes as the response. Being a stream, I don't know how you can get around leaving it open for the sake of returning its contents as you do in your prototype, but then being able to close it when you're done.