Firebase AppCheck token always null - c#

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.

Related

Could not open database file (Misuse) SqlLiteAsyncConnection

I am getting the exception "Could not open database file: [path] (Misuse)" when trying to open my SQLite connection.
I'm creating a Xamarin.Forms application and am doing the debugging in UWP which is where I'm getting the exception.
The constructor to my data store class creates the connection and the tables:
internal static string DBPath
{
get
{
const string FILE_NAME = "TheRandomizer.db3";
if (Device.RuntimePlatform == Device.Android)
{
return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), FILE_NAME);
}
else
{
return Path.Combine(ApplicationData.Current.LocalFolder.Path, FILE_NAME);
}
}
}
public SqliteDataStore()
{
_database = new SQLiteAsyncConnection(DBPath, SQLiteOpenFlags.Create);
// Fails trying to perform this action:
_database.CreateTableAsync<GeneratorTable>().Wait();
_database.CreateTableAsync<TagTable>().Wait();
}
The full source can be viewed here on my GitHub.
Stack trace:
at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout,
CancellationToken cancellationToken) at
System.Threading.Tasks.Task.Wait() at
TheRandomizer.Services.SqliteDataStore..ctor() at
TheRandomizer.ViewModels.BaseViewModel.get_DataStore() at
TheRandomizer.ViewModels.GeneratorListViewModel.ExecuteLoadItemsCommand()
Update
I have tested your code locally and saw the behavior is actually happening and after some debugging I think I might have two reasons:
First, the constructor has only the SQLiteOpenFlags.Create flag. Apparently this does not give you any other permissions including read/write. Instead, you can either omit this second argument altogether:
_database = new SQLiteAsyncConnection(DBPath);
Or include explicit ReadWrite flag (I also included the FullMutex flag as it is recommended for async connection):
_database = new SQLiteAsyncConnection(
DBPath,
SQLiteOpenFlags.Create |
SQLiteOpenFlags.FullMutex |
SQLiteOpenFlags.ReadWrite );
Second problem occurs when creating the GeneratorTable table in DB. SQLite does not know how to store the Version property as it is a custom GeneratorVersion type. So you will probably have to break it down to simple properties or add an [Ignore] attribute.
Original answer
I have checked your source code and found out you are trying to store the database in the Environment.SpecialFolder.Personal folder. For UWP this actually resolves to C:\Users\$Username$\Documents, which a UWP app does not have access to as it is running in a sandbox and does not have access to.
Instead, you must use the application's data folder (which you probably actually intended to):
Path.Combine(ApplicationData.Current.LocalFolder.Path, FILE_NAME);

"Object reference not set to an instance of an object" exception when assigning EF property to variable

I'm getting an "Object reference not set to an instance of an object" exception when I'm trying to assign one of the property of my EF object model to a variable but can't figure out why as the EF object definitely contains data and is accessible in the Immediate Window.
I call the following code to get data from a specific organization:
var organizationModelFromDb = this.DbContext.Organizations.
SingleOrDefault(o => o.OrganizationId ==
organizationEditViewModel.Organization.OrganizationId);
This definitely returns data as I can see data displayed when expanding the tooltip when hovering my mouse over the organizationModelFromDb object. I can also access the data when I type:
organizationModelFromDb.MembershipType
in the Immediate Window but when I try to assign this property from my object model as such:
var membershipType = organizationModelFromDb.MembershipType;
I get the mentioned exception.
Everything within this Controller's method is working as expected but I was in the process of introducing new functionality but I'm stuck with this problem.
Any idea what may be happening. I'm pretty sure I'm assigning EF data to variables using the same technique all over the place in my project but for whatever reason it just won't work in this method.
What am I missing?
UPDATE-1:
This is not a duplicate question. The referenced article deal with the fact that object may actually be null and how best handle each scenario but as explained my object is not actually null. Data is being returned and it is available via the immediate window and the tooltip.
Update-2
This is the data I get when I'm calling "organizationModelFromDb" from the immediate window:
{System.Data.Entity.DynamicProxies.
OrganizationModel_2AEF19E09C5699B8E172F0AA73D6DB
71945EF111ADF7AE5EAEB3AD073A15D5A3}
AdditionalDetails:
{System.Data.Entity.DynamicProxies.OrganizationAddition_
05739F8DE2F5D549B3A7FC852AC32ED9C002953ED41AAA7751B12289E23D8A6C}
AutoImport: false
Members: Count = 1
MembershipType: Full
OrganizationId: "4be433d5-48a9-4891-a008-c70fe4cfoie3"
OrganizationName: "My Company"
StatusType: Approved
Website: ""
_entityWrapper: {System.Data.Entity.Core.Objects.Internal.EntityWrapperWithoutRelationships<System.Data.Entity.DynamicProxies.OrganizationModel_2AEF19E09C5699B8E172F0AA73D6DB71945EF111ADF7AE5EAEB3AD073A15D5A3>}
As you can see, there is data in the object.
But as mentioned, when I call this line of code:
var membershipType = organizationModelFromDb.MembershipType;
in my code, I get the exception with the following StackTrace:
"System.NullReferenceException: Object reference not set to an instance of an object.
at Mywebsite.Controllers.OrganizationsController.d__8.MoveNext() in C:\Work\MyWebsite\Controllers\OrganizationsController.cs:line 349"
Hope this helps resolving my problem.
Update-3
I've removed the code originally provided in this update to keep things tidy rather than providing yet another update but the code below is the full code contained in my controller but note that I've removed unnecessary code for readability sake:
var organizationModelFromDb = await this.DbContext.Organizations
.FirstOrDefaultAsync<OrganizationModel>(o => o.OrganizationId ==
organizationEditViewModel.Organization.OrganizationId);
if (ReferenceEquals(organizationModelFromDb, null))
return HttpNotFound();
organizationModelFromDb.StatusType = StatusType.Approved;
var memberModelsFromDb =
this.DbContext.Members.Where(
m => m.OrganizationId ==
organizationEditViewModel.Organization.OrganizationId).ToList();
if (memberModelsFromDb.Count > 0)
{
foreach (var memberModel in memberModelsFromDb.ToList())
{
var user = new ApplicationUser
{
UserName = memberModel.Email,
Email = memberModel.Email,
UserType = UserType.IsMember
};
var password = RandomPassword.Generate();
var result = await this.UserManager.CreateAsync(user, password);
if (result.Succeeded)
{
await this.UserManager.AddToRoleAsync(user.Id, JoiffRoles.IsMember);
try
{
var membershipType = organizationModelFromDb.MembershipType;
}
catch (Exception e)
{
Console.WriteLine(e);
}
string code = await this.UserManager.
GenerateEmailConfirmationTokenAsync(user.Id);
string codeHtmlVersion = HttpUtility.UrlEncode(code);
new Thread(async () =>
{
await CustomEmailService.
SendConfirm(this, Request, user, codeHtmlVersion);
}).Start();
}
}
}
Now as you can see, there's nothing special about this code. I'm checking if an organization exists, then I'm getting all the members for that organization and then I'm looping through each member and creating a user and adding roles to the database. Once created successfully, it sends an email to the newly created user with credential information.
Now the weird part, the exception "Object reference not set to an instance of an object" occurs with the above code but somehow, it doesn't occur if I comment either section of code:
1) Remove everything above the try/catch but leave the email section below the try catch:
var password = RandomPassword.Generate();
var result = await this.UserManager.CreateAsync(user, password);
if (result.Succeeded)
{
await this.UserManager.AddToRoleAsync(user.Id, JoiffRoles.IsMember);
…
}
2) Remove the email section
new Thread(async () =>
{
await CustomEmailService.SendConfirm(this,
Request, user, codeHtmlVersion);
}).Start();
I know this sounds ridiculous, I've gone through it over and over again and if I leave the code as is, I get this error when trying to set the variable to the OrganizationFromDb.MembershipType. If I remove either of the section mentioned above, everything works as expected.
As #CamiloTerevinto mentioned, I do believe it is related to something that hasn't been fully fetched and is only partially built but how are either section affecting this?
Any suggestions?
I haven't got to the bottom as to why this is happening nor why does it work when removing snippets of codes as mentioned in my updates but I'm pretty sure it is indeed related to what #CamiloTerevinto previously mentioned regarding the EF entity being only partially built/queried.
I can only assume that displaying data in the Immediate window and/or via the tooltip behaves differently than using it at run-time when assigned to a variable.
Anyway, rather than trying to fixed and/or figure out why removing these snippets of codes did the trick, I thought I'd try a different approach.
Since my organization details were only required to be pulled once there was no need for it to be within the members loop, so
I decided to assign the MembershipType variable outside the Members
loop
and this appeared to have done the trick.
I wonder if it is related to EF's lazy loading or something similar where it is trying to fetch the organization's EF entity details when requested within a loop that's also fetching details about another object. I'm not sure to be honest.
Would love someone to highlight and explain the actual reason.
I hope this help.

Cognitive Services Exception in Xamarin App

Hi I am using Microsoft Cognitive Services and it's giving me an exception for some unknown reason. This is the way I declared FaceServiceRestClient:
var faceServiceClient = new FaceServiceRestClient("MY_KEY");
when I run above code it throws an exception by saying "Your Subscription key is invalid". I checked 3-4 times Key is correct, I also regenerated key and used it still exception is there.
Now, I added second parameter, thats URL so not my declaration is as follows:
var faceServiceClient = new FaceServiceRestClient("MY_KEY", "https://australiaeast.api.cognitive.microsoft.com/face/v1.0" );
For above statement I get an exception as "Java.Lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=MY_KEY/detect"
This is how I am calling detect method (If you want to see)
Com.Microsoft.Projectoxford.Face.Contract.Face[] result = faceServiceClient.Detect(#params[0], true, false, null);
I do not understand exactly where to look at or which declaration is correct. & BTW this is Xamarin application and I used Xamarin.Microsoft.Cognitive.Face package. If you want to anything else in my code please Comment I will share code snippet.
Can anyone please help?
Thank you
"Java.Lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=MY_KEY/detect"
That package wraps the Android/Java API and that API is different then the other platforms. In the case of FaceServiceRestClient, the Azure Face Endpoint is the first param, and your Face API key is the second.
Note: They did not even name the parameters in the binding library so you will see param names such as p0 p1 throughout the C# API :-( I ended up using Rekognition to work around the throughput limitations of Cognitive services, but that is a different story)
I stripped down a camera/photo tagger that I wrote to get you started.
Example:
await Task.Run(() =>
{
var faceServiceClient = new FaceServiceRestClient(faceEndpoint, faceAPIKey);
using (var imageFileStream = camera.SingleImageStream)
{
var faceAttributes = new FaceServiceClientFaceAttributeType[] { FaceServiceClientFaceAttributeType.Gender, FaceServiceClientFaceAttributeType.Age, FaceServiceClientFaceAttributeType.Smile, FaceServiceClientFaceAttributeType.Glasses, FaceServiceClientFaceAttributeType.FacialHair };
var faces = faceServiceClient.Detect(imageFileStream, true, false, faceAttributes);
foreach (var face in faces)
{
Log.Debug(TAG, $"{face.FaceRectangle.Left}:{face.FaceRectangle.Top}:{face.FaceRectangle.Width}:{face.FaceRectangle.Height}");
DrawFaceRect(face.FaceRectangle);
TagPhoto(face.FaceAttributes);
}
}
});

async Pedometer.GetSystemHistoryAsync API for Universal apps crashes

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);

NullPointerException with MR2 in windows

I have installed Hadoop 2.3.0 in windows and able to execute MR jobs successfully. But while trying with streaming sample in C# [with HadoopSDK's .Net assemblies] the app ends with the following exception
14/05/16 18:21:06 INFO mapreduce.Job: Task Id : attempt_1400239892040_0003_r_000000_0, Status : FAILED
Error: java.lang.NullPointerException
at org.apache.hadoop.mapred.Task.getFsStatistics(Task.java:347)
at org.apache.hadoop.mapred.ReduceTask$OldTrackingRecordWriter.<init>(ReduceTask.java:478)
at org.apache.hadoop.mapred.ReduceTask.runOldReducer(ReduceTask.java:414)
at org.apache.hadoop.mapred.ReduceTask.run(ReduceTask.java:392)
at org.apache.hadoop.mapred.YarnChild$2.run(YarnChild.java:168)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:415)
at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1548)
at org.apache.hadoop.mapred.YarnChild.main(YarnChild.java:163)
Update:
I was able to drill down the problem and found that the exception raised in the following line
matchedStats = getFsStatistics(FileOutputFormat.getOutputPath(job), job);
at org.apache.hadoop.mapred.ReduceTask$OldTrackingRecordWriter.<init>(ReduceTask.java:478)
In the above, the result of 'FileOutputFormat.getOutputPath(job)' returns null, which throws the null pointer exception. Below are the codes for the getOutputPath() function.
public static final String OUTDIR = "mapreduce.output.fileoutputformat.outputdir";
public static Path getOutputPath(JobConf conf) {
String name = conf.get(org.apache.hadoop.mapreduce.lib.output.
FileOutputFormat.OUTDIR);
return name == null ? null: new Path(name);
}
So Is it needed to set value for property "mapreduce.output.fileoutputformat.outputdir" anywhere in the configuration files to get this issue resolved?
Thanks
The problem is that the hadoop services have been started from a different user [SYSTEM in my case] and the mapreduce sample was submitted from my local user. So this makes the issue by returning the FileSystem statistics [for the local user] as Null.
Once i started Hadoop from my local user, the above issue gets resolved.

Categories