C# - Get all app reviews in PlayStore - c#

I want to create a Solution to get all app reviews in PlayStore, but I don't know how to do it. I have a code for connecting to Google Analytics, but I've a lot of errors when I ran it.
Here is the code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Google.Apis.AnalyticsReporting.v4;
using Google.Apis.AnalyticsReporting.v4.Data;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
namespace Google_api
{
class Program
{
static void Main(string[] args)
{
try
{
var filepath = "..."; // path to the json file for the Service account
var viewid = "..."; // ID to access your view in G.A
GoogleCredential credentials;
using (var stream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
{
string[] scopes = { AnalyticsReportingService.Scope.AnalyticsReadonly };
var googleCredential = GoogleCredential.FromStream(stream);
credentials = googleCredential.CreateScoped(scopes);
}
var reportingService = new AnalyticsReportingService(
new BaseClientService.Initializer
{
HttpClientInitializer = credentials
});
var dateRange = new DateRange
{
StartDate = "2017-05-01",
EndDate = "2017-05-31"
};
var sessions = new Metric
{
Expression = "ga:sessions",
Alias = "Sessions"
};
var date = new Dimension { Name = "ga:date" };
var reportRequest = new ReportRequest
{
DateRanges = new List<DateRange> { dateRange },
Dimensions = new List<Dimension> { date },
Metrics = new List<Metric> { sessions },
ViewId = viewid
};
var getReportsRequest = new GetReportsRequest
{
ReportRequests = new List<ReportRequest> { reportRequest }
};
var batchRequest = reportingService.Reports.BatchGet(getReportsRequest);
var response = batchRequest.Execute();
foreach (var x in response.Reports.First().Data.Rows)
{
Console.WriteLine(string.Join(", ", x.Dimensions) + " " + string.Join(", ", x.Metrics.First().Values));
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
Console.ReadLine();
}
}
}
I've received this error:
System.Configuration.ConfigurationErrorsException: error creating the web proxy specified in the 'system.net/defaultproxy'
---> System.Net.Sockets.SocketException: Invalid argument supplied in
System.Net.SafeCloseSocketAndEvent.CreateWSASocketWithEvent(AddressFamily
addressFamily, SocketType socketType, ProtocolType protocolType,
Boolean autoReset, Boolean signaled) in
System.Net.NetworkAddressChangePolled..ctor() in
System.Net.AutoWebProxyScriptEngine.AutoDetector.Initialize() in
System.Net.AutoWebProxyScriptEngine.AutoDetector.get_CurrentAutoDetector()
in System.Net.AutoWebProxyScriptEngine..ctor(WebProxy proxy, Boolean
useRegistry) in System.Net.WebProxy.UnsafeUpdateFromRegistry() in
System.Net.WebProxy..ctor(Boolean enableAutoproxy) in
System.Net.Configuration.DefaultProxySectionInternal..ctor(DefaultProxySection
section) in
System.Net.Configuration.DefaultProxySectionInternal.GetSection() --
--- End of internal exception stack trace ---
in Google.Apis.Requests.ClientServiceRequest'1.Execute()
in Google_api.Program.Main(String[] args) na X:\example\Program.cs:line 64
I'll create a metric to catch all reviews in PlayStore with the GA. Is this possible? In case not, can you help me? I want to catch all the reviews in PlayStore and all the information of devices that rated my app. The Reviews API return only information about those that commented. If anyone could provide some sample code or point me in the right direction to get some basic report data using the .net API, it would be greatly appreciated.
Thanks! (And sorry for my bad English...)

Related

Google Analytics Data API Get All Viewd Items

I need to retrieve data from Google Analytics Data API and get all items with item_id and item_name properties. With this code, I only get the total number of items but without item details. Any idea how to do that?
I have this code in my Console app:
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Google.Analytics.Data.V1Beta;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Util.Store;
namespace AnalyticsSamples
{
class Program
{
private const string PropertyId = "xxxxxxxxx";
private const string PathToCreds = #"C:\Temp\json1.json";
static async Task Main(string[] args)
{
Console.WriteLine("Start");
await SampleRunReport(PropertyId);
}
static async Task SampleRunReport(string propertyId = "xxxxxxxxx")
{
// Using a default constructor instructs the client to use the credentials
// specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
//var client = await BetaAnalyticsDataClient.CreateAsync(CancellationToken.None);
BetaAnalyticsDataClient client;
await using (var stream = new FileStream(PathToCreds, FileMode.Open, FileAccess.Read))
{
// Requesting Authentication or loading previously stored authentication for userName
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
new[] { "https://www.googleapis.com/auth/analytics.readonly" },
"userName",
CancellationToken.None,
new FileDataStore("credPath", true)).Result;
client = await new BetaAnalyticsDataClientBuilder
{
TokenAccessMethod = credential.GetAccessTokenForRequestAsync
}.BuildAsync();
}
var request = new RunReportRequest
{
Property = "properties/" + PropertyId,
Dimensions = { new Dimension { Name = "date" }, },
Metrics = { new Metric { Name = "itemViewEvents" }, new Metric { Name = "itemsViewed" } },
DateRanges = { new DateRange { StartDate = "2023-01-01", EndDate = "today" }, },
};
var response = await client.RunReportAsync(request);
Console.WriteLine("Report result:");
foreach (var row in response.Rows)
{
Console.WriteLine(
$"{row.DimensionValues[0].Value}, {row.MetricValues[0].Value}, {row.MetricValues[1].Value}");
}
}
}
}
And this code in my web page where I fire the event view_item
gtag("event", "view_item", {
currency: "EUR",
value: 200,
items: [
{
item_id: "SKU_12345",
item_name: "Samsung TV"
}
]
});

How to authorize Google anlaytics data api with OAuth2

I am trying to connect to the new Google Analytics Data api using C# to request data from the new google analytics GA4. The only sample i can find is
Quickstart client libraries .net This does work but it uses a service account. The cloud .net client library google-cloud-dotnet only has examples for using a service account.
When i try to pass it desktop app credentials for using Oauth" authorization i get
Error creating credential from JSON. Unrecognized credential type.
using System;
using System.Threading;
using System.Threading.Tasks;
using Google.Analytics.Data.V1Beta;
namespace GoogleAnalyticsExamplesData
{
class Program
{
private const string PropertyId = "250796939";
private const string PathToCreds = #"C:\dev\ServiceAccountCred.json";
static async Task Main(string[] args)
{
Console.WriteLine("Hello World!");
// Check whether the environment variable exists.
var environmentVariable = Environment.GetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS");
// If necessary, create it.
if (environmentVariable == null)
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", PathToCreds);
await SampleRunReport(PropertyId);
}
static async Task SampleRunReport(string propertyId = "YOUR-GA4-PROPERTY-ID")
{
// Using a default constructor instructs the client to use the credentials
// specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
var client = await BetaAnalyticsDataClient.CreateAsync(CancellationToken.None);
var request = new RunReportRequest
{
Property = "properties/" + PropertyId,
Dimensions = {new Dimension {Name = "date"},},
Metrics = {new Metric {Name = "totalUsers"}, new Metric {Name = "newUsers"}},
DateRanges = {new DateRange {StartDate = "2021-04-01", EndDate = "today"},},
};
var response = await client.RunReportAsync(request);
Console.WriteLine("Report result:");
foreach (var row in response.Rows)
{
Console.WriteLine(
$"{row.DimensionValues[0].Value}, {row.MetricValues[0].Value}, {row.MetricValues[1].Value}");
}
}
}
}
Links to Google.Analytics.Data.V1Beta Web client credentials, desktop credentials
After several hours of digging around i found that you can use ICredential using a builder. This works with a Desktop app credentials, for installed applications.
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Google.Analytics.Data.V1Beta;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Util.Store;
namespace GoogleAnalyticsExamplesData
{
class Program
{
private const string PropertyId = "250796939";
private const string PathToCreds = #"C:\dev\credentials.json";
static async Task Main(string[] args)
{
Console.WriteLine("Hello World!");
await SampleRunReport(PropertyId);
}
static async Task SampleRunReport(string propertyId = "YOUR-GA4-PROPERTY-ID")
{
// Using a default constructor instructs the client to use the credentials
// specified in GOOGLE_APPLICATION_CREDENTIALS environment variable.
//var client = await BetaAnalyticsDataClient.CreateAsync(CancellationToken.None);
BetaAnalyticsDataClient client ;
await using (var stream = new FileStream(PathToCreds, FileMode.Open, FileAccess.Read))
{
// Requesting Authentication or loading previously stored authentication for userName
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
new[] { "https://www.googleapis.com/auth/analytics.readonly"},
"userName",
CancellationToken.None,
new FileDataStore("credPath", true)).Result;
client = await new BetaAnalyticsDataClientBuilder
{
TokenAccessMethod = credential.GetAccessTokenForRequestAsync
}.BuildAsync();
}
var request = new RunReportRequest
{
Property = "properties/" + PropertyId,
Dimensions = {new Dimension {Name = "date"},},
Metrics = {new Metric {Name = "totalUsers"}, new Metric {Name = "newUsers"}},
DateRanges = {new DateRange {StartDate = "2021-04-01", EndDate = "today"},},
};
var response = await client.RunReportAsync(request);
Console.WriteLine("Report result:");
foreach (var row in response.Rows)
{
Console.WriteLine(
$"{row.DimensionValues[0].Value}, {row.MetricValues[0].Value}, {row.MetricValues[1].Value}");
}
}
}
}

Initiate a call with Microsoft Graphs SDK to Teams User

I'm attempting to initiate a call with the Microsoft Graph SDK Create call API using the code sample below. The attempt fails with a Not Found exception.
I have registered the bot application, added the API call permissions and I am able to receive incoming calls from Teams.
It's not clear from the Microsoft documentation whether Teams users can be called directly or whether they have to be allocated a VoIP number. Has anyone been able to use the Graph SDK to call a Teams User? Is there some special configuration a User needs to have in order to be able to receive a call?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Graph.Communications.Common.Telemetry;
using Microsoft.Extensions.Logging;
using Microsoft.Graph;
using Microsoft.Graph.Communications.Calls;
using Microsoft.Graph.Communications.Calls.Media;
using Microsoft.Graph.Communications.Client;
using Microsoft.Skype.Bots.Media;
namespace sipbotcaller
{
class Program
{
private static string APP_NAME = "";
private static string APP_ID = "";
private static string APP_SECRET = "";
private static string TENANT_ID = "";
private static string CALLBACK_URI = "";
private static string CERTIFICATE_THUMBPRINT = "";
private static int MEDIA_PORT = 10000;
private static string PUBLIC_IP = "";
private static string HOSTNAME = "";
static async Task Main(string[] args)
{
Console.WriteLine("Teams Call Console:");
GraphLogger graphLogger = new GraphLogger(APP_NAME);
graphLogger.DiagnosticLevel = System.Diagnostics.TraceLevel.Verbose;
ILogger logger = new ConsoleLogger(graphLogger);
AuthenticationProvider authProvider = new AuthenticationProvider(
APP_NAME,
APP_ID,
APP_SECRET,
TENANT_ID,
graphLogger);
GraphServiceClient graphClient = new GraphServiceClient(authProvider);
var users = await graphClient.Users.Request().GetAsync();
foreach (var user in users)
{
Console.WriteLine($"user Id: {user.Id}.");
Console.WriteLine($"user Display Name: {user.DisplayName}.");
}
var mediaPlatformSettings = new MediaPlatformSettings()
{
MediaPlatformInstanceSettings = new MediaPlatformInstanceSettings()
{
CertificateThumbprint = CERTIFICATE_THUMBPRINT,
InstanceInternalPort = MEDIA_PORT,
InstancePublicIPAddress = IPAddress.Parse(PUBLIC_IP),
InstancePublicPort = MEDIA_PORT,
ServiceFqdn = HOSTNAME,
},
ApplicationId = APP_ID,
};
var builder = new Microsoft.Graph.Communications.Client.CommunicationsClientBuilder(
APP_NAME,
APP_ID,
graphLogger);
builder
.SetAuthenticationProvider(authProvider)
.SetNotificationUrl(new Uri(CALLBACK_URI))
.SetMediaPlatformSettings(mediaPlatformSettings)
.SetServiceBaseUrl(new Uri(CALLBACK_URI));
var client = builder.Build();
AudioSocketSettings audioSockSettings = new AudioSocketSettings {
CallId = Guid.NewGuid().ToString(),
SupportedAudioFormat = AudioFormat.Pcm16K,
StreamDirections = StreamDirection.Sendrecv
};
AudioSocket audioSock = new AudioSocket(audioSockSettings);
var mediaConfig = MediaPlatform.CreateMediaConfiguration(audioSock);
Console.WriteLine($"media config: {mediaConfig}");
Console.WriteLine($"Attempting to call {users.First().DisplayName}.");
var call = new Call
{
CallbackUri = CALLBACK_URI,
TenantId = TENANT_ID,
Targets = new List<InvitationParticipantInfo>()
{
new InvitationParticipantInfo
{
Identity = new IdentitySet
{
User = new Identity
{
DisplayName = users.First().DisplayName,
Id = users.First().Id
},
}
}
},
RequestedModalities = new List<Modality>()
{
Modality.Audio
},
MediaConfig = new AppHostedMediaConfig()
{
Blob = mediaConfig.ToString(Newtonsoft.Json.Formatting.None)
},
};
var callResult = await client.Calls().AddAsync(call);
Console.WriteLine($"Call result {callResult.Id}.");
Console.WriteLine("Finished.");
Console.WriteLine("Press any key to exit...");
Console.ReadLine();
}
}
}
Result:
<snip>
StatefulCall: Verbose
StatefulCall: Info
StatefulCall: Verbose
StatefulCall: Info
StatefulCall: Info
StatefulCall: Error {
"error": {
"code": "itemNotFound",
"message": "Unexpected exception returned from the service.\r\nStatus Code: NotFound"
}
}
StatefulCall: Info

Google Analytics Reporting API V4 for .NET having issue

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.

Google DataProc API spark cluster with c#

I have data in Big Query I want to run analytics on in a spark cluster. Per documentation if I instantiate a spark cluster it should come with a Big Query connector. I was looking for any sample code to do this, found one in pyspark. Could not find any c# examples. Also found some documentation on the functions in DataProc APIs nuget package.
Looking for a sample to start a spark cluster in Google cloud using c#.
After installing Google.Apis.Dataproc.v1 version 1.10.0.40 (or higher):
Below is a quick sample console app for creating a Dataproc cluster in C#:
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Dataproc.v1;
using Google.Apis.Dataproc.v1.Data;
using System;
using System.Threading;
namespace DataprocSample {
class Program
{
static void Main(string[] args)
{
string project = "YOUR PROJECT HERE";
string dataprocGlobalRegion = "global";
string zone = "us-east1-b";
string machineType = "n1-standard-4";
string clusterName = "sample-cluster";
int numWorkers = 2;
// See the docs for Application Default Credentials:
// https://developers.google.com/identity/protocols/application-default-credentials
// In general, a previous 'gcloud auth login' will suffice if running as yourself.
// If running from a VM, ensure the VM was started such that the service account has
// the CLOUD_PLATFORM scope.
GoogleCredential credential = GoogleCredential.GetApplicationDefaultAsync().Result;
if (credential.IsCreateScopedRequired)
{
credential = credential.CreateScoped(new[] { DataprocService.Scope.CloudPlatform });
}
DataprocService service = new DataprocService(
new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "Dataproc Sample",
});
// Create a new cluster:
Cluster newCluster = new Cluster
{
ClusterName = clusterName,
Config = new ClusterConfig
{
GceClusterConfig = new GceClusterConfig
{
ZoneUri = String.Format(
"https://www.googleapis.com/compute/v1/projects/{0}/zones/{1}",
project, zone),
},
MasterConfig = new InstanceGroupConfig
{
NumInstances = 1,
MachineTypeUri = String.Format(
"https://www.googleapis.com/compute/v1/projects/{0}/zones/{1}/machineTypes/{2}",
project, zone, machineType),
},
WorkerConfig = new InstanceGroupConfig
{
NumInstances = numWorkers,
MachineTypeUri = String.Format(
"https://www.googleapis.com/compute/v1/projects/{0}/zones/{1}/machineTypes/{2}",
project, zone, machineType),
},
},
};
Operation createOperation =
service.Projects.Regions.Clusters.Create(newCluster, project, dataprocGlobalRegion).Execute();
// Poll the operation:
while (!IsDone(createOperation))
{
Console.WriteLine("Polling operation {0}", createOperation.Name);
createOperation =
service.Projects.Regions.Operations.Get(createOperation.Name).Execute();
Thread.Sleep(1000);
}
Console.WriteLine("Done creating cluster {0}", newCluster.ClusterName);
}
static bool IsDone(Operation op)
{
return op.Done ?? false;
}
}
}

Categories