In Xamarin Forms, SetEnvironmentVariable - c#

In Xamarin Forms with .Net Standard code sharing app, I want to set the environment variable for the Google Datastore. So that I can communicate with Google Datastore through the mobile app.
Below piece of code is working fine in console app but in Xamarin Forms throwing error while trying to create the Datastore db object.
Error reading credential file from location /DB.json: Could not find file "/DB.json"
Please check the value of the Environment Variable GOOGLE_APPLICATION_CREDENTIALS
I put the DB.json on the root of the solution.
try
{
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", #"DB.json");
var dir = Environment.CurrentDirectory;
// Your Google Cloud Platform project ID.
string projectId = "xamarin-project";
//We are storing movies. So this is a Movie kind.
string kind = "Country";
//Create the datastore db
var db = DatastoreDb.Create(projectId);
// City entity
Entity cityEntities = new Entity
{
Key = db.CreateKeyFactory(kind).CreateKey($"US"),
["CountryCode"] = "US",
["Name"] = "United States"
};
//Lets send the city to the datastore
using (var transction = db.BeginTransaction())
{
transction.Upsert(cityEntities);
transction.Commit();
}
}
catch (Exception ex)
{
await DisplayAlert("Error", ex.Message, "OK");
Console.WriteLine(ex.Message);
}
Read the file using Dependency is also not working. I tried with .Android project.

If you are looking to use a database directly from your mobile app, I'd suggest you use Cloud Firestore (https://cloud.google.com/firestore/) instead. It has explicit security features to allow accessing the database directly from clients.
I think what you are trying to do with the snippet above is to load your service account credentials in the app which will give any user of your full access to your database.

Related

Query Azure Application Insights CustomEvents in Azure function in C#.Net

I need to query CustomEvents under application insights in an azure function.
I was able to read CustomEvents using below package:
Microsoft.Azure.ApplicationInsights.Query
Here is the code:
string applicationId = "xxxx-xxxx-xxxx";
string key = "xxxxxxxxxxx";
// Create client
var credentials = new ApiKeyClientCredentials(key);
var applicationInsightsClient = new ApplicationInsightsDataClient(credentials);
// Query Application Insights
var query = "customEvents" +
" | where timestamp > ago(840h)" +
" | take 3";
var response = await applicationInsightsClient.Query.ExecuteWithHttpMessagesAsync(applicationId, query);
The library 'Microsoft.Azure.ApplicationInsights.Query is however deprecated and suggestion is to use Azure.Monitor.Query
Below is the code that Microsoft documentation has as an example to query logs using Azure.Monitor.Query :
Azure.Response<Azure.Monitor.Query.Models.LogsQueryResult> response = await logsQueryClient.QueryWorkspaceAsync(
"<workspaceId>",
"customEvents ",
new QueryTimeRange(TimeSpan.FromMinutes(300)));
Since this library queries using workspace id, I linked my application insights instance to a log analytics workspace instance. However the function fails with a BadArgumentError "Failed to resolve table or column expression named 'customEvents'"
Is there a way we can query CustomEvents using the package Azure.Monitor.Query?
Any help is appreciated.
Thanks
Yes, it works.
Below is a tested code.
Once you link your Application Insights to Azure Monitor workspace, you can query your AI tables from that WS, without the need to use app().
The thing is that the tables` names are different, e.g., traces becomes AppTraces.
In the same manner, customEvents becomes AppEvents.
Well, it turns out it is even documented, under Migrate to workspace-based Application Insights resources
Legacy table name
New table name
Description
availabilityResults
AppAvailabilityResults
Summary data from availability tests.
browserTimings
AppBrowserTimings
Data about client performance, such as the time taken to process the incoming data.
dependencies
AppDependencies
Calls from the application to other components (including external components) recorded via TrackDependency() – for example, calls to REST API, database or a file system.
customEvents
AppEvents
Custom events created by your application.
customMetrics
AppMetrics
Custom metrics created by your application.
pageViews
AppPageViews
Data about each website view with browser information.
performanceCounters
AppPerformanceCounters
Performance measurements from the compute resources supporting the application, for example, Windows performance counters.
requests
AppRequests
Requests received by your application. For example, a separate request record is logged for each HTTP request that your web app receives.
exceptions
AppExceptions
Exceptions thrown by the application runtime, captures both server side and client-side (browsers) exceptions.
traces
AppTraces
Detailed logs (traces) emitted through application code/logging frameworks recorded via TrackTrace().
using Azure;
using Azure.Identity;
using Azure.Monitor.Query;
using Azure.Monitor.Query.Models;
string workspaceId = "...";
var client = new LogsQueryClient(new DefaultAzureCredential());
try
{
Response<LogsQueryResult> response = await client.QueryWorkspaceAsync(
workspaceId,
"AppEvents | count",
QueryTimeRange.All);
LogsTable table = response.Value.Table;
foreach (var row in table.Rows)
{
Console.WriteLine(row);
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}

Get AWS caller Identity with C# SDK

When I execute this with the aws cli, i.ex. inside a fargate task, I can see the UserId that my application is going to use
aws sts get-caller-identity
with this output on the console
{
"Arn": "arn:aws:sts::643518765421:assumed-role/url_process_role/6ae81f92-66f3-30de-1eaa-3a7d1902bad9",
"UserId": "ARDYOAZLVOAQXTT5ZXTV4:4ea81f97-66f3-40de-beaa-3a7d1902bad9",
"Account": "692438514791"
}
I would like to get the same information but using the C# SDK. I tried with the methods exposed in this doc but I can see some account related details but not the UserId assigned.
So far I've tried with this but I cannot see any profile when running in a Fargate task.
var awsChain = new Amazon.Runtime.CredentialManagement.CredentialProfileStoreChain();
System.Console.WriteLine($"Found {awsChain.ListProfiles().Count} AWS profiles.");
My final goal is to get it and add to some task processed with Fargate to save a correlation Id in the database when something fails and easily find the Fargate log stream.
IAmazonSecurityTokenService will provide the same information when executed with .netcore. Notice that the above example will only work inside the AWS domain as the endpoint is not publicly available if testing from a development machine.
var getSessionTokenRequest = new GetSessionTokenRequest
{
DurationSeconds = 7200
};
var stsClient = hostContext.Configuration.GetAWSOptions().CreateServiceClient<IAmazonSecurityTokenService>();
var iden = stsClient.GetCallerIdentityAsync(new GetCallerIdentityRequest { }).Result;
System.Console.WriteLine($"A={iden.Account} ARN={iden.Arn} U={iden.UserId}");

Roles come back as null from Azure Analysis Services database when connecting using AMO in C#

I have a tabular Azure Analysis Services database with compatibility level 1400. When I connect and try to retrieve the roles using the AMO package the Roles property is always null, the same for the DatabasePermissions property that is mentioned in this answer.
I am using the Tabular.Server and Tabular.Database objects as recommended in the official docs.
I have based my code off this answer and I am connecting using an administrator account.
Proof that roles are setup on the DB that I am accessing:
Inspecting the database object:
Interestingly enough I have two other databases inside the same Azure Analysis Services server and they have the same issue.
My code:
using (Server server = new Server())
{
string serverDomain = "australiasoutheast.asazure.windows.net";
string serverName = "redacteddevpilotv1";
string databaseModel = "PilotV1";
string serverAddress = $"asazure://{serverDomain}/{serverName}";
//string token = await GetAccessToken($"https://{serverDomain}");
//string connectionString = $"Provider=MSOLAP;Data Source={serverAddress};Initial Catalog={databaseModel};User ID=;Password={token};Persist Security Info=True;Impersonation Level=Impersonate";
string connectionString = $"Provider=MSOLAP;Data Source={serverAddress};Initial Catalog={databaseModel};User ID=redacted;Password=redacted;Persist Security Info=True;Impersonation Level=Impersonate";
var t = server.SupportedCompatibilityLevels;
var x = server.Roles;
server.Connect(connectionString);
t = server.SupportedCompatibilityLevels;
x = server.Roles;
Database d = server.Databases.FindByName(databaseModel);
}
The documentation goes into how to add roles not how to retrieve them...
It turns out that instead of accessing roles through database.Roles I need to access them via database.Model.Roles. I'm not sure why this is or if it is documented anywhere but I was put onto this fact by another question.
After doing this I now have access to the ModelRole objects that I want.

How to connect to Cloud Firestore DB with .net core?

So far all the examples of using Google Cloud Firestore with .net show that you connect to your Firestore db by using this command:
FirestoreDb db = FirestoreDb.Create(projectId);
But is this skipping the step of authentication? I can't seem to find an example of wiring it up to use a Google service account. I'm guessing you need to connect using the service account's private_key/private_key_id/client_email?
You can also use the credentials stored in a json file:
GoogleCredential cred = GoogleCredential.FromFile("credentials.json");
Channel channel = new Channel(FirestoreClient.DefaultEndpoint.Host,
FirestoreClient.DefaultEndpoint.Port,
cred.ToChannelCredentials());
FirestoreClient client = FirestoreClient.Create(channel);
FirestoreDb db = FirestoreDb.Create("my-project", client);
I could not compile #Michael Bleterman's code, however the following worked for me:
using Google.Cloud.Firestore;
using Google.Cloud.Firestore.V1;
var jsonString = File.ReadAllText(_keyFilepath);
var builder = new FirestoreClientBuilder {JsonCredentials = jsonString};
FirestoreDb db = FirestoreDb.Create(_projectId, builder.Build());
Packages I use:
<PackageReference Include="Google.Cloud.Firestore" Version="2.0.0-beta02" />
<PackageReference Include="Google.Cloud.Storage.V1" Version="2.5.0" />
But is this skipping the step of authentication?
No. It will use the default application credentials. If you're running on Google Cloud Platform (AppEngine, GCE or GKE), they will just be the default service account credentials for the instance. Otherwise, you should set the GOOGLE_APPLICATION_CREDENTIALS environment variable to refer to a service account credential file.
From the home page of the user guide you referred to:
When running on Google Cloud Platform, no action needs to be taken to authenticate.
Otherwise, the simplest way of authenticating your API calls is to download a service account JSON file then set the GOOGLE_APPLICATION_CREDENTIALS environment variable to refer to it. The credentials will automatically be used to authenticate. See the Getting Started With Authentication guide for more details.
It's somewhat more awkward to use non-default credentials; this recent issue gives an example.
This worked for me.
https://pieterdlinde.medium.com/netcore-and-cloud-firestore-94628943eb3c
string filepath = "/Users/user/Downloads/user-a4166-firebase-adminsdk-ivk8q-d072fdf334.json";
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", filepath);
fireStoreDb = FirestoreDb.Create("user-a4166");
The simplest way:
Get service account json file and hardcode values into a class:
public class FirebaseSettings
{
[JsonPropertyName("project_id")]
public string ProjectId => "that-rug-really-tied-the-room-together-72daa";
[JsonPropertyName("private_key_id")]
public string PrivateKeyId => "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
// ... and so on
}
Add it Startup.cs
var firebaseJson = JsonSerializer.Serialize(new FirebaseSettings());
services.AddSingleton(_ => new FirestoreProvider(
new FirestoreDbBuilder
{
ProjectId = firebaseSettings.ProjectId,
JsonCredentials = firebaseJson // <-- service account json file
}.Build()
));
Add wrapper FirebaseProvider
public class FirestoreProvider
{
private readonly FirestoreDb _fireStoreDb = null!;
public FirestoreProvider(FirestoreDb fireStoreDb)
{
_fireStoreDb = fireStoreDb;
}
// ... your methods here
}
Here is a full example of a generic provider.
https://dev.to/kedzior_io/simple-net-core-and-cloud-firestore-setup-1pf9

TF400813: Resource not available for anonymous access. Client authentication required

I am working on the CodedUI Test Automation project. i am developing a framework in which i am trying to access Test Cases in VSTS through RestAPI. I have worked on an MVC application previously in which i did the same thing to pull data from VSTS using RestAPI.
Now the problem is i am not able to access the VSTS. Everytime i am trying to access the VSTS, i got the exception TF400813: Resource not available for anonymous access. Client authentication required.
I am using the same PAT token. I have all the required access on my team project. I am able to access all work items in my project from browser. I have tried all the option mentioned in below thread but still its not working.
Client authentication error when starting Visual Studio 2015.3Any leads will be appreciated.Below is my code to get data from VSTS:
public static List<WorkItem> GetWorkItemsWithSpecificFields(IEnumerable<int> ids)
{
var collectionUri = "https://<name>.visualstudio.com";
var fields = new string[] {
"System.Id",
"System.Title",
"System.WorkItemType",
"Microsoft.VSTS.Scheduling.RemainingWork"
};
using (WorkItemTrackingHttpClient workItemTrackingHttpClient = new WorkItemTrackingHttpClient(new Uri(collectionUri), new VssBasicCredential("", System.Configuration.ConfigurationManager.AppSettings["PATToken"])))
{
// Exception is coming on below line
List<WorkItem> results = workItemTrackingHttpClient.GetWorkItemsAsync(ids, fields).Result;
return results;
}
}

Categories