I'm trying to take events from Google Calendar and display them in a listView for Xamarin.Forms.
Google Calendar uses an RFC3339 format when you call start.dateTime the format is yyyy-mm-dd.
I'm trying to do a string day of the week format (Mon Jan 1, 2018) similar to .Net DateTime.ToLongDateString Method.
My Code so far is this:
namespace TheFirstAcademy.ViewModels{
class EventListViewModel
{
public List<SchoolEvent> SchoolEvents { get; set; }
public SchoolCalendar SelectedCalendar { get; set; }
public EventListViewModel(SchoolCalendar selectedcalendar)
{
SelectedCalendar = selectedcalendar;
SchoolEvents = GetSchoolEvents();
}
public List<SchoolEvent> GetSchoolEvents()
{
// Create Google Calendar API service.
var service = new CalendarService(new BaseClientService.Initializer()
{
ApiKey = "Key",
ApplicationName = "TFA Calendar Mobile App",
});
// Define parameters of request.
EventsResource.ListRequest request = service.Events.List(SelectedCalendar.SchoolCalId);
request.TimeMin = DateTime.Now;
request.ShowDeleted = false;
request.SingleEvents = true;
request.MaxResults = 10;
request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime;
// List events.
Events events = request.Execute();
List<SchoolEvent> schoolEvents = new List<SchoolEvent>();
if (events.Items != null && events.Items.Count > 0)
{
foreach (var eventItem in events.Items)
{
string when = eventItem.Start.DateTime.ToString();
if (String.IsNullOrEmpty(when))
{
when = eventItem.Start.Date;
}
schoolEvents.Add(new SchoolEvent() {
EventTitle = eventItem.Summary,
EventDescription = eventItem.Description,
EventStartTime = when,
EventEndTime = eventItem.End.Date
});
}
}
return schoolEvents;
}
}
}
This will eventually get displayed in a ListView for iOS and Android using Xamarin.Forms. The Event for a calendar would look something like this:
[Event Name]
[Event Location]
Starts: Fri May 25, 2018 12:00 PM
Ends: Sat May 26, 2018 12:00 PM
Some references I have been found:
Google Calendar v3 Events info
https://developers.google.com/calendar/v3/reference/events
RFC to dateTime (not sure if this is the right direction).
How do I parse and convert a DateTime to the RFC 3339 date-time format?
Any help is appreciated.
I figured out the conversion by using. DateTime.Parse()
I converted the eventItem.Start.Date (which is a string)to DateTime using DateTime.Parse(). Then I converted the DateTime to string ("ddd MMM dd, yyyy").
Probably basic stuff Maybe this will help someone.
Related
I am getting Events with below code:
EventsResource.ListRequest req = service.Events.List(calresult[i].Id);
DateTime minLimit = DateTime.Now.AddMonths(-1);
DateTime maxLimit = DateTime.Now.AddMonths(3);
req.TimeZone = googleapiTimezone; //Pacific/Honolulu
req.TimeMin = minLimit;
req.TimeMax = maxLimit;
var events = req.Execute().Items;
The code is working find except it is not considering the Timezone parameter in any case it returns the Event DateTime info in the default event timezone.
What am i doing wrong here?
I am trying to do a UWP app that changes wallpaper and lockscreen based on the time of the day (as a start). I am facing difficulties implementing this:
I have the task "SetWallpaperAsync" on main page (I am making sure it works before shifting it to a background task) as fallowing:
private async Task<bool> SetWallpaperAsync()
{
bool success = false;
if (UserProfilePersonalizationSettings.IsSupported())
{
var imageID = DateTime.Now.Hour.ToString("HH");
var uri = new Uri($"ms-appx:///Dynamic/Dynamic-{imageID}.jpg");
var file = await StorageFile.GetFileFromApplicationUriAsync(uri);
success = await UserProfilePersonalizationSettings.Current.TrySetWallpaperImageAsync(file);
success = await UserProfilePersonalizationSettings.Current.TrySetLockScreenImageAsync(file);
}
return success;
}
But it only worked once then it stopped, which lead me to believe that the imageID string is not returning the correct value (the value is between 00 and 23, corresponding to the hours in a day in a 24 format).
I have also tried to link a textblock to the same value and different formats, but it did not appear on the app homepage. I am not sure at all where its going wrong!
// Time format
var formatter = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("hour");
DateTime dateToFormat = DateTime.Now;
var mydate = formatter.Format(dateToFormat);
TimeDescriptionTextBlock.Text = mydate.ToString();
// another try with the time
TimeHours.Text = DateTime.Now.ToString("HH:mm:ss");
How can I debug this code and see where its stopping?
If you output the imageID variable in the Output windows using Debug.Writeline:
var imageID = DateTime.Now.Hour.ToString("HH");
Debug.WriteLine(imageID);
You can see that the output is: HH.
The reason for this is that the format string HH works on DateTime variables, but you are actually calling it on the Hour variable only, which is just a number.
There are two possible solutions:
Remove the .Hour from the call: var imageID = DateTime.Now.ToString("HH");
Just use the Hour as a number: var imageID = DateTime.Now.Hour.ToString();
Both solutions are equivalent and will yield a 24-hour format hour number.
I am currently working on an app that checks all appointments on an individual email, it can update appointments, delete them, create new etc. This part is working already.
I am now trying to put all appointment starting from a specified last modified time into a list, and here is my issue. Code:
public void getByModifiedDate(CalendarFolder calendar)
{
bool found = false;
string date;
Console.WriteLine("Modified date: ");
date = Convert.ToString(Console.ReadLine());
List<TAppointments> tempList = new List<TAppointments>();
var appointments = getAppointments(calendar);
//loop through every appts on calendar
foreach (Appointment a in appointments)
{
if (a.LastModifiedTime.ToString() == date)
{
TAppointments app = new TAppointments(a.ICalUid.ToString(), a.Subject.ToString(), a.Start.ToString(), a.End.ToString(), a.LastModifiedTime.ToString());
currentApp = app;
tempList.Add(app);
found = true;
}
}
if (!found)
{
Console.WriteLine("No appointment found.");
}
printAppointments(tempList);
}
Here I can only find a single item, because well that's what I coded. Is there a way to specified a starting date? Something like lastmodifiedtime >= date? I've made some researched and did not find anything.
I fixed my case. I simply converted my specified date to DateTime, then I could compare it properly, as seen below. I hope it helps some people who has the same issue.
foreach (Appointment a in appointments)
{
if (a.LastModifiedTime >= Convert.ToDateTime(date))
{
i++;
TAppointments app = new TAppointments(a.ICalUid.ToString(), a.Subject.ToString(), a.Start.ToString(), a.End.ToString(), a.LastModifiedTime.ToString());
currentApp = app;
tempList.Add(app);
found = true;
}
}
I am getting inbox messages using Gmail API in my c# ASP.net application. All messages are from different time zones(states/countries), I wanna display there date in my own time zone as it displays in Gmail App. I searched a lot for conversion between timezones but can't solve it may be i am not getting it properly.
My code for but i tried so far is: (Its working for most of messages but for few of them its not displaying right DateTime)
For Example:
Time displayed in Gmail App: 30/11/2017 2:11 AM
My code Input/ value from Gmail API: Wed, 29 Nov 2017 10:11:35 -0800
Below are some values i am getting from my current gmail inbox messages:
var re = service.Users.Messages.List("me");
re.LabelIds = "INBOX";
re.Q = "is:all";
var res = re.Execute();
if (res != null && res.Messages != null)
{
foreach (var email in res.Messages)
{
var emailInfoResponse = service.Users.Messages.Get("me", email.Id).Execute();
if (emailInfoResponse != null)
{
foreach (var mParts in emailInfoResponse.Payload.Headers)
{
if (mParts.Name == "Date")
{
date = mParts.Value;
}
}
}
}
}
My Time Zone is: (UTC+08:00) Perth
Any help would be appreciated. Thanks!
{
"id": string,
"threadId": string,
....
"internalDate": long,
"payload": {
....
internalDate long
The internal message creation timestamp (epoch ms), which determines ordering in the inbox. For normal SMTP-received email, this represents the time the message was originally accepted by Google, which is more reliable than the Date header. However, for API-migrated mail, it can be configured by client to be based on the Date header.
REF: https://developers.google.com/gmail/api/v1/reference/users/messages
Based on the above Google documentation, here's one way:
//Some epoch time in ms
var gmail_date = 1512007768005;
//Get DateTime of epoch ms
var to_date = DateTimeOffset.FromUnixTimeMilliseconds(gmail_date).DateTime;
//This is your timezone offset GMT +8
var offset = 8;
Console.WriteLine(to_date - new TimeSpan(offset *-1, 0, 0));
Gets you 11/30/2017 10:09:28 AM
I would like to add a recurring event with C#. I found on the Web that the following should work. When I run the method to insert the entry, It fails on the
EventEntry insertedEntry = service.Insert(calendarUri, entry); statement !
I get this error :
"Execution of request failed:
https://www.google.com/calendar/feeds/user#gmail.com/private/full?gsessionid=6eGsOTuhQ-YUVWp2BV_25g"
When I remove the recurrence code, everything works fine ! I noticed that this piece of code is pretty old ! How can I simply add a recurring event on Google Calendar with the .NET library ?
EventEntry entry = new EventEntry();
entry.Title.Text = "Hello World !";
// Recurring event:
String recurData =
"RRULE:FREQ=WEEKLY;WKST=SU;UNTIL=20131010;BYDAY=SU\r\n";
Recurrence recurrence = new Recurrence();
recurrence.Value = recurData;
entry.Recurrence = recurrence;
string htmlDescription = "Woww, really ?";
if (htmlDescription != null && htmlDescription.Length > 0)
{
entry.Content.Type = "html";
entry.Content.Content = htmlDescription;
}
Where eventLocation = new Where();
eventLocation.ValueString = "Somewhere";
entry.Locations.Add(eventLocation);
DateTime start = DateTime.Now;
When eventTime = new When();
eventTime.StartTime = start;
DateTime endTime = DateTime.Now.AddHours(2);
eventTime.EndTime = endTime;
entry.Times.Add(eventTime);
eventTime.AllDay = true;
EventEntry insertedEntry = service.Insert(calendarUri, entry);
Straight from Google (click the .NET example if it doens't come up as a default):Create Recurring Events
Hopefully this will give you some ideas if not out-right answer your question.
Cheers.
Your recurrence string telling it when to end requires a full time entry. You simply said UNTIL=20131010. The question is 20131010 where? We can assume you want midnight, but then... midnight where?
String recurData =
"RRULE:FREQ=WEEKLY;WKST=SU;UNTIL=20131010T000000-05:00;BYDAY=SU\r\n";
The above change should make your event recur until Midnight US Eastern time on 2013-10-10.