Send notification on google calendar event delete - c#

I want to send notification when deleting an event :
var certificate = new X509Certificate2("myp12filepath", "notasecret", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = Scopes
}.FromCertificate(certificate));
BaseClientService.Initializer initializer = new BaseClientService.Initializer();
initializer.HttpClientInitializer = credential;
initializer.ApplicationName = ApplicationName;
var service1 = new CalendarService(initializer);
var googleCalendarEvent = service1.Events.Delete("calendarId", "eventId").Execute();
The delete function does not accept a third parameter (indicating whether or not to send a notification) as mentioned in this link (there is no c# example)
So is there a way to send email notifications after deleting an event?

Create an instance of delete request and assign notification as true. See below.
var certificate = new X509Certificate2("myp12filepath", "notasecret", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = Scopes
}.FromCertificate(certificate));
BaseClientService.Initializer initializer = new BaseClientService.Initializer();
initializer.HttpClientInitializer = credential;
initializer.ApplicationName = ApplicationName;
var service1 = new CalendarService(initializer);
EventsResource.DeleteRequest delReq = service1.Events.Delete("calendarId", "eventId");
delReq.SendNotifications = true;
var googleCalendarEvent = delReq.Execute();

AFAIK, you need to set sendNotifications to true if you want to send notifications about the deletion of the event as also mentioned in your given link. And in addition to that, for a user to receive notifications, user's notification setting should also be checked for each of the calendars as mentioned in this forum and also as given here.
Listed below are the steps to turn notification on or off:
You can choose whether to have notifications for events, and whether you want to get notifications over email or in your browser.
Open Google Calendar on your computer.
In the top right, click Settings (gear icon) > Settings.
At the top of the page, click the Calendars tab.
Next to your calendar's name, click Edit notifications.
Click Add notification or edit an existing notification.
At the bottom of the page, click Save.
Note: To get notifications on your computer, you need to have Google Calendar open in your browser.
Lastly, since there is not much sample for C#, the .NET client might help.

Related

Send message as user alias

Is there a way to use the Gmail API to send as one of the provided users aliases instead of the users direct email?
I have a general user in my Google Org and it has a few aliases such as help#example.com, support#example.com which all belong to generaluser#example.com
At the moment it sends fine but different sections of my app need to send email as the specified alias.
Below is my code which sends email as the specified user without error.
private static async Task<GmailService> GetAuthorizedGmailService()
{
var serviceAccountEmail = "serviceaccount#gserviceaccount.com";
string AuthFile = HttpContext.Current.Server.MapPath("");
X509Certificate2 certificate = new X509Certificate2(AuthFile,"", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential;
credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
User = "user#email.com",
Scopes = Scopes
}.FromCertificate(certificate));
GmailService service = null;
if (await credential.RequestAccessTokenAsync(CancellationToken.None))
{
service = new GmailService(new BaseClientService.Initializer()
{
ApplicationName = ApplicationName,
HttpClientInitializer = credential,
});
}
return service;
}
The above is my code for creating my GmailService and below is my execution of the SendRequest:
var mimeMessage = MimeKit.MimeMessage.CreateFromMailMessage(mail);
var gmailMessage = new Google.Apis.Gmail.v1.Data.Message
{
Raw = Encode(mimeMessage.ToString())
};
var service = await GetAuthorizedGmailService();
UsersResource.MessagesResource.SendRequest request = service.Users.Messages.Send(gmailMessage, "user#email.co.za");
await request.ExecuteAsync();
Anyone know how I can specify which alias should be used in the from address?
I have tried setting it in the from section of the HTTP header and I still get the message from the users direct email address. I would very much like to not have to create a user account for each of these alias just so I can send as the appropriate email address.
The comment made by Tholle was correct. Adding the alias in the From header makes it use the alias.
The problem I was having is while the user had the alias assigned to them you have to also add it to the Send mail as in the users Gmail Settings.
All I had to do was go add the alias there and then it didn't override the From header with the users primary address.
Setting is located in: Settings > Acounts > Send mail as:

Can't get entry for specific email as primary calendar

I'm using Google Calendar API with a service account. Actually I'm going to create an application that synchronize the events from a local database to a specific email user. The adding of an event seems working pretty well but the problem's coming when I need to update an event. In particular before the update I check if the event exist or not on the Google Calendar of a specific user, let me show an example, this is how I create the service account:
string[] scopes = new string[]
{
CalendarService.Scope.Calendar,
CalendarService.Scope.CalendarReadonly
};
var certificate = new X509Certificate2(CPath, "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer("my service account email")
{
Scopes = scopes
}.FromCertificate(certificate));
CalendarService service = new CalendarService(
new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = ApplicationName
});
return service;
before updating or adding an event I check if the event exist in this way:
public bool EventExist(string id)
{
try
{
var service = AuthenticationService();
Event foundResponse = service.Events.Get("foo#gmail.com", id).Execute(); //id is the id of the event
return true;
}
catch (Exception ex)
{
Log.Write(ex.Message);
return false;
}
}
Now AuthenticationService() service is the method that return the service variable (the first code wrote). Later, I use the service variable for get the event of a specific user, note that the email is the primary calendar of the user. Now if I pass "primary", the event was found, instead if I pass the email, as in this case, the event was not found.
I don't know why, maybe the service-account save the event of a specific user somewhere? This situation is very bad for me, 'cause if an user delete an event with a particular id I need to check if the element exist or not into the calendar of the user.
Maybe I'm wrong with something or Google don't allow to do this?

How to retrive events from google calendar API fro c# .net using API key

I am able to retrieve event from google calendar API using OAuth authentication by code given here, but how to code for getting event information using API key.
API key is for use with PUBLIC data. For an API key to work with a calendar I would assume said calendar would have to be set to public.
var service = new CalendarService(new BaseClientService.Initializer()
{
ApiKey = "XXX",
ApplicationName = "xyz",
});
var events = service.Events.List("en.danish#holiday#group.v.calendar.google.com").Execute();
foreach (var myEvent in events.Items)
{
Console.WriteLine(string.Format("Event: {0} Start: {1} End: {2}", myEvent.Summary, myEvent.Start.DateTime.ToString(), myEvent.End.DateTime.ToString()));
}
I have an example / tutorial of accessing events on public calendars here
I think you should consider looking at a service account instead this will allow you to grant the service account access to your calendar and you wont need to go though the Oauth2 authentication which I suspect is what you don't want to be doing.
string[] scopes = new string[] {
CalendarService.Scope.Calendar, // Manage your calendars
CalendarService.Scope.CalendarReadonly // View your Calendars
};
var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail) {
Scopes = scopes
}.FromCertificate(certificate));
I have a tutorial on how to us a service account here

Google Analytics Api on Azure

I want to use the google analytics api in my MVC website, im authenticating using the api service account and oauth2 with have no issues on my localhost but as soon as I deploy to Azure i get a 502 error:
"502 - Web server received an invalid response while acting as a
gateway or proxy server. There is a problem with the page you are
looking for, and it cannot be displayed. When the Web server (while
acting as a gateway or proxy) contacted the upstream content server,
it received an invalid response from the content server."
heres my code:
const string ServiceAccountUser = "xxxxxxxxxx-cpla4j8focrebami0l87mbcto09j9j6k#developer.gserviceaccount.com";
AssertionFlowClient client = new AssertionFlowClient(
GoogleAuthenticationServer.Description,
new X509Certificate2(System.Web.Hosting.HostingEnvironment.MapPath("/Areas/Admin/xxxxxxxxxxxxxxxxxx-privatekey.p12"),
"notasecret", X509KeyStorageFlags.Exportable))
{
Scope = AnalyticsService.Scopes.AnalyticsReadonly.GetStringValue(),
ServiceAccountId = ServiceAccountUser //Bug, why does ServiceAccountUser have to be assigned to ServiceAccountId
//,ServiceAccountUser = ServiceAccountUser
};
OAuth2Authenticator<AssertionFlowClient> authenticator = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState);
I cant figure out whats causing it? Am im missing something within Azure?
Thanks for any help.
I also ran into the same issue but passing X509KeyStorageFlags.MachineKeySet into the constructor as well fixed the issue for me.
X509Certificate2 certificate = new X509Certificate2(file, "key", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);
After hours of pain on this exact same problem, I found a work around by piecing together various sources of info.
The problem arises from trying to read the p12 file from the Azure web site, i.e. this line in my code fails
var key = new X509Certificate2(keyFile, keyPassword, X509KeyStorageFlags.Exportable);
No idea why, but it works if you split the file into a cer and key.xml file?
Firstly, extract these files, (I just used a console app)
// load pfx/p12 as "exportable"
var p12Cert = new X509Certificate2(#"c:\Temp\xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-privatekey.p12", "notasecret", X509KeyStorageFlags.Exportable);
// export .cer from .pfx/.p12
File.WriteAllBytes(#"C:\Temp\MyCert.cer", p12Cert.Export(X509ContentType.Cert));
// export private key XML
string privateKeyXml = p12Cert.PrivateKey.ToXmlString(true);
File.WriteAllText(#"C:\Temp\PrivateKey.xml", privateKeyXml);
Then copy them to your website then load them in like so
//Store the authentication description
AuthorizationServerDescription desc = GoogleAuthenticationServer.Description;
//Create a certificate object to use when authenticating
var rsaCryptoServiceProvider = new RSACryptoServiceProvider();
rsaCryptoServiceProvider.FromXmlString(File.ReadAllText(keyFile));
var key = new X509Certificate2(certFile) {PrivateKey = rsaCryptoServiceProvider};
//Now, we will log in and authenticate, passing in the description
//and key from above, then setting the accountId and scope
var client = new AssertionFlowClient(desc, key)
{
//cliendId is your SERVICE ACCOUNT Email Address from Google APIs Console
//looks something like 12345-randomstring#developer.gserviceaccount.com
//~IMPORTANT~: this email address has to be added to your Google Analytics profile
// and given Read & Analyze permissions
ServiceAccountId = clientId,
Scope = "https://www.googleapis.com/auth/analytics.readonly"
};
//Finally, complete the authentication process
//NOTE: This is the first change from the update above
var auth = new OAuth2Authenticator<AssertionFlowClient>(client, AssertionFlowClient.GetState);
//First, create a new service object
//NOTE: this is the second change from the update
//above. Thanks to James for pointing this out
var gas = new AnalyticsService(new BaseClientService.Initializer { Authenticator = auth });
This now works for me and I hope it helps you.

How to post to friend's notification area?

I have a web site facebook app. I can login and post to users wall.What I really want is when a user creates an image on my web site , he can create a notification on couple friends to take an action on the image. How can I do this ?
I have this code but I don't see a notification at my notification area ?
var f = new FacebookClient();
dynamic result = f.Get("oauth/access_token", new
{
client_id = FACEBOOK_APP_ID,
client_secret = FACEBOOK_SECRET,
grant_type = "client_credentials"
});
var token = result.access_token as string;
var reqClient = new FacebookClient(token);
var args = new Dictionary<string, object>();
args["message"] = "Invitation to action message";
args["data"] = "Invitation to action data";
var reqResult = reqClient.Post("/" + facebookId.ToString() + "/apprequests", args);
The app generated request go to the bookmarks counter and not to the top notifications (with the globe image).
There's no way for an app to send that kind of notification to a user (that I'm aware of).
You can check in the Social Channels guide on the options that are available for you, also you can check the Requests documentation.
Use app notifications. The guide I've linked to shows a lot of documentation.

Categories

Resources