Google Analytics Reporting API V4 for .NET having issue - c#

When i run and try to run application i got below error on
GoogleCredential.FromStream(stream); line.
"Error creating credential from JSON. Unrecognized credential type"
Below is my client_secret details.
{
"installed": {
"client_id": ".......",
"project_id": ".......",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_secret": ".......",
"redirect_uris": [ "urn:ietf:wg:oauth:2.0:oob", "http://localhost" ]
}
}
C# Code
// Create the DateRange object. Here we want data from last week.
var dateRange = new DateRange
{
StartDate = DateTime.UtcNow.AddDays(-7).ToString("yyyy-MM-dd"),
EndDate = DateTime.UtcNow.ToString("yyyy-MM-dd")
};
// Create the Metrics and dimensions object.
var metrics = new List<Metric> { new Metric { Expression = "ga:sessions", Alias = "Sessions" } };
var dimensions = new List<Dimension> { new Dimension { Name = "ga:pageTitle" } };
//Get required View Id from configuration
var ViewId = ConfigurationManager.AppSettings["ViewId"];
// Create the Request object.
var reportRequest = new ReportRequest
{
DateRanges = new List<DateRange> { dateRange },
Metrics = metrics,
Dimensions = dimensions,
ViewId = ViewId
};
var getReportsRequest = new GetReportsRequest();
getReportsRequest.ReportRequests = new List<ReportRequest> { reportRequest };
and
public static GetReportsResponse GetReport(GetReportsRequest getReportsRequest)
{
var analyticsService = GetAnalyticsReportingServiceInstance(ConfigurationManager.AppSettings["KeyFileName"]);
return analyticsService.Reports.BatchGet(getReportsRequest).Execute();
}
private static AnalyticsReportingService GetAnalyticsReportingServiceInstance(string keyFileName)
{
string[] scopes = { AnalyticsReportingService.Scope.AnalyticsReadonly }; //Read-only access to Google Analytics
GoogleCredential credential;
//string Fpath = File.Exists(keyFileName)//System.IO.Path.GetFullPath("/" + keyFileName);
string Path = #"C:\Users\umang.soni\source\repos\Google Analytics API Console\Google Analytics API Console\" + keyFileName;
using (var stream = new FileStream(Path, FileMode.Open, FileAccess.Read, FileShare.Read))
{
//I Got error on below line.
credential = GoogleCredential.FromStream(stream);
credential.CreateScoped(scopes);
}
// Create the Analytics service.
return new AnalyticsReportingService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Google Analytics API Console",
});
}
I googled a lot but not get any meaning full answer.
My application is console application.

Related

c# How do we give access to users from a dynamically generated google sheet?

I' am creating dynamically some google sheet given an array of data on one of my endpoints.
it creates successfully, but when I open the generated url, I get the following:
The documentation is not very clear, but I wish to add permissions to a given domain (or set of people) every time I generate a new sheet.
code:
private static readonly string[] Scopes = { SheetsService.Scope.Drive, SheetsService.Scope.Spreadsheets };
public string Create(string templateName, List<IList<object>> values, int numberOfRows)
{
var sheetId = 0;
var spreadSheetId = string.Empty;
var initializer = new ServiceAccountCredential.Initializer(SheetsOptionsConstants.ServiceAccountEmail)
{
Scopes = Scopes
}.FromPrivateKey(SheetsOptionsConstants.PrivateKey);
var credential = new ServiceAccountCredential(initializer);
// Create Google Sheets API service.
var service = new SheetsService(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = applicationName
});
// Create a new sheet
var sheetTitle = $"[{templateName}] {_clock.Now:yyyy-MM-dd HH-mm}";
try
{
var sheet = new BatchUpdateSpreadsheetRequest
{
Requests = new List<Request>
{
new Request
{
AddSheet = new AddSheetRequest
{
Properties= new SheetProperties
{
Title = sheetTitle
}
}
}
}
};
var createRequest = new Spreadsheet
{
Properties = new SpreadsheetProperties
{
Title = sheetTitle
}
};
var spreadSheetCreate = service.Spreadsheets.Create(createRequest).Execute();
spreadSheetId = spreadSheetCreate.SpreadsheetId;
var request = service.Spreadsheets.BatchUpdate(sheet, spreadSheetId);
var result = request.Execute();
sheetId = result.Replies.First().AddSheet.Properties.SheetId.GetValueOrDefault(0);
// Add data in sheet
var range = $"'{sheetTitle}'!A1:X{numberOfRows + 1}";
var valueRange = new ValueRange
{
Range = range,
Values = values
};
var valuesRequest = service.Spreadsheets.Values.Update(valueRange, spreadSheetId, range);
valuesRequest.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.USERENTERED;
valuesRequest.Execute();
_logger.LogInformation("Create sheet with name {sheetTitle} and {count} lines", sheetTitle, numberOfRows);
}
catch (Exception exception)
{
_logger.LogError(exception, "Error to create sheet with name {sheetTitle}", sheetTitle);
}
return string.Format(TemplateUrl, spreadSheetId, sheetId);
}
Thanks in advance
You need to use the Drive API to create the permissions for the Sheet. To do so, initialize the Drive Service and create a permissions object. Then, apply it to the Sheet Id using the method create().
You should include the following to your code:
using Google.Apis.Drive.v3;
using Google.Apis.Drive.v3.Data; //This might be not necessary if you already use Drive.v3
The required scopes:
https://www.googleapis.com/auth/drive.file
Create the permissions object:
//(example to give writing permissions to a domain)
Permission perms = new Permission();
perms.Role = "writer";
perms.Type = "domain";
perms.Domain = "your_domain";
And then the request:
// Create Drive API service.
var service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName,
});
service.Permissions.Create(perms, sheetId).Execute();
References:
.NET Quickstart
Manage sharing
Permissions from the Drive Api

Google People Api Contact is created but I can't see it anywhere

I'm using PeopleService in order to create contacts straight into my G Suit Account. I followed the security steps about getting the key for a type of Service Account. My Application will create contacts so that there's no need to request a specific user permission. It has its own key and credentials.
My code seems to work except because the CreateContactRequest provides me ResourceName with value "people/c171255166120767303". And every time I request I got a different resourceName like this "people/c9013378989213012841".
The problem is, where the hell that goes? At my G Suite account, I can’t see the created contact anywhere.
But the resulting Person object seems to be ok.
How can I check if this works? Where the contact was created?
The code is as bellow:
private static string _clientId = "1........1";
private static string _clienteScret = "i******************_";
private static string _serviceAccountId = "aaaa#bbbb.iam.gserviceaccount.com";
public static void Cadastrar(Models.SignupRequest message)
{
var chave =
#"D:\********.p12";
var certificate = new X509Certificate2(chave, "notasecret", X509KeyStorageFlags.Exportable);
var credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(_serviceAccountId)
{
Scopes = new[] {
PeopleService.Scope.Contacts,
PeopleService.Scope.ContactsReadonly,
"https://www.google.com/m8/feeds"
}
}.FromCertificate(certificate));
var service = new PeopleService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Client for www",
});
var contactToCreate = new Person();
var names = new List<Name> {new Name() {GivenName = message.name, FamilyName = "Doe"}};
contactToCreate.Names = names;
contactToCreate.EmailAddresses = new List<EmailAddress>
{
new EmailAddress()
{
DisplayName = message.name,
Value = message.email
}
};
contactToCreate.Organizations = new List<Organization>
{
new Organization()
{
Current = true,
Name = message.nome_fantasia,
}
};
contactToCreate.Biographies = new List<Biography>
{
new Biography()
{
Value = message.ToString()
}
};
contactToCreate.PhoneNumbers = new List<PhoneNumber>
{
new PhoneNumber()
{
Type = "mobile",
Value = message.celular
},
new PhoneNumber()
{
Type = "work",
Value = message.telefone
}
};
var request = new Google.Apis.PeopleService.v1.PeopleResource.CreateContactRequest(service, contactToCreate);
var createdContact = request.Execute();
}
If you want to create contact for user with 'email#yourdomain.com' through a service account you need:
Use "setServiceAccountUser(userEmail)" to impersonate the user
Enable impersonation on your G-Suite for People API service. For this point:
See section "Delegating domain wide access" here
Get client-id from your credential account
Use "https://www.googleapis.com/auth/contacts" as scope.

Google Photos Api return null

When I try to list albums with the PhotosLibraryService API, I always return null, has anyone been able to use the new Google Photos API yet? The picasa API no longer works.
public void ListAlbums()
{
var json = File.ReadAllText(_diretorio + "/PhotoClient/" + "client.json");
var cr = JsonConvert.DeserializeObject<PersonalServiceAccountCred>(json);
var xCred = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(cr.client_email)
{
Scopes = this._scopes
}.FromPrivateKey(cr.private_key));
// Create the service.
var service = new PhotosLibraryService(new Google.Apis.Services.BaseClientService.Initializer()
{
HttpClientInitializer = xCred
});
var albums = service.Albums.List().Execute();
}
Thanks!

Using Azure GraphClient API how can you create a new Native Application?

It looks like the Application object in Microsoft.Azure.ActiveDirectory.GraphClient allows a Webapplication to be created. I cannot see how I can use this to create a new Native application.
thanks
Updates:
TaskCompletionSource<string> tcs = new TaskCompletionSource<string>();
tcs.SetResult(accessToken);
var graphClient = new ActiveDirectoryClient(
new Uri($"{GraphApiBaseUrl}{tenantId}"),
async () => { return await tcs.Task; });
var password = Guid.NewGuid().ToString("N");
var cred = new PasswordCredential()
{
StartDate = DateTime.UtcNow,
EndDate = DateTime.UtcNow.AddYears(1),
Value = password
};
var app = await GetApplicationByUrlAsync(accessToken, tenantId, appName, identifierUrl);
if(app == null)
{
app = new Application()
{
DisplayName = appName,
Homepage = homePageUrl,
IdentifierUris = new List<string>() { identifierUrl },
LogoutUrl = logoutUrl,
ReplyUrls = new List<string>() { replyUrl },
PasswordCredentials = new List<PasswordCredential>() { cred },
};
await graphClient.Applications.AddApplicationAsync(app);
}
The fact that an app is a native client application is identified by the PublicClient boolean property on the Application object. (See client types from the OAuth 2.0 spec.)
So, you could register a native client app with the following code:
var app = new Application()
{
DisplayName = "My native client app",
ReplyUrls = new List<string>() { "urn:ietf:wg:oauth:2.0:oob" },
PublicClient = true
};
await graphClient.Applications.AddApplicationAsync(app);
Console.WriteLine("App created. AppId: {0}, ObjectId: {1}", app.AppId, app.ObjectId);
Note that the native client app does not have password credentials or key credentials (or any other secret).
Details about these and other properties of Application objects are available in the API reference documentation: https://msdn.microsoft.com/en-us/library/azure/ad/graph/api/entity-and-complex-type-reference#application-entity

How to authorize console application c# for Google Contacts API

I have an issue with the authorization in Google Contacts.
Until June my console C# application worked.
I have made steps to get contacts https://developers.google.com/google-apps/contacts/v3/?hl=en.
I cannot get the contacts; I have only access to serviceAccountEmail (xxxxxxxxxxxxxxxxxxx#developer.gserviceaccount.com).
I have 2 contacts stored there and I have access only to them.
I want to have access to my 7000 Gmail contacts.
Is there any tutorial for this in C#?
I found ones for analytics and for calendar but not for contacts.
Below is my code:
const string serviceAccountEmail = "xxxxxxxxxxxxxxxxxxx#developer.gserviceaccount.com";
var certificate = new X509Certificate2("grdom-all-xxxxxxxxxxxx.p12", "notasecret",
X509KeyStorageFlags.Exportable);
ServiceAccountCredential.Initializer serviceAccountCredentialInitializer =
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { "https://www.google.com/m8/feeds/" },
}.FromCertificate(certificate);
var credential = new ServiceAccountCredential(serviceAccountCredentialInitializer);
if (!credential.RequestAccessTokenAsync(CancellationToken.None).Result)
throw new InvalidOperationException("Access token request failed.");
var oauthParameters = new OAuth2Parameters()
{
AccessToken = credential.Token.AccessToken,
AccessType = "offline",
ApprovalPrompt = "force",
};
var settings = new RequestSettings("grdom-all", oauthParameters)
{
AutoPaging = true,
UseSSL = true,
};
ContactsRequest cr = new ContactsRequest(settings);
var query = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
Feed<Contact> f = cr.GetContacts();
foreach (Contact entry in f.Entries)
{
//do something
};

Categories