I've got this code and I'm using it to show a button which allows the user to choose an image from his library and use it as a background for my app.
So I create a PhotoChooserTask, set it to show the camera and bind it to a method that has to be executed when the task is completed.
The button will start the task by showing the PhotoChooserTask.
The action to do on complete is quite easy, I've just got to set a boolean value and update an image source.
PhotoChooserTask pct_edit = new PhotoChooserTask();
pct_edit.ShowCamera = true;
pct_edit.Completed += pct_edit_Completed;
Button changeImageButton = new Button { Content = "Change Image" };
changeImageButton.Tap += (s, e) =>
{
pct_edit.Show();
};
void pct_edit_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
bi.SetSource(e.ChosenPhoto);
IsRebuildNeeded = true;
}
}
The problem is that it won't show the PhotoChooserTask but it will give me an exception, taking me to
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (Debugger.IsAttached)
{
Debugger.Break();
}
}
in App.xaml.cs.
This looks weird as I've got another PhotoChooserTask in the same class and this one works fine.
What's wrong with it?
VisualStudio won't even tell me what's the exception and so there's no way to figure it out!
EDIT:
I just found out that the exception is thrown when I call
pct_edit.Show();
in the button's tap event.
You should be defining your chooser as a field in your class. It's a requirement that you have page scope for the PhotoChooser. You then subscribe to it in your constructor. This is stated on the MSDN here
class SomeClass
{
readonly PhotoChooserTask pct_edit = new PhotoChooserTask();
SomeClass()
{
pct_edit.ShowCamera = true;
pct_edit .Completed += new EventHandler<PhotoResult>(pct_edit_Completed);
}
}
You can use try to check what is the problem
changeImageButton.Tap += (s, e) =>
{
try
{
PhotoChooserTask pct_edit = new PhotoChooserTask();
pct_edit.ShowCamera = true;
pct_edit.Completed += (s,e) =>
{
if (e.TaskResult == TaskResult.OK)
{
var bi = new BitmapImage() // maybe you didn't initialize bi?
bi.SetSource(e.ChosenPhoto);
IsRebuildNeeded = true;
}
}
pct_edit.Show();
}
catch (Exception ex)
{
Message.Show(ex.Message);
}
};
Put brakepoint on Message, then you can check everything inside ex.
Related
In my windows phone application I'm getting the using current location using the following code
private void GetCoordinate()
{
var watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High)
{
MovementThreshold = 2
};
watcher.PositionChanged += this.watcher_PositionChanged;
watcher.StatusChanged += this.watcher_StatusChanged;
watcher.Start();
}
void watcher_StatusChanged(object sender, GeoPositionStatusChangedEventArgs e)
{
switch (e.Status)
{
case GeoPositionStatus.Disabled:
MessageBox.Show("Current position not available!!");
break;
case GeoPositionStatus.NoData:
MessageBox.Show("Current position not available!!");
break;
}
}
private void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
try
{
var pos = e.Position.Location;
StaticData.currentCoordinate = new GeoCoordinate(pos.Latitude, pos.Longitude);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
As shown above I am calling the GetCoordinate method in the page load event of the application page. By using that GPS coordinate values I was enabling or disabling some controls on the page. But here, the issue is page load code executing first and then we are getting the Gps coordinate values..
I need the GPS Coordinate values in pageload. please suggest
You shall start the watcher in the page load, and once the GeoCoordinateWatcher collects the GeoCoordinate value it triggers PositionChanged event where in you shall code for enabling disabling the controls.
So now your code would look like this
private void GetCoordinate()
{
var watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High)
{
MovementThreshold = 2
};
watcher.PositionChanged += this.watcher_PositionChanged;
watcher.StatusChanged += this.watcher_StatusChanged;
watcher.Start();
}
private void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
try
{
var pos = e.Position.Location;
if(position==required one)
{
//enable disable here
}
StaticData.currentCoordinate = new GeoCoordinate(pos.Latitude, pos.Longitude);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I have a WPF application into which I'm adding some top level, catch all error handling. I handle the DispatcherUnhandledException event like so:
private void App_OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
if (_isHandlingError)
{
_log.Error("Critical unhandled error", e.Exception);
e.Handled = true;
return;
}
_isHandlingError = true;
var vm = _windsorContainer.Resolve<ErrorReporterViewModel>();
Dispatcher.Invoke(() =>
{
vm.Details = FailureMessageBuilder.CreateContent(e.Exception);
var view = new ErrorReporterView { DataContext = vm };
view.Show();
});
e.Handled = true;
NotifyOfException(e.Exception, vm.Description);
_isHandlingError = false;
}
The problem is, that the call to Show() (or ShowDialog) never returns, and the error dialog is never shown.
What might be the issue?
Do you have attached your event to the Application?
cApp.Dispatcher.UnhandledException += new DispatcherUnhandledExceptionEventHandler(Dispatcher_UnhandledException);
cApp.InitializeComponent();
cApp.Run(new MainWindow());
And then
private static void Dispatcher_UnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
...e.Exception.Message
}
This case is using C# WPF. I want to instantly disable a button after clicking it to prevent clicking it twice in short succession. I disabled the button in OnClick_Event but still clickable.
Part of source is as below.
private void Button_Click_UpdateBurndownChart(object sender, RoutedEventArgs e)
{
if(threadNotWorking)
{
updateButton.IsEnabled = false;
startWorkThread();
}
}
private void startWorkThread()
{
... ...
//after finish required process
updateButton.IsEnabled = true;
}
Is there any way to accomplish this?
you may want to use a dispatcher, there is probably a threading problem (callback function running on seperate thread and trying to access ui which runs on another thread). try this . .
updateButton.Dispatcher.BeginInvoke(
new ThreadStart(() => updateButton.IsEnabled = false),
System.Windows.Threading.DispatcherPriority.Input, null);
instead of
updateButton.IsEnabled = false;
What happens if you were instead to change the order of your events from:
updateButton.IsEnabled = false;
startWorkThread();
To
startWorkThread();
updateButton.IsEnabled = false;
Let me know how this goes.
What it looks like is that you are starting your thread then immediatly enabling your button before your thread has finished. You would be better off using a BackgroundWorker and enable your Button in the RunWorkerCompleted Event. Though you can do something similar by enabling your button using a BeginInvoke at the end of your Process.
public void doWork()
{
System.Threading.Thread.Sleep(10000); //Simulating your Process
Dispatcher.BeginInvoke(new System.Threading.ThreadStart(delegate() { updateButton.IsEnabled = true; }), System.Windows.Threading.DispatcherPriority.Background);
}
Example with BackgroundWorker
using System.ComponentModel;
public partial class MainWindow : Window
{
BackgroundWorker bgw;
public MainWindow()
{
InitializeComponent();
bgw = new BackgroundWorker();
bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgw_RunWorkerCompleted);
}
void bgw_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
updateButton.IsEnabled = true;
}
void bgw_DoWork(object sender, DoWorkEventArgs e)
{
System.Threading.Thread.Sleep(10000); //Simulating your work
}
private void startWorkThread()
{
bgw.RunWorkerAsync();
}
private void updateButton_Click(object sender, RoutedEventArgs e)
{
if (bgw.IsBusy != true)
{
updateButton.IsEnabled = false;
startWorkThread();
}
}
}
I want to return a photo using PhotoChooserTask like this:
private void getimage_Click(object sender, EventArgs e)
{
photoChooserTask = new PhotoChooserTask();
photoChooserTask.Completed += new EventHandler<PhotoResult>(photoChooserTask_Completed);
try
{
photoChooserTask.Show();
}
catch (System.InvalidOperationException ex)
{
MessageBox.Show("An error occurred.");
}
}
void photoChooserTask_Completed(object sender, PhotoResult ee)
{
if (ee.TaskResult == TaskResult.OK)
{
BitmapImage bmp = new BitmapImage();
bmp.SetSource(ee.ChosenPhoto);
if (ee.TaskResult == TaskResult.OK && ee.Error == null)
{
WriteableBitmap wb = new WriteableBitmap(bmp);
notes.Add(new chatinfo() { sendimage = bmp });
noteListBox.ItemsSource = null;
noteListBox.ItemsSource = notes;
}
}
}
but everytime the program arrived here:"bmp.SetSource(ee.ChosenPhoto);" A SocketException will be called.
private void OnRecieveFrom()
{
var receiveArgs = new SocketAsyncEventArgs();
receiveArgs.RemoteEndPoint = this.IPEndPoint;
receiveArgs.SetBuffer(new Byte[MAX_BUFFER_SIZE], 0, MAX_BUFFER_SIZE);
var strBdr = new StringBuilder();
receiveArgs.Completed += (__, result) =>
{
string message = CreateMessage(result);
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
this.RaiseReceived(message);
});
socket.ReceiveFromAsync(receiveArgs);
};
socket.ReceiveFromAsync(receiveArgs);
}
The SocketException is called by " socket.ReceiveFromAsync(receiveArgs);"
I just want to get a photo from the phone,and there is not send or recieve operation.I don't know why receive function was called.
Would the app lose the socket communication when it jumps to the photo album (the value "RemoteEndPoint" of socket change to null)? p.s. "socket" is an object of class "Socket".
If so, should I recreate the "socket" every time the app jumps out?
Thank you!
Once the PhotoChooserTask is called your app will be Fast App Switched (or maybe even Tombstoned).
Either way your socket will be closed. You'll have to reopen your socket when your app is Activated again.
The problem is: When I remove the first message box line, my program doesn't run and throws "Exception has been thrown by the target of an invocation" on the if statement line. However, when I leave the messagebox there, it runs fine. Can someone explain to me why this is happening and what I can do to fix it? I'm fairly new to WPF by the way, any help would be appreciated.
public BrowserMode() {
InitializeComponent();
MessageBox.Show("Entering Browser Mode");
if (webBrowser1.Source.Scheme == "http")
{
//cancel navigation
//this.NavigationService.Navigating += new NavigatingCancelEventHandler(Cancel_Navigation);
qd = new QuestionData();
// code where stuff happens
var url = webBrowser1.Source;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
// from h.RequestUri = "webcam://submit?question_id=45"
var parseUrl = request.RequestUri; //the uri that responded to the request.
MessageBox.Show("The requested URI is: " + parseUrl);
This sort of work is not suited for a constructor and should be moved out until after the WebBrowser is fully loaded. You have two options:
Hook Control.Loaded and perform this behavior there.
public BrowserMode()
{
InitializeComponent();
this.Loaded += BroswerMode_Loaded;
}
void BrowserMode_Loaded(object sender, EventArgs e)
{
if (webBrowser1.Source != null
&& webBrowser1.Source.Scheme == "http")
{
qd = new QuestionData();
// ...
}
}
Hook WebBrowser.Navigating and perform this behavior there.
public BrowserMode()
{
InitializeComponent();
this.webBrowser1.Navigating += WebBrowser_Navigating;
}
void WebBrowser_Navigating(object sender, NavigatingCancelEventArgs e)
{
if (e.Uri.Scheme == "http")
{
qd = new QuestionData();
// ...
}
}