System.UnauthorizedAccessException with text-to-speech in Windows Phone 8 - windows-phone-8

I have the following piece of code for using text to speech feature in Windows Phone 8. I am using ssml, with bookmarks. But when changing any UI element in the Bookmark event called function, raises Unauthorized Exception.
private void Initialise_synthesizer()
{
this.synthesizer = new SpeechSynthesizer();
synthesizer.BookmarkReached += new TypedEventHandler<SpeechSynthesizer, SpeechBookmarkReachedEventArgs>
(BookmarkReached);
}
void BookmarkReached(object sender, SpeechBookmarkReachedEventArgs e)
{
Debugger.Log(1, "Info", e.Bookmark + " mark reached\n");
switch (e.Bookmark)
{
case "START":
cur = start;
break;
case "LINE_BREAK":
cur++;
break;
}
**error here** t1.Text = cur.ToString();
}
But on running it gives the following error
A first chance exception of type 'System.UnauthorizedAccessException' occurred in System.Windows.ni.dll
An exception of type 'System.UnauthorizedAccessException' occurred in System.Windows.ni.dll and wasn't handled before a managed/native boundary
Invalid cross-thread access.
Any idea how to fix this error, or any work around.

Just got the answer.
Since the synthesizer.SpeakSsmlAsync() is an async function, to perform UI operations Dispatcher has to be used, something like this -
Dispatcher.BeginInvoke(() =>
t1.Text = cur.ToString());

It's pretty much unrelated to the speech recognition. It seems that it's related to accessing elements which are on the UI thread from a different thread.
Try this:
Dispatcher.BeginInvoke(() =>
{
t1.Text = cur.ToString();
}
);

From AppManifest.xml turn on capability ID_CAP_SPEECH_RECOGNITION.

Related

Geolocator.RequestAccessAsync throws "method called at unexpected time" exception

I have a chunk of code I use to get device location. This is done in a monogame windows uwp project. The following code worked before (I was on VS2015 Community). I recent did a fresh OS and install VS2017 Community. I finally got my project to build and run. The only thing not working is the Geolocator.RequestAccessAsync is throwing a "method called at unexpected time" exception. Any ideas?
public async Task<Vector2> GetDeviceGps()
{
var accessStatus = await Geolocator.RequestAccessAsync();
switch (accessStatus)
{
case GeolocationAccessStatus.Allowed:
// If DesiredAccuracy or DesiredAccuracyInMeters are not set (or value is 0), DesiredAccuracy.Default is used.
Geolocator geolocator = new Geolocator { DesiredAccuracyInMeters = 10 };
// Subscribe to the StatusChanged event to get updates of location status changes.
//geolocator.StatusChanged += OnStatusChanged;
// Carry out the operation.
Geoposition pos = await geolocator.GetGeopositionAsync();
return new Vector2((float)pos.Coordinate.Point.Position.Longitude, (float)pos.Coordinate.Point.Position.Latitude);
case GeolocationAccessStatus.Denied:
//Do something!
break;
case GeolocationAccessStatus.Unspecified:
//Murp
break;
}
return Vector2.Zero;
}
This is invoked and handled like so (called from update method of game):
mapper.GetDeviceGps().ContinueWith(pos =>
{
Vector2 bob = pos.Result;
});
When you run the RequestAccessAsync for the first time in your app, the user will be asked to grant your app the location permission. Therefore the method needs to be executed in the UI thread.

MVC5 AntiForgeryToken - how to handle "The provided anti-forgery token was meant for user "", but the current user is "xxx"." exception?

I want to protect our login actions by AntiforgeryToken attribute - I know why the exception from the topic occurs, however I can't seem to find any good solution for it.
Let say we have the following situations:
It's 8:00 AM, application users are coming to work, they sit down and starting the login process - right now it is very possible that some of the users will get the same ValidationToken. After the first one logs in - all other will see the above exception (or some other custom exception screen) when they attempt to login.
Some user logged in, then accidentally pressed the "back" button and attempted to log in again - while this is more unlikely, it can happen, and I don't want users to see exceptions when it does.
So the question is simple - how to prevent the above situations, or how to handle them so that users won't notice anything. I have tried the following:
Setting the AntiForgeryConfig.SuppressIdentityHeuristicChecks = true; in Application_Start in Global.asax - it didn't fix the problem, I still get the same exception
Setting the [OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")] on the method with [ValidateAntiForgeryToken] attribute - again, no luck there
Right now I was thinking to manually validate the token in action body, catch the error, and check if attempt was made by anonymous user:
public ActionResult SomeAction()
{
try
{
AntiForgery.Validate();
}
catch(HttpAntiForgeryException ex)
{
if(String.IsNullOrEmpty(HttpContext.User.Identity.Name))
{
throw;
}
}
//Rest of action body here
//..
//..
}
The above seems to prevent the errors - but is it safe? What alternatives are there?
Thanks in advance.
Best regards.
EDIT:
The final "solution" was to disable token validation on login form - there may be a better way to handle it, but it seems that all solutions I found, were ugly workarounds similar to mine proposed above.
Since there is no way to know how "safe" those alternatives are (if they are safe at all), we decided to do disable token validation on login.
Try setting (in global.cs):
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
This will add the name identifier to your token,
As for the double login issue try to use a script to document the date and time of the original submit to stop a second submit with the same token.
// jQuery plugin to prevent double submission of forms
jQuery.fn.preventDoubleSubmission = function() {
$(this).on('submit',function(e){
var $form = $(this);
if ($form.data('submitted') === true) {
// Previously submitted - don't submit again
e.preventDefault();
} else {
// Mark it so that the next submit can be ignored
$form.data('submitted', true);
}
});
// Keep chainability
return this;
};
So we know one thing; users like the back button and have a habit of the double click, this is a big issue with AntiforgeryToken.
But depending on what your application does there are ways to limit their compulsion to do so. The simplest of which is to do your best to try and make the visitor not feel like they need to “rewind” their request to alter it.
Ensure that form error messaging is clear and concise to ensure the
user knows what is wrong. Contexual errors give bonus points.
Always maintain form state between form submissions. Apart from
passwords or credit card numbers, there’s no excuse thanks the to MVC
form helpers. #Html.LabelFor(x => x.FirstName)
If forms are spread across tabs or hidden divs such as those used in
SPA frameworks like Angular or ember.js, be smart and show the
controller layouts or form that the errors actually originated from in
the form submission when displaying the error. Don’t just direct them
to the home controller or first tab.
“What’s going on?” - Keeping the user informed
When a AntiForgeryToken doesn’t validate your website will throw an Exception of type System.Web.Mvc.HttpAntiForgeryException.
If you’ve set up correctly you’ve got friendly errors turned on and this will mean your error page will not show an Exception and show a nice error page that tells them what is up.
You can make this a little easier by at least giving the user a more informative page targeted at these exceptions by catching the HttpAntiForgeryException.
private void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
if (ex is HttpAntiForgeryException)
{
Response.Clear();
Server.ClearError(); //make sure you log the exception first
Response.Redirect("/error/antiforgery", true);
}
}
and your /error/antiforgery view can tell them Sorry you have tried to submit the same information twice
Another Idea is to log the error and return the user to the login screen:
Create a HandleAntiforgeryTokenErrorAttribute class that Overrides the OnException method.
HandleAntiforgeryTokenErrorAttribute.cs:
public class HandleAntiforgeryTokenErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
filterContext.ExceptionHandled = true;
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(new { action = "Login", controller = "Account" }));
}
}
Global Filter:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new HandleAntiforgeryTokenErrorAttribute()
{ ExceptionType = typeof(HttpAntiForgeryException) }
);
}
}
I would also use a few tools to record all your information as login is critical part of your application
NLog for general logging and emails on critical application exceptions (including web exceptions).
Elmah for filtering and email of web exceptions.
EDIT:
Also you may want to look at a jQuery plugin called SafeForm. Link
EDIT:
I have seen allot of debate on this and everyone's views on the subject have valid points, How i look at it is (Taken from owasp.org)
Cross-Site Request Forgery (CSRF) is an attack that forces an end user
to execute unwanted actions on a web application in which they're
currently authenticated, CSRF attacks specifically target state-changing requests, not theft of data. The anti-forgery token is
specific to 'who is logged on'. So once you login, then go back, the
old token is no longer valid
Now i also use authorized IP addresses for login to allot of my applications with 2 factor authorization if the users IP address changes, so if Cross-Site Request Forgery was in play the user wouldn't match the IP address and request 2 factor authorization. almost like the way a security router would work. but if you want to keep it on your login page i don't see a problem as long as you have your friendly error pages set up people will not get upset as they will see they did something wrong.
I just wanted to add to the pool pro's answer - regarding the Filter part - that one must be careful since that will override all the exceptions about AntiforgeryToken, and if you (like myself) have this token validation on other parts of your application you might consider adding some validation to the filter:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new HandleAntiforgeryTokenErrorAttribute() { ExceptionType = typeof(HttpAntiForgeryException) });
}
}
public class HandleAntiforgeryTokenErrorAttribute : HandleErrorAttribute
{
public override void OnException(ExceptionContext filterContext)
{
string actionName = filterContext.Controller.ControllerContext.RouteData.Values["action"].ToString();
string controllerName = filterContext.Controller.ControllerContext.RouteData.Values["controller"].ToString();
if (actionName.ToLower() == "login" && controllerName.ToLower() == "account")
{
//Handle Error
//In here you handle the error, either by logging, adding notifications, etc...
//Handle Exception
filterContext.ExceptionHandled = true;
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(new { action = "Login", controller = "Account" }));
}
else
{
base.OnException(filterContext);
}
}
}
Note that I separate the cases where this exception is thrown on the Account/Login method, from all the other mehtods where a [ValidateAntiForgeryToken] might be used.

Flash update 12 broke my video recorder

When flash pushed the 12.0.0.70 version to Chrome it broke my video recorder.
According to the patch notes here, one thing was changed that might have broken my flash-based recorder
[3689061] [Video] Resolves an issue injected in Flash Player
11.9.900.170 that caused the video buffer to no longer be filled if the buffer was emptied while playing an RTMP stream
My recorder breaks when it's time to stop the stream and save the video to the Adobe Media Server.
I tried debugging it with the 12.0.0.70 flash debugger, but it doesn't crash when I'm using the debugger. Only when using the non-debugger Chrome version does it crash.
I can't debug it and get any useful information out of my swf, apart from making a bunch of external calls to console.log to see where it fails.
If someone also ran into a similar issue with flash-based, media-server-connected webcam recorders, and can guess at what might fix my problem, I'd be grateful.
I'm building this swf with Flex 4.6.0
Here's the function that stops the video recorder.
public function doStop():void{
if(status=="paused"){
doResume();
}
rectColor.color=0x000000;
rectColor.alpha=1;
var timer:Timer=new Timer(1 * 10);
timer.addEventListener(TimerEvent.TIMER,function(e:TimerEvent):void{
timer.stop();
timer.reset();
myns.close();
myTimer.stop();
if(!thumbBeginning){
if(status=="recording"){
takeScreenShot();
}
}else{
if(status=="recording"){
recordingTime = formatTime(realTime);
recordingLength = myTimer.currentCount;
if(!redoFlag){
ExternalInterface.call("CTRecorder.stopOk");
myTime.text = formatTime(0);
VD1.attachCamera(myCam);
setState("ready");
status = "stopped, ready"
playbackTimer.reset();
msg(recordingTime);
recording=false;
pauseTime=0;
}else{
pauseTime=0;
myTime.text = formatTime(0);
VD1.attachCamera(myCam);
playbackTimer.reset();
msg(recordingTime);
recording=false;
}
}
if(shutterGroup.visible){
toggleShutter();
}
myTimer.stop();
myTimer.reset();
if(redoFlag){
doRecord();
redoFlag=false;
trace("redoFlag turned off");
}
}
rectColor.alpha=.5;
});
timer.start();
}
This isn't really an answer, but it's too long for a comment.
"I can't debug it" - it only breaks in the release version? Is the release version the pepper plugin (i.e. Chrome's version of Flash), and the debug is the NPAPI plugin (i.e. Adobe's version)?
A likely candidate for where it's breaking is the ExternalInterface.call("CTRecorder.stopOk"); call. Are you testing this locally, or remotely? If locally, then you might be running into this bug: https://code.google.com/p/chromium/issues/detail?id=137734 where the Flash <-> JS communication is broken because of Trusted locations being ignored in PPAPI flash. In any case, try installing the release NPAPI version of Flash and see does it still crash (you can verify which one is running by visiting chrome://plugins/)
To help debugging the release version, you need a logging system - instead of making trace() calls, you call a custom log() function, that, as well as trace()ing, also stores the message somewhere, like in an Array. Then, in your SWF, when you hit a certain key, show a TextField on the screen, and populate it with your log() messages. That way, you'll be able to see trace() statements in release mode.
Also, don't forget to listen to any relative error events and thrown exceptions - ExternalInterface.call() will throw an Error and SecurityError for example. You can also set the marshallExceptions property, which will pass ActionScript exceptions to the browser and JavaScript exceptions to the player: http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/external/ExternalInterface.html#marshallExceptions
Finally, add a listener for the UncaughtErrorEvent.UNCAUGHT_ERROR event on your main class, which will catch any uncaught thrown errors (funnily enough), which will at least mean that your app doesn't collapse:
mainClass.loaderInfo.uncaughtErrorEvents.addEventListener( UncaughtErrorEvent.UNCAUGHT_ERROR, this._onUncaughtErrorEvent );
private function _onUncaughtErrorEvent( e:UncaughtErrorEvent ):void
{
var message:String = null;
var stackTrace:String = null;
// get the message
if ( e.error is Error )
{
message = ( e.error as Error ).message;
try { stackTrace = ( e.error as Error ).getStackTrace(); }
catch ( error:Error ) { stackTrace = "No stack trace"; }
}
else if ( e.error is ErrorEvent )
message = ( e.error as ErrorEvent ).text;
else
message = e.error.toString();
// show an alert
trace( "An uncaught exception has occurred: " + e.errorID + ": " + e.type + ": " + message + ", stack:\n" + stackTrace );
e.preventDefault();
}

Windows Phone 8 HRESULT: 0X80042706

I'm developing a Windows Phone 8 Application that uses the map control. I have followed the tutorial, but I keep geeting the messagebox error: HRESULT: 0X80042706. Here is the code from the tutorial
protected override void OnNavigatedTo(NavigationEventArgs e)
{
map.ColorMode = MapColorMode.Light; map.CartographicMode = MapCartographicMode.Road; map.LandmarksEnabled = true; map.PedestrianFeaturesEnabled = true; map.ZoomLevel = 17;
routeQuery.TravelMode = TravelMode.Walking; routeQuery.QueryCompleted += rq_QueryCompleted;
base.OnNavigatedTo(e);
}
...
void rq_QueryCompleted(object sender, QueryCompletedEventArgs<Route> e) {
if (null == e.Error) {
//Recommended way to display route on map
Route MyRoute = e.Result;
MapRoute MyMapRoute = new MapRoute(MyRoute);
map.AddRoute(MyMapRoute);
}
else
MessageBox.Show("Error occured:\n" + e.Error.Message);
}
I tried to search what kind of error HRESULT: 0X80042706 was from here, but I have no idea what that meant.
I even tried to switch the if condition to e.Error == null, but still no good. Can anyone help me?
The error is because your device does not support CHAP authentication while connecting to Virtual Disk Service (i.e. Maps)
This is because you don't have an authentication id from Microsoft.
Follow the details here ( for wp8 maps another authentication is required)
http://msdn.microsoft.com/en-us/library/windowsphone/develop/jj207033(v=vs.105).aspx
I received the same error from the same tutorial, and found it was due to no internet access to my PC (and hence no map data). Restored Internet access and the error resolved itself.
Please once check your Manifestfile and select Capability option click in ID_CAP_MAP.

Can I turn on WiFi-Direct from code? on Android API-14 (ICS)

I'm using the new Wi-Fi Direct API from google on Android 4.0
and in Sample code they send the User to Settings, to activate WiFi -Direct Mode.
Is there a way to Start it by code???
all they offer is to listen to WIFI_P2P_STATE_CHANGED_ACTION intent, and then use this code
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
// UI update to indicate wifi p2p status.
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
// Wifi Direct mode is enabled
} else {
// Wifi Direct mode is disabled
}
Yes there is a way using reflection. Works on my GSII (and fails gracefully on non Wifi Direct HTC Sensation) but as this is reflection it may not work on all phones.
p2pManager = (WifiP2pManager) getSystemService(WIFI_P2P_SERVICE);
channel = p2pManager.initialize(getApplicationContext(),
getMainLooper(), null);
try {
Class<?> wifiManager = Class
.forName("android.net.wifi.p2p.WifiP2pManager");
Method method = wifiManager
.getMethod(
"enableP2p",
new Class[] { android.net.wifi.p2p.WifiP2pManager.Channel.class });
method.invoke(p2pManager, channel);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Please note:
On Jelly Bean and above, when you try to use the WifiP2pManager API, WiFi-Direct is automatically enabled (as long as WiFi is on), so there is no need to use this hack.
No, all you could do is notify the user to turn on WiFi.
On some devices, even though Wi-Fi direct is supported, it's not enabled due to some system bugs. Here's a more reliable way to check whether it's enabled (unfortunately it requires root) using Kotlin.
val matcher = "^mNetworkInfo .* (isA|a)vailable: (true|false)"
.toPattern(Pattern.MULTILINE)
.matcher(su("dumpsys ${Context.WIFI_P2P_SERVICE}"))
if (!matcher.find()) return "Root unavailable"
if (matcher.group(2) != "true") return "Wi-Fi Direct unavailable"
return "Wi-Fi Direct available"
This should work for Android 4.3 - 8.1. Check source code below:
https://android.googlesource.com/platform/frameworks/base/+/f0afe4144d09aa9b980cffd444911ab118fa9cbe%5E%21/wifi/java/android/net/wifi/p2p/WifiP2pService.java
https://android.googlesource.com/platform/frameworks/opt/net/wifi/+/a8d5e40/service/java/com/android/server/wifi/p2p/WifiP2pServiceImpl.java#639
https://android.googlesource.com/platform/frameworks/base.git/+/f0afe4144d09aa9b980cffd444911ab118fa9cbe/core/java/android/net/NetworkInfo.java#433
https://android.googlesource.com/platform/frameworks/base.git/+/220871a/core/java/android/net/NetworkInfo.java#415