How can I share an event handler? - windows

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.

Related

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

Metro App OnNavigatedTo setting textbox value in a different method

I am following around on a kindle book I bought for developing metro apps. For some reason I cannot set the text value of a text box in a method outside the OnNavigatedTo method. This is the code that the book provides:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
//passed in the view model
viewModel = e.Parameter as ViewModel;
this.DataContext = viewModel;
viewModel.PropertyChanged += (sender, eventArgs) =>
{
if (eventArgs.PropertyName == "SelectedItemIndex")
{
if (viewModel.SelectedIndex == -1)
{
SetItemDetail(null);
}
else
{
SetItemDetail(viewModel.GroceryList[viewModel.SelectedIndex]);
}
}
SetItemDetail(viewModel.GroceryList[viewModel.SelectedIndex]);
};
}
private void SetItemDetail(GroceryItem item)
{
ItemDetailName.Text = "test"; //(item == null) ? "" : item.Name;
ItemDetailQuantity.Text = "test"; //(item == null) ? "" : item.Quantity.ToString();
//if (item != null)
//{
// ItemDetailStore.SelectedItem = item.Store;
//}
//else
//{
// ItemDetailStore.SelectedIndex = -1;
//}
}
I have commented parts out in the set item detail method, but I still cannot set the value of a textbox when I click it (this is supposed to be the behavior). I have used break points and the property of the textbox is getting set, however, it is not displayed on screen.
Thanks.

Clickable URL in Windows Phone Message box

I want to display an URL in my message box that the user can click and navigate to on Wp7 mango. Is this Possible? If yes how do i implement it ?
My message box is coded as below:
public static void customizedMessageBox(int messageboxtype, string title, string text, IEnumerable<string> buttons, int focusbutton, MessageBoxIcon icon, AsyncCallback callback, object state)
{
if (!Guide.IsVisible)
{
try
{
ProgressBarControl.dismissProgressBar();
Guide.BeginShowMessageBox(" ", text, buttons, focusbutton, MessageBoxIcon.None, callback, state);
messageboxType = messageboxtype;
}
catch (GuideAlreadyVisibleException ex)
{
Logger.log("MsgBox", "Exception : messageboxtype: " + messageboxtype
+ "\n" + ex.Message + "\n" + ex.StackTrace);
}
}
//return messageboxtype;
}
public static void OnMessageBoxClosed(IAsyncResult ar)
{
int? dialogResult = Guide.EndShowMessageBox(ar);
Game game;
try
{
Logger.log("MsgBox", "result: " + dialogResult + " msg type: " + messageboxType);
switch (messageboxType)
{ case 7:
//ERROR E4000 case
switch (dialogResult)
{
case 0:
string url;
//url = CacheManager.getInstance().getApplicationSettings(CacheManager.APP_APK_UPGRADE_URI);
url = DataManager.URL_VALUE;
if (Utils.isNullString(url))
{
//url = CacheManager.getInstance().getUpgradeURL();
}
WebBrowserTask browse = new WebBrowserTask();
browse.URL = url;
browse.Show();
break;
default:
//delete data from the DB
ProgressBarControl.displayProgressBar(0, 10, AppResources.DOWNLOADING);
try
{
//byte[] data = (byte[])CacheManager.getInstance().getPersistanceData(Utils.MINOR_UPGRADE_DATA);
byte[] data = (byte[])CacheManager.getInstance().getDataFromDataFile();
if (data != null && data.Length > 0)
{
DataManager.getInstance().processMyWidgetResponse(data);
DataManager.getInstance().refresUI();
}
}
catch (Exception ex)
{
}
finally
{
//CacheManager.getInstance().deletaFromApplicationCache(Utils.MINOR_UPGRADE_DATA);
}
break;
}
break;
default:
break;
}
}
catch (Exception ex)
{
Logger.log(TAG, ex.Message);
}
finally
{
ProgressBarControl.dismissProgressBar();
}
}
I am calling the messagebox like this:-
UIListen.customizedMessageBox(Utils.ERROR_CODE_E4000, ERROR_FORCE_REGISTRATION, responseHeaders[HEADER_URL_NAME, 1], Utils.valuesOk, 0);
take a look a this: http://coding4fun.codeplex.com/
explore different kind of custom dialogs\message boxed he made. You can take this as ref and make your own or you can directly use the existing one.
consider showing a custom screen or xaml page which gives user the correct options. You can provide whatever options you want. Buttons etc .

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 7 - wait for Webclient to complete

I'm developing an app and have run into a problem with asynchronous calls... Here's what i'm trying to do.
The app consumes a JSON API, and, when run, fills the ListBox within a panorama item with the necessary values (i.e. a single news article). When a user selects a ListBox item, the SelectionChanged event is fired - it picks up the articleID from the selected item, and passes it to an Update method to download the JSON response for the article, deserialize it with JSON.NET, and taking the user to the WebBrowser control which renders a html page from the response received.
The problem with this is that I have to wait for the response before I start the NavigationService, but I'm not sure how to do that properly. This way, the code runs "too fast" and I don't get my response in time to render the page.
The event code:
private void lstNews_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (lstNews.SelectedIndex == -1)
{
return;
}
ShowArticle _article = new ShowArticle();
ListBox lb = (ListBox)sender;
GetArticles item = (GetArticles)lb.SelectedItem;
string passId = ApiRepository.ApiEndpoints.GetArticleResponseByID(item.Id);
App.Current.JsonModel.JsonUri = passId;
App.Current.JsonModel.Update();
lstNews.SelectedIndex = -1;
NavigationService.Navigate(new Uri("/View.xaml?id=" + item.Id, UriKind.Relative));
}
OnNavigatedTo method in the View:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
base.OnNavigatedTo(e);
long sentString = long.Parse(NavigationContext.QueryString["id"]);
string articleUri = ApiRepository.ApiEndpoints.GetArticleResponseByID(Convert.ToInt32(sentString));
//this throws an error, runs "too fast"
_article = App.Current.JsonModel.ArticleItems[0];
}
The update method:
public void Update()
{
ShowArticle article = new ShowArticle();
try
{
webClient.DownloadStringCompleted += (p, q) =>
{
if (q.Error == null)
{
var deserialized = JsonConvert.DeserializeObject<ShowArticle>(q.Result);
_articleItems.Clear();
_articleItems.Add(deserialized);
}
};
}
catch (Exception ex)
{
//ignore this
}
webClient.DownloadStringAsync(new Uri(jsonUri));
}
async callback pattern:
public void Update(Action callback, Action<Exception> error)
{
webClient.DownloadStringCompleted += (p, q) =>
{
if (q.Error == null)
{
// do something
callback();
}
else
{
error(q.Error);
}
};
webClient.DownloadStringAsync(new Uri(jsonUri));
}
call:
App.Current.JsonModel.Update(() =>
{
// executes after async completion
NavigationService.Navigate(new Uri("/View.xaml?id=" + item.Id, UriKind.Relative));
},
(error) =>
{
// error handling
});
// executes just after async call above

Resources