async Pedometer.GetSystemHistoryAsync API for Universal apps crashes - c#

I'm trying to throw together a simple app that uses pedometer data on a Windows 10 phone. I normally live down in kernel-land, and this is my first time using most of the c# async stuff, so I'm wondering if I'm missing a core concept here.
My first attempt at getting data out was to simply report the number of recorded steps over the last hour to a textbox in my XAML app. I just created a basic XAML app, dropped a text box in, and added this event handler:
private async void Page_Loaded(object sender, RoutedEventArgs e)
{
var history = await Pedometer.GetSystemHistoryAsync(DateTimeOffset.Now.AddHours(-1), TimeSpan.FromHours(1));
int count = history.Sum(entry => entry.CumulativeSteps);
textSteps.Text = count.ToString();
}
A breakpoint on the first line triggers, but before it hits the next line I get an unhandled exception. Error code -2147467259, message "Error HRESULT E_FAIL has been returned from a call to a COM component."
The top frame of the stack is in my code, but it's just the boilerplate line from App.g.i.cs that triggers a break on an unhandled exception. Below that is mscorlib and the WinRT invoker.
I looked through the app capabilities list in the manifest, and didn't find anything that looked like it applied to the pedometer. I'm testing this on a Lumia 950.
UPDATE: I just tried calling the API to get the default pedometer sensor:
Pedometer p = await Pedometer.GetDefaultAsync();
It turns out that this triggers an access denied exception with the same worthless stack. I'm currently doing more research to see if there is something that needs to be specified in the manifest.

After further experimenting got me an access denied error, I looked into the manifest more. The manifest Microsoft example project for the pedometer declares a device property that I can't find a way to add through the designer view. Adding it to the code worked perfectly. It's saying I've taken 300,000 steps in the last hour, but I'm sure some simple debugging will find the answer there. (The property is called CumulativeSteps, so that's a good hint...)
<Capabilities>
<DeviceCapability Name="activity" />
</Capabilities>

var currentReadings = await Pedometer.GetSystemHistoryAsync(DateTime.Today);
var walklist = new List<PedometerReading>();
var runlist = new List<PedometerReading>();
foreach (var cuurentreading in currentReadings)
{
if (cuurentreading.StepKind == PedometerStepKind.Walking)
{
walklist.Add(cuurentreading);
}
if (cuurentreading.StepKind == PedometerStepKind.Running)
{
runlist.Add(cuurentreading);
}
}
var item = walklist.Last();
var item1 = walklist.First();
var item2 = runlist.Last();
var item3 = runlist.First();
Steps1.Value += (item.CumulativeSteps - item1.CumulativeSteps);
Steps1.Value += (item2.CumulativeSteps - item3.CumulativeSteps);

Related

Firebase AppCheck token always null

I'm having this issue since one week on a Xamarin Android application.
I get the token with this method:
public async void GetToken()
{
var AppCheckToken = await AppCheck.GetToken(false);
if (AppCheckToken is AppCheckTokenResult Tok)
{
string r;
r = Tok.Token;
Preferences.Set("AppCheckToken", r);
}
}
that always return this string eyJlcnJvciI6IlVOS05PV05fRVJST1IifQ== on both debug and physical (production) mode. I also tried to make internal tests in Play Console and then download the app from there, but result is always the same.
Here's how I initialize AppCheck:
auth = FirebaseAuth.GetInstance(app);
PlayIntegrityAppCheckProviderFactory f = new PlayIntegrityAppCheckProviderFactory();
f.Create(app);
AppCheck = FirebaseAppCheck.GetInstance(app);
AppCheck.InstallAppCheckProviderFactory(f);
AppCheck.SetTokenAutoRefreshEnabled(true);
I noticed also that AppCheckToken variable declared in GetToken() method is always null and returns this FirebaseException:
--- End of managed Firebase.FirebaseException stack trace --- com.google.firebase.FirebaseException: null at
com.google.firebase.appcheck.internal.DefaultFirebaseAppCheck.lambda$getToken$1(DefaultFirebaseAppCheck.java:205)
at
com.google.firebase.appcheck.internal.DefaultFirebaseAppCheck$$ExternalSyntheticLambda1.then(Unknown
Source:0) at
com.google.android.gms.tasks.zze.run(com.google.android.gms:play-services-tasks##18.0.2:1)
at android.os.Handler.handleCallback(Handler.java:942) at
android.os.Handler.dispatchMessage(Handler.java:99) at
android.os.Looper.loopOnce(Looper.java:201) at
android.os.Looper.loop(Looper.java:288) at
android.app.ActivityThread.main(ActivityThread.java:7892) at
java.lang.reflect.Method.invoke(Native Method) at
com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:936) Caused
by: java.lang.NumberFormatException: null at
java.lang.Long.parseLong(Long.java:699) at
java.lang.Long.parseLong(Long.java:861) at
com.google.firebase.appcheck.playintegrity.internal.PlayIntegrityAppCheckProvider.lambda$getPlayIntegrityAttestation$4$com-google-firebase-appcheck-playintegrity-internal-PlayIntegrityAppCheckProvider(PlayIntegrityAppCheckProvider.java:105) at
com.google.firebase.appcheck.playintegrity.internal.PlayIntegrityAppCheckProvider$$ExternalSyntheticLambda1.then(Unknown
Source:4) at
com.google.android.gms.tasks.zzo.run(com.google.android.gms:play-services-tasks##18.0.2:1)
... 8 more
I tried also to generate a debug token from Firebase Console to use in the app in debug mode but when I make the call to Firebase Storage (that is already enforced) it keeps saying "AppCheck Token is invalid".
UPDATE:
I've tried also this approach: FirebaseAppCheck AppCheck = FirebaseAppCheck.Instance; AppCheck.InstallAppCheckProviderFactory(PlayIntegrityProviderFactory.Instance);
and for just one time FirebaseException was saying something like "PlayStore is not uptodate in your device". So I've updated PlayStore and now it throws the same error described above. I've tried to get the token with an AddOnSuccessListener(this) but result is the same.
Also I have to tell that var AppCheckToken declared before the if statement becomes always an object of class DefaultFirebaseAppCheckTokenResult.
I don't know what else to do...
IMHO there's a problem with declaration of objects (that are nulls), but since there aren't documents on how to use AppCheck on C# I'm screwed.

UIAutomation throws AccessViolationException on Windows 11

The issue:
We have an application written in C# that uses UIAutomation to get the current text (either selected or the word behind the carret) in other applications (Word, OpenOffice, Notepad, etc.).
All is working great on Windows 10, even up to 21H2, last update check done today.
But we had several clients informing us that the application is closing abruptly on Windows 11.
After some debugging I've seen some System.AccessViolationException thrown when trying to use the TextPatternRange.GetText() method:
System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'
What we've tried so far:
Setting uiaccess=true in manifest and signing the app : as mentionned here https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/350ceab8-436b-4ef1-8512-3fee4b470c0a/problem-with-manifest-and-uiaccess-set-to-true?forum=windowsgeneraldevelopmentissues => no changes (app is in C:\Program Files\
In addition to the above, I did try to set the level to "requireAdministrator" in the manifest, no changes either
As I've seen that it may come from a bug in Windows 11 (https://forum.emclient.com/t/emclient-9-0-1317-0-up-to-9-0-1361-0-password-correction-crashes-the-app/79904), I tried to install the 22H2 Preview release, still no changes.
Reproductible example
In order to be able to isolate the issue (and check it was not something else in our app that was causing the exception) I quickly made the following test (based on : How to get selected text of currently focused window? validated answer)
private void btnRefresh_Click(object sender, RoutedEventArgs e)
{
var p = Process.GetProcessesByName("notepad").FirstOrDefault();
var root = AutomationElement.FromHandle(p.MainWindowHandle);
var documentControl = new
PropertyCondition(AutomationElement.ControlTypeProperty,
ControlType.Document);
var textPatternAvailable = new PropertyCondition(AutomationElement.IsTextPatternAvailableProperty, true);
var findControl = new AndCondition(documentControl, textPatternAvailable);
var targetDocument = root.FindFirst(TreeScope.Descendants, findControl);
var textPattern = targetDocument.GetCurrentPattern(TextPattern.Pattern) as TextPattern;
string text = "";
foreach (var selection in textPattern.GetSelection())
{
text += selection.GetText(255);
Console.WriteLine($"Selection: \"{selection.GetText(255)}\"");
}
lblFocusedProcess.Content = p.ProcessName;
lblSelectedText.Content = text;
}
When pressing a button, this method is called and the results displayed in labels.
The method uses UIAutomation to get the notepad process and extract the selected text.
This works well in Windows 10 with latest update, crashes immediately on Windows 11 with the AccessViolationException.
On Windows 10 it works even without the uiaccess=true setting in the manifest.
Questions/Next steps
Do anyone know/has a clue about what can cause this?
Is Windows 11 way more regarding towards UIAutomation?
On my side I'll probably open an issue by Microsoft.
And one track we might follow is getting an EV and sign the app itself and the installer as it'll also enhance the installation process, removing the big red warnings. But as this is an app distributed for free we had not done it as it was working without it.
I'll also continue testing with the reproductible code and update this question should anything new appear.
I posted the same question on MSDN forums and got this answer:
https://learn.microsoft.com/en-us/answers/questions/915789/uiautomation-throws-accessviolationexception-on-wi.html
Using IUIautomation instead of System.Windows.Automation works on Windows 11.
So I'm marking this as solved but if anyone has another idea or knows what happens you're welcome to comment!

UWP FolderPicker.PickSingleFolderAsync fails with COMException / E_FAIL

In my UWP app I have the following code:
private async void testButton_Click(object sender, RoutedEventArgs e)
{
var picker = new Windows.Storage.Pickers.FolderPicker();
StorageFolder folder = await picker.PickSingleFolderAsync();
}
but when I run this it fails on the second line with the message An exception of type 'System.Runtime.InteropServices.COMException' occurred in .... but was not handled in user code. The HRESULT from the exception is -2147467259 = 0x80004005 = E_FAIL.
I'm using file pickers already elsewhere in the app without problem. This is running on a Win10 desktop (launched from VS2015). Can anyone suggest why the error occurs and/or what to do to resolve it? Having a meaningless error message in what appears to be the simplest code possible I'm not sure how to proceed.
This is a bit of an oddity in WinRT. Although it is not mentioned in the documentation explicitly, it is necessary to add at least one item in the FileTypeFilter collection:
var folderPicker = new FolderPicker();
folderPicker.FileTypeFilter.Add("*");
await folderPicker.PickSingleFolderAsync();
You can use a specific extension like ".jpg", but it doesn't seem to have effect in a FolderPicker anyway. The only thing that matters is that at least one valid item is present.

c# Bluetooth LE - write configuration error - ValueChanged never called

So I try to connect my c# WPF program to a BLE device and this is the code to connect to the device:
private async Task ConnectToWatcher(DeviceInformation deviceInfo) {
try {
// get the device
BluetoothLEDevice device = await BluetoothLEDevice.FromIdAsync(deviceInfo.Id);
// get the GATT service
Thread.Sleep(150);
var gattServicesResult = await device.GetGattServicesForUuidAsync(new Guid(RX_SERVICE_UUID));
service = gattServicesResult.Services[0];
// get the GATT characteristic
Thread.Sleep(150);
var gattCharacteristicsResult = await service.GetCharacteristicsForUuidAsync(new Guid(RX_CHAR_UUID));
characteristic = gattCharacteristicsResult.Characteristics[0];
// register for notifications
Thread.Sleep(150);
characteristic.ValueChanged += (sender, args) => {
Debug.WriteLine($"[{device.Name}] Received notification containing {args.CharacteristicValue.Length} bytes");
};
GattWriteResult result =
await characteristic.WriteClientCharacteristicConfigurationDescriptorWithResultAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);
Debug.WriteLine($"Characteristics write result: status={result.Status}, protocolError={result.ProtocolError}");
} catch (Exception ex) when ((uint)ex.HResult == 0x800710df) {
Debug.WriteLine("bluetooth error 1");
// ERROR_DEVICE_NOT_AVAILABLE because the Bluetooth radio is not on.
}
}
The line
Debug.WriteLine($"Characteristics write result: status={result.Status}, protocolError={result.ProtocolError}"
creates the output
Characteristics write result: status=protocolError, protocolError=3
I couldn't find anywhere whats that supposed to mean. The effect is the Method characteristic.ValueChanged never gets called.
Do I have to do more to have the characteristic configurated? And has anybody any idea why the method isn't called or what that error message means?
Thanks a bunch.
Apparently, some Windows 10 builds have a COM security bug.
Solution was to register for Windows-Insider-Program and update Windows.
Update:
There are two more solutions to this:
1) Calling CoInitializeSecurity from outside your c#-code (didn't bring it to work)
- or-
2) Writing two new keys into the windows registry. You cann create a file "Bluetooth.reg", which will add those two keys on a doubleklick. This answer from https://social.msdn.microsoft.com/Forums/en-US/58da3fdb-a0e1-4161-8af3-778b6839f4e1/bluetooth-bluetoothledevicefromidasync-does-not-complete-on-10015063?forum=wdk was my solution:
Hi Kamen, I have experienced exactly same issue. You can give a quick try of the following:
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\AppID{C6BFD646-3DF0-4DE5-B7AF-5FFFACB844A5}]
"AccessPermission"=hex:01,00,04,80,9c,00,00,00,ac,00,00,00,00,00,00,00,14,00,\
00,00,02,00,88,00,06,00,00,00,00,00,14,00,07,00,00,00,01,01,00,00,00,00,00,\
05,0a,00,00,00,00,00,14,00,03,00,00,00,01,01,00,00,00,00,00,05,12,00,00,00,\
00,00,18,00,07,00,00,00,01,02,00,00,00,00,00,05,20,00,00,00,20,02,00,00,00,\
00,18,00,03,00,00,00,01,02,00,00,00,00,00,0f,02,00,00,00,01,00,00,00,00,00,\
14,00,03,00,00,00,01,01,00,00,00,00,00,05,13,00,00,00,00,00,14,00,03,00,00,\
00,01,01,00,00,00,00,00,05,14,00,00,00,01,02,00,00,00,00,00,05,20,00,00,00,\
20,02,00,00,01,02,00,00,00,00,00,05,20,00,00,00,20,02,00,00
[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\AppID\YOURAPP.exe]
"AppID"="{C6BFD646-3DF0-4DE5-B7AF-5FFFACB844A5}"
Copy above content to a text file.
Replace 'YOURAPP.EXE' with your executable name
Optionally replace GUIDs (I have created a new one for you)
Save text file with an extension as .reg
Double click on the file.
You would see a message 'The Keys and values contained in ..... .reg have been successfully added to the registry.'
With this, I don't need to call CoInitializeSecurity from my app.
you need to call CoInitializeSecurity before
more info here. couple of weeks I spent looking for solution :)
https://social.msdn.microsoft.com/Forums/en-US/58da3fdb-a0e1-4161-8af3-778b6839f4e1/

Error while executing script for a TableObject located at the PageFooter section

We have a report that displays at the PageFooter which payment way the customer used to pay an order, in that area we have three other TableObjects that are working correctly, but there's one that executes a script to build manually the TableObject, the problem we located is when it executes that script it fails showing the message StackOverflowException in System.Drawing.dll
The message on top means the report generation is executing.
The script that I located it fails is this one, if this script is not executing the report displays correctly but without the information we want to display in that TableObject
private void TableModalidadPago_ManualBuild(object sender, EventArgs e)
{
// get the data source by its name
DataSourceBase rowData = Report.GetDataSource("DOCUMENTO_MODALIDAD_PAGO");
// init the data source
rowData.Init();
if (rowData.RowCount == 0)
{
TableModalidadPago.Visible = false;
return;
}
// print the first table row - it is a header
TableModalidadPago.PrintRow(0);
TableModalidadPago.PrintColumns();
TableModalidadPago.PrintRow(1);
TableModalidadPago.PrintColumns();
// now enumerate the data source and print the table body
while (rowData.HasMoreRows)
{
// print the table body
TableModalidadPago.PrintRow(2);
TableModalidadPago.PrintColumns();
// go next data source row
rowData.Next();
}
TableModalidadPago.CanBreak = false;
TableModalidadPago.CanGrow = true;
}
It fails at line
TableModalidadPago.PrintRow(0);
And if I put the TableObject in other section that is not the PageFooter it works perfectly.
Anyone knows if there's any restriction to execute code at PageFooter or if there's any error at the provided script?
I already posted this information in FastReports forum but still no answer(Link)
Edit: I also created a ticket in FastReports Support centre and still no answer...
Edit2: 24/06/2016 today I saw they published a new version of the FastReports.Net (2016.3 previous was 2016.2) and I downloaded and install it, after cleaning up my project and tried again, the error still ocurring, with this new version the program just unexplectly closes and doesn't display any error message, I updated my ticket with support center
Thanks.
The stack overflow error suggests that the while loop may be infinite. Could it actually be failing at the line
TableModalidadPago.PrintRow(2);
Perhaps you need to remove rows from rowData object once you've printed them?

Categories