Windows Phone app throws exception (quit automatically) when running under 3G, but fine with WIFI. Very weird - windows-phone-7

I have tried hundreds of times to find errors for this piece of codes.
It only works through WIFI, but When I switch off WIFI on my phone, and run the app again, this app just shut down automatically, which means it thrown an exception.
The app is simple, I used WebClint() to download HTML source and parsed it with HTML Agility Pack, then added them to a list, foreach the list to creat each news object.
I have tried catch the exception stacktrace and bind it to a texblock, It said some of ArgumentOutOfRange exception and Genericlist(int32 index)???
I have no idea about it, It was fine in wifi, but not in 3G network. Can anyone help?
public partial class MainPage : PhoneApplicationPage
{
string srcHTML;
HtmlNode UrlNode;
ObservableCollection<News> newsList = new ObservableCollection<News>();
List<HtmlNode> headlines;
HtmlDocument hd;
News n;
// Constructor
public MainPage()
{
InitializeComponent();
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
WebClient webClenet = new WebClient();
webClenet.Encoding = new HtmlAgilityPack.Gb2312Encoding();
webClenet.DownloadStringAsync(new Uri("http://www.6park.com/news/multi1.shtml", UriKind.RelativeOrAbsolute));
webClenet.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClenet_DownloadStringCompleted);
}
private void webClenet_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
srcHTML = e.Result;
GetHeadlinePage(srcHTML);
}
private void GetHeadlinePage(string srcHTML)
{
hd = new HtmlDocument();
hd.LoadHtml(srcHTML);
try
{
UrlNode = hd.DocumentNode.ChildNodes[1].ChildNodes[3].ChildNodes[8].ChildNodes["tr"].ChildNodes["td"].ChildNodes["ul"];
headlines = UrlNode.Descendants("a").ToList();
foreach (var headline in headlines)
{
if (headline.Attributes["href"].Value.Contains("6park"))
{
n = new News();
n.NewsTitle = headline.InnerText;
n.NewsUrl = headline.Attributes["href"].Value;
n.NewsDetails = headline.NextSibling.InnerText.Replace("- ", "新闻来源:") + headline.NextSibling.NextSibling.InnerText + headline.NextSibling.NextSibling.NextSibling.InnerText;
newsList.Add(n);
}
}
}
catch (Exception ex)
{
//NewsSource.Text = ex.StackTrace + "\n" + ex.Message;
}
NewslistBox.ItemsSource = newsList;
//NewsHeadlineWebBrowser.NavigateToString(ConvertExtendedASCII(headNews));
}
}

I'd debug the value passed to GetHeadlinePage().
I'd suspect that the response is different based on the network or the request is timing out or you're getting some other error.
I'd assume that the call to LoadHtml() is failing as this isn't inside any exception handling/trapping and you've not validating the value passed to it.

Related

GeoCoordinateWatcher isn't working after migration to WP8

I developed a navigation application for windows phone 7.1. It was running fine there. After updating to 8.0 my GeoCoordinateWatcher isnt working anymore. I know that I could use Geolocator instead, but I refuse to do so, because of lack of time.
For my app I read the current position of my watcher to store it for an object instance with location information. When I save my object instance the longitude and latitude are 0.0. Even when I change the position in my emulator still 0.0. The same issue occurs on my other pages, which use GeoCoordinateWatcher. It doesnt work. As I already said, on WP 7.1 - 7.8 it works very well.
public Map()
{
InitializeComponent();
watcher = new GeoCoordinateWatcher();
watcher.MovementThreshold = 20;
watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged);
watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
}
void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
if (e.Position.Location.IsUnknown)
{
MessageBox.Show("Please wait while your prosition is determined.");
return;
}
geo.Latitude = e.Position.Location.Latitude;
geo.Longitude = e.Position.Location.Longitude;
}
try this code:
GeoCoordinateWatcher watch;
public GeoCoordinate loc = null;
public MainPage()
{
InitializeComponent();
if (watch == null)
{
watch = new GeoCoordinateWatcher(GeoPositionAccuracy.High)
{
MovementThreshold=10
};
watch.Start();
watch.PositionChanged += watch_PositionChanged;
}
}
void watch_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
//throw new NotImplementedException();
Dispatcher.BeginInvoke(()=>LocUpdate(e));
}
void LocUpdate(GeoPositionChangedEventArgs<GeoCoordinate> e)
{
try
{
location = new GeoCoordinate(e.Position.Location.Latitude, e.Position.Location.Longitude);
}
catch
{
MessageBox.Show("Error");
}
}

Set the query string, but still get NullReferenceException

I want to show the error message on the other page. I got the NullReferenceException, but the query string is set on the page which has error. Would someone tell me what is wrong with my code?
catch (Exception ex)
{
//Dispatcher.BeginInvoke(new Action(() =>MessageBox.Show(ex.StackTrace,"Error!",MessageBoxButton.OK)));
string query=#"/ErrorPage.xaml?msg=" + ex.StackTrace.ToString() ;
Dispatcher.BeginInvoke(new Action(() =>this.NavigationService.Navigate(new Uri(query, UriKind.Relative))));
}
There is the code for showing the error message when the page is loaded on other page
public ErrorPage()
{
InitializeComponent();
string msg = NavigationContext.QueryString["msg"].ToString();
lstMessage.Items.Add(msg);
}
I should put my code into the MainPage_Load method. It works.
public ErrorPage()
{
InitializeComponent();
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
MessageBoxResult result = MessageBox.Show(CMSPhoneApp.App.GlobalVariables.strNofifyEmailSubject,
"Report Error", MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK)
{
//according to the serach it works on real devices (not on the emulator)
//the reason the EmailComposer not pop up because can't set up an email account on the emulator
EmailComposeTask emailcomposer = new EmailComposeTask();
emailcomposer.To = CMSPhoneApp.App.GlobalVariables.reportAddress;
emailcomposer.Subject = CMSPhoneApp.App.GlobalVariables.strNofifyEmailSubject;
emailcomposer.Body = CMSPhoneApp.App.GlobalVariables.errorMsg;
emailcomposer.Show();
}
else
{
App.GoBack();
}
}

Code to execute if a navigation fails

Hello I have no idea where I should start looking. I add few prop (before that my code run fine), then I get
System.Diagnostics.Debugger.Break();
so then I comment that changes, but that didn't help.
Could you suggest me where I should start looking for solution?
MyCode:
namespace SkydriveContent
{
public partial class MainPage : PhoneApplicationPage
{
private LiveConnectClient client;
FilesManager fileManager = new FilesManager();
// Constructor
public MainPage()
{
InitializeComponent();
}
private void signInButton1_SessionChanged(object sender, LiveConnectSessionChangedEventArgs e)
{
if (e.Status == LiveConnectSessionStatus.Connected)
{
client = new LiveConnectClient(e.Session);
infoTextBlock.Text = "Signed in.";
client.GetCompleted +=
new EventHandler<LiveOperationCompletedEventArgs>(OnGetCompleted);
client.GetAsync("/me/skydrive/files/");
fileManager.CurrentFolderId = "/me/skydrive/files/";
}
else
{
infoTextBlock.Text = "Not signed in.";
client = null;
}
}
void OnGetCompleted(object sender, LiveOperationCompletedEventArgs e)
{
//Gdy uda nam się podłaczyc do konta skydrive
if (e.Error == null)
{
signInButton1.Visibility = System.Windows.Visibility.Collapsed;
infoTextBlock.Text = "Hello, signed-in user!";
List<object> data = (List<object>)e.Result["data"];
fileManager.FilesNames.Clear();
filemanager.filesnames.add("..");
foreach (IDictionary<string,object> item in data)
{
File file = new File();
file.fName = item["name"].ToString();
file.Type = item["type"].ToString();
file.Url = item["link"].ToString();
file.ParentId = item["parent_id"].ToString();
file.Id = item["id"].ToString();
fileManager.Files.Add(file);
fileManager.FilesNames.Add(file.fName);
}
FileList.ItemsSource = fileManager.FilesNames;
}
else
{
infoTextBlock.Text = "Error calling API: " +
e.Error.ToString();
}
}
private void FileList_Tap(object sender, GestureEventArgs e)
{
foreach (File item in fileManager.Files)
{
if (item.fName == FileList.SelectedItem.ToString() )
{
switch (item.Type)
{
case "file":
MessageBox.Show("Still in progress");
break;
case "folder":
fileManager.CurrentFolderId = item.ParentId.ToString();
client.GetAsync(item.Id.ToString() + "/files");
break;
default:
MessageBox.Show("Coś nie działa");
break;
}
}
else if (FileList.SelectedItem.ToString() == "..")
{
client.GetAsync(fileManager.CurrentFolderId + "/files");
}
}
}
}
}
Running stop at that line.
// Code to execute if a navigation fails
private void RootFrame_NavigationFailed(object sender, NavigationFailedEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
// A navigation has failed; break into the debugger
System.Diagnostics.Debugger.Break();
}
}
You should check all of the URLs you have both in the XAML and code. When you get to the NavigationFailed function, it means that the phone tried to navigate to some page that did not existed. We would be able to help more if you could tell what were you doing when the app threw the exception.
System.Diagnostics.Debugger.Break();
usually happens because of an Uncaught Exception.
Either post the code which started giving problems, or the stack trace when you encounter this problem.
No one can tell anything without actually seeing what you are doing.

DownloadStringCompleted event does not fire

I am developing a windows phone application. The webclient does not fire as I expected. The related code is as below:
public PArticle(PocketListItem aPli)
{
this.pli = aPli;
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isf.FileExists(aPli.ID + ".json"))
{
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
client.DownloadStringAsync(new Uri(pli.Url));
}
else
{
string json = RetrieveDataFromLocalStorage(aPli.ID + ".json");
PocketArticle pa = JsonConvert.DeserializeObject<PocketArticle>(json);
this.text = pa.text;
}
}
}
void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
var readability = Readability.Create(e.Result);
this.text = readability.Content;
}
I know it's a synchronous/asynchronous problem. But I have no idea about how to handle it.
Thanks in advance.
I have tested the WebClient part of your code with 2 different URLs http://riktamtech.com and http://google.com. In both cases, the DownloadStringCompleted event is raised. I observed it by placing a break point.
So I suggest you to test again with break points.

UI not updating in async web request callback

I'm using this to make a web request and download some data:
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
var client = new WebClient();
client.DownloadStringCompleted += (s, e) => {
textBlock1.Text = e.Result;
};
client.DownloadStringAsync(new Uri("http://example.com"));
}
}
The text of textBlock1 never changes even though e.Result has the correct data. How do I update that from the callback?
Edit: If I add MessageBox.Show(e.Result); in the callback along with the textBlock1.Text assignment, both the messsage box and the text box show the correct data.
Edit Again: If I add a TextBox and set it's text right after the line textBlock1.Text line, they both show the correct text.
I think, it's a bug.
I also ran into some problems with updating the UI from different dispatchers. What I finally did was use the TextBlock's (or other UI Element) own dispatcher and that worked for me. I think the phone framework may be using different dispatchers between the app and UI Elements. Notice the change from dispatcher.BeginInvoke to textbox1.Dispatcher...
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
var dispatcher = Deployment.Current.Dispatcher;
var client = new WebClient();
client.DownloadStringCompleted += (s, e) =>
{
var result = e.Result;
textBlock1.Dispatcher.BeginInvoke(
()=> textBlock1.Text = result
);
};
client.DownloadStringAsync(new Uri("http://example.com"));
}
From browsing through the WP7 forums, a bunch of people were reporting that this was related to a video card driver issue. I've updated my ATI Radeon HD 3400 drivers to the latest version and it appears to work now.
client.DownloadStringAsync is expecting a Uri like this:
client.DownloadStringAsync(new Uri("http://example.com"));
also, shouldn't you update your TextBlock through a Dispatcher.BeginInvoke like this:
client.DownloadStringCompleted += (s, e) =>
{
if (null == e.Error)
Dispatcher.BeginInvoke(() => UpdateStatus(e.Result));
else
Dispatcher.BeginInvoke(() => UpdateStatus("Operation failed: " + e.Error.Message));
};
public partial class MainPage : PhoneApplicationPage
{
public MainPage()
{
InitializeComponent();
Loaded += MainPage_Loaded;
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
var dispatcher = Deployment.Current.Dispatcher;
var client = new WebClient();
client.DownloadStringCompleted += (s, e) =>
{
var result = e.Result;
dispatcher.BeginInvoke(
()=> textBlock1.Text = result
);
};
client.DownloadStringAsync(new Uri("http://example.com"));
}
}
I want to comment but can't yet. Yes, I have a very similar issue. In my case it's my viewmodel that is updating a DownloadStatus property, then when the download is completed I do some more work and continue updating this property.
The view stops updating once the ViewModel code hits the OpenReadCompleted method. I've stepped carefully through the code. PropertyChanged fires, and the view even comes back and retrieves the new property value, but never shows the change.
I was sure it was a bug, but then I created a brand new project to reproduce the issue, and it works fine!
Here's a snippet of my non-reproducing code. The UI textblock bound to "DownloadStatus" happily updates properly all the way through. But the same paradigm doesn't work in my main project. Infuriating!
public void BeginDownload(bool doWorkAfterDownload)
{
DownloadStatus = "Starting ...";
_doExtraWork = doWorkAfterDownload;
var webClient = new WebClient();
string auth = "Basic " + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("test:password"));
webClient.Headers["Authorization"] = auth;
webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(webClient_DownloadProgressChanged);
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(webClient_OpenReadCompleted);
webClient.OpenReadAsync(new Uri("http://www.ben.geek.nz/samsung1.jpg"));
}
void webClient_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
if (e.Error != null)
{
DownloadStatus = e.Error.Message;
return;
}
DownloadStatus = "Completed. Idle.";
if(_doExtraWork)
{
Thread t = new Thread(DoWork);
t.Start(e.Result);
}
}
void DoWork(object param)
{
InvokeDownloadCompleted(new EventArgs());
// just do some updating
for (int i = 1; i <= 10; i++)
{
DownloadStatus = string.Format("Doing work {0}/10", i);
Thread.Sleep(500);
}
DownloadStatus = "Completed extra work. Idle.";
InvokeExtraWorkCompleted(new EventArgs());
}

Resources