Microsoft Graph C# SDK, Date Range - c#

Just started having to learn Microsoft.Graph SDK C#. I am getting it to work however I am running in to an issue and cant seem to find the correct documentation for using this in C#
I am trying to get a week worth of event date.
var filterString = $"start ge 2023-01-09& lt eq 2023-01-16";
var events = await graphServiceClient.Me.Calendar.Events
.Request().Filter(filterString)
.GetAsync();
ResultText.Text = "";
foreach (var response in events)
{
ResultText.Text += response.Subject;
ResultText.Text += Environment.NewLine;
}
However, I am receiving the following in Chrome and trying to figure out what I am doing wrong. Perhaps I could not locate the correct documentation for this. Most is for the Rest API and no the C# SDK I have tried using the rest $filter and to no avail.
Code: BadRequest
Message: Invalid filter clause
Inner error:
AdditionalData:
date: 2023-01-09T19:50:50
request-id: 427f24b9-62ab-4541-bc4e-a49e02bcc508
client-request-id: 427f24b9-62ab-4541-bc4e-a49e02bcc508
ClientRequestId: 427f24b9-62ab-4541-bc4e-a49e02bcc508

start property is of type dateTimeTimeZone with the property dateTime of type string.
You need to filter by start/dateTime
// filter events between 2023-01-09 and 2023-01-16
var filterString = "start/dateTime ge '2023-01-09T08:00' and start/dateTime le '2023-01-16T08:00'";
var events = await graphClient.Me.Calendar.Events
.Request()
.Filter(filterString)
.GetAsync();
Supported operators for dateTime are less than (lt), greater than (gt), less than or equal to (le) and greater than or equal to (ge).
Documentation:
$filter query operator

Related

SMS history between 2 dates - Twilio

I'm developing an SMS communication test app in WPF C# with Twilio. Almost everything works like a charm but I cannot retrieve the SMS history between 2 given dates.
The strange thing is that I can retrieve the total SMS costs between 2 dates which is almost the same...
Now here is my code to retrieve the costs for 2 given dates (which works) :
public void SmsBilling()
{
var records = RecordResource.Read(
category: RecordResource.CategoryEnum.SmsOutbound,
startDate: DateTime.Parse(bills.StartDate),
endDate: DateTime.Parse(bills.EndDate));
foreach (var record in records)
{
bills.NbSms = record.Count;
bills.SmsCost = record.Price;
}
}
This is the code to retrieve the history between 2 dates
(which crashes with the following exception : System.ArgumentNullException: 'The string reference is not set to an instance of a string.
Parameter name: s')
private void GetSms()
{
smsList.Sms = new List<Sms>();
var messages = MessageResource.Read(
limit: 20,
dateSentAfter: DateTime.Parse(bills.StartDate),
dateSentBefore: DateTime.Parse(bills.EndDate));
foreach (var record in messages)
{
smsList.Sms.Add(new Sms { DateHour = record.DateSent, Recipient = record.To, Source = record.From.ToString() });
}
smslist.ItemsSource = smsList.Sms;
}
What am I missing?
You can't pass a null reference to DateTime.Parse.
You may want to replace null values with DateTime.MinValue and DateTime.MaxValue:
dateSentAfter: DateTime.Parse(bills.StartDate ?? DateTime.MinValue),
dateSentBefore: DateTime.Parse(bills.EndDate ?? DateTime.MaxValue));

Invalid response from ElasticSearch using NEST. I am getting valid responses from curl using CLI however

I am using NEST to make ElasticSearch work with my .net core project. I've just been following the basic tutorial to get started here: https://www.elastic.co/guide/en/elasticsearch/client/net-api/current/nest-getting-started.html
Unfortunately I have gotten to the point where I am trying to retrieve the data that I just put into the elasticsearch database and I am being told it is invalid when I check the result of the search.
var searchResponse = client.Search<Person>(s => s
.Index("person")
.MatchAll(
I checked a few things and I can use the CLI command to return my documents I put in without issue:
{"took":1024,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits": {"total":{"value":2,"relation":"eq"},"max_score":1.0,"hits": [{"_index":"people","_type":"_doc","_id":"1","_score":1.0,"_source": {"id":1,"firstName":"Martijn","lastName":"Laarman"}}, {"_index":"people","_type":"_doc","_id":"2","_score":1.0,"_source": {"id":2,"firstName":"Martijn2","lastName":"Laarman2"}}]}}
The error message I am getting from NEST:
Invalid NEST response built from a successful (404) low level call on POST: /person/_search?typed_keys=true\r\n# Audit trail of this API call:\r\n - [1] HealthyResponse: Node: http://localhost:9200/ Took: 00:00:00.0878608\r\n# Request:\r\n{\"query\":{\"match_all\":{}}}\r\n# Response:\r\n{\"error\":{\"root_cause\":[{\"type\":\"index_not_found_exception\",\"reason\":\"no such index [person]\",\"resource.type\":\"index_or_alias\",\"resource.id\":\"person\",\"index_uuid\":\"_na_\",\"index\":\"person\"}],\"type\":\"index_not_found_exception\",\"reason\":\"no such index [person]\",\"resource.type\":\"index_or_alias\",\"resource.id\":\"person\",\"index_uuid\":\"_na_\",\"index\":\"person\"},\"status\":404}\r\n"
In terms of the code I am using, I tried to follow the tutorial pretty tightly:
var settings = new ConnectionSettings(new Uri("http://localhost:9200")).DefaultIndex("people")
.DisableDirectStreaming();
var client = new ElasticClient(settings);
var person = new Person
{
Id = 2,
FirstName = "Martijn2",
LastName = "Laarman2"
};
var ndexResponse = client.IndexDocument(person);
/////////This searchResponse is what is coming back as invalid.
var searchResponse = client.Search<Person>(s => s
.Index("person")
.MatchAll(
)
);
var people = searchResponse.Documents;
return people.ToString();
Hoping someone can help clarify what's going on... very confused :c

How to filter AppInsights custom metrics with REST API

I am trying to use REST API for retrieving AppInsights custom metrics and use a filter in the query.
The code to create the metric:
var telemetry = new MetricTelemetry();
telemetry.Context.InstrumentationKey = instrumentationKey;
telemetry.Name = FacebookFupMetricName;
telemetry.Value = amount;
telemetry.Timestamp = DateTime.Now;
telemetry.Properties["agencyCode"] = agencyCode;
telemetry.Properties["accountCode"] = accountCode;
telemetry.Properties["category"] = category;
telemetry.Properties["action"] = action;
var client = new TelemetryClient();
client.TrackMetric(telemetry);
client.Flush();
The metric is created in Azure when run this code.
Now I would like to use REST API for retrieving metrics and use a filter in the query. When I use a filter
category eq 'cat001'
the query ends with an error
The following dimensions are not valid in the filter clause for this metric: category
The query url is:
https://dev.applicationinsights.io/apiexplorer/metrics?appId=<appId>&apiKey=<apiKey>&metricId=customMetrics%2FFacebookFupAction&timespan=P1D&aggregation=sum&filter=category%20eq%20%27cat001%27
The question is, is it possible to filter custom metrics with dimensions?
In the filter field, you should use customDimensions/category eq 'cat001'.
The generated url is in this format:
`https://dev.applicationinsights.io/apiexplorer/metrics?appId=<appId>&apiKey=<apiKey>&metricId=customMetrics%2FFacebookFupMetricName&aggregation=sum&filter=customDimensions%2Fcategory%20eq%20'cat001'`
The screenshot as below:

How do I get all Teams in MS Graph C#?

I have created a Team in the group successfully, now I need to cycle through the Teams so I can get their names and IDs.
I have tried the following code but without any success.
IGraphServiceTeamsCollectionPage teams = graphServiceClient
.Teams
.Request()
.GetAsync()
.Result;
foreach (Team team in teams)
{
Console.WriteLine(team.Id);
}
I get
Code: UnknownError
Message:
{
"message":"No HTTP resource was found that matches the request URI 'https://api.teams.skype.com/v1.0/teams'."
}
I've also tried doing the same against Groups without success:
var groups = await graphServiceClient.Groups
.Request()
.GetAsync();
foreach (var group in groups)
{
Console.WriteLine(group.DisplayName);
Console.WriteLine(group.Team.Id);
}
Now I get the displayName of the Group, but when trying to access the Group's Team Id I get
Object reference not set to an instance of an object.
EDIT:
I have realized that Group ID = Teams ID, however, last week I was able to update the specific team with the following command:
await graphServiceClient
.Teams[groupID]
.Request()
.UpdateAsync(team3);
but now it does not work and says:
No team found with Group Id {9032fa63-50bb-4....}
I have confirmed in PowerShell and Graph Explorer, that the Id is correct and, as I've said, it worked on Friday of last week.
Further to my comment, it seems the PageIterator class doesn't work with group collection that's returned (or I'm doing something wrong, which is possible!). In any event, this code works for getting all the groups with Teams in my environment, so you should be able to pass the Id property of each group to the Teams endpoint in Graph to carry on:
var groups = await client.Groups.Request().Select("id,displayName,resourceProvisioningOptions").Filter("resourceProvisioningOptions/Any(x:x eq 'Team')").GetAsync();
do
{
foreach(var g in groups)
{
Console.WriteLine(g.DisplayName);
Console.WriteLine(g.Id);
}
if(groups.NextPageRequest != null)
{
groups = await groups.NextPageRequest.GetAsync();
}
}
while (groups.NextPageRequest != null);
Note that filtering on resource provisioning options requires using the Beta endpoint in Graph, this currently isn't available in V1.
I am using the groupID which is equal to teamID.
var groups = await graphServiceClient.Groups.Request().GetAsync();
foreach (var group in groups)
{
Console.WriteLine(group.DisplayName);
Console.WriteLine(group.Id);
}

Get events of a specific time range

I'm working with the Office365 Outlook Calendar API. I need to get events of a specific time range. I tried to compare the DateTimeTimeZone values inside of the foreach command, but it seems like it only supports a == operator:
if ( calendarEvent.Start >= new DateTimeTimeZone()
{
TimeZone = TimeZoneInfo.Local.Id,
DateTime = DateTime.Now.ToString("s")
})
This code snippet fails with the error: Cannot apply operator '>=' to operands of type 'Microsoft.Office365.OutlookServices.DateTimeTimeZone' and 'Microsoft.Office365.OutlookServices.DateTimeTimeZone'
Are there any other ways get events of a specific time range, e.g. future events?
This is my GetEvents()-method so far:
[Route("GetEvents")]
public async Task GetEvents()
{
//Get client
OutlookServicesClient client = await this.GetClient();
//Get events
var events = await client.Me.Events
.Take(10)
.ExecuteAsync();
foreach (var calendarEvent in events.CurrentPage)
{
//
if ( calendarEvent.Subject == "Test 1" )
{
System.Diagnostics.Debug.WriteLine("Event '{0}'.", calendarEvent.Subject) ;
}
}
}
You should use the CalendarView to get events within a time range.
DateTimeOffset startDateTime, endDateTime;
var events = client.Me.GetCalendarView(startDateTime, endDateTime);

Categories

Resources