C# Google Calendar - c#

Everything is already setup on the google calendar api (not sure if i configure correctly or i missed something out)
I created a c# console application,that writes an appointment to google calendar.
What i want to achieve is that , i want to get all the user's or subscriber who subscribe to my app, so what i can write
on there calendar if there is an event.
What configuration do i need?

That's actually a multi-domain problem.
Some questions to consider:
What calender is it? A public one?
How do they subscribe with your console?
What happens when the software shuts down, crashes, etc?
Do you need to know the event after it was written to the calendars?
If not, do new subscriber get previously added calender entries?
Other than that, you should have a look at Webclient. Then we have here the reference for the Google Calendar API. The main request method you're searching is this one: Events Insert. With that, we can craft our own inseration variant.
```
private readonly List<string> _calendarIDs;
/* lets assume you imported webrequests and you're going to write a method
* Further we assume, you have a List of calendars as object attribute
*/
public void InsertEntry(DateTime start, DateTime end,
string title, string description) {
using(var client = new WebClient()) {
var epochTicks = new DateTime(1970, 1, 1);
var values = new NameValueCollection();
values["attachements[].fileUrl"] = "";
values["attendees[].email"] = "";
values["end.date"] = end.ToString("yyyy-MM-dd");
values["end.dateTime"] = (end - epoch).Seconds;
values["reminders.overrides[].minutes"] = 0;
values["start.date"] = start.ToString("yyyy-MM-dd");
values["start.dateTime"] = (start - epoch).Seconds;
values["summary"] = title; // This is the calendar entrys title
values["description"] = description;
foreach(string calendarID in _calendarIDs) {
var endpoint = String.Format("https://www.googleapis.com/calendar/v3/calendars/{0}/events", calendarID)
var response = client.UploadValues(endpoint, values);
var responseString = Encoding.Default.GetString(response);
}
}
This is a minimal example and the api has a lot of endpoints and parameter. You should have a deep look into it, maybe you find more useful parameter.

Below is the sample code,
GoogleCalendarUtils utils = new GoogleCalendarUtils();
ArrayList months = /* the list of months*/;
// Update the content window.
foreach( ThistleEventMonth month in months )
{
foreach( ThistleEvent thistleEvent in month.ThistleEvents )
{
utils.InsertEntry( thistleEvent );
}
}

Related

How to get subreddits of current user?

I trying to write simple application that will notify me about new posts in my subreddits from few hours ago.
example of code is:
var reddit = new RedditClient("this is appId", "this is refreshToken");
string subRedditor = "funny";
Subreddit sr = reddit.Subreddit(subRedditor).About();
DateTime dtAfter = DateTime.Now.AddHours(-8);
List<Post> searchedPosts = sr.Posts.GetNew(new CategorizedSrListingInput(after: dtAfter.ToString(), limit: 100));
for (int i=0; i<searchedPosts.Count; i++)
{
Console.WriteLine(searchedPosts[i].Created+" | "+ searchedPosts[i].Title+" | "+searchedPosts[i].Listing.URL);
}
It works nice when I know subreddit name. But the names are nonconstant values, they can change if moderators want. So I wonder to know Is exists some api to get subreddits of current user?
Something like this:
User currUser = reddit.User();
currUser.GetSubreddits;
You didn't mention what SDK you use, so I've assumed it's Reddit.NET by Kris Craig.
Subscribed subreddits can be accessed via the MySubscribedSubreddits method in the Account class:
var subscribed = reddit.Account.MySubscribedSubreddits();

Google Calendar API Insert Event

I can read calendar list and event list. There is any problem with login.
I trying add new event, i will not get any exception but never adding.
How can i create new event ?
My code (I can not find v3 sample for .NET, I made up this, could be wrong)
Event newEvent = new Event();
newEvent.Summary = tb_Title.Text;
newEvent.Description = tb_Desc.Text;
newEvent.Start = new EventDateTime();
newEvent.Start.DateTime = dateTimePicker1.Value;
newEvent.End = new EventDateTime();
newEvent.End.DateTime = dateTimePicker1.Value.AddHours(1);
calendarService.Events.Insert(newEvent, calendarId);
I can read calendar list and event list. There is any problem with
login.
This means that your OAuth2 authentication worked, but you still may have chosen the wrong scope/write permissions.
I trying add new event, i will not get any exception but never adding.
This is because you aren't executing your query. You need to use an Execute() method.
My code (I can not find v3 sample for .NET, I made up this, could be wrong)
The properties you chose work fine, and the dates are formatted correctly. The only thing you need to change is to execute your query with an Execute() method. He's an example based on your code:
Event newEvent = new Event();
using (frmAddEvent frmAddEvent = new frmAddEvent()){
frmAddEvent.ShowDialog();
newEvent.Summary = frmAddEvent.txtTitle.Text;
newEvent.Description = frmAddEvent.txtDesc.Text;
newEvent.Start = new EventDateTime();
newEvent.Start.DateTime = frmAddEvent.dateTimePicker1.Value;
newEvent.End = new EventDateTime();
newEvent.End.DateTime = frmAddEvent.dateTimePicker1.Value.AddHours(1);
if (frmAddEvent.DialogResult == DialogResult.OK) {
var eventResult = await service.Events.Insert(newEvent, calendarID).ExecuteAsync();
}
}
This query returns the event that you just created rather than a status type.

Retrieve Entries from Google Calendar

I'm working on a function that retrieves Events from a google calendar. I have implemented it according the tutorial found here
The function does work but only retrieves a maximum of 25 events and I'm wondering if I'm missing something.
That's my function
void retrieveEvents()
{
EventQuery query = new EventQuery();
CalendarService service = new CalendarService("MyTest");
service.setUserCredentials("email", "password");
service.QueryClientLoginToken();
query.Uri = new Uri("http://www.google.com/calendar/feeds/USER-ID/private/full");
query.StartTime = new DateTime(2010, 1, 1);
query.EndTime = DateTime.Now;
EventFeed calfeed = service.Query(query);
foreach (EventEntry ee in calfeed.Entries)
{
ListViewItem lvi = new ListViewItem(ee.Title.Text + "\r\n");
listEvents.Items.Add(lvi);
}
}
First off, v2 is deprecated. You really should move your code up to using v3 of the API.
From the FAQ:
How do I retrieve more than 25 results in an event feed?
You can use the query parameter max-results to retrieve more than the default 25. If you wish to retrieve all of the events in a feed, set the max-results parameter to a really large number. You can also page through events by taking advantage of the next links, available as child elements of a feed.

How do I create an Outlook "appointment" with DDay.iCal?

I'm using the DDay library to create an iCal event, so that users of my site can add something to their calendar.
I want them to add an appointment as opposed to a meeting request in Office 2010 (and hopefully others too). When I use the library and set the method to PUBLISH, it does appear as an appointment, but it reports that the meeting cannot be found in the calendar. Then when I click no response required, the item gets deleted and doesn't stay in their calendar.
If I change the method to REQUEST, it shows up as a meeting request. This would an okay second best option, but the 'to' field is blank. If that's the best I can do, how can I set the 'to' field? I guess I would have them respond to themselves.
private static string CreateCalendarEvent(
string title, string body, DateTime startDate, double duration,
string location, string organizer, string eventId, bool allDayEvent)
{
// mandatory for outlook 2007
if(String.IsNullOrEmpty(organizer))
throw new Exception("Organizer provided was null");
var iCal = new iCalendar
{
Method = "PUBLISH",
Version = "2.0"
};
// "REQUEST" will update an existing event with the same UID (Unique ID) and a newer time stamp.
//if (updatePreviousEvent)
//{
// iCal.Method = "REQUEST";
//}
var evt = iCal.Create<Event>();
evt.Summary = title;
evt.Start = new iCalDateTime(startDate);
evt.Duration = TimeSpan.FromHours(duration);
evt.Description = body;
evt.Location = location;
evt.IsAllDay = allDayEvent;
evt.UID = String.IsNullOrEmpty(eventId) ? new Guid().ToString() : eventId;
evt.Organizer = new Organizer(organizer);
evt.Alarms.Add(new Alarm
{
Duration = new TimeSpan(0, 15, 0),
Trigger = new Trigger(new TimeSpan(0, 15, 0)),
Action = AlarmAction.Display,
Description = "Reminder"
});
return new iCalendarSerializer().SerializeToString(iCal);
}
When I set the organizer to an email address, as opposed to a test string, it worked fine. I had written all of this up, so I thought I'd share it in case anyone else had the same problem
My app stopped working when the exchange server was upgraded to Outlook 2010 from 2003. Before the upgrade PUBLISH worked fine but now I had to change to REQUEST
Thanks for the article

How to delete all event entries from a specific calendar from Google calendar API .NET

I am trying editing a tool to allow a user to select from a list of their calendars and then clear all event entries / add new ones based on Microsoft project tasks.
Heres the original tool: http://daball.github.com/Microsoft-Project-to-Google-Calendar/
I am completely unexperienced with Google APIs / the calendar API, and am having some trouble. The program I'm editing keeps track of which CalendarEntry the user has selected from a list of their calendars. What I am currently trying to do is create a EventFeed which gives me the EventEntries of that selected calendar, so I can then delete all of them. The purpose of this is to allow someone to use this tool to also update the calendar from the project file whenever changes are made. Here's my function attempting the delete.
private void clearPreviousCalendarEntries(CalendarEntry calendarEntry)
{
EventQuery query = new EventQuery();
query.Uri = new Uri(calendarEntry.Links[0].AbsoluteUri);
EventFeed feed = (EventFeed)calendarService.Query(query);
AtomFeed batchFeed = new AtomFeed(feed);
foreach (EventEntry entry in feed.Entries)
{
entry.Id = new AtomId(entry.EditUri.ToString());
entry.BatchData = new GDataBatchEntryData(GDataBatchOperationType.delete);
batchFeed.Entries.Add(entry);
}
EventFeed batchResultFeed = (EventFeed)calendarService.Batch(batchFeed, new Uri(feed.Batch));
foreach (EventEntry entry in batchResultFeed.Entries)
{
if (entry.BatchData.Status.Code != 200 && entry.BatchData.Status.Code != 201)
this.listBoxResults.SelectedIndex = this.listBoxResults.Items.Add("Problem deleteing " + entry.Title.Text + " error code: " + entry.BatchData.Status.Code);
else
this.listBoxResults.SelectedIndex = this.listBoxResults.Items.Add("Deleted " + entry.Title.Text);
}
}
My feed doesn't return the results I was hoping for, but to be honest I'm not sure how to request the events correctly.
query.Uri = new Uri(calendarEntry.Links[0].AbsoluteUri); is something I grabbed from the portion of the program which is adding event to a specific calendar
AtomEntry insertedEntry = calendarService.Insert(new Uri(calendarEntry.Links[0].AbsoluteUri), eventEntry);
These posts are definitely related to what I'm looking for but I haven't arrived at a solution
google-calendar-get-events-from-a-specific-calendar
how can i retrieve a event exclusive from a calendar that i created (not default one)?
Try something like this:
CalendarService myService = new CalendarService("your calendar name");
myService.setUserCredentials(username, password);
CalendarEntry calendar;
try
{
calendar = (CalendarEntry)myService.Get(http://www.google.com/calendar/feeds/default/owncalendars/full/45kk8jl9nodfri1qgepsb65fnc%40group.calendar.google.com);
foreach (AtomEntry item in calendar.Feed.Entries)
{
item.Delete();
}
}
catch (GDataRequestException)
{
}
You can find "Calendar ID" (something like this: 45kk8jl9nodfri1qgepsb65fnc%40group.calendar.google.com) from Calendar Details page inside Google Calendar.
this is a related post:
google calendar api asp.net c# delete event
this is a useful doc:
http://code.google.com/intl/it-IT/apis/calendar/data/2.0/developers_guide_dotnet.html
A way I eventually arrived at was gathering the calendarID from the URI of the calendar, and then creating a new EventQuery using that id. Here's the new version of the code above
private void clearPreviousCalendarEntries(CalendarEntry calendarEntry)
{
this.listBoxResults.SelectedIndex = this.listBoxResults.Items.Add("Clearing previous calender entries");
String calendarURI = calendarEntry.Id.Uri.ToString();
//The last part of the calendarURI contains the calendarID we're looking for
String calendarID = calendarURI.Substring(calendarURI.LastIndexOf("/")+1);
EventQuery query = new EventQuery();
query.Uri = new Uri("http://www.google.com/calendar/feeds/" + calendarID + "/private/full");
EventFeed eventEntries = calendarService.Query(query);
AtomFeed batchFeed = new AtomFeed(eventEntries);
foreach (AtomEntry entry in eventEntries.Entries)
{
entry.Id = new AtomId(entry.EditUri.ToString());
entry.BatchData = new GDataBatchEntryData(GDataBatchOperationType.delete);
batchFeed.Entries.Add(entry);
}
EventFeed batchResultFeed = (EventFeed)calendarService.Batch(batchFeed, new Uri(eventEntries.Batch));
//check the return values of the batch operations to make sure they all worked.
//the insert operation should return a 201 and the rest should return 200
bool success = true;
foreach (EventEntry entry in batchResultFeed.Entries)
{
if (entry.BatchData.Status.Code != 200 && entry.BatchData.Status.Code != 201)
{
success = false;
listBoxResults.SelectedIndex = listBoxResults.Items.Add("The batch operation for " +
entry.Title.Text + " failed.");
}
}
if (success)
{
listBoxResults.SelectedIndex = listBoxResults.Items.Add("Calendar event clearing successful!");
}
}
I'm not particular happy with this, it seems odd to use string manipulation to gather the info and chop together my own query. But it works and I have been struggling to find a way to get this done.

Categories

Resources