Read my Google Fit data via REST - c#

I'd like to programmatically read my Google Fit GPS data via the REST API. I'm able to get a list of data sources but I just can't seem to get any session or dataset results back.
For example:
GET https://www.googleapis.com/fitness/v1/users/me/sessions?oauth_token=mytoken
and:
POST https://www.googleapis.com/fitness/v1/users/me/dataset:aggregate?oauth_token=mytoken
{"aggregateBy": [{"dataTypeName": "com.google.location.sample"}]}
What am I missing? Is it even possible for my app to download data that it wasn't responsible for storing?
FWIW, I'm using the following Google.Apis.Fitness.v1 package test code in C#:
var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = "myid",
ClientSecret = "mysecret"
},
new[]
{
FitnessService.Scope.FitnessLocationRead,
FitnessService.Scope.FitnessActivityRead,
FitnessService.Scope.FitnessBodyRead
},
"user",
CancellationToken.None,
new FileDataStore("google-fit.json", true));
var service = new FitnessService(
new BaseClientService.Initializer {HttpClientInitializer = credential});
var dataSources = await service.Users.DataSources.List("me").ExecuteAsync();
var sessions = await service.Users.Sessions.List("me").ExecuteAsync();
var dataSets = await service.Users.Dataset.Aggregate(
new AggregateRequest {AggregateBy = new[] {
new AggregateBy {DataTypeName = "com.google.location.sample"}}}, "me")
.ExecuteAsync();

Related

Problem to send message to teams channel with Microsoft graph

I'm working to send a message to Teams by using Graph API.
my application is a daemon application that sends a message automatically in the background.
I have written code like an official reference link below:
https://learn.microsoft.com/en-gb/graph/sdks/choose-authentication-providers?tabs=CS#client-credentials-provider
in my case, I use the client-credentials-provider but, I still can't send a message, and always get the below error message.
surely I have already registered my application in Azure and set for the grant of scope
How can I fix this?
Following this api document, you need to give Application api permission Teamwork.Migrate.All, and try this code below:
using Azure.Identity;
using Microsoft.Graph;
public void sendMesgAsync()
{
var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "your_tenant_name.onmicrosoft.com";
var clientId = "azure_ad_app_client_id";
var clientSecret = "client_secret";
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var chatMessage = new ChatMessage
{
Body = new ItemBody
{
Content = "Hello World"
}
};
await graphClient.Teams["{team-id}"].Channels["{channel-id}"].Messages
.Request()
.AddAsync(chatMessage);
}

how to create a web service for microsoft graph (C#)

I've recently started working as a junior c# developer. My boss asked me to build methods to CRUD teams in our AAD using the microsoft graph API. I've achieved this with a test application like that:
public async Task<string> createTeam()
{
// readying data from registry
var clientId = "********************"; //application (client) ID
var clientSecret = "********************";
var redirectUri = "https://login.microsoftonline.com/common/oauth2/nativeclient";
var authority = "https://login.microsoftonline.com/********************/v2.0";
var cca = ConfidentialClientApplicationBuilder.Create(clientId)
.WithAuthority(authority)
.WithRedirectUri(redirectUri)
.WithClientSecret(clientSecret)
.Build();
List<string> scopes = new List<string>
{
"https://graph.microsoft.com/.default"
};
//
var authenticationProvider = new MsalAuthenticationProvider(cca, scopes.ToArray());
//
GraphServiceClient graphClient = new GraphServiceClient(authenticationProvider);
// Code to create a Team
var team = new Team
{
DisplayName = "0000My Sample Team",
Description = "My Sample Team’s Description",
AdditionalData = new Dictionary<string, object>()
{
{"template#odata.bind", "https://graph.microsoft.com/v1.0/teamsTemplates('standard')"}
}
};
var result = await graphClient.Teams.Request().AddAsync(team);
return result.DisplayName;
}
With that piece of code working, I've created an asp.net web Application (.net framework) and added the class to it. The plan was to deploy it to an IIS server and and publish the methods as web services.
[WebMethod]
public async Task<string> createTeamAsync()
{
//The class where my methods reside
TeamServices ts = new TeamServices();
var result = await ts.createTeam();
return "OK";
}
I registered the app and deployed but when I try to use it, it does not create any Team.
Do you know what I'm doing wrong of what I should learn next get the app working? Im just a few weeks in c# and I'm completely lost in all that .net echosystem
Thanks in advance

404 error while creating Online Meeting using microsoft graph api c# without login into AzureActiveDirectory

I am trying to create Online Meeting using microsoft graph api without login into AzureActiveDirectory with asp.net web application.For this my app has below permissions which are required as per documentation https://learn.microsoft.com/en-us/graph/api/application-post-onlinemeetings?view=graph-rest-1.0&tabs=csharp with client credential auth flow https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow without immediate interaction with a user.I am able to retrive access token successfully as per client-creds-grant-flow.
I tried Micosoft.Graph and Micosoft.Graph.Beta still getting 404 error.
Create online meeting code
var graphClient = GetAuthenticatedClientCredential();
var onlineMeeting = new OnlineMeeting
{
StartDateTime = DateTimeOffset.Parse("2020-10-01T10:30:34.2444915+00:00"),
EndDateTime = DateTimeOffset.Parse("2020-10-01T11:00:34.2464912+00:00"),
Subject = "Create Online Meeting-Without user login to Office 365"
};
return await graphClient.Me.OnlineMeetings
.Request()
.AddAsync(onlineMeeting);
Access Token code
public static async Task<string> GetUserAccessTokenAsyncByCc()
{
IConfidentialClientApplication cca = ConfidentialClientApplicationBuilder.Create(appId)
.WithTenantId(appTenantId)
.WithClientSecret(appSecret)
.Build();
string[] scopes1 = new string[] { "https://graph.microsoft.com/.default" };
//string[] scopes1 = new string[] { "https://graph.microsoft.com/OnlineMeetings.ReadWrite.All" };
// string[] scopes1 = new string[] { "https://graph.microsoft.com/beta/OnlineMeetings.Read.All" };
//string[] scopes1 = new string[] { "https://graph.microsoft.com/beta/.default" };
var result = await cca.AcquireTokenForClient(scopes1).ExecuteAsync();
return result.AccessToken;
}
and Auth Provider code
public static GraphServiceClient GetAuthenticatedClientCredential()
{
DelegateAuthenticationProvider provider = new DelegateAuthenticationProvider(
async (requestMessage) =>
{
string accessToken = await GetUserAccessTokenAsyncByCc();
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
});
GraphServiceClient graphClient = new GraphServiceClient(provider);
return graphClient;
}
app permission image
below are the necessary app permission
You can only use delegated permissions to create an onlineMeeting, so you must log in as a user, and you cannot use the client credential flow. You need to use the auth code flow to obtain the token.

Google API AndroidPublisher does not return reviews

I'm using Googles official .NET library to access the reviews of my app (https://developers.google.com/android-publisher/api-ref/reviews/list is the corresponding API)
"Google.Apis.AndroidPublisher.v2": "1.16.0.594"
This is (roughly) my code:
var credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer("client_email_from_service_account_json"
{
Scopes = new[] { AndroidPublisherService.Scope.Androidpublisher }
}.FromPrivateKey("private_key_from_service_account_json"));
var service = new AndroidPublisherService(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = "some_name",
});
var request = service.Reviews.List("my_app_id");
using (var reader = new StreamReader(request.ExecuteAsStream()))
{
var json = reader.ReadToEnd();
// json is only "{}\n"
}
var requestResult = await request.ExecuteAsync();
// requestResult.Reviews is null
I get the same (empty) result when I take the access_token from credential and to the HTTP GET call manually.
There is no error, so access should be working correctly - but I only ever get an empty JSON object.
When I try to access a specific review via its ID, it works fine (again, not pointing to an access problem).
According to https://github.com/google/google-api-nodejs-client/issues/589 the reviews API only returns reviews posted in the last 7 days.

Why is Youtube's v3 api claiming my access token does not have permissions to insert live streams?

In the authorization stage of my application I'm requesting access via:
var req = new Google.Apis.Auth.OAuth2.Requests.GoogleAuthorizationCodeRequestUrl(new Uri(string.Format(Settings.Google.OAuth.Url, "auth")));
req.ClientId = Settings.Google.OAuth.ClientId;
req.ResponseType = "code";
req.Scope = "https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/youtubepartner";
req.RedirectUri = string.Format(Settings.Integration.HandshakeUrl, "youtube");
req.AccessType = "offline"; // required to get refreshToken.
req.ApprovalPrompt = "force";
req.State = Application.Cryptography.Encrypt(Application.JSON.SerializeToString<State>(new State { UID = userId, PROFILEID = profileId, SUCCESS = request.SuccessUrl, FAIL = request.FailUrl }), Settings.Cryptography.SymetricKey);
// Return the url that the requesting application should redirect to in order to perform the authorization.
return req.Build().ToString();
This successfully gets me an access token and refresh token. Now I wanted to insert a new stream based on the information in the google api docs
var token = new Google.Apis.Auth.OAuth2.Responses.TokenResponse { RefreshToken = refreshToken, AccessToken = accessToken };
var credentials = new UserCredential(new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = "<id>",
ClientSecret = "<secret>",
}
}), string.Empty, token);
var service = new YouTubeService(new BaseClientService.Initializer
{
HttpClientInitializer = credentials
});
var streamResource = new LiveStreamsResource(service);
var result = streamResource.Insert(new LiveStream
{
Snippet = new LiveStreamSnippet
{
Title = "Stream"
},
Cdn = new CdnSettings
{
Format = "1080p",
IngestionType = "rtmp"
}
}, "id, snippet, cdn, status");
var returnedStream = result.Execute();
When this runs Execute() gives the following exception:
Google.Apis.Requests.RequestError
Request is not authorized [403]
Errors [
Message[Request is not authorized] Location[ - ] Reason[insufficientLivePermissions] Domain[youtube.liveStream]
]
I can't figure out what I'm doing wrong in this process. Even the API explorer
Apparently, I was looking at this all wrong (and Google's API documentation should really describe this).
The response isn't that I don't have access to the proper scopes, it's that even though I was authorizing myself for the youtube scope, my youtube account did not have live streams enabled (separate option).
After enabling live streaming on my account this code worked properly.

Categories