Windows 8 Metro Style Clipboard Exception - windows-8

I have developed an application which reads clipboard data in DispatcherTimer Tick() method.
Every second the clipboard data is read.
The application throws no exception in development machine (in debug or relase mode), however if I publish the application on a Win RT Tablet device, I have an exception while reading clipboard, but strangely only in "snap view" mode.
in full view mode, it works without any problem.
The exception is:
"Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))".
The code looks like;
private async Task Populate()
{
try
{
var clipboardText = await this.GetTextFromClipboard();
.....
}
catch (Exception ex)
{
this.HandleException("Error occured while reading clipboard: ", ex);
}
}
private async Task<string> GetTextFromClipboard()
{
var dataPackageView = Clipboard.GetContent(); // Exception occurs here!!!
if (dataPackageView.Contains(StandardDataFormats.Text))
{
var clipboardText = await dataPackageView.GetTextAsync();
return clipboardText;
}
return string.Empty;
}
What is wrong here and why it happens only at Snap View mode?

Related

How to detect when client has closed stream when writing to Response.Body in asp.net core

I'm trying to write an infinite length response body and detect when a client disconnects so I can stop writing. I'm used to getting socket exceptions or similar when a client closes the connection but that doesn't seem to be happening when writing directly to Response.Body. I can close the client applications and the server side just keeps on writing. I've included the relevant code below. It's entirely possible there is a better way to do it but this came to mind. Basically I have a live video feed which should go on forever. I'm writing to ResponseBody as chunked content (No content length, flushing after each video frame). The video frames are received via an event callback from elsewhere in the program so I'm subscribing to the events in the controller method and then forcing it to stay open with the await Task.Delay loop so the Response stream isn't closed. The callback for H264PacketReceived is formatting the data as a streaming mp4 file and writing it to the Response Stream. This all seems to work fine, I can play the live stream with ffmpeg or chrome, but when I close the client application I don't get an exception or anything. It just keeps writing to the stream without any errors.
public class LiveController : ControllerBase
{
[HttpGet]
[Route("/live/{cameraId}/{stream}.mp4")]
public async Task GetLiveMP4(Guid cameraId, int stream)
{
try
{
Response.StatusCode = 200;
Response.ContentType = "video/mp4";
Response.Headers.Add("Cache-Control", "no-store");
Response.Headers.Add("Connection", "close");
ms = Response.Body;
lock (TCPVideoReceiver.CameraStreams)
{
TCPVideoReceiver.CameraStreams.TryGetValue(cameraId, out cameraStream);
}
if (this.PacketStream == null)
{
throw new KeyNotFoundException($"Stream {cameraId}_{stream} not found");
}
else
{
connected = true;
this.PacketStream.H264PacketReceived += DefaultStream_H264PacketReceived;
this.PacketStream.StreamClosed += PacketStream_StreamClosed;
}
while(connected)
{
await Task.Delay(1000);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
finally
{
connected = false;
this.PacketStream.H264PacketReceived -= DefaultStream_H264PacketReceived;
this.PacketStream.StreamClosed -= PacketStream_StreamClosed;
}
}
private bool connected = false;
private PacketStream PacketStream;
private Mp4File mp4File;
private Stream ms;
private async void PacketStream_StreamClosed(PacketStream source)
{
await Task.Run(() =>
{
try
{
Console.WriteLine($"Closing live stream");
connected = false;
ms.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
});
}
private async void DefaultStream_H264PacketReceived(PacketStream source, H264Packet packet)
{
try
{
if (mp4File == null && packet.IsIFrame)
{
mp4File = new Mp4File(null, packet.sps, packet.pps);
var _p = mp4File.WriteHeader(0);
await ms.WriteAsync(mp4File.buffer, 0, _p);
}
if (mp4File != null)
{
var _p = mp4File.WriteFrame(packet, 0);
var start = mp4File._moofScratchIndex - _p;
if (_p > 0)
{
await ms.WriteAsync(mp4File._moofScratch, start, _p);
await ms.FlushAsync();
}
}
return;
}
catch (Exception ex)
{
connected = false;
Console.WriteLine(ex.ToString());
}
}
Answering my own question.
When the client disconnects mvc core sets the cancellation token HttpContext.RequestAborted
By monitoring and/or using that cancellation token you can detect a disconnect and clean everything up.
That said, the entire design can be improved by creating a custom stream which encapsulates the event handling (producer/consumer). Then the controller action can be reduced to.
return File(new MyCustomStream(cameraId, stream), "video/mp4");
The File Method already monitors the cancellation token and everything works as you'd expect.

Plugin Development: Eclipse hangs when testing plugin

I am new to developing plugins, and was wondering what causes a test plugin to hang when started i.e. Eclipse is unresponsive.
I know that my code is working as I developed a voice recognition plugin to write to the screen what is said and when I open notepad everything I say is printed to notepad.
So I was wondering, am I missing something in the plugin life-cycle that causes the IDE to hang when my plugin is started?
package recognise.handlers;
public class SampleHandler extends AbstractHandler {
public SampleHandler() {
}
/**
* the command has been executed, so extract extract the needed information
* from the application context.
*/
public Object execute(ExecutionEvent event) throws ExecutionException {
boolean finish = false;
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
MessageDialog.openInformation(
window.getShell(),
"Recognise",
"Starting Recognition");
TakeInput start = new TakeInput();
//Stage a = new Stage();
//SceneManager scene = new SceneManager();
try {
start.startVoiceRecognition(finish);
//scene.start(a);
} catch (IOException | AWTException e) {
e.printStackTrace();
}
return null;
}
}
Does the start.startVoiceRecognition() need to be threaded?
Thanks in advance and let me know if you would like to see my manifest/activator etc.
Conclusion
Added a job separate to the UI thread
/*
* Start a new job separate to the main thread so the UI will not
* become unresponsive when the plugin has started
*/
public void runVoiceRecognitionJob() {
Job job = new Job("Voice Recognition Job") {
#Override
protected IStatus run(IProgressMonitor monitor) {
TakeInput start = new TakeInput();
try {
start.startVoiceRecognition(true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (AWTException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// use this to open a Shell in the UI thread
return Status.OK_STATUS;
}
};
job.setUser(true);
job.schedule();
}
As shown start.startVoiceRecognition() is running in the UI thread, and it will block the UI thread until it is finished and the app will be unresponsive during that time. So if it is doing a significant amount of work either use a Thread or use an Eclipse Job (which runs work in a background thread managed by Eclipse).
To unblock your UI you have to use Display thread.
/**
* the command has been executed, so extract extract the needed information
* from the application context.
*/
public Object execute(ExecutionEvent event) throws ExecutionException {
Display.getDefault().asyncExec(new Runnable() {
public void run() {
boolean finish = false;
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
MessageDialog.openInformation(
window.getShell(),
"Recognise",
"Starting Recognition");
TakeInput start = new TakeInput();
//Stage a = new Stage();
//SceneManager scene = new SceneManager();
try {
start.startVoiceRecognition(finish);
//scene.start(a);
} catch (IOException | AWTException e) {
e.printStackTrace();
}
MessageDialog.openInformation(shell, "Your Popup ",
"Your job has finished.");
}
});
return null;
}
You can use Display.getDefault().asyncExec() as mentioned above, so your UI will be unblocked, while your non UI code will be executing.

How to "catch" unhandled Exceptions

We've developed a .NET 3.5 CF Application and we're experiencing some application crashes due to unhandled exceptions, thrown in some lib code.
The application terminates and the standard application popup exception message box is shown.
Is there a way to catch all unhandled exceptions? Or at least, catch the text from the message box. Most of our customers simply restart the device, so that we're not able to have a look on the exception message box.
Any ideas?
Have you added an UnhandledException event handler?
[MTAThread]
static void Main(string[] args)
{
AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
// start your app logic, etc
...
}
static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
var exception = (Exception)e.ExceptionObject;
// do something with the info here - log to a file or whatever
MessageBox.Show(exception.Message);
}
I do something similar to what ctacke does.
private static Form1 objForm;
[MTAThread]
static void Main(string[] args)
{
objForm = new Form1();
try
{
Application.Run(objForm);
} catch (Exception err) {
// do something with the info here - log to a file or whatever
MessageBox.Show(err.Message);
if ((objForm != null) && !objForm.IsDisposed)
{
// do some clean-up of your code
// (i.e. enable MS_SIPBUTTON) before application exits.
}
}
}
Perhaps he can comment on whether my technique is good or bad.

Error in Windows 8 xaml Modern app with thread

I have following two methods. When user clicks on start button from ui, the step geoLocator_PositionChanged in geoLocator_PositionChanged method is fired and calls the other method geoLocator_PositionChanged.But when it comes to try block while executing the first statement it throws the following error:
"The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))"
private async void btnStartStop_Click_1(object sender, RoutedEventArgs e)
{
geoLocator.PositionChanged += geoLocator_PositionChanged;
}
async void geoLocator_PositionChanged(Geolocator sender, PositionChangedEventArgs args)
{
MessageDialog msgdlg = null;
bool bDisplayDialog = false;
try
{
lblAltValue.Text = args.Position.Coordinate.Altitude.ToString();
}
catch
{
}
}
Any help how can I fix this issue ?
You try to access the UI-Thread from another one.
Try something like ths
Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync
(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
//HERE GOES THE UI ACCESS LIKE this.textbox.text = "MY AWESOME TEXT";
});

handling app that requires web service - dealing with EndpointNotFoundExceptions

I'm almost finished my first WP7 application and I'd like to publish it to the marketplace. However, one of the stipulations for a published app is that it must not crash unexpectedly during use.
My application almost completely relies on a WCF Azure Service - so I must be connected to the Internet at all times for my functions to work (communicating with a hosted database) - including login, adding/deleting/editing/searching clients and so forth.
When not connected to the internet, or when the connection drops during use, a call to the web service will cause the application to quit. How can I handle this? I figured the failure to connect to the service would be caught and I could handle the exception, but it doesn't work this way.
LoginCommand = new RelayCommand(() =>
{
ApplicationBarHelper.UpdateBindingOnFocussedControl();
MyTrainerReference.MyTrainerServiceClient service = new MyTrainerReference.MyTrainerServiceClient();
// get list of clients from web service
service.LoginCompleted += new EventHandler<LoginCompletedEventArgs>(service_LoginCompleted);
try
{
service.LoginAsync(Email, Password);
}
**catch (Exception ex)
{
throw new Exception(ex.Message);
}**
service.CloseAsync();
});
EDIT:
My main problem is how to handle the EndpointNotFoundException in WP7 without the application crashing.
Thanks,
Gerard.
Your code should look like
LoginCommand = new RelayCommand(Login);
...
public void Login()
{
var svc = new MyTrainerReference.MyTrainerServiceClient();
try
{
svc.LoginCompleted += LoginCompleted;
svc.LoginAsync();
}
catch (Exception e)
{
svc.CloseAsync();
ShowError(e);
}
}
private void LoginCompleted(object sender, LoginCompletedEventArgs e)
{
((MyTrainerReference.MyTrainerServiceClient)sender).LoginCompleted -= LoginCompleted;
((MyTrainerReference.MyTrainerServiceClient)sender).CloseAsync();
if (e.Error == null && !e.Cancelled)
{
// TODO process e.Result
}
else if (!e.Cancelled)
{
ShowError(e.Error);
}
}
private void ShowError(Exception e)
{
// TODO show error
MessageBox.Show(e.Message, "An error occured", MessageBoxButton.OK);
}
Your code calls LoginAsync and then immediately CloseAsync, I think this will cause problems...