'How do I add a metric name to MetricOrderBy when using Google.Analytics.Data.V1Beta?

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?



Solution 1:[1]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Nene