Set the query string, but still get NullReferenceException - windows-phone-7

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();
}
}

Related

How can I share an event handler?

private void ExitAndSave(object sender, EventArgs e)
{
foreach (Form form in MdiChildren)
{
if (form is TextForm tf)
{
tf.BringToFront();
DialogResult dr = MessageBox.Show("Do you want to save your document?", "Save document?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dr == DialogResult.Yes)
{
//counter++;
var textBoxValue = tf.FetchTextBoxValue();
//string filePath = $"{DateTime.Now.Ticks.ToString()}.txt";
string filePath = $"composition{DateTime.Now.Ticks.ToString()}.txt";
File.WriteAllText(filePath, textBoxValue);
}
if (dr == DialogResult.No)
{
continue;
}
}
else if (form is ImageDocumentForm)
{
MessageBox.Show("Please note that only text documents can be saved.", "Advisory:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
Close();
}
This code works fine. I need it to be called when the user exits the program. I'm not able to assign this event to the form closing event in the design view.
Your event argument needs to be of the form FormClosingEventArgs e
Change that and try again.

Exception of type 'System.Collections.Generic.KeyNotFoundException' was thrown ? in Xamarin.Forms

i wanna use simple database in Xamarin Forms. So i used this code;
public partial class DBExample : ContentPage
{
string _dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal),"myDB.db3");
public DBExample ()
{
InitializeComponent ();
}
private async void InsertButton(object sender, EventArgs e)
{
SQLiteConnection db=null;
try
{
db = new SQLiteConnection(_dbPath);
}
catch (Exception ex)
{
await DisplayAlert(null, ex.Message, "OK");
}
db.CreateTable<Users>();
var maxPk = db.Table<Users>().OrderByDescending(c => c.Id).FirstOrDefault();
Users users = new Users()
{
Id = (maxPk == null ? 1 : maxPk.Id + 1),
Name = userName.Text
};
db.Insert(users);
await DisplayAlert(null,userName.Text + "saved","OK");
await Navigation.PopAsync();
}
}
and i have problem. You can see it in Headtitle.
"Exception of type 'System.Collections.Generic.KeyNotFoundException' was thrown"
im waiting your support. Thanks for feedback.

How to use SOAP in windows phone 7

Dont know what to do.
I have all the data i need but dont know how to use it right.
I have started to add a "Service Reference". I added the URL wich is this one: transpawebserviceslive/gateway.asmx
So what i have done now is this. For my click event on my button to verify that the password and username is correct i have done the following and i dont know if i am doing it right here:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
ServiceReference.GatewaySoapClient client = new ServiceReference.GatewaySoapClient();
client.AuthenticateAsync(username.Text,password.Text,sign.Text,password.Text);
client.AuthenticateCompleted += client_AuthenticateCompleted;
}
void client_AuthenticateCompleted(object sender, ServiceReference.AuthenticateCompletedEventArgs e)
{
ServiceReference.AuthenticatedDto test = new ServiceReference.AuthenticatedDto();
if (kund.Text == test.CustomerUser)
{
MessageBoxResult m = MessageBox.Show("Ok", "Ok", MessageBoxButton.OK);
}
else
{
MessageBoxResult m = MessageBox.Show("Wrong", "W", MessageBoxButton.OK);
}
Dont know what i am doing here, whould be nice with some help.
All that you did there is correct. You just have to parse the response and proceed.
void client_AuthenticateCompleted(object sender, ServiceReference.AuthenticateCompletedEventArgs e)
{
if (e.Error == null) //To ensure there is no error in the request
{
if (e.Result.Contains("ERROR"))
MessageBox.Show("Authentication failed", "Ok", MessageBoxButton.OK);
else
MessageBox.Show("Authenticaion success", "Ok", MessageBoxButton.OK);
}
}

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.

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

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.

Resources