[iCal.net] 透過HTTP 存取iCalandar 資料

iCalendar 是一套RFC 制式用作排程管理 (RFC 5545), iCal.net 是一套 C# 套件以存取ics 檔案. 在此示範中, 利用政府的公眾假期做示範, 如何存取ics 檔案並deserialize 作object.CalendarReader.cs

public class CalendarReader
    {
        public IList<CalendarEvent> LoadCalendarEventsByFile(string filePath)
        {
            if (!File.Exists(filePath))
                throw new FileNotFoundException("File " + filePath + " could not be found.");
            string icalText = File.ReadAllText(filePath);
            IList<CalendarEvent> calendarEvents = Calendar.Load<CalendarEvent>(icalText);
            return calendarEvents;
        }

        public IList<CalendarEvent> LoadCalendarEventsByHttp(string url, string httpMethod = "GET")
        {
            HttpWebRequest httpRequest = WebRequest.Create(url) as HttpWebRequest;
            httpRequest.Method = httpMethod;
            IList<CalendarEvent> calendarEvents = new List<CalendarEvent>();
            try
            {
                using (WebResponse webResponse = httpRequest.GetResponse())
                {
                    using (Stream webResponseStream = webResponse.GetResponseStream())
                    {
                        StreamReader streamReader = new StreamReader(webResponseStream);
                        string responseText = streamReader.ReadToEnd();
                        Calendar calendar = Calendar.Load(responseText);
                        calendarEvents = calendar.Events.ToList();
                    }
                }    
            }
            catch (Exception ex)
            {
                throw(ex);
            }
            return calendarEvents;
        }
    }

MainWindowViewModel.cs

 public class MainWindowViewModel
    {
        public ObservableCollection<CalendarEvent> CalendarEvents;
        private CalendarReader _calendarReader = new CalendarReader();

        public MainWindowViewModel()
        {
            CalendarEvents = new ObservableCollection<CalendarEvent>(_calendarReader.LoadCalendarEventsByHttp("http://www.1823.gov.hk/common/ical/en.ics"));
        }
    }

利用HTTPWebRequest 讀取檔案, 並將Response stream 作string, 並用iCal.net.load() 讀取.

參考資料

About C.H. Ling 262 Articles
a .net / Java developer from Hong Kong and currently located in United Kingdom. Thanks for Google because it solve many technical problems so I build this blog as return. Besides coding and trying advance technology, hiking and traveling is other favorite to me, so I will write down something what I see and what I feel during it. Happy reading!!!

Be the first to comment

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.