Silverlight's WebClient isn't connecting to my server - asp.net

I've got a problem here.
I've got an ASP.net website hosting a silverlight 2 application.
I'd like the site to communicate to and fro from the silverlight app, and I'm doing this via http requests. Incidentally, if anyone knows a better way, please do tell me.
My server's got the following http listener set up. I copied this from a tutorial site somewhere, since it's mainly experimentation at the moment :
HttpListener listener = new HttpListener ( );
listener.Prefixes.Add("http://localhost:4531/MyApp/");
listener.Start( );
// Wait for a client request:
HttpListenerContext context = listener.GetContext( );
// Respond to the request:
string msg = "You asked for: " + context.Request.RawUrl;
context.Response.ContentLength64 = Encoding.UTF8.GetByteCount (msg);
context.Response.StatusCode = (int) HttpStatusCode.OK;
using (Stream s = context.Response.OutputStream)
using (StreamWriter writer = new StreamWriter (s))
writer.Write (msg);
listener.Stop( );
I'm using the following code to send a request :
private void MyButton_Click(object sender, RoutedEventArgs e)
{
Button b = sender as Button;
b.Content = "Hello World";
Uri serviceUri = new Uri("http://localhost:4531/MyApp/");
WebClient downloader = new WebClient();
downloader.DownloadStringCompleted += new DownloadStringCompletedEventHandler(TestDownloadStoriesCompleted);
downloader.DownloadStringAsync(serviceUri);
}
void TestDownloadStoriesCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
{
TextBox1.Text = e.Result;
}
}
My problem is that I can connect to the webserver from a console application using pretty much the same code (I tested it by setting a breakpoint in the code), however nothing happens when I click the button in silverlight. (I've added the "Hello World" to test that I am indeed connecting the delegate to the button.)
I've read that silverlight needs policies to connect via webclient, but it shouldn't be the case if I'm using the same server and the same domain for both the server and the silverlight application!
Thanks for all your replies!
EDIT : I am recieving this exception :
System.Security.SecurityException ---> System.Security.SecurityException: Security error.
Also, based on what I'm reading apparently to be site-of-origin, the deployment URI of the xap and the request URI must also be of the same port.
However, when I set the properties for the server to be hosted on a specific port, and I set the listener to listen to that same port, it fails with the message that The process cannot access the file because it is being used by another process. I assume it is because the http listener can't listen to the same port being used to host it :|
But then how can I make Silverlight perform host of origin webclient requests?

Since this is only a test add an "else TextBox1.Text=e.Error.ToString();" in your TestDownloadStoriesCompleted handler to see what error you get.
EDIT:
You can't host both the asp.net app and your listener on the same port - you could fix this by using a different port and serving a clientaccesspolicy.xml from your httplistener.
However I think it would make more sense for you to take a look at WCF web services (you add the svc to your asp.net app). Here's a sample.

you can use tools like http://www.fiddler2.com/fiddler2/
to actually see what is going on during the request....
This can give some help for further debugging...

I am now using HTTP handlers for communication. It seems that they will work fine enough for my purpose, although I still want to try out some WCF.

Related

Can't see WebClient post request in Fiddler

I have an ASP.NET WebForms app (sender) which sends a WebClient post request to another ASP.NET app (receiver) on the same dev machine. The WebClient post is initiated by clicking a button in the sender app. It's a test app and the form has only the button. I can see the post from the button in Fiddler but I don't see the post request from the WebClient method. Why?
I know the WebClient post runs successfully because the breakpoint is hit in the receiver app and the Forms collection has the value of the input field from the WebClient request from the sender app. (Using Windows 8.1)
Update This is the call:
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
var data = "FirstName=John";
var result = client.UploadString("http://localhost/testform/default.aspx", "POST", data);
Console.WriteLine(result);
}
.NET and IE(before version 9) are not sending requests to localhost through any proxies. There are 3 possible solutions:
Use machine name or hostname: http://<machine name>/testform/default.aspx
Add ipv4.fiddler to the URL: http://localhost.fiddler/testform/default.aspx
Add custom rule to the fiddler:
static function OnBeforeRequest(oSession:Fiddler.Session){
if (oSession.HostnameIs("MYAPP")) {
oSession.host = "<put your ip address and port here>";
}
}
Then you should be able to capture traffic through http://myapp/testform/default.aspx
Reference Problem: Traffic sent to http://localhost or http://127.0.0.1 is not captured.
Could be multiple things. Here are some possibilities
You have Fiddler set to filter to only show things from a particular process (or some other type of filter but process is the easiest one to accidentally turn on)
You have not turned on HTTPS capture in Fiddler but this missing request is HTTPS (it's off by default)
Your WebClient has a custom proxy configured and isn't pulling the default settings from IE

WebRequest fails when executed in Asp.net server side but passes when executed from Windows application

IIS 8 & Windows 8
I have below sample code which I am trying to check whether a url exists, when I ran from console app it works fine, response is obtained, but when executed from server side ASP.net page it throws socket exception.
Sample code:
try
{
Uri uri = new Uri("HTTPS://test");
WebRequest http = HttpWebRequest.Create(uri);
HttpWebResponse response = (HttpWebResponse)http.GetResponse();
Stream stream = response.GetResponseStream();
}
catch (UriFormatException sds)
{
}
catch (IOException sdsd)
{
}
Error:
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
Any suggestions in this regard would helpful.
Without more information, my guess would be that the asp.net application is running under an account which does not have enough privs to access a network resource. You can try changing the account under which the asp.net application runs or impersonate a user with network access rights.

HttpModule not receiving cookies on IIS 6

I have an HttpModule that I created and am running on IIS 6 using Windows Server 2003. I can send cookies to the browser, but I can not read them on the next request, cookie is always null.
If I run this module on IIS 7 though, it works just fine. IIS 7 not an option at the moment as we have not switched over and this needs to get done before that will happen.
Also, I've already tried using the PostAcquireRequestState hook.
public void Init(HttpApplication httpApp)
{
httpApp.BeginRequest += OnBeginRequest;
}
public void OnBeginRequest(Object sender, EventArgs e)
{
var httpApp = (HttpApplication)sender;
var context = httpApp.Context;
const string cookieName = "sId";
if (!string.IsNullOrEmpty(context.Request.QueryString["cookie"]))
{
var ck = new HttpCookie(cookieName)
{
Value = httpApp.Context.Request.QueryString["cookie"],
Expires = DateTime.Now.AddDays(1)
};
httpApp.Response.Cookies.Add(ck);
}
else
{
var cookie = httpApp.Request.Cookies[cookieName]
}
}
I ran into a similar problem, but had a different solution, so I thought I'd share, in case it helps someone. I took zengchun's suggestion as well to use some tools to inspect request & response headers. Since I'm using IE, the F12 Dev Tools works great for this. As soon as I saw the response header for the cookie, I noticed the secure flag was set. Sure enough, I had copied code from a production SSL-hosted site to a test site that did not use SSL, so the secure flag on the cookie prevented the code from being able to read it. I updated the web.config to remove requireSSL from the httpcookies node, and my site started working. :)
your code look worked.the problem may be occur in the client-side how to request the next page.you can use the firebug with firefox or the fidder tools that can log your client-side request and see the request whether send cookd value in the request header to the server.
for example
the request headers:
get /1.aspx
.....
Cookie: sId=123 [if the client has a cookie then it will appear in here.]
the response headers:
Set-Cookie: sId=123; expires=Fri, 30-Mar-2012 07:20:23 GMT;
path=/
if the server add cookie to the response,then response it look like the above.
now,i guess the problem in your cook domain or you cookie path is different.
the best method to set cookie is like the follow code:
var ck = new HttpCookie(cookieName)
{
Value = httpApp.Context.Request.QueryString["cookie"],
Expires = DateTime.Now.AddDays(1),
Path="/",
Domain="your domain"
};
good luck.
Thanks to zhengchun I was able to get to the root of the problem. It turns out I was unable to set the cookie using requests to static files. I created .aspx files for my initial requests that redirected to the static files after setting the cookie. My HttpModule could then read the cookie after being set in the .aspx file. Not sure why I need a .aspx file to set the cookie instead of the HttpModule, but this fixed it.

msxml3.dll error '80072ee2' in ASP Page

We have just moved to a new dedicated server that has Windows 2008 and SQL Server 2008. I am trying to access an ASP page on the same server using Server.CreateObject("MSXML2.ServerXMLHTTP").
On our previous 2003 server this worked correctly, however with the new 2008 server the operation just times out.
Here is the code:
strURL = "http://www.storeboard.com/profile/profile_view.asp?MemberID=" & MemberID & "&sid=" & cSession.SessionID
Set oXMLHttp = Server.CreateObject("MSXML2.ServerXMLHTTP")
oXMLHttp.open "GET", strURL, false
oXMLHttp.send()
IF oXMLHttp.status = 200 THEN
strOut = oXMLHttp.responseText
ELSE
strOut = "Could not get XML data."
END IF
Set oXMLHttp = nothing
The code is very simple but I get the following error:
msxml3.dll error '80072ee2'
The operation timed out
/handle404.asp, line 291
Line 291 refers to oXMLHttp.Send() line.
Is there an alternative code I can use? I use the script other places on the server that access files on other servers and they work correctly, but any access to files on our server doesn't work.
Is there an alternative method that will allow me to keep the URL intact in the browser? The person could write the URL in their browser: http://www.example.com/hello the file doesn't exist but I have a 404 handler that then points the user to the correct path without changing the browser URL which is essential for our SEO ratings.
Microsoft has a published a KB article entitled INFO: Do Not Send ServerXMLHTTP or WinHTTP Requests to the Same Server
If the ServerXMLHTTP or WinHTTP component must send a request to
another ASP on the same server, the target ASP must be located in a
different virtual directory and set to run in high isolation. Avoid
using ServerXMLHTTP or WinHTTP to send a request to an ASP that is
located in the same virtual directory.
...
A finite number of worker threads (in the Inetinfo.exe or Dllhost.exe
process) is available to execute ASP pages. If all of the ASP worker
threads send HTTP requests back to the same Inetinfo.exe or
Dllhost.exe process on the server from which the requests are sent,
the Inetinfo.exe or Dllhost.exe process may deadlock or stop
responding (hang), because the pool of worker threads to process the
incoming requests will be exhausted. This is by design.
As far as alternatives go, it depends on what you're doing with the response after you receive it. If the entire purpose of the script is to forward the request to profile_view.asp, you might be able to use Server.Transfer instead.
I had this same issue. In my case the web request I was trying to make was an internal site url (within the same app pool). With server side debugging set to enabled, the asp app pool seems to be restricted to a single worker thread. By disabling this feature, the request was then able to be processed.
msxml3.dll is pretty old. It was distributed with Internet Explorer 6 to give you a rough idea.
Can you have someone install a later version on the server?
http://support.microsoft.com/kb/269238 gives you a list of versions to send to whoever it responsible for the server.
If the problem is genuinely down to a time out you could look into switching ASP buffering off. (This based soley on a guess that if the server object started to receive a response it would hold off on the timeout front.
Alternatively you coudl try processing the value on the client side, below is a function from some code I wrote which does this....
function getDets(RateID) {
var xmlHttp;
try {
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
}
catch (e) {
try {
// Internet Explorer
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4) {
var str;
var newStr;
str=xmlHttp.responseText
newStr=str.split("|");
window.document.all.OR2.style.display="block";
window.document.all.OR3.style.display="block";
window.document.OvertimeRates.Description.value=newStr[0];
window.document.OvertimeRates.Factor.value=newStr[1];
}
}
if (RateID==0) {
window.document.OvertimeRates.Description.value="";
window.document.OvertimeRates.Factor.value="";
}
else {
xmlHttp.open("GET","GetOvertimeRate.asp?RateID="+RateID,true);
xmlHttp.send(null);
}
}
Good luck!

The remote host closed the connection. The error code is 0x80070057

I'm getting a lot of these error messages in my logs on one of my servers and intermittently on two others.
Googling didn't reveal very much information, mostly related to file uploads or downloads being interrupted.
My pages are basically just text files with "ok" in them that only have .aspx extension for future plans, there's no actual code powering the pages. Servers are all Windows Server 2008 RC2 x64 running IIS7 / ASP.NET 4.
Statistically it's happening well under 1% of the time but because of the volume of traffic that still clutters my event log with 2 or 3 of these messages per minute.
Edit:
I tracked down the problem, setting buffering to true stopped it occurring.
I know this has been answered, but on the off chance this helps someone else, it happened in my MVC project sometimes when I had one dbContext set at the top of a repository. When I switched to a using statement for database connections, the error never appeared again.
So, I went from this at the top of each repository:
DbContext db = new DbContext();
To this for each individual connection:
using (DbContext db = new DbContext())
{
//db connection stuff here....
}
Worth saying that no one ever reported seeing the error and no error was ever shown to the browser, but nice to get it off the logs all the same!
Are you returning a Stream?
You might need to close it after the method finishes.
Check out this: Closing Returned Streams in WCF
Here is the code this blog suggests:
public Stream GetFile(string path)
{
Stream fileStream = null;
try
{
fileStream = File.OpenRead(path);
}
catch(Exception)
{
return null;
}
OperationContext clientContext = OperationContext.Current;
clientContext.OperationCompleted +=
new EventHandler(delegate(object sender, EventArgs args)
{
if (fileStream != null) fileStream.Dispose();
});
return fileStream;
}

Resources