How does one query specific pages? I only need to grab the data from specific pages.
Example: domain.com/thisPage, domain.com/anotherPage, etc..
ReportRequest reportRequestLandingPath = new ReportRequest
{
ViewId = GoogleAnalyticsIds,
DateRanges = new List<DateRange>() { dateRange },
Dimensions = new List<Dimension>() { landingPagePath },
Metrics = new List<Metric>() { avgSessionDuration, sessions, pageviewsPerSession }
};
I'm trying to get results that look something like this so I can add them to a google chart I'm building.
My problem is that I get back all 78 results for each page I have on my domain. I only need to get avgSessionDuration, sessions, pageviewsPerSession from 5-6 specific pages.
You should add a filter to your request just add which ever pages that you want to see data for and only the data for those pages will be returned.
var metrics = new List<Metric>();
metrics.Add(new Metric { Expression = "ga:avgSessionDuration", Alias = "Avg. Session Duration" });
metrics.Add(new Metric { Expression = "ga:sessions", Alias = "Sessions" });
metrics.Add(new Metric { Expression = "ga:pageviewsPerSession", Alias = "Pageviews Per Session" });
var dimensions = new List<Dimension>();
dimensions.Add(new Dimension { Name = "ga:landingPagePath" });
var filterClause = new DimensionFilterClause();
var filter = new DimensionFilter
{
DimensionName = "ga:landingPagePath",
Operator__ = "PARTIAL",
Expressions = new List<string> { "accessing-google-calendar-with-php-oauth2" }
};
filterClause.Filters = new List<DimensionFilter> { filter };
ReportRequest reportRequest = new ReportRequest
{
ViewId = "78110423",
DateRanges = new List<DateRange>() { new DateRange() { StartDate = "3daysago", EndDate = "today" } },
Dimensions = dimensions,
Metrics = metrics,
DimensionFilterClauses = new List<DimensionFilterClause> { filterClause }
};
List<ReportRequest> requests = new List<ReportRequest>();
requests.Add(reportRequest);
// Create the GetReportsRequest object.
GetReportsRequest getReport = new GetReportsRequest() { ReportRequests = requests };
I recommend using Query explorer for testing your filters it can be tricky to get them to work.
Related
I'm using the Google Analytics Data API v1 beta to fetch GA4 properties' data in C#.NET.
And I'm initializing the filters for it like this:
FilterExpression dimensionFilterExpression = new FilterExpression();
FilterExpression metricFilterExpression = new FilterExpression();
which I'll later fill if any filters are provided from frontend something like this:
dimensionFilterExpression.Filter = new Filter { FieldName = field_name, InListFilter = new Filter.Types.InListFilter { CaseSensitive = case_sensitive } };
And then I would simply create a request using RunReportRequest with the required parameters
request = new RunReportRequest
{
Property = "properties/" + property_id,
Dimensions = { dimensionsList },
Metrics = { metricsList },
DateRanges = { new AnalyticsDataApi.DateRange { StartDate = start_date, EndDate = end_date } },
DimensionFilter = dimensionFilterExpression,
MetricFilter = metricFilterExpression
};
but when the filters are empty I get an exception
StatusCode="InvalidArgument", Detail="FilterExpression requires an expression field"
and same goes for OrderBys MetricFilter as well
how can we handle the situation of no filters or no orderby since then would just have to write all combinations of if else for each case which would not be feasible
I am writing come code in c# with Visual Studio 2022 to fetch Google G4 analytics data and cannot get one piece to work correctly. It is the part where a create an "OrderBy" list for the "RunReportRequest". I have defined 3 lists for each of dimensions, metrics & orderby
List<Dimension> Dlist = new();
List<Metric> Mlist = new();
List<OrderBy> Olist = new();
when I add items to the Dlist and MList using the following it works fine.
Dlist.Add(new Dimension { Name = "country" });
Mlist.Add(new Metric { Name = "activeUsers" });
when I try to add the OrderBy it fails.
OrderBy orderBy = new OrderBy();
orderBy.Metric.MetricName = "activeUsers";
orderBy.Desc = true;
Olist.Add(orderBy);
Although the program compiles and runs but stops at the line
orderBy.Metric.MetricName = "activeUsers";
with the error message
'Object reference not set to an instance of an object.'
I also tried another way
Olist.Add(new OrderBy { Metric = "activeUsers", Desc = true });
but this indicates an error
Cannot implicitly convert type "string" to "Google.Analytics.Data.V1Beta.OrderBy.Types.MetricOrderBy"
the code that creates the report request is as follows
var G4request2 = new RunReportRequest
{
Property = "properties/" + Grequest.PropertyId,
Dimensions = { Dlist },
Metrics = { Mlist },
DateRanges = { new DateRange { StartDate = Grequest.StartDate, EndDate = Grequest.EndDate } },
OrderBys = { Olist }
};
If I do not include the Olist and don't use the OrderBys = { Olist} line in the RunReportRequest the program works and the Google Date is retrieved (just not sorted in the order I want though).
Can anyone help me with a suggestion how to fix the issue with the OrderBy part please?
Try using orderbys in the following manner:
RunReportRequest request = new RunReportRequest
{
Property = "properties/" + propertyId,
Dimensions = { new Dimension { Name = Dimensions },},
Metrics = { new Metric { Name = Matrix }, },
DateRanges = { new DateRange { StartDate = strStartDate, EndDate = strEndDate }, },
OrderBys = {new OrderBy {Dimension = new OrderBy.Types.DimensionOrderBy() { DimensionName = "date" }, Desc = false}, }
};
This gives the response sorted by date in ascending order.
here is the code:-
static I used its worked fine.. how can I store product dynamically in using asp.net c#
LineItems = new List<SessionLineItemOptions>
{
for (int i = 0; i < dtOrder.Rows.Count; i++){
new SessionLineItemOptions
{
Name=dtOrder.Rows[i]["ProductName"].toString(),
Currency="cad",
Amount =Convert.toInt64(dtOrder>Rows[i]["Price"])*100,
Quantity = 1,
},
}
},
Extending the snippet shown in the API reference here, we can replace Price = 'price_123' with PriceData (API ref) like so:
var options = new SessionCreateOptions
{
SuccessUrl = "https://example.com/success",
CancelUrl = "https://example.com/cancel",
PaymentMethodTypes = new List<string>
{
"card",
},
LineItems = new List<SessionLineItemOptions>
{
new SessionLineItemOptions
{
PriceData = new SessionLineItemPriceDataOptions
{
Currency = "usd",
UnitAmount = 50000,
ProductData = new SessionLineItemPriceDataProductDataOptions
{
Name = "some product name",
}
},
Quantity = 2,
},
},
Mode = "payment",
};
var service = new SessionService();
service.Create(options);
You can find all the type definitions in the source code.
I integrated Mulitple Account Payment of stripe and fixed the issue like this
and its working for me now , you can also use simple checkout method like this fetching dynamically product from db
List lineItemsOptions = new List();
string cmdText = "select * from tableorder where sessionid='"+ sessionid + "'";
DataSet ds = dbm.getDs(cmdText);
foreach (DataRow row in ds.Tables[0].Rows)
{
var currentLineItem = new SessionLineItemOptions
{
Name = row["ProductName"].ToString(),
Amount = 100,//Convert.ToInt32( row["variationPrice"].ToString()),
Currency = "usd",
Quantity = Convert.ToInt32(row["Quantity"].ToString()),
};
lineItemsOptions.Add(currentLineItem);
}
StripeConfiguration.ApiKey = ".......................................";
var options = new SessionCreateOptions();
options = new SessionCreateOptions
{
PaymentMethodTypes = new List<string>
{
"card",
},
LineItems = lineItemsOptions,
PaymentIntentData = new SessionPaymentIntentDataOptions
{
ApplicationFeeAmount = 1,
},
Mode = "payment",
SuccessUrl = "https://www.......com/success.aspx",
CancelUrl = "https://example.com/cancel",
};
var requestOptions = new RequestOptions
{
StripeAccount = ".............",
};
var service = new SessionService();
Session session = service.Create(options, requestOptions);
My problem as it is right now. It is that I must have made such that a customer can buy an item that is only paid once. Thus assigned Invoice id and PDf to the database.
As it is right now I only get hold of Invoice id while PDF is null.
I've read a little more about this.
Invoice Id return with null after change using Stripe
var options = new ProductCreateOptions
{
Name = "Starter Setup",
};
var service = new ProductService();
var product = service.Create(options);
var optionsA = new PriceCreateOptions
{
Product = product.Id,
UnitAmount = 2000,
Currency = "usd",
};
var serviceA = new PriceService();
var price = serviceA.Create(optionsA);
var optionsB = new CustomerCreateOptions
{
Email = model.Mail,
Name = model.FuldName,
Source = token
};
var serviceB = new CustomerService();
var customer = serviceB.Create(optionsB);
var optionsC = new InvoiceItemCreateOptions
{
Customer = customer.Id,
Price = price.Id,
};
var serviceC = new InvoiceItemService();
var invoiceItem = serviceC.Create(optionsC);
var invoiceId = invoiceItem.Id;
var serviceE = new InvoiceService();
var f = serviceE.Get(invoiceId);
var pdf = f.InvoicePdf;// This here gives zero.
If I do it this way, I'll get this out of it. I get the Invoice ID that I want here but I get nothing on the invoice that shows that it is zero.
{
"id": "ii_1IR4UtFnB7TvDVRrzPwWo8ZW",
"object": "invoiceitem",
"amount": 2000,
"currency": "usd",
"customer": "cus_J3Aqpyt4PwqCcN",
"date": 1614815575,
"description": "Starter Setup",
"discountable": true,
"discounts": [
],
"invoice": null,
"livemode": false,
"metadata": {
},
....
}
With this, my thinking is whether I will in a way be able to make such that I make a membership which then stops immediately but that it says in the invoice that the purchase is only of a single item and not several months.
The way I have done it in relation to membership I have done like this.
var createCustomer = new CustomerCreateOptions
{
Source = token,
Name = model.FuldName,
Email = model.Mail
};
var addService = new CustomerService();
var customer = addService.Create(createCustomer);
var optionsProduct = new ProductCreateOptions
{
Name = $"Single buy - {DateTime.Now} - Kursus Id : {id}",
Type = "service",
};
var serviceProduct = new ProductService();
Product product = serviceProduct.Create(optionsProduct);
var optionsPlan = new PlanCreateOptions
{
Currency = "dkk",
Interval = Helpers.Stripe.interval,
Nickname =
$"Single buy - {DateTime.Now} - Kursus Id : {id}",
Amount = amount,
Product = product.Id,
IntervalCount = 1
};
var servicePlan = new PlanService();
Plan plan = servicePlan.Create(optionsPlan);
var items = new List<SubscriptionItemOptions>()
{
new SubscriptionItemOptions()
{
Plan = plan.Id,
Quantity = 1
},
};
var createSubscruptionA = new SubscriptionCreateOptions
{
Customer = customer.Id,
Items = items,
OffSession = true,
};
var addserviceA = new SubscriptionService();
Subscription subscription = addserviceA.Create(createSubscruptionA);
var invoiceId = subscription.LatestInvoiceId;
var service = new InvoiceService();
var pdf = service.Get(invoiceId).InvoicePdf;
That which I would like to achieve by this. It is that I can get hold of PDF and Invoice id as I will use it for my system in the future etc.
EDIT
var optionsB = new CustomerCreateOptions
{
Email = model.Mail,
Name = model.FuldName,
Source = token
};
var serviceB = new CustomerService();
var customer = serviceB.Create(optionsB);
var optionsC = new InvoiceItemCreateOptions
{
Customer = customer.Id,
Price = price.Id,
};
var serviceC = new InvoiceItemService();
var invoiceItem = serviceC.Create(optionsC);
var invoiceId = invoiceItem.Id;
var invoiceOptions = new InvoiceCreateOptions
{
Customer = customer.Id,
AutoAdvance = true,
};
var invoiceService = new InvoiceService();
var invoice = invoiceService.Create(invoiceOptions);
For one-off Invoices you need to create Invoice Items for the Customer (as you've done), but importantly you then need to create an Invoice that will contain those Items.
This line is not correct for what you're trying to accomplish:
var invoiceId = invoiceItem.Id;
Instead, you need to create the invoice as shown in the docs linked above:
var invoiceOptions = new InvoiceCreateOptions
{
Customer = "cus_123",
AutoAdvance = true,
};
var invoiceService = new InvoiceService();
var invoice = invoiceService.Create(invoiceOptions);
The Invoice object will have an invoice_pdf URL (docs) after you finalize it.
var service = new InvoiceService();
service.FinalizeInvoice(
"in_123"
);
I have been able to authenticate my app on google analytics and display some data around unique page views. Now I want to get the page views based on Traffic source but I'm not quite sure how to get the filters on the dimensions. I have written my code in c# and can't get my head around examples in other languages I've seen. i have used the api Query Explorer and got the right expressions and results. My difficulty is how to translate that into my code. My code is below
var filepath = Server.MapPath("~/jsonfile"); // path to the json file for the Service account
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 = "2016-10-28",
EndDate = "2016-12-20"
};
var sessions = new Metric
{
Expression = "ga:uniquePageviews",
Alias = "Sessions"
};
var social = new Dimension { Name = "ga:socialNetwork" };
var reportRequest = new ReportRequest
{
DateRanges = new List<DateRange> { dateRange },
Dimensions = new List<Dimension> { social },
Metrics = new List<Metric> { sessions },
ViewId = "myviewid"
};
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.FirstOrDefault().Data.Rows)
{
Response.Write(string.Join(", ", x.Dimensions) + " " + string.Join(", ", x.Metrics.First().Values));
}
You should create a DimensionFilterClauses and pass it to the ReportRequest as follows:
//Create the Dimension Filter
var dimensionFilter = new DimensionFilter();
dimensionFilter.DimensionName = "ga:socialNetwork";
dimensionFilter.Expressions = new List<string> { "someValue" };
var dimensionFilterClause = new DimensionFilterClause();
dimensionFilterClause.Filters = new List<DimensionFilter> { dimensionFilter };
Then modify your ReportRequest:
var reportRequest = new ReportRequest
{
DateRanges = new List<DateRange> { dateRange },
Dimensions = new List<Dimension> { social },
Metrics = new List<Metric> { sessions },
ViewId = "myviewid",
DimensionFilterClauses = new List<DimensionFilterClause> { dimensionFilterClause }
};
P.S:
Furthermore, if you need to filter Metric instead of Dimension, you would need to create a MetricFilterClauses as follows and then pass it to MetricFilterClauses in your ReportRequest:
//Create the Metric Filter
var metricFilter = new MetricFilter();
metricFilter.MetricName = "someMetric";
metricFilter.ComparisonValue = "someValue";
var metricFilterClause = new MetricFilterClause();
metricFilterClause.Filters = new List<MetricFilter> { metricFilter };