Add conference to event Google Calendar API - c#

I can create an event but I can't create an event with a conference.
I tried all these types: "eventHangout" "eventNamedHangout" "hangoutsMeet" but still getting Invalid conference type value
Google.GoogleApiException: 'Google.Apis.Requests.RequestError
Invalid conference type value. [400]
Errors [
Message[Invalid conference type value.] Location[ - ] Reason[invalid] Domain[global]
]
Here's the code that creates and executes an event:
CalendarService service = GetCalendarService();
EventDateTime start = new EventDateTime();
start.DateTime = new DateTime(2021, 02, 19, 18, 47, 0);
EventDateTime end = new EventDateTime();
end.DateTime = new DateTime(2021, 02, 19, 18, 50, 0);
Event newEvent = new Event();
newEvent.Start = start;
newEvent.End = end;
newEvent.Summary = "New event";
newEvent.Description = "description";
newEvent.ConferenceData = CreateConferenceData();
EventsResource.InsertRequest request = service.Events.Insert(newEvent, calendarId);
request.ConferenceDataVersion = 1;
Event createdEvent = request.Execute();
Here's the code of CreateConferenceData() method:
ConferenceData conferenceData = new ConferenceData()
{
CreateRequest = new CreateConferenceRequest()
{
RequestId = Guid.NewGuid().ToString(),
ConferenceSolutionKey = new ConferenceSolutionKey()
{
Type = "hangoutsMeet" // Change according to your preferences
};
}
};
return conferenceData;

this is my service and worked perfect conference event
_calenarService = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = GenerateCredentials(),
ApplicationName = this._applicationName
});
var myEvent = new Event
{
Summary = "Google Calendar API Testing ",
Location = "Islamabad, Punjab, Pakistan",
Start = new EventDateTime()
{
DateTime = new DateTime(2021, 4, 5, 14, 0, 0),
TimeZone = "Asia/Karachi"
},
End = new EventDateTime()
{
DateTime = new DateTime(2021, 9, 10, 15, 0, 0),
TimeZone = "Asia/Karachi"
},
Recurrence = new String[] { "RRULE:FREQ=WEEKLY;BYDAY=MO" },
//If you want to add attendee
//Attendees = new List<EventAttendee>()
//{
// new EventAttendee { Email = "......com" },
// new EventAttendee { Email = "......." }
//},
ConferenceData = new ConferenceData
{
ConferenceSolution = new ConferenceSolution
{
Key = new ConferenceSolutionKey
{
Type = "hangoutsMeet"
}
},
CreateRequest = new CreateConferenceRequest
{
RequestId = "qwerfsdiob",
ConferenceSolutionKey = new ConferenceSolutionKey
{
Type = "hangoutsMeet"
},
},
EntryPoints = new List<EntryPoint> ()
{
new EntryPoint { EntryPointType = "video" },
}
}
};
var recurringEvent = _calenarService.Events.Insert(myEvent, "primary");
recurringEvent.SendNotifications = true;
recurringEvent.ConferenceDataVersion = 1;
Event eventData = recurringEvent.Execute();

Related

Get event ID of Google Calendar event after it has been created C#

I've written some code to add an event to Google Calander:
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId = "ID",
ClientSecret = "Secret",
},
new[] { CalendarService.Scope.Calendar },
Account.Text,
CancellationToken.None).Result;
var service = new CalendarService(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = "Custom CRM",
});
var myEvent = new Event
{
Summary = Title.Text,
Location = AppointmentLocation.Text,
ColorId = Convert.ToString(AppointmentColourInt),
Description = Description.Text,
Start = new EventDateTime()
{
DateTime = new DateTime(StartDate.Value.Year, StartDate.Value.Month, StartDate.Value.Day, Convert.ToInt32(StartTime.Text.Substring(0, 2)), Convert.ToInt32(StartTime.Text.Substring(StartTime.Text.Length - 2)), 00),
TimeZone = "Europe/London"
},
End = new EventDateTime()
{
DateTime = new DateTime(EndDate.Value.Year, EndDate.Value.Month, EndDate.Value.Day, Convert.ToInt32(EndTime.Text.Substring(0, 2)), Convert.ToInt32(EndTime.Text.Substring(EndTime.Text.Length - 2)), 00),
TimeZone = "Europe/London"
},
};
var recurringEvent = service.Events.Insert(myEvent, CalendarID);
recurringEvent.SendNotifications = true;
recurringEvent.Execute();
Is there a way I could get the ID of the event once it has been created so that I can save it to my database for future reference?
Thanks.
var recurringEvent = service.Events.Insert(myEvent, CalendarID);
recurringEvent.SendNotifications = true;
var results = recurringEvent.Execute();
Execute will return to you the object it inserted. The Id should be in there.

c# using Google.Apis.Calendar.v3 create meeting for next month every weekday 30 min event

I want to create daily weekdays event for 30 minit. it seems there is something wrong in
Recurrence = new String[] { "RRULE:FREQ=MONTHLY;BYDAY=MO,TU,WE,TH,FR;UNTIL=" + nextmonthlastdayString + "T040000Z" },
I am not able to find solution tried many things.
public async Task<ActionResult> NewEvent()
{
var credential = await GetCredentialForApiAsync();
var initializer = new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "ASP.NET MVC5 Calendar Sample",
};
var service = new CalendarService(initializer);
var today = DateTime.Now;
var nextmonth = today.AddMonths(1).AddDays(-today.Day + 1);
var nextmonthString = nextmonth.ToString("yyyyMMdd");
var nxtmonthLastDate= DateTime.DaysInMonth(nextmonth.Year, nextmonth.Month);
DateTime lastDayNextMonth = nextmonth.AddDays(-nextmonth.Day + nxtmonthLastDate);
var nextmonthlastdayString = lastDayNextMonth.ToString("yyyyMMdd");
var lastDayofMonthString = DateTime.DaysInMonth(nextmonth.Year, nextmonth.Month).ToString(nextmonth.Year + "" + nextmonth.Month + "" + nextmonth.Day);
DateTime start = DateTime.Now;
DateTime end = start + TimeSpan.FromMinutes(30);
//start = DateTime.SpecifyKind(start, DateTimeKind.Local);
//end = DateTime.SpecifyKind(end, DateTimeKind.Local);
Event newEvent = new Event()
{
Summary = " Dealer Meeting",
Location = "1600 Amphitheatre Parkway., Mountain View, CA 94043",
Description = "A chance to learn more about Google APIs.",
Start = new EventDateTime()
{
DateTime = nextmonth,
TimeZone = "Asia/Kolkata",
},
End = new EventDateTime()
{
DateTime = lastDayNextMonth,
TimeZone = "Asia/Kolkata",
},
//Recurrence = new String[] { "RRULE:FREQ=DAILY;COUNT=5" },
//Recurrence = new String[] { "RRULE:FREQ=WEEKLY;BYDAY=MO,TU,WE,TH,FR;UNTIL="+ nextmonth + "T040000Z" },
Recurrence = new String[] { "RRULE:FREQ=MONTHLY;BYDAY=MO,TU,WE,TH,FR;UNTIL=" + nextmonthlastdayString + "T040000Z" },
Attendees = new EventAttendee[] {
new EventAttendee() { Email = "test#test.com" },
},
Reminders = new Event.RemindersData()
{
UseDefault = false,
Overrides = new EventReminder[] {
new EventReminder() { Method = "email", Minutes = 24 * 60 },
new EventReminder() { Method = "sms", Minutes = 10 },
}
}
};
String calendarId = "primary";
EventsResource.InsertRequest request = service.Events.Insert(newEvent, calendarId);
Event createdEvent = request.Execute();
return View();
}
Your RRULE is correct, the problem is theend date
As per documentation:
end
The (exclusive) end time of the event. For a recurring event, this is the end time of the first instance.
This means that you should modify
{
DateTime = lastDayNextMonth,
TimeZone = "Asia/Kolkata",
}
to
End = new EventDateTime()
{
DateTime = start + TimeSpan.FromMinutes(30),
TimeZone = "Asia/Kolkata",
}
Sample:
Start = new EventDateTime()
{
DateTime = "2021-11-01T09:00:00",
TimeZone = "Asia/Kolkata",
}
End = new EventDateTime()
{
DateTime = "2021-11-01T09:30:00",
TimeZone = "Asia/Kolkata",
}

problem is events added only single user respect with client id and client key

Header 1
The issue was only single user adds the events in google calendar with client id and client key.
But my requirement is multiple users can add events to google calendar when click on link it redirects to google calendar login page. Events details coming from db. I attached my previous code.
string eventName = "Dummy";
DateTime startDate = new DateTime(2020, 04, 28, 16, 30, 00);
DateTime endDate = new DateTime(2020, 04, 28, 17, 00, 00);
string location = null;
startDate = DateTime.SpecifyKind(startDate, DateTimeKind.Local);
endDate = DateTime.SpecifyKind(endDate, DateTimeKind.Local);
string link = "www.sample.in";
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
ClientId ="Key",
ClientSecret = "Key",
},
new[] { CalendarService.Scope.Calendar },
"user",
CancellationToken.None).Result;
// Create the service.
var service = new CalendarService(new BaseClientService.Initializer
{
HttpClientInitializer = credential,
ApplicationName = "Calendar API Sample",
});
var myEvent = new Event
{
Summary = eventName,
Location = location,
Start = new EventDateTime
{
DateTime = startDate,
TimeZone = "Asia/India",
},
End = new EventDateTime
{
DateTime = endDate,
TimeZone = "Asia/India",
},
Recurrence = new String[] { "RRULE:FREQ=WEEKLY;BYDAY=MO" },
//Attendees = new List
//{
//new EventAttendee { Email = "xxxxx#gmail.com"}
//},
};
var recurringEvent = service.Events.Insert(myEvent, "primary");
recurringEvent.SendNotifications = true;
recurringEvent.Execute();

DynamoDB Conditional SaveAsync

I'm using the following code:
DynamoDBContextConfig config = new DynamoDBContextConfig()
{
ConsistentRead = false,
Conversion = DynamoDBEntryConversion.V2
};
using (DynamoDBContext context = new DynamoDBContext(config))
{
long unixTimestamp = (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
QTrackStatus qTrackStatus = new QTrackStatus()
{
Key = "m#m.com",
EventCode = "CC",
EventDateTime = "2019-09-09 14:00:30",
EventLocation = "BFS",
EventLastUpdate = unixTimestamp
};
DynamoDBOperationConfig dynamoDBOperationConfig = new DynamoDBOperationConfig()
{
QueryFilter = new List<ScanCondition>()
{
{ new ScanCondition("EventCode", ScanOperator.NotEqual, "CC") }
},
ConditionalOperator = ConditionalOperatorValues.And
};
await context.SaveAsync(qTrackStatus, dynamoDBOperationConfig);
}
What I'm trying to do is only save the record if the EventCode is not CC. Currently it's always saving. I could retrieve the record first, do a check and then call SaveAsync if required - however I'd like to do it all in the SaveAsync call. Is this possible?
Unless I've missed something, it doesn't look like this is possible with the higher level api. I ended up re-factoring to the following:
AmazonDynamoDBClient client = new AmazonDynamoDBClient();
UpdateItemRequest updateItemRequest = new UpdateItemRequest()
{
TableName = "QTrackStatus",
ReturnValues = ReturnValue.ALL_NEW,
ConditionExpression = "EventCode <> :ec",
UpdateExpression = "SET EventCode = :ec, EventDateTime = :edt, EventLocation = :el, EventLastUpdate = :elu",
ExpressionAttributeValues = new Dictionary<string, AttributeValue>()
{
{ ":ec", new AttributeValue("CC") },
{ ":edt", new AttributeValue("2019-09-09 14:00:30") },
{ ":el", new AttributeValue("BFS") },
{ ":elu", new AttributeValue() { N = ((long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds).ToString() } }
},
Key = new Dictionary<string, AttributeValue>()
{
{ "Key", new AttributeValue("m#m.com") }
}
};
try
{
UpdateItemResponse updateItemResponse = await client.UpdateItemAsync(updateItemRequest);
}
catch(ConditionalCheckFailedException e)
{
}
This allows me to achieve my goal.

Error while inserting weight data through C# google fit api

What am I doing wrong?
I've got error when inserting data to GoogleFit (last line).
I know that C# API doesn't include detailed error information but I don't know how to send it through google console website.
Google.GoogleApiException HResult=0x80131500
Message=Google.Apis.Requests.RequestError Bad Request [400] Errors
[Message[Bad Request] Location[ - ] Reason[invalidArgument]
Domain[global]]
using Google.Apis.Auth.OAuth2;
using Google.Apis.Fitness.v1;
using Google.Apis.Fitness.v1.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.Threading;
namespace GoogleFitImport
{
class Program
{
static void Main(string[] args)
{
GoogleFitImport.InsertToGoogleFit();
}
}
public class GoogleFitImport
{
private static readonly DateTime zero = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
public static long ToJavaMiliseconds(DateTime dt)
{
return (long)(dt - zero).TotalMilliseconds;
}
public static long ToJavaNanoseconds(DateTime dt)
{
return (long)(dt - zero).TotalMilliseconds * 10 ^ 6;
}
public static DateTime FromJavaNanoseconds(long? nanoseconds)
{
if (nanoseconds == null)
nanoseconds = 0;
return FromJavaMiliseconds((nanoseconds.Value / (10 ^ 6)));
}
public static DateTime FromJavaMiliseconds(long mili)
{
return zero.AddMilliseconds((double)mili);
}
public static void InsertToGoogleFit()
{
string UserId = "me";
List<KeyValuePair<DateTime, float>> measures = new List<KeyValuePair<DateTime, float>>();
measures.Add(new KeyValuePair<DateTime, float>(new DateTime(2000, 01, 01, 12, 0, 0, DateTimeKind.Utc), 10.1f));
measures.Add(new KeyValuePair<DateTime, float>(new DateTime(2000, 01, 02, 12, 0, 0, DateTimeKind.Utc), 10.2f));
measures.Add(new KeyValuePair<DateTime, float>(new DateTime(2000, 01, 03, 12, 0, 0, DateTimeKind.Utc), 10.3f));
// https://www.googleapis.com/auth/fitness.body.write
var clientId = "000000000000-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com"; // From https://console.developers.google.com
var clientSecret = "XXXXXXXXXXXXXXXXXXXXXXXX"; // From https://console.developers.google.com
//Scopes for use with the Google Drive API
string[] scopes = new string[]
{
FitnessService.Scope.FitnessBodyWrite,
FitnessService.Scope.FitnessBodyRead,
};
// here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync
(
new ClientSecrets
{
ClientId = clientId,
ClientSecret = clientSecret
},
scopes,
Environment.UserName,
CancellationToken.None,
new FileDataStore("Google.Fitness.Auth", false)
).Result;
FitnessService fitnessService = new FitnessService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "FromLibraCsvToGoogleFit" //Assembly.GetExecutingAssembly().GetName().Name,
});
DataSource dataSource = new DataSource()
{
Type = "raw", //""derived",
Application = new Google.Apis.Fitness.v1.Data.Application()
{
Name = "maweightimport"
},
DataType = new DataType()
{
Name = "com.google.weight",
Field = new List<DataTypeField>()
{
new DataTypeField() {Name = "weight", Format = "floatPoint"}
}
},
Device = new Device()
{
Type = "scale",
Manufacturer = "unknown",
Model = "unknown",
Uid = "maweightimport",
Version = "1.0"
}
};
//string dataSourceId = "derived:com.google.weight:{clientId}:unknown:unknown:maweightimport"
string dataSourceId =
$"{dataSource.Type}:{dataSource.DataType.Name}:{clientId.Split('-')[0]}:{dataSource.Device.Manufacturer}:{dataSource.Device.Model}:{dataSource.Device.Uid}";
try
{
DataSource googleDataSource = fitnessService.Users.DataSources.Get(UserId, dataSourceId).Execute();
}
catch (Exception ex) //create if not exists
{
Console.WriteLine(ex);
DataSource googleDataSource = fitnessService.Users.DataSources.Create(dataSource, UserId).Execute();
}
Google.Apis.Fitness.v1.Data.Dataset weightsDataSource = new Google.Apis.Fitness.v1.Data.Dataset()
{
DataSourceId = dataSourceId,
Point = new List<DataPoint>()
};
DateTime minDateTime = DateTime.MaxValue;
DateTime maxDateTime = DateTime.MinValue;
foreach (var weight in measures)
{
long ts = ToJavaNanoseconds(weight.Key);
weightsDataSource.Point.Add
(
new DataPoint()
{
DataTypeName = "com.google.weight",
StartTimeNanos = ts,
EndTimeNanos = ts,
Value = new List<Value>()
{
new Value()
{
FpVal = weight.Value
}
}
}
);
if (minDateTime > weight.Key)
minDateTime = weight.Key;
if (maxDateTime < weight.Key)
maxDateTime = weight.Key;
}
weightsDataSource.MinStartTimeNs = ToJavaNanoseconds(minDateTime);
weightsDataSource.MaxEndTimeNs = ToJavaNanoseconds(maxDateTime);
string dataSetId = "2000.01.01-2000.01.03";
var save = fitnessService.Users.DataSources.Datasets.Patch(weightsDataSource, UserId, dataSourceId, dataSetId).Execute(); //ERROR HERE !
//var read = fitnessService.Users.DataSources.Datasets.Get(UserId, dataSourceId, dataSetId).Execute();
}
}
}
string dataSetId = "2000.01.01-2000.01.03";
Has to be in Nanos.

Categories