I'm trying to write a function in my Silverlight app that requests a particular page that doesn't exist on the same domain as where my Silverlight app is hosted.
For example:
Silverlight App: http://www.mysilverlightsite.com/
Target Page: http://www.mysite.com/MyPage.aspx
However, this generates a 'SecurityException':
{System.Security.SecurityException:
Security error. at
System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult
asyncResult) at
System.Net.Browser.ClientHttpWebRequest.EndGetResponse(IAsyncResult
asyncResult) ...}
From what I understand, this is related to cross-domain requests being restricted, and found some posts that mentioned that this article (http://msdn.microsoft.com/en-us/library/cc197955(VS.95).aspx) might be related.
Here's my code:
public static void CheckPageContentsAsync(CheckPageContentsCallback callback, DependencyObject uiObject)
{
bool result = false;
try
{
HttpWebRequest request = WebRequest.CreateHttp("http://www.mysite.com/MyPage.aspx");
request.BeginGetResponse((asyncHandle) =>
{
try
{
uiObject.Dispatcher.BeginInvoke(new VoidDelegate(() =>
{
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncHandle);
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
string content = sr.ReadToEnd();
if (content.Contains("Value"))
{
result = true;
}
if (callback != null)
{
callback.Invoke(result);
}
}
}), null);
}
catch (Exception excep)
{
throw new Exception("Failed to process response.", excep);
}
}, null);
}
catch(Exception excep2)
{
throw new Exception("Failed to generate request.", excep2);
}
}
Haven't been able to make much sense of the applicability of the "clientaccesspolicy.xml" or "crossdomain.xml" files as a solution.
Can anyone explain clearly how I modify my app, or the web server I'm requesting from, to resolve this issue?
I use to copy this file in the root of my app:
<cross-domain-policy>
<allow-access-from domain="*.*" headers="SOAPAction"/>
<allow-http-request-headers-from domain="*.*" headers="SOAPAction"/>
<site-control permitted-cross-domain-policies="master-only"/>
</cross-domain-policy>
Name it crossdomain.xml.
Related
I need to upgrade our service bus nuget package to 3.2.2 (think the evenprocessor host requires it) but I have always kept our service bus project lib at 2.8.2. This is mainly due to the fact that BeginReceive() and EndReceive() looks to have been removed. Is there any reason or anyway I can easily convert this
public void StartReceiving(RecieverCallback callback, TimeSpan waittime, object state = null)
{
this._recieverCallback = callback;
_queueClient = this.MessagingFactory.CreateQueueClient(QueueName, ReceiveMode);
// make initial async call
_asyncresult = _queueClient.BeginReceive(waittime, ReceiveDone, _queueClient);
}
public void ReceiveDone(IAsyncResult result)
{
if (result != null)
{
try
{
var tmpClient = result.AsyncState as QueueClient;
var brokeredMessage = tmpClient.EndReceive(result);
if (brokeredMessage != null)
{
if (ReceiveMode == ReceiveMode.PeekLock)
{
brokeredMessage.Complete();
}
var tmpMessage = brokeredMessage.GetBody<T>();
ProcessMessageProperties(tmpMessage, brokeredMessage);
_recieverCallback(tmpMessage);
}
}
catch (Exception ex)
{
_logger.Fatal("ReceiveDone: {0}", ex.Message);
Console.WriteLine(ex.Message);
}
}
// do recieve for next message
_asyncresult = _queueClient.BeginReceive(ReceiveDone, _queueClient);
}
Image showing the error
Following image shows what happens if I upgrade servicebus to 3.2.2 which I believe will solve the original error (program running 3.2.2, lib project running 2.8.x)
I figured it out see link
https://gist.github.com/sitereactor/8953583
If anyone has a similar issue, let me know and will post my code but its 95% the same as per the link.
Hi everyone im trying to create a method that will always return a url source, if for example internet goes off it will continue working until it comes up and return the url source and so on if something else occurs. So far in my method when i "turn off" the internet and "turn it on" back procedures continue normaly but im having an issue when a timeout occurs and im "falling" in a loop i know that the while(true) is not the right approach but im using it for my tests.
So how can i skip the timeout exception and "retry" my method?
public static async Task<string> GetUrlSource(string url)
{
string source = "";
while (true)
{
HttpWebRequest hwr = (HttpWebRequest)WebRequest.Create(url);
hwr.AllowAutoRedirect = true;
hwr.UserAgent = UserAgent;
hwr.Headers.Add(hd_ac_lang[0], hd_ac_lang[1]);
hwr.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
hwr.Timeout = 14000;
try
{
using (var response = hwr.GetResponse())
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
source = await reader.ReadToEndAsync();
if (check_source(source))
{
return source;
}
}
}
}
catch (WebException ex)
{
hwr.Abort();
if (ex.Status == WebExceptionStatus.ProtocolError)
{
if (((HttpWebResponse)ex.Response).StatusCode == HttatusCode.NotFound)
{
// handle the 404 here
return "404";
}
}
else
{
Console.WriteLine(ex.Status.ToString());
}
}
}
}
Note: i used to have the hwr.Abort(); into a finnaly clause but it didnt help.
Edit: the console is writting this message every 14 seconds as my timeout i think its something related with that.
ِAn alternative solution to get rid of timeout problem can be is to use WebBrowser component and to navigate to the required url(webbrowser1.Navigate(url);) ,and to wait in a loop until the documentcompleted event is raised and then to get the source code by this line :
string source = webbrowser1.DocumentText;
Well it seems that i found a solution that was related with the service point of the request.
So in my catch when a timeout occurs im using this to release the connection.
hwr.ServicePoint.CloseConnectionGroup(hwr.ConnectionGroupName);
I'll keep this updated.
public async static Task<WebResponse> GetResponseAsync(this HttpWebRequest request, Dictionary<string, object> post)
{
var tcs = new TaskCompletionSource<WebResponse>();
try
{
request.BeginGetRequestStream((arReq) =>
{
var stream = request.EndGetRequestStream(arReq);//throw NotSupportedException
writeMultipartObject(stream, post);
stream.Close();
request.BeginGetResponse((ar) =>
{
var response = request.EndGetResponse(ar);
tcs.SetResult(response);
}, null);
}, null);
}
catch (Exception we)
{
tcs.SetException(we);
}
return await tcs.Task;
}
when i post something, it no works..=.=
var stream = request.EndGetRequestStream(arReq);//throw NotSupportedException
tell me why? ToT.................
System.NotSupportedException ---> System.NotSupportedException: Specified method is not supported.
at System.Net.Browser.ClientHttpWebRequest.InternalEndGetResponse(IAsyncResult asyncResult)
at System.Net.Browser.ClientHttpWebRequest.<>c_DisplayClasse.b_d(Object sendState)
at System.Net.Browser.AsyncHelper.<>c_DisplayClass1.b_0(Object sendState)
I have experienced similar behaviour (on Windows Phone only) and got it working by explicitly disposing the stream you're writing to.
So try to add
stream.Flush();
before, and
stream.Dispose();
after your
stream.Close();
statement and see if that helps.
Apparently, the behaviour of the networking stack in .Net is different dependent on the platform your code runs on, due to the fact that the .Net framework is "redeveloped" for each platform.
I hope this helps.
Cheers,
Kristof.
I'm using this code, to fetch the latest version of my app in *Form1_Load*:
string result1 = null;
string url1 = "http://site.com/version.html";
WebResponse response1 = null;
StreamReader reader1 = null;
try
{
HttpWebRequest request1 = (HttpWebRequest)WebRequest.Create(url1);
request1.Method = "GET";
response1 = request1.GetResponse();
reader1 = new StreamReader(response1.GetResponseStream(), Encoding.UTF8);
result1 = reader1.ReadToEnd();
}
catch (Exception ex)
{
// show the error if any.
}
finally
{
if (reader1 != null)
reader1.Close();
if (response1 != null)
response1.Close();
}
The problem is that when I shut the server down the whole application is stucking and a window is popping out,saying:
Unable to connect to the remote server
Which seems legit.
Is there a way to bypass this crash (when the server is down) and break out of the version checking?
Add an additional catch block that catches the specific Exception type that you're seeing... the code will look like...
try
{
//*yadda yadda yadda*
}
catch (System.Net.WebException WebEx)
{
//*Correctly set up a situation where the rest of your program will know there was a connection problem to the website.*
}
catch (Exception ex)
{
//*Do the error catching you do now*
}
finally
{
//*yadda yadda*
}
This construction will allow you to handle WebExceptions differently from other kinds of exceptions: note that all Exceptions derive from one base class, Exception, and you can make your own for uses like this.
I am using this code to get an xml from an uri
try
{
doc = await XmlDocument.LoadFromUriAsync(new Uri(apiRequest));
}
catch(Exception e)
{
return false;
}
The problem is that the function isn't throwing any exception when not connected to the internet, and the whole program just blocks. It does throw an exception if I set the uri to something invalid like "http://notanactualluri.com" or to a valid uri that doesn't contain an xml.