When I want to execute the event, it doesn't execute (which means that the event is not in my calendar), and I get the following error:
System.FormatException: The "Deadline calendar" google-api-dotnet-client/1.42.0.0 (gzip) value format is not valid.
Any idea how to fix this? It worked some month ago and I just noticed that it doesn't work anymore.
Some code example:
public static CalendarService getCalendarService
{
get
{
var credential = GoogleWebAuthorizationBroker.AuthorizeAsync(new ClientSecrets { ClientId = clientId, ClientSecret = clientSecret },
new[] { CalendarService.Scope.Calendar }, "user", CancellationToken.None).Result;
return new CalendarService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "Deadline calendar" });
}
};
var ev = new Event
{
ICalUID = project.RefId,
Description = project.Description,
Summary = string.Format("'{0} ({1})' project deadline", project.Name, project.RefId),
Location = project.Location,
Start = new EventDateTime { TimeZone = "MST", DateTime = project.EndDate.Value.Date },
End = new EventDateTime { TimeZone = "MST", DateTime = project.EndDate.Value.Date.AddDays(1) },
Attendees = attendees.Select(x => new EventAttendee() { Email = x.Email, Organizer = (x.Id == project.Responsible ? true : false) }).ToList()
};
var projectEvent = getCalendarService.Events.Insert(ev, "primary");
projectEvent.SendNotifications = true;
projectEvent.Execute();
Well, the problem was the format of the application name. I used characters which aren't allowed in this string, like: "á, ő".
Thanks your anwers anyway! :)
Related
I'm trying to schedule events in my O365 user calendars.
I'm using an administrator account, creating a GraphServiceClient on authentication.
There are no errors (apparently) but the event is not created. Neither on the account used nor on the Attendees.
It seems to me that the problem is in the authorization of the GraphServiceClient. I already checked in the Azure portal and the user has "Calendars.ReadWrite" permission.
Any help, please?
try
{
var scopes = new[] { "Calendars.ReadWrite.All" };
// Multi-tenant apps can use "common",
// single-tenant apps must use the tenant ID from the Azure portal
var tenantId = "common";
Configuracoes Dados = new Configuracoes();
// Values from app registration
string clientId = Dados.EMailCV.ToString();
string clientSecret = Dados.PasswordCV.ToString();
// using Azure.Identity;
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
// This is the incoming token to exchange using on-behalf-of flow
var oboToken = "JWT_TOKEN_TO_EXCHANGE";
var cca = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithTenantId(tenantId)
.WithClientSecret(clientSecret)
.Build();
// DelegateAuthenticationProvider is a simple auth provider implementation
// that allows you to define an async function to retrieve a token
// Alternatively, you can create a class that implements IAuthenticationProvider
// for more complex scenarios
var authProvider = new DelegateAuthenticationProvider(async (request) =>
{
// Use Microsoft.Identity.Client to retrieve token
var assertion = new UserAssertion(oboToken);
var result = await cca.AcquireTokenOnBehalfOf(scopes, assertion).ExecuteAsync();
request.Headers.Authorization =
new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", result.AccessToken);
});
GraphServiceClient graphClient = new GraphServiceClient(authProvider);
var #event = new Event
{
Subject = "Let's go for lunch",
Body = new ItemBody
{
ContentType = BodyType.Html,
Content = "Does noon work for you?"
},
Start = new DateTimeTimeZone
{
DateTime = "2022-11-04T12:00:00",
TimeZone = "GMT Standard Time"
},
End = new DateTimeTimeZone
{
DateTime = "2017-04-15T14:00:00",
TimeZone = "GMT Standard Time"
},
// Location = new Location
// {
// displayName = "Harry's Bar"
// },
Attendees = new List<Attendee>()
{
new Attendee
{
EmailAddress = new EmailAddress
{
Address = "p560#esenviseu.net",
Name = "Nuno Barros"
},
Type = AttendeeType.Required
}
},
AllowNewTimeProposals = true,
IsOnlineMeeting = true,
OnlineMeetingProvider = OnlineMeetingProviderType.TeamsForBusiness
};
graphClient.Me.Events
.Request()
.Header("Prefer", "outlook.timezone=\"GMT Standard Time\"")
.AddAsync(#event);
}
catch (Exception ex)
{
lblTexto.Text = "Erros!<br>" + ex.Message;
}
finally
{
lblTexto.Text = "Sem erros!";
}
I have registered the App with application permission in Azure Directory and I am able to get Token and schedule a event by using the Same token for the single User at a time, but when I add the multiple Attendees (vinay#yfdln.onmicrosoft.com,AdeleV#yfdln.onmicrosoft.com) in the list then it's not creating the meeting for another user which I have not mentioned in the
GraphServiceClient(accessToken).Users["AdeleV#yfdln.onmicrosoft.com"].Events.Request().AddAsync(#event);
and am receiving the email saying
Delivery has failed to these recipients or groups:
Vinay#yfdln.onmicrosoft.com
Your message wasn't delivered because the recipient's email provider rejected it.
and I also got Some Error in the mail for
Diagnostic information for administrators:
Generating server: SA0PR19MB4602.namprd19.prod.outlook.com
Vinay#yfdln.onmicrosoft.com
Remote Server returned '550 5.7.501 Service unavailable. Spam abuse detected from IP range. For more information please go to http://go.microsoft.com/fwlink/?LinkId=526653. S(2017052602) [BYAPR19MB3063.namprd19.prod.outlook.com]'
Original message headers:
Received: from SA0PR19MB4602.namprd19.prod.outlook.com
([fe80::d4d8:a608:e081:3249]) by SA0PR19MB4602.namprd19.prod.outlook.com
([fe80::d4d8:a608:e081:3249%7]) with mapi id 15.20.5373.018; Tue, 28 Jun 2022
13:43:23 +0000
MIME-Version: 1.0
Content-Type: text/plain
Date: Tue, 28 Jun 2022 13:43:23 +0000
Message-ID:
<SA0PR19MB4602896A05ED8C22B925567688B89#SA0PR19MB4602.namprd19.prod.outlook.com>
Subject: Schedule From .Net
Code
public static async Task<Event> CreateEvent(string accessToken)
{
Event event1 = new Event();
var #event = new Event
{
Subject = "Schedule From .Net",
Body = new ItemBody
{
ContentType = BodyType.Html,
Content = "Test Schedule"
},
Start = new DateTimeTimeZone
{
DateTime = "2022-07-10T12:00:00",
TimeZone = "Pacific Standard Time"
},
End = new DateTimeTimeZone
{
DateTime = "2022-07-10T14:00:00",
TimeZone = "Pacific Standard Time"
},
Location = new Location
{
DisplayName = "OR1"
},
Attendees = new List<Attendee>()
{
new Attendee
{
EmailAddress = new EmailAddress
{
Address = "vinay#yfdln.onmicrosoft.com",
Name = "Vinay"
},
Type = AttendeeType.Required
},
new Attendee
{
EmailAddress = new EmailAddress
{
Address = "AdeleV#yfdln.onmicrosoft.com",
Name = "Adelev"
},
Type = AttendeeType.Required
}
},
TransactionId = Guid.NewGuid().ToString()
};
try
{
event1 = await GraphServiceClient(accessToken).Users["AdeleV#yfdln.onmicrosoft.com"].Events.Request().AddAsync(#event);
}
catch (Exception ex)
{
}
return event1;
}
Can anybody can you please check and suggest how we can schedule for multiple users at thee same time by using the same.
is there any option to change below code to add multiple emails in Users[] array
GraphServiceClient(accessToken).Users["AdeleV#yfdln.onmicrosoft.com"].Events.Request().AddAsync(#event);
to
GraphServiceClient(accessToken).Users["AdeleV#yfdln.onmicrosoft.com,AdeleV#yfdln.onmicrosoft.com"].Events.Request().AddAsync(#event);
but this gives error as below
Code: ResourceNotFound
Message: Resource could not be discovered.
Inner error:
AdditionalData:
date: 2022-06-28T14:41:33
request-id: 41cf2d89-de6d-44df-b42f-1e11d2fe430e
client-request-id: 41cf2d89-de6d-44df-b42f-1e11d2fe430e
ClientRequestId: 41cf2d89-de6d-44df-b42f-1e11d2fe430e
can please suggest which way we have to call
Regards
Srikanth
Sorry pls follow the code below and have a test.
I double confirmed your code and checked the official api document, I noticed that what you wrote is await GraphServiceClient(accessToken).Users["AdeleV#yfdln.onmicrosoft.com"].Events.Request().AddAsync(#event) while the sample code is await graphClient.Me.Calendars["{calendar-id}"].Events.Request().AddAsync(#event);, so you may need to use code GraphServiceClient(accessToken).Users["AdeleV#yfdln.onmicrosoft.com"].Calendars["{calendar-id}"].Events.Request().AddAsync(#event); instead.
public void CreateEvent()
{
var scopes = new[] { "https://graph.microsoft.com/.default" };
var tenantId = "your_tenant_name.onmicrosoft.com";
var clientId = "azure_ad_app_id";
var clientSecret = "client_secret";
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var #event = new Event
{
Subject = "Schedule From .Net",
Body = new ItemBody
{
ContentType = BodyType.Html,
Content = "Test Schedule"
},
Start = new DateTimeTimeZone
{
DateTime = "2022-07-10T12:00:00",
TimeZone = "Pacific Standard Time"
},
End = new DateTimeTimeZone
{
DateTime = "2022-07-10T14:00:00",
TimeZone = "Pacific Standard Time"
},
Location = new Location
{
DisplayName = "OR1"
},
Attendees = new List<Attendee>()
{
new Attendee
{
EmailAddress = new EmailAddress
{
Address = "vinay#yfdln.onmicrosoft.com",
Name = "Vinay"
},
Type = AttendeeType.Required
},
new Attendee
{
EmailAddress = new EmailAddress
{
Address = "AdeleV#yfdln.onmicrosoft.com",
Name = "Adelev"
},
Type = AttendeeType.Required
}
},
TransactionId = Guid.NewGuid().ToString()
};
var res = await graphClient.Users["userId"].Calendars["{calendar-id}"].Events.Request().AddAsync(#event);
}
Well.. I'm trying this code to create an Event
CalendarService service;
GoogleCredential credential;
try
{
string[] scopes = new string[] { CalendarService.Scope.Calendar };
using (var stream = new FileStream(#"C:\Prueba\meet.json", FileMode.Open, FileAccess.Read))
{
credential = GoogleCredential.FromStream(stream)
.CreateScoped(scopes);
}
service = new CalendarService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential
});
Event calendarEvent = new Event();
DateTime start = DateTime.Now;
calendarEvent.Kind = "";
calendarEvent.Summary = "prueba";
calendarEvent.Status = "confirmed";
calendarEvent.Visibility = "public";
calendarEvent.Description = "prueba";
calendarEvent.Creator = new Event.CreatorData
{
Email = "email#example.com", //email#example.com
Self = true
};
calendarEvent.Organizer = new Event.OrganizerData
{
Email = "email#example.com",
Self = true
};
calendarEvent.Start = new EventDateTime
{
DateTime = start,
TimeZone = "America/Mexico_City"
};
calendarEvent.End = new EventDateTime
{
DateTime = start.AddHours(1),
TimeZone = "America/Mexico_City"
};
calendarEvent.Recurrence = new String[] { "RRULE:FREQ=DAILY;COUNT=1" };
calendarEvent.Sequence = 0;
calendarEvent.HangoutLink = "";
calendarEvent.ConferenceData = new ConferenceData
{
CreateRequest = new CreateConferenceRequest
{
RequestId = "1234abcdef",
ConferenceSolutionKey = new ConferenceSolutionKey
{
Type = "hangoutsMeet"
},
Status = new ConferenceRequestStatus
{
StatusCode = "success"
}
},
EntryPoints = new List<EntryPoint>
{
new EntryPoint
{
EntryPointType = "video",
Uri = "",
Label = ""
}
},
ConferenceSolution = new ConferenceSolution
{
Key = new ConferenceSolutionKey
{
Type = "hangoutsMeet"
},
Name = "Google Meet",
IconUri = ""
},
ConferenceId = ""
};
//calendarEvent.EventType = "default";
EventsResource.InsertRequest request = service.Events.Insert(calendarEvent, "email#example.com");
request.ConferenceDataVersion = 0;
Event createEvent = request.Execute();
string url = createEvent.HangoutLink;
}
catch (Exception ex)
{
}
The source code is here
When I execute the line 116: Event createEvent = request.Execute();
I get this error: Google.Apis.Requests.RequestError Invalid conference type value. [400] Errors [Message[Invalid conference type value.] Location[ - ] Reason[invalid] Domain[global]
I don't know what means this error o with line I wrong
Could anyone help me with an example to create an event using classes C# from Google API Calendar?
As described in the C# library documentation for createRequest:
Either conferenceSolution and at least one entryPoint, or createRequest is required.
This means that you should use only CreateConferenceRequest as this conference is brand new (if it already existed then you would be wanting to use ConferenceSolution along with EntryPoints ). Therefore, simply remove ConferenceSolution and EntryPoints to leave just CreateConferenceRequest which as specified in the documentation is used for generating a new conference and attach it to the event.
In Google Cloud Platform the DataProc API is enabled. I am using the same key I use to access GCS and Big query to create a new cluster per this example. I get a Request had insufficient authentication scopes error on the following line.
Operation createOperation =
service.Projects.Regions.Clusters.Create(newCluster, project, dataprocGlobalRegion).Execute();
My complete code:
public static class DataProcClient
{
public static void Test()
{
string project = ConfigurationManager.AppSettings["Google.ProjectName"]; ;
string dataprocGlobalRegion = "global";
string zone = "us-east1-b";
string machineType = "n1-standard-4";
string clusterName = "sample-cluster";
int numWorkers = 2;
String serviceAccountEmail= ConfigurationManager.AppSettings["Google.ServiceAccountEmail"];
String certificateFile = ConfigurationManager.AppSettings["KeyDirectory"] + ConfigurationManager.AppSettings["Google.CertificateFile"];
X509Certificate2 certificate = new X509Certificate2(certificateFile, "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { StorageService.Scope.DevstorageFullControl }
}.FromCertificate(certificate));
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);
}
}
static bool IsDone(Operation op)
{
return op.Done ?? false;
}
}
When creating your ServiceAccountCredential, change:
new[] { StorageService.Scope.DevstorageFullControl }
to:
new[] { DataprocService.Scope.CloudPlatform }
I am getting the following error when attempting to Insert a new calendar to the user who is currently logged in. Users are able to log in and register but attempting to add a new calendar gives us this error.
Google.Apis.Requests.RequestError
Insufficient Permission [403]
Errors [
Message[Insufficient Permission] Location[ - ] Reason[insufficientPermissions] Domain[global]
]
The error occurs at the execute of the following code:
CalendarService googlecalender = new CalendarService(await (new GoogleAuthentication()).GetInitializer());
Calendar calendar = new Calendar();
calendar.Summary = "sampleCalendar";
calendar.Id = "_Sample";
calendar.Kind = "calendar#calendar";
var calendarRequest = googlecalender.Calendars.Insert(calendar);
var result = calendarRequest.Execute();
I have modified the google authentication to the following:
var authenInfo = new GoogleOAuth2AuthenticationOptions();
authenInfo.Scope.Add("openid");
authenInfo.Scope.Add("profile");
authenInfo.Scope.Add("email");
authenInfo.Scope.Add("https://www.googleapis.com/auth/plus.login");
authenInfo.Scope.Add("https://www.googleapis.com/auth/plus.me");
authenInfo.Scope.Add(YouTubeService.Scope.Youtube);
authenInfo.Scope.Add(CalendarService.Scope.Calendar);
authenInfo.Scope.Add(CalendarService.Scope.CalendarReadonly);
authenInfo.ClientId = "CLIENTID";
authenInfo.ClientSecret = "CLIENTSECRET";
authenInfo.Provider = new GoogleOAuth2AuthenticationProvider();
app.UseGoogleAuthentication(authenInfo);
and the GoogleAuthentication class is this:
public GoogleAuthentication()
{
ClientSecret = new ClientSecrets();
ClientSecret.ClientSecret = "CLIENTSECRET";
ClientSecret.ClientId = "CLIENTID";
Scope = new[] {
"https://www.googleapis.com/auth/plus.login",
YouTubeService.Scope.Youtube,
CalendarService.Scope.Calendar
};
}
private async void Authorize()
{
Credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
ClientSecret,
Scope,
"user",
CancellationToken.None
);
}
public async Task<BaseClientService.Initializer> GetInitializer()
{
if (Credential == null)
Authorize();
else if (Credential.Token.IsExpired(SystemClock.Default))
{
Boolean tokenRefreshed = await Credential.RefreshTokenAsync(CancellationToken.None);
}
return new BaseClientService.Initializer()
{
HttpClientInitializer = Credential,
ApplicationName = Properties.Settings.Default.ApplicationName
};
}