How to get GoogleApiClient instance in Xamarin? - c#

I want to integrate my xamarin android app with google play services leaderboards and achievements. I am not getting how to convert below code from android documentation to c#.
// Create the Google Api Client with access to the Play Game and Drive services.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Games.API).addScope(Games.SCOPE_GAMES)
.addApi(Drive.API).addScope(Drive.SCOPE_APPFOLDER) // Drive API
.build();
// ...
I tried to convert something like below
GoogleApiClient api = new GoogleApiClient.Builder(this)
.AddApi(Android.Gms.Games.API)
.Build();
It's giving error under "Android.Gms.Games.API"
None of the things mentioned in this stack overflow thread are working. Looks like most of these things deprecated.
Please suggest if any other easy way available to integrate with leaderboards.
EDIT: Made changes and now giving below error.

You will be able to get access to GoogleClientAPI via:
var googleClientAPI = new GoogleApiClient.Builder(Application.Context).AddApi(XXX).Build();
Example using a blocking connect as a quick test:
var client = new GoogleApiClient.Builder(Application.Context)
.AddApi(GamesClass.API)
.AddScope(GamesClass.ScopeGames)
.Build();
Task.Run(() => {
client.BlockingConnect();
System.Diagnostics.Debug.WriteLine(client.IsConnected);
});
Note: This assumes that you have registered your app, otherwise you will get a fatal developer error... see Play Connecting
Since you are needing access to leaderboard and achievements, make sure that you have added the packages:
Xamarin.GooglePlayServices.Games
Xamarin.GooglePlayServices.Identity
These will auto-include the .Base and .Basement package
Namespaces to look at after adding the packages:
using Android.Gms.Common.Apis;
using Android.Gms.Games.LeaderBoard;
using Android.Gms.Games.Achievement;

Related

New-AzurePIMRequest as .net-function?

I want to initiate an Azure-PIM using c#/.net
I already found a PowerShell-Function to do this:
New-AzurePIMRequest ... inside the "PIMTools"-packages: https://www.powershellgallery.com/packages/PIMTools/0.4.0.0
This is working just fine and of course I could just execute a PS-Script containing this from within my C#-Application. But I would prefer to natively achieving the same using a NuGet-Package or a library from within my application.
Is there a package that allows me to achieve the same from within C#?
Those PIMTools are just wrapping some existing powershell modules.You can check the details here: https://github.com/janegilring/PIMTools/blob/main/functions/New-AzurePIMRequest.ps1
As you can see they mainly use the AzureADPreview module which is giving access to the Microsoft Graph Endpoint. Microsoft Graph is a RESTful web API that enables you to access Microsoft Cloud service resources.
You can find the Graph SDK here: https://github.com/microsoftgraph/msgraph-sdk-dotnet
With the SDK installed you can use something like this to issue a PIM Request:
var graphClient = new GraphServiceClient(new DefaultAzureCredential());
var privilegedRoleAssignmentRequest = new PrivilegedRoleAssignmentRequestObject
{
Duration = "2",
Reason = "DevWork",
AssignmentState = "Active",
RoleId = "b24988ac-6180-42a0-ab88-20f7382dd24c",
};
await graphClient.PrivilegedRoleAssignmentRequests
.Request()
.AddAsync(privilegedRoleAssignmentRequest);
Note: You might have to the use the /beta Endpoint of the SDK to get PIM working. However, APIs under the /beta version in Microsoft Graph are subject to change. Use of these APIs in production applications is not supported.

Azure error: DefaultAzureCredential authentication failed

I am working on the Official Azure sample: Getting started - Managing Compute Resources using Azure .NET SDK. And getting the following error on line resourceGroup = await resourceGroups.CreateOrUpdateAsync(resourceGroupName, resourceGroup); of the following code where app is trying to create a Resource Group. I have followed the instructions for Registering an app and from this link provided by the sample. And, have assigned a role to app as follows:
Error:
Azure.Identity.AuthenticationFailedException
HResult=0x80131500
Message=DefaultAzureCredential authentication failed.
Source=Azure.Identity
Inner Exception 2:
MsalServiceException: AADSTS70002: The client does not exist or is not enabled for consumers. If you are the application developer, configure a new application through the App Registrations in the Azure Portal
static async Task Main(string[] args)
{
var subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID");
var resourceClient = new ResourcesManagementClient(subscriptionId, new DefaultAzureCredential());
// Create Resource Group
Console.WriteLine("--------Start create group--------");
var resourceGroups = resourceClient.ResourceGroups;
var location = "westus2";
var resourceGroupName = "QuickStartRG";
var resourceGroup = new ResourceGroup(location);
resourceGroup = await resourceGroups.CreateOrUpdateAsync(resourceGroupName, resourceGroup);
Console.WriteLine("--------Finish create group--------");
// Create a Virtual Machine
await Program.CreateVmAsync(subscriptionId, "QuickStartRG", location, "quickstartvm");
// Delete resource group if necessary
//Console.WriteLine("--------Start delete group--------");
//await (await resourceGroups.StartDeleteAsync(resourceGroupName)).WaitForCompletionAsync();
//Console.WriteLine("--------Finish delete group--------");
//Console.ReadKey();
}
UPDATE:
As per instructions in the sample, following is how I Used the portal to create an Azure AD application and service principal that can access resources. I may not have done something right here. Please let me know what I am not doing right here:
Role Assignment for the registered app in Access Control (IAM):
Authentication and Direct URI:
API Permissions for the Registered App:
UPDATE-2:
Working with #JoyWan, I was able to resolve the issue (thank you Joy). Below is the screenshot of successful creation of all required compute resources including VM. NOTE: Clicking on the image would provide a better view of the screenshot.
I test the code, it works fine on my side. The steps you mentioned are also correct.
In this sample, the DefaultAzureCredential() actually uses the EnvironmentCredential() in local, so if you run the code in local, make sure you have Set Environment Variables with the AD App Client ID, Client Secret, Tenant ID.
Update:
From #nam's comment, the issue was that environment vars were not refreshed yesterday, since he had shutdown the machine yesterday and restarted it again today, the environment var got in sync and hence the app started working.

Azure resourceManager

I'm trying to scale programmatically an Azure worker role and I can't find the right syntax for the resource name.
// Create the autoscale client.
AutoscaleClient autoscaleClient = new AutoscaleClient(new CertificateCloudCredentials(subscriptionId, cert));
AutoscaleSettingGetResponse get =autoscaleClient.Settings.Get(AutoscaleResourceIdBuilder.BuildCloudServiceResourceId("WRK-GROUP-NE01","CIW.GROUPS",true) );
AutoscaleSetting setting = get.Setting;
It returns : ResourceNotFound: The resource service name monitoring is not supported.
Can you point me to the right syntax?
The guide which you're following is based on the Azure Service Management model, aka Classic mode, which is deprecated and only exists mainly for backward compatibility support.
You should use the latest Microsoft.Azure.Insights nuget package for getting the autoscale settings.
Sample code using the nuget above is as below:
using Microsoft.Azure.Management.Insights;
using Microsoft.Rest;
//... Get necessary values for the required parameters
var client = new InsightsManagementClient(new TokenCredentials(token));
client.AutoscaleSettings.Get(resourceGroupName, autoScaleSettingName);
See the REST API Reference below for getting the autoscale settings.
GET
https://management.azure.com/subscriptions/{subscription-id}/resourceGroups/{resource-group-name}/providers/microsoft.insights/autoscaleSettings/{autoscale-setting-name}?api-version={api-version}
For updating Autosale setting you can use below api
PUT https://management.azure.com/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/microsoft.insights/autoscalesettings/{autoscaleSettingName}?api-version=2015-04-01
https://learn.microsoft.com/en-us/rest/api/monitor/autoscalesettings/createorupdate
Hope it helps.

Authorization exception with Azure using C# and Microsoft.Azure.Management.Fluent

I am a student and I am currently trying to learn Azure platform and how to use the C# libraries to manage it.
I was able to create, delete blob and files with no problem using the package WindowsAzure.Storage.
Then I wanted to list VMs using this tutorial : https://learn.microsoft.com/en-us/azure/virtual-machines/windows/csharp
This is my code:
var credentials = SdkContext.AzureCredentialsFactory.FromFile(Environment.GetEnvironmentVariable("AZURE_AUTH_LOCATION"));
var azure = Azure
.Configure()
.WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
.Authenticate(credentials)
.WithDefaultSubscription();
Console.WriteLine(azure.VirtualMachines.List().Count());
My connection file look like this:
subscription=********-****-****-****-************
client=********-****-****-****-************
key=qeFkWjPm0YHn5xw8UMS2ytLhf9Oi0rEMxZVOTpk3aMQ=
tenant=********-****-****-****-************
managementURI=https://management.core.windows.net/
baseURL=https://management.azure.com/
authURL=https://login.windows.net/
graphURL=https://graph.windows.net/
But I get this error:
Unhandled Exception: Microsoft.Rest.Azure.CloudException: The client '********-****-****-****-************' with object id '********-****-****-****-************' does not have authorization to perform action 'Microsoft.Compute/virtualMachines/read' over scope '/subscriptions/********-****-****-****-************'.
There is two weird things I noticed :
1 - In the exception message, the client id and object id are the same and I dont know where they come from.
2 - When I create a new application registration on AzureAD, I can't see it in "My apps" but only in "All Apps", and I cant add myself as an owner.
Click here to see a screenshot
I have searched for 2 days and I cant figured out why it's not working.
(This is a simple .Net Core 2 console project, I am on Linux if it can help to find out)
Thank you in advance.
Edit #1 :
Thank's to #juunas, working now.
Help link: https://learn.microsoft.com/en-US/azure/azure-resource-manager/resource-group-create-service-principal-portal#assign-application-to-role
To read details about a VM, the application should have a Reader role on the VM, its resource group, or the subscription. If you need to modify things, Contributor allows all modifications. You should add the application to a role via the Access Control IAM tab on the subscription/resource group/resource.

Calling SpeechAPI for text to speech on Azure

I have the following very basic TTS code running on my local server
using System.Speech.Synthesis;
...
SpeechSynthesizer reader = new SpeechSynthesizer();
reader.Speak("This is a test");
This code has a dependency on System.Speech for which I have added a Reference in my VS 2015 project.
Works fine but from what I have read and from trying it I know this will not work when the code is hosted on Azure.
I have read several posts on SO querying if it is actually possible to do TTS on azure. Certainly 2 yrs ago it did not appear to be possible. How to get System.Speech on windows azure websites?
All roads seem to lead to the Microsoft Speech API
https://azure.microsoft.com/en-gb/marketplace/partners/speechapis/speechapis/
I have signed up and have gotten my private and sec keys for calling into this API.
However my question is this. How do I actually call the SpeechAPI? What do I have to change in the simple code example above so that this will work when running on azure?
The speech API you referred to at the Azure marketplace is part of an AI Microsoft project called ProjectOxford which offers an array of APIs for computer vision, speech and language.
These are all RESTful APIs, meaning that you will be constructing HTTP requests to send to a hosted online service in the cloud.
The speech-to-text documentation is available here and you can find sample code for various clients on github. Specifically for C# you can see some code in this sample project.
Please note that ProjectOxford is still in preview (Beta). Additional support for using these APIs can be found on the ProjectOxford MSDN forum.
But just to give you an idea of how your program will look like (taken from the above code sample on github):
AccessTokenInfo token;
// Note: Sign up at http://www.projectoxford.ai for the client credentials.
Authentication auth = new Authentication("Your ClientId goes here", "Your Client Secret goes here");
...
token = auth.GetAccessToken();
...
string requestUri = "https://speech.platform.bing.com/synthesize";
var cortana = new Synthesize(new Synthesize.InputOptions()
{
RequestUri = new Uri(requestUri),
// Text to be spoken.
Text = "Hi, how are you doing?",
VoiceType = Gender.Female,
// Refer to the documentation for complete list of supported locales.
Locale = "en-US",
// You can also customize the output voice. Refer to the documentation to view the different
// voices that the TTS service can output.
VoiceName = "Microsoft Server Speech Text to Speech Voice (en-US, ZiraRUS)",
// Service can return audio in different output format.
OutputFormat = AudioOutputFormat.Riff16Khz16BitMonoPcm,
AuthorizationToken = "Bearer " + token.access_token,
});
cortana.OnAudioAvailable += PlayAudio;
cortana.OnError += ErrorHandler;
cortana.Speak(CancellationToken.None).Wait();

Categories

Resources