MessageDialog closes Popup - windows-8

in my Popup windows (contains game options control) I have "Reset HighScores" Button. Button fire a MessageDialog with a TextBlock "Are you sure that ..." and two Buttons "Yes" and "No". However, when MessageDialog opens, Popup closes. Do you know how to make popup still alive?

I was able to get around this using an Action delegate as a callback for when the MessageDialog is closed.
The key is to call the Action after an await on MessageDialog's ShowAsync in an async function.
Another key is to Close and Open your popup to get the IsLightDismissEnabled to actually take hold.
XAML:
<Popup
IsLightDismissEnabled="{Binding IsLightDismiss, Mode=TwoWay}"
IsOpen="{Binding IsPopupOpen, Mode=TwoWay}">
ViewModel:
private bool isPopupOpen;
public bool IsPopupOpen
{
get { return this.isPopupOpen; }
set { this.SetProperty(ref this.isPopupOpen, value); }
}
private bool isLightDismiss;
public bool IsLightDismiss
{
get { return this.isLightDismiss; }
set { this.SetProperty(ref this.isLightDismiss, value); }
}
protected void ShowDialog()
{
this.IsLightDismiss = false;
this.IsPopupOpen = false;
this.IsPopupOpen = true;
Action showPopup = () => {
this.IsLightDismiss = true;
this.IsPopupOpen = false;
this.IsPopupOpen = true;
};
ShowMessageDialog("message", "title", showPopup);
}
private async void ShowMessageDialog(string message, string title, Action callback)
{
var _messageDialog = new MessageDialog(message, title);
await _messageDialog.ShowAsync();
callback();
}

set your Popup's IsLightDismissEnabled property to false to achieve that.
popup.IsLightDismissEnabled = false;

Related

Codename One location sometimes not working

Old question: Codename One app not provide real location
We still have problem getting current location.
Sometimes it's ok, "Localizzazione..." dialog shows, then location ok callback dispose the dialog.
Sometimes the dialog is never disposed and I don't see GPS in the top bar, which is visible when location is ok and dispose the dialog.
Slider s1 = new Slider();
Display.getInstance().callSerially(() -> {
blocco_loc_in_corso = makeDialog("Localizzazione...", s1, null, 'a');
blocco_loc_in_corso.show();
});
LocationManager locationManager = LocationManager.getLocationManager();
locationManager.setLocationListener(new LocationListener() {
#Override
public void locationUpdated(Location location) {
if(location != null) {
Display.getInstance().callSerially(() -> {
if(blocco_loc_in_corso != null) {
blocco_loc_in_corso.dispose();
}
});
paintLocation(location, true);
}
}
#Override
public void providerStateChanged(int newState) {
}
}, new LocationRequest(LocationRequest.PRIORITY_HIGH_ACCUARCY, 1000));
I have this problem for at least 6 months. We only need to block user until we have his GPS location which may can change (GPS updates callback).
Edited:
public Dialog makeDialog(String label, Component c, String buttonText, char btIcon) {
Dialog dlg_r = new Dialog();
Style dlgStyle = dlg_r.getDialogStyle();
dlgStyle.setBorder(Border.createEmpty());
dlgStyle.setBgTransparency(255);
dlgStyle.setBgColor(0xffffff);
Label title = dlg_r.getTitleComponent();
title.getUnselectedStyle().setFgColor(0xff);
title.getUnselectedStyle().setAlignment(Component.LEFT);
dlg_r.setLayout(BoxLayout.y());
Label blueLabel = new Label(label);
blueLabel.setShowEvenIfBlank(true);
blueLabel.getUnselectedStyle().setBgColor(0xff);
blueLabel.getStyle().setFgColor(0x0a0afc);
blueLabel.getStyle().setAlignment(Component.CENTER);
blueLabel.getUnselectedStyle().setPadding(1, 1, 1, 1);
blueLabel.getUnselectedStyle().setPaddingUnit(Style.UNIT_TYPE_PIXELS);
dlg_r.add(blueLabel);
dlg_r.add(c);
if (buttonText != null) {
Button dismiss = new Button(buttonText);
dismiss.getAllStyles().setBorder(Border.createEmpty());
dismiss.getAllStyles().setFgColor(0);
dismiss.getAllStyles().set3DText(true, true);
dismiss.setIcon(FontImage.createMaterial(btIcon, dismiss.getStyle()));
dismiss.addActionListener(((evt) -> {
dlg_r.dispose();
}));
dlg_r.add(dismiss);
}
return dlg_r;
}
To make sure this code is threadsafe make the following change:
public void locationUpdated(Location location) {
locationFound = true;
// ...
}
Then in the make dialog method:
dlg_r.addShowListener(e -> {
if(locationFound) {
dlg_r.dispose();
}
});
Since this event can happen in the dead time of showing the dialog transition.

`TypeError: cannot write property 'implementation' of undefined` error in frida

I am trying to inject the below script using frida
setImmediate(function() { //prevent timeout
console.log("[*] Starting script");
Java.perform(function() {
var bClass = Java.use("sg.vantagepoint.uncrackable1.a");
bClass.onClick.implementation = function(v) {
console.log("[*] onClick called");
// do nothing
}
console.log("[*] onClick handler modified")
})
})
Throws the below error
Attaching...
[*] Starting script
TypeError: cannot write property 'implementation' of undefined
at [anon] (../../../frida-gum/bindings/gumjs/duktape.c:57636)
at /inject.js:10
at frida/node_modules/frida-java-bridge/lib/vm.js:11
at E (frida/node_modules/frida-java-bridge/index.js:346)
at frida/node_modules/frida-java-bridge/index.js:298
at frida/node_modules/frida-java-bridge/lib/vm.js:11
at frida/node_modules/frida-java-bridge/index.js:278
at /inject.js:13
at frida/runtime/core.js:55
command i am using frida -U -l inject.js owasp.mstg.uncrackable1
Below one is the decompiled code of the apk file.
package sg.vantagepoint.uncrackable1;
public class MainActivity extends Activity {
private void a(String str) {
AlertDialog create = new AlertDialog.Builder(this).create();
create.setTitle(str);
create.setMessage("This is unacceptable. The app is now going to exit.");
create.setButton(-3, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
System.exit(0);
}
});
create.setCancelable(false);
create.show();
}
Try to inject this script
setImmediate(function () {
console.log("[*] Starting script");
Java.perform(function () {
var bClass = Java.use("sg.vantagepoint.uncrackable1.MainActivity$1");
bClass.onClick.implementation = function (v) {
console.log("[*] onClick called.");
}
console.log("[*] onClick handler modified")
var aaClass = Java.use("sg.vantagepoint.a.a");
aaClass.a.implementation = function (arg1, arg2) {
var retval = this.a(arg1, arg2);
var password = ''
for (var i = 0; i < retval.length; i++) {
password += String.fromCharCode(retval[i]);
}
console.log("[*] Decrypted: " + password);
return retval;
}
console.log("[*] sg.vantagepoint.a.a.a modified");
});
});
This is happening because you're trying to override the onClick function of the main activity: sg.vantagepoint.uncrackable1.MainActivity$1 doesn't have an onClick() function. You can either cancel the function call entirely by overriding the a function to do nothing, or if you want to retain the logic but instead just cancel the display, should use Java.choose(...) API to choose the alert dialogue once it is instantiated and change it to fit your needs - for example, you can make the dialogue window cancelable, like this:
setImmediate(function() { //prevent timeout
console.log("[*] Starting script");
Java.perform(function() {
var bClass = Java.use("sg.vantagepoint.uncrackable1.a");
var oldImpl = bClass.a.implementation;
bClass.a.implementation = function(v){
console.log("Initial activity logic is launching");
oldImpl(v);
Java.choose("android.app.AlertDialog", {
onMatch: function(instance){
console.log("Found an alert dialog, making it cancelable")
instance.setCancelable(true);
}
onComplete: function(){
console.log("Done")
}
})
}
})
})

How to check if an application is it's first run or not in xamarin crosspaltform

I want to show some pages in the first time app is installed, and the next time when I open the app show some other pages.
I tried this code
protected override void OnStart()
{
if (Application.Current.Properties.ContainsKey("id"))
{
MainPage = new NavigationPage(new Page2());
}
else
{
Application.Current.Properties["id"] = 2;
MainPage = new NavigationPage(new Page1());
}
}
The values in the Properties dictionary are only stored when the app goes to sleep
For a cross-platform approach, you can use the Settings Plugin
Then you can create a boolean property, for example, DidOpenOnce, and if it is false, show your initial welcome page or whatever. Then afterwards, set it to true.
protected void checkApplicationInstallState()
{
//retreive
var prefs = Application.Context.GetSharedPreferences("MyApp", FileCreationMode.Private);
var somePref = prefs.GetBool("IsApplicationOpenedForOnce", null);
if (!somePref) {
// Your Application is opened for the very first time. Now change the value to true as you have now opened the app so next time opening this application should get a true value.
var prefEditor = prefs.Edit();
prefEditor.PutBool(true, "IsApplicationOpenedForOnce");
prefEditor.Commit();
}
}
public MainPage()
{
InitializeComponent();
if (Application.Current.Properties.ContainsKey("FirstUse"))
{
//Do things when it's NOT the first use...
loadinit();
}
else
{
Application.Current.Properties["FirstUse"] = false;
//Do things when it IS the first use...
}
}
public async void loadinit()
{
await Navigation.PushAsync(new LoadPage());
}

Xamarin Forms Switch XAML

I'm new in Xamarin and i'm trying to create a simple page with some components.
One of these component is a Switch it works fine by itself but i would like to change the basic text "inactive/active" by "male/female"
I've seen that in Xaml for windows phone there is a ToggleSwitch Component with a On/OffContent property but i can't seems to find an equivalent in XAML for Xamarin Forms
any idea ?
Thank you!
The lack of built in switch options, or at least the lack of being able to rename the switch options, has been asked a few times.
You could go with custom renders, modify the text at the OS level or do like I chose to do, just build your own switch.
This switch is two buttons laid out horizontally with the text Yes and No. The selected button gets a red border, and the unselected a transparent border.
class CustomSwitch : Grid
{
public event EventHandler<SelectedItemChangedEventArgs> ItemSelected;
private Button negative;
private Button positive;
public static readonly BindableProperty SelectedItemProperty = BindableProperty.Create<CustomSwitch, Object>(t => t.SelectedItem, null, BindingMode.TwoWay, propertyChanged: OnSelectedItemChanged);
public CustomSwitch()
{
try
{
this.HorizontalOptions = LayoutOptions.Center;
this.VerticalOptions = LayoutOptions.Center;
negative = new Button();
negative.Text = "No";
negative.Style = <YourNameSpace>.AppStyling.Style_Button_Switch;
negative.Clicked += (o,s) => OnSelectedItemChanged(this, ItemSelected, (int)Classes.Collections.Enums.SelectionStatus.False);
positive = new Button();
positive.Text = "Yes";
positive.Style = <YourNameSpace>.AppStyling.Style_Button_Switch;
positive.Clicked += (o, s) => OnSelectedItemChanged(this, ItemSelected, (int)Classes.Collections.Enums.SelectionStatus.True);
this.Children.Add(negative, 0,0);
this.Children.Add(positive, 1,0);
}
catch(System.Exception ex)
{
<YourNameSpace>.Classes.Helpers.Helper_ErrorHandling.SendErrorToServer(ex, this.GetType().Name, System.Reflection.MethodBase.GetCurrentMethod().Name);
}
}
public Object SelectedItem
{
get
{
return base.GetValue(SelectedItemProperty);
}
set
{
if (SelectedItem != value)
{
base.SetValue(SelectedItemProperty, value);
InternalUpdateSelected();
}
}
}
private void InternalUpdateSelected()
{
if((int)SelectedItem == (int)Classes.Collections.Enums.SelectionStatus.False)
{
negative.BorderColor = <YourNameSpace>.AppStyling.Color_Selected;
positive.BorderColor = <YourNameSpace>.AppStyling.Color_UnSelected;
positive.Opacity = <YourNameSpace>.AppStyling.Opaque_High;
}
else if ((int)SelectedItem == (int)Classes.Collections.Enums.SelectionStatus.True)
{
negative.BorderColor = <YourNameSpace>.AppStyling.Color_UnSelected;
negative.Opacity = <YourNameSpace>.AppStyling.Opaque_High;
positive.BorderColor = <YourNameSpace>.AppStyling.Color_Selected;
}
else
{
negative.BorderColor = <YourNameSpace>.AppStyling.Color_UnSelected;
negative.Opacity = <YourNameSpace>.AppStyling.Opaque_High;
positive.BorderColor = <YourNameSpace>.AppStyling.Color_UnSelected;
positive.Opacity = <YourNameSpace>.AppStyling.Opaque_High;
}
}
private static void OnSelectedItemChanged(BindableObject bindable, object oldValue, object newValue)
{
CustomSwitch boundSwitch = (CustomSwitch)bindable;
if((int)newValue != (int)Classes.Collections.Enums.SelectionStatus.Unselected)
{
boundSwitch.SelectedItem = (int)newValue == (int)Classes.Collections.Enums.SelectionStatus.False ? (int)Classes.Collections.Enums.SelectionStatus.False : (int)Classes.Collections.Enums.SelectionStatus.True;
}
if (boundSwitch.ItemSelected != null)
{
boundSwitch.ItemSelected(boundSwitch, new SelectedItemChangedEventArgs(newValue));
}
boundSwitch.InternalUpdateSelected();
}
}

How can I detect when the XAML Slider is Completed?

In XAML I have the <Slider />. It has the ValueChanged event. This event fires with every change to Value. I need to detect when the value change is over. LostFocus, PointerReleased are not the correct event. How can I detect this?
XAML, WinRT, Windows8.1 and UWP:
PointerCaptureLost event should work for mouse / touch
KeyUp event for keyboard
You can create a new class and inherit from Slider. From there on, you can look for the Thumb control & listen for the events you want.
Something like this should work:
public class SliderValueChangeCompletedEventArgs : RoutedEventArgs
{
private readonly double _value;
public double Value { get { return _value; } }
public SliderValueChangeCompletedEventArgs(double value)
{
_value = value;
}
}
public delegate void SlideValueChangeCompletedEventHandler(object sender, SliderValueChangeCompletedEventArgs args);
public class ExtendedSlider : Slider
{
public event SlideValueChangeCompletedEventHandler ValueChangeCompleted;
private bool _dragging = false;
protected void OnValueChangeCompleted(double value)
{
if (ValueChangeCompleted != null)
{
ValueChangeCompleted(this, new SliderValueChangeCompletedEventArgs(value) );
}
}
protected override void OnApplyTemplate()
{
base.OnApplyTemplate();
var thumb = base.GetTemplateChild("HorizontalThumb") as Thumb;
if (thumb != null)
{
thumb.DragStarted += ThumbOnDragStarted;
thumb.DragCompleted += ThumbOnDragCompleted;
}
thumb = base.GetTemplateChild("VerticalThumb") as Thumb;
if (thumb != null)
{
thumb.DragStarted += ThumbOnDragStarted;
thumb.DragCompleted += ThumbOnDragCompleted;
}
}
private void ThumbOnDragCompleted(object sender, DragCompletedEventArgs e)
{
_dragging = false;
OnValueChangeCompleted(this.Value);
}
private void ThumbOnDragStarted(object sender, DragStartedEventArgs e)
{
_dragging = true;
}
protected override void OnValueChanged(double oldValue, double newValue)
{
base.OnValueChanged(oldValue, newValue);
if (!_dragging)
{
OnValueChangeCompleted(newValue);
}
}
}
You can use pair of bool values isValueChanged and (if possible change value without manipulation of pointer
) isPressed;
private void Slider_ValueChanged(object s, RangeBaseValueChangedEventArgs e) {
if (!isPressed) {
AcceptChanges();
} else {
isValueChanged = true;
}
}
Initialization code:
Window.Current.CoreWindow.PointerPressed += (e, a) => { isPressed = true; };
Window.Current.CoreWindow.PointerReleased += (e, a) => {
isPressed = false;
if (isValueChanged) AcceptChanges();
};
I had a similar issue using a Slider on Windows8/WinRT.
My problem was the following: I was reacting to the ValueChanged Event and performing a long lasting operation (writing asynchronously to a file) after each trigger. And thus running into a concurrent editing exception. In order to avoid this, I used a DispatcherTimer.
//Class member
private DispatcherTimer myDispatcherTimer = null;
private void OnSliderValueChanged(object sender, RangeBaseValueChangedEventArgs e)
{
//I update my UI right away
...
//If the dispatcher is already created, stop it
if (myDispatcherTimer!= null)
myDispatcherTimer.Stop();
//Overwrite the DispatcherTimer and thus reset the countdown
myDispatcherTimer= new DispatcherTimer();
myDispatcherTimer.Tick += (sender, o) => DoSomethingAsync();
myDispatcherTimer.Interval = new TimeSpan(0,0,2);
myDispatcherTimer.Start();
}
private async void DoSomethingAsync()
{
await DoThatLongSaveOperation();
}
You cannot directly detect what the final value is, but you can at least delay the operation until there is a long pause between two updates (e.g. in my case, if the user drags the slider and stops while maintaining the drag for 2 seconds, the save operation will be fired anyway).