get html content of a page with Silverlight - c#

I'm trying to get the html content of a page using silverlight. Webresponse and request classes don't work in silverlight.
I did some googling and I found something. This is what i tried:
public partial class MainPage : UserControl
{
string result;
WebClient client;
public MainPage()
{
InitializeComponent();
this.result = string.Empty;
this.client = new WebClient();
this.client.DownloadStringCompleted += ClientDownloadStringCompleted;
}
private void btn1_Click(object sender, RoutedEventArgs e)
{
string url = "http://www.nu.nl/feeds/rss/algemeen.rss";
this.client.DownloadStringAsync(new Uri(url, UriKind.Absolute));
if (this.result != string.Empty && this.result != null)
{
this.txbSummery.Text = this.result;
}
}
private void ClientDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
this.result = e.Result;
//handle the response.
}
}
It gives me a runtime error after pressing the button:
Microsoft JScript runtime error: Unhandled Error in Silverlight Application An exception occurred during the operation, making the result invalid. Check InnerException for exception details. at System.ComponentModel.AsyncCompletedEventArgs.RaiseExceptionIfNecessary()
at System.Net.DownloadStringCompletedEventArgs.get_Result()
at JWTG.MainPage.ClientDownloadStringCompleted(Object sender, DownloadStringCompletedEventArgs e)
at System.Net.WebClient.OnDownloadStringCompleted(DownloadStringCompletedEventArgs e)
at System.Net.WebClient.DownloadStringOperationCompleted(Object arg)
I've tried numerous things but all failed.
What am i missing? Or does anyone know how i could achieve this in a different way?
Thanks in advance!

This is related to clientaccesspolicy.xml. Read more here:
http://msdn.microsoft.com/en-us/library/cc645032(VS.95).aspx
"If the connection request was from a WebClient or an HTTP class to a cross-domain site, the Silverlight runtime tries to download the security policy file using the HTTP protocol. The Silverlight runtime first tries to download a Silverlight policy file with a name of "clientaccesspolicy.xml" at the root of the requested target domain using the HTTP protocol.
If the "clientaccesspolicy.xml" is either not found (the web request returns a 404 status code), returned with an unexpected mime-type, is not valid XML, or has an invalid root node, then the Silverlight runtime will issue a request for a for the Flash policy file with a name of "crossdomain.xml" at the root of the requested target domain, using the HTTP protocol.
HTTP redirects for the policy file are not allowed. A redirect for a policy file will result in a SecurityException of access denied."

Try this one, instead of your btn1_Click and ClientDownloadStringCompleted methods. It invokes the GUI thread after the feed is downloaded to update the textbox. If it fails because of an error on the network, it will unpack the exception (contained as an inner exception in a TargetInvocationException) and rethrow the inner exception.
private void btn1_Click(object sender, RoutedEventArgs e)
{
string url = "http://www.nu.nl/feeds/rss/algemeen.rss";
this.client.DownloadStringAsync(new Uri(url));
}
private void ClientDownloadStringCompleted(object sender,
DownloadStringCompletedEventArgs e)
{
try
{
Dispatcher.BeginInvoke(() => this.txbSummery.Text = e.Result ?? "");
}
catch (TargetInvocationException tiex)
{
throw tiex.InnerException;
}
}
If the error occures again (I guess that will happen), please post a stacktrace and error message here.

You try it
private void btn1_Click(object sender, RoutedEventArgs e)
{
string url = "http://www.nu.nl/feeds/rss/algemeen.rss";
this.client.DownloadStringAsync(new Uri(url, UriKind.Absolute));
}
private void ClientDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
Stream s = e.Result;
StreamReader strReader = new StreamReader(s);
string webContent = strReader.ReadToEnd();
s.Close();
this.txbSummery.Text =webContent;
}

In this line
this.client.DownloadStringAsync(new Uri(url, UriKind.Absolute));
you are stating an asynchroneous download in a background thread. And in the next line you somehow expect that it is aready completed?
If you have no knowledge about Threading just try with DownloadString first. Then your code will work.

Related

ASP.NET: Only catch certain errors at page level?

Looking at:
https://learn.microsoft.com/en-us/aspnet/web-forms/overview/getting-started/getting-started-with-aspnet-45-web-forms/aspnet-error-handling
and specifically:
private void Page_Error(object sender, EventArgs e)
{
Exception exc = Server.GetLastError();
// Handle specific exception.
if (exc is HttpUnhandledException)
{
ErrorMsgTextBox.Text = "An error occurred on this page. Please verify your " +
"information to resolve the issue."
}
// Clear the error from the server.
Server.ClearError();
}
Is there a way to only handle asp.net file uploader file size too big (e.g. over 50MB) and let all other errors be handled at the application level?
BTW, here is code to catch files that are too big at the application level:
//Global.asax
private void Application_Error(object sender, EventArgs e)
{
var ex = Server.GetLastError();
var httpException = ex as HttpException ?? ex.InnerException as HttpException;
if(httpException == null) return;
if (((System.Web.HttpException)httpException.InnerException).WebEventCode == System.Web.Management.WebEventCodes.RuntimeErrorPostTooLarge)
{
//handle the error
Response.Write("Too big a file, dude"); //for example
}
}
So in other words, can we "throw" an application level error from a page level error method (e.g., when it's anything other than that file size exception that we want to handle on that specific page)?

RingCentral incoming call notification

I am developing a winform application to get incoming call notification in real time. I am getting error on authorise method
Below is my code snippet
private async void button1_Click(object sender, EventArgs e)
{
//rc = new RestClient(txtClientID.Text, txtClientSecrete.Text, !chkIsSandBox.Checked);
rc = new RestClient(txtClientID.Text, txtClientSecrete.Text);
await rc.Authorize(txtUsrName.Text, txtExtension.Text, txtPWD.Text);
RegisterSubscription();
}
async void RegisterSubscription()
{
var subscription = rc.Restapi().Subscription().New();
//subscription.EventFilters.Add("/restapi/v1.0/account/~/extension/~/message-store");
subscription.EventFilters.Add("/restapi/v1.0/account/~/extension/~/presence");
subscription.PresenceEvent += subscription_PresenceEvent;
await subscription.Register();
}
void subscription_PresenceEvent(object sender, SubscriptionEventArgs e)
{
rtLog.Text += e.Message;
}
private async Task<TokenInfo> Authorize()
{
return await rc.Authorize(txtUsrName.Text, txtExtension.Text, txtPWD.Text);
}
I would like to receive notification for incoming call.
Thanks in advance.
Thanks for posting your answer on GitHub, Shridhar. I posted it here so people can find it if they run into the same issue:
I was able to resolve this by adding assembly to the GAC using Gacutil.exe.
https://github.com/ringcentral/ringcentral-csharp-client/issues/32

NullReferenceException when trying to send bytes via Bluetooth in C#

This is first time I am doing with Bluetooth connection in C#. I am trying to send byte (data type) from application written in C# over Bluetooth.
This is my code:
public class ConnectionManager
{
private StreamSocket socket;
private DataWriter dataWriter;
public void Initialize()
{
socket = new StreamSocket();
}
public void Terminate()
{
if (socket != null)
{
socket.Dispose();
}
}
public async void connect(HostName hostName)
{
if (socket != null)
{
await socket.ConnectAsync(hostName, "1");
dataWriter = new DataWriter(socket.OutputStream);
}
}
//sending data via Bluetooth
public void sendCommand(byte command)
{
dataWriter.WriteByte(command);
}
}
private ConnectionManager connectionManager;
// Constructor
public MainPage()
{
InitializeComponent();
connectionManager = new ConnectionManager();
}
private async void AppToDevice()
{
PeerFinder.AlternateIdentities["Bluetooth:Paired"] = "";
var pairedDevices = await PeerFinder.FindAllPeersAsync();
if (pairedDevices.Count == 0)
{
Debug.WriteLine("No devices found.");
}
else
{
foreach (var pairedDevice in pairedDevices)
{
if (pairedDevice.DisplayName == "HC-06")
{
connectionManager.connect(pairedDevice.HostName);
continue;
}
}
}
}
private void send_Click(object sender, RoutedEventArgs e)
{
byte command = Convert.ToByte(commandTextBox.Text);
connectionManager.sendCommand(command);
}
private void connect_Click(object sender, RoutedEventArgs e)
{
AppToDevice();
}
When I enter some value (for example 1 or 2) in commandTextBox and tap on Send button application crashes. This is the error message: An exception of type 'System.NullReferenceException' occurred in TestBluetooth.DLL but was not handled in user code
Can someone help me?
Sounds like a very basic error. Some object is null. It will happen when you try to access a method or a property on an object that is null.
Troubleshooting:
Check the stacktrace of the error. It says where it fails.
Turn on break on all exceptions when you debug so you can see where exactly it fails, and see which object is null.
If you can not debug it, add a try/catch around all the code in every method you have and use a MessageBox.Show(ex.ToString()) to display the full error with stacktrace when it fails.
If the error occurs in a third party dll, make sure to turn off Debugging->"Enable Just My Code" in Options in Visual Studio.
Download and install Red Gate's Reflector if it fails outside your code and you dont have the source for it. Reflector will "extract" out the code of the DLL and show you exactly the line it fails (or so I believe it does).
When you get an error saying "was not handled in user code" it means an Exception was thrown and not handled by a try/catch by you. I have a finger on the async method you have there.
If I ever play around with threads, i ALWAYS have a try/catch around all my code within the threaded code. I recommend adding a try/catch in the AppToDevice() method. Also add it for all your Form events. Show a message of error to the user or handle it and hide the error from the user.
Check these:
Best Practice for Exception Handling in a Windows Forms Application?
Exception handling in threads

Windows service starts and then stops, can't figure out the bug [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
I am trying to read a file at constant intervals and then send the data queried to a specific webserver. The following is the code I am using, but the service starts and stops without doing any thing. I can't Figure out the bug.
public partial class IPTProjectService : ServiceBase
{
private Thread checkingThread;
private System.Timers.Timer timer;
Boolean sendingTime;
public IPTProjectService()
{
InitializeComponent();
checkingThread = new Thread(update);
timer = new System.Timers.Timer(Properties.Settings.Default.TIMEINTERVAL);
timer.Elapsed += timer_Elapsed;
sendingTime = true;
}
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
setSendingTime();
if (!File.Exists("Testfile.txt"))
{
File.Create("Testfile.txt");
timer_Elapsed(sender, e);
}
else
{
File.WriteAllText("Testfile.txt", timer.ToString());
}
}
private void setSendingTime()
{
sendingTime = true;
}
private void update()
{
while (true)
{
if (sendingTime)
{
CarpoolWebClient.sendData(Properties.Settings.Default.DATAFILE);
sendingTime = false;
}
}
}
protected override void OnStart(string[] args)
{
try
{
timer.Start();
checkingThread.Start();
}
catch (Exception ex)
{
Debug.Fail(ex.ToString());
}
}
protected override void OnStop()
{
try
{
timer.Stop();
checkingThread.Abort();
}
catch(Exception e)
{
StreamWriter writer = new StreamWriter("testfile.txt", true);
writer.Write(e.ToString());
writer.Close();
}
}
}
class CarpoolWebClient
{
public static void sendData(String fileName)
{
WebRequest req = null;
WebResponse rsp = null;
try
{
//URL of message broker
string uri = "http://localhost/IPTProject/receive_xml.php";
req = WebRequest.Create(uri);
req.Method = "POST";
req.ContentType = "text/xml";
// Wrap the request stream with a text-based writer
StreamWriter writer = new StreamWriter(req.GetRequestStream());
// Write the xml text into the stream
writer.WriteLine(GetTextFromXMLFile(#fileName));
writer.Close();
rsp = req.GetResponse();
}
catch (WebException webEx)
{
//MessageBox.Show(webEx.Message);
throw webEx;
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message);
throw ex;
}
finally
{
if (req != null) req.GetRequestStream().Close();
if (rsp != null) rsp.GetResponseStream().Close();
}
}
private static string GetTextFromXMLFile(string file)
{
StreamReader reader = new StreamReader(file);
string ret = reader.ReadToEnd();
reader.Close();
return ret;
}
}
If you can, debug the service. If it's a problem because the service is set to automatically start then you can use this "trick" to automatically attach the debugger and figure out what is going wrong that way.
The call to
File.Create("Testfile.txt");
timer_Elapsed(sender, e);
will create a file and return a FileStream to the newly created file. This file is subsequently still open then timer_Elapsed is called and will cause the application to fail as it cannot open the file a second time. See the MSDN Docs on the subject.
The Create call is not required for your code, you can simplyfying the method to the example below, and it should resolve this issue. Alternatively, close the FileStream object.
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
setSendingTime();
File.WriteAllText("Testfile.txt", timer.ToString());
}
File.WriteAllText will create the file is it does not exist, and overwrite the file if it does exist, effectively doing the same thing as your check.
If this does not resolve the issue, check the event log for errors, or alternatively provided error handling code in your timer_Elapsed and update methods that log the error message.
As I was requesting the webserver on my own computer i.e. localhost, I didn't noticed that wampserver was not running. I checked the event log which showed me the WebException. Starting the wampserver code works fine. Thank you every one.
Yes, I encountered similar issues a lot of times...
Log all uncaught exceptions:
// Somewhere at the start of the constructor:
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
[...]
void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
// Log exeption e.ExceptionObject.ToString to a file
}
Also, I would use a try-catch + log in the update method to make sure that if the thread exits for any unknown reason, you find out the reason.
If these things don't work, it's usually something stupid like a missing DLL, the incorrect version of a DLL (64/32-bit mix), or something like that. This can be found in the event log.
That should do it :-)
If you are running this on a machine that has Visual Studio installed (e.g., your dev machine), add a call to
System.Diagnostics.Debugger.Launch();
in your startup or wherever appropriate. This will launch the Visual Studio debugger, so you don't have to fight with timing issues (Service stopping before you can manually attach the debugger)

Trying to convert Global.asax 1.0 file to 3.5 Issues with Application_Error + Session and Redirect

So in the Global.asax is this:
protected void Application_Error(object sender, System.EventArgs
{
Session["CustomError"] = Server.GetLastError();
Server.ClearError();
Response.Redirect("~/ErrorPage.aspx");
}
And in ErrorPage.aspx is this:
private void Page_Load(object sender, System.EventArgs e)
{
Exception currentException = ((Exception)Session["CustomError"]).InnerException;
// Writes the error message
if (currentException != null)
txtErrorMessage.Text = currentException.Message;
// Loops through the inner exceptions.
currentException = (Exception)Session["CustomError"];
while (currentException != null)
{
message.Append(currentException.Message).Append("\r\n").Append(currentException.StackTrace);
message.Append("\n==============================================\n");
currentException = currentException.InnerException;
}
As this is old 1.0 code it barfs when converted to a 3.5 Global.asax file. It tells me that "Session" is not available and also that I can't redirect?? I think one of the issues may be that there is also an error being thrown from Application_Start. But if I comment out all the application start code I still get errors but they never get redirected to the error page.
This link might help: Exceptional Gotchas!.
In addition, use the web.config file to define your default redirect page for errors.

Categories

Resources