65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 .NET 创建 Google 日历事件

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.57/5 (19投票s)

2009年5月17日

CPOL

1分钟阅读

viewsIcon

105091

downloadIcon

5800

.NET 代码用于 Google 日历。

引言

本文将提供有关如何在 .NET 中操作 Google 日历事件的信息。我只实现了两个功能:完全检索日历,然后在选定的日历上填充事件。最后,为选定的 Google 日历创建事件。

使用代码

您需要添加以下 DLL 的引用

  • Google.Google.GData.AccessControl.dll
  • Google.GData.Calendar.dll
  • Google.GData.Client.dll
  • Google.GData.Extensions.dll

首先,我们将获取拥有 Google 日历的用户拥有的所有日历。为此,我们将创建一个 CalendarService 对象,如下所示。这里,UserNamePassword 将是您的 Google 凭据。之后,我们将创建一个 CalendarQuery 对象,并使用 CalendarService 对象根据给定的查询获取日历。

现在,为了获取选定日历的事件,首先,我们需要为特定的日历创建 CalendarURI。然后,我们将创建一个 RequestFactory 来创建特定查询(选择、更新、删除等)的请求以及(如果需要)代理对象。最后,我们将向 CalendarService 对象提供最终查询,以从选定的日历获取 EventFeed 数组(事件)。在 Google 日历中创建事件的功能非常相似,除了查询会发生变化(这次,我们将请求插入并为事件设置不同的值,例如名称、描述、位置等)。

CalendarQuery query = new CalendarQuery();

query.Uri = new Uri("http://www.google.com/calendar" + 
                    "/feeds/default/owncalendars/full");
CalendarFeed resultFeed = myService.Query(query);

if (cmbGoogleCalendar.SelectedIndex >= 0)
{
    //Get the selected calendar whose events you want to retrieve
    this.CalendarURI.Text = "http://www.google.com/calendar/feeds/" + 
      ((CalendarEntry)(cmbGoogleCalendar.SelectedItem)).SelfUri.ToString(
      ).Substring(((CalendarEntry)
      (cmbGoogleCalendar.SelectedItem)).SelfUri.ToString().LastIndexOf("/") 
      + 1) + "/private/full"; 
}

string calendarURI = this.CalendarURI.Text;
userName = this.UserName.Text;
passWord = this.Password.Text;
this.entryList = new ArrayList(50); 
ArrayList dates = new ArrayList(50); 
EventQuery query = new EventQuery();
GDataGAuthRequestFactory requestFactory = 
   (GDataGAuthRequestFactory)service.RequestFactory;
IWebProxy iProxy = WebRequest.GetSystemWebProxy();
WebProxy myProxy = new WebProxy();

// potentially, setup credentials on the proxy here
myProxy.Credentials = CredentialCache.DefaultCredentials;
myProxy.UseDefaultCredentials = false;

if (ProxyAddress.Text.Trim() != "" && ProxyPort.Text.Trim() != "")
{
    myProxy.Address = new Uri("http://" + ProxyAddress.Text.Trim() + 
                              ":" + ProxyPort.Text.Trim());
}

if (userName != null && userName.Length > 0)
{
    service.setUserCredentials(userName, passWord);
}

// only get event's for today - 1 month until today + 1 year
query.Uri = new Uri(calendarURI);
requestFactory.CreateRequest(GDataRequestType.Query, query.Uri);// = myProxy;

if (calendarControl.SelectionRange != null)
{
    query.StartTime = calendarControl.SelectionRange.Start.AddDays(-1) ;
    query.EndTime = calendarControl.SelectionRange.End.AddDays(1) ;
}
else
{
    query.StartTime = DateTime.Now.AddDays(-12);
    query.EndTime = DateTime.Now.AddMonths(0);
}

EventFeed calFeed = service.Query(query) as EventFeed;

// now populate the calendar
if (calFeed != null && calFeed.Entries.Count == 0)
{
    MessageBox.Show("No Event found");
}
else
{
    while (calFeed != null && calFeed.Entries.Count > 0)
    {
        // look for the one with dinner time...
        foreach (EventEntry entry in calFeed.Entries)
        {
            this.entryList.Add(entry);

            if (entry.Times.Count > 0)
            {
                foreach (When w in entry.Times)
                {
                    dates.Add(w.StartTime);
                }
            }
        }

        // just query the same query again.
        if (calFeed.NextChunk != null)
        {
            query.Uri = new Uri(calFeed.NextChunk);
            calFeed = service.Query(query) as EventFeed;
        }
        else
            calFeed = null;
    }
    DateTime[] aDates = new DateTime[dates.Count];

    int i = 0;
    foreach (DateTime d in dates)
    {
        aDates[i++] = d;
    }

    this.calendarControl.BoldedDates = aDates;
    // this.calendarControl.SelectionRange = 
    //         new SelectionRange(DateTime.Now, DateTime.Now);
    if (aDates.Length >0)
    {
        MessageBox.Show("Please select the Dates marked " + 
                        "bold in the calendar to see events");
    }
    else
    {
        MessageBox.Show("No Event found against selected dates rage and calendar");
    }
}

try
{
    EventEntry entry = new EventEntry();
    // Set the title and content of the entry.
    entry.Title.Text = EventName.Text;
    entry.Content.Content = Description.Text;
    // Set a location for the event.
    Where eventLocation = new Where();
    eventLocation.ValueString = location.Text;
    entry.Locations.Add(eventLocation);
    DateTime dtstartdatetime = calStartDate.Value;
    DateTime dtenddatetime = CalEndDate.Value;
    string[] str = new string[1];
    str[0] = ":";

    double dblHour = Convert.ToDouble(cmbStartTime.SelectedItem.ToString().Split(
                     str, StringSplitOptions.RemoveEmptyEntries)[0]);
    double dblMinutes = Convert.ToDouble(cmbStartTime.SelectedItem.ToString().Split(
                        str, StringSplitOptions.RemoveEmptyEntries)[1]);
    dtstartdatetime.AddHours(dblHour);
    dtstartdatetime.AddMinutes(dblMinutes);

    dblHour = Convert.ToDouble(cmbEndTime.SelectedItem.ToString().Split(
              str, StringSplitOptions.RemoveEmptyEntries)[0]);
    dblMinutes = Convert.ToDouble(cmbEndTime.SelectedItem.ToString().Split(
                 str, StringSplitOptions.RemoveEmptyEntries)[1]);
    dtenddatetime.AddHours(dblHour);
    dtenddatetime.AddMinutes(dblMinutes);
    When eventTime = new When(dtstartdatetime, dtenddatetime);
    entry.Times.Add(eventTime);
    userName = UserName.Text;
    passWord = Password.Text;

    if (userName != null && userName.Length > 0)
    {
        service.setUserCredentials(userName, passWord);
    }

    Uri postUri;
    postUri = new Uri("http://www.google.com/calendar" + 
                      "/feeds/default/private/full");

    if (GoogleCalendar.SelectedIndex >= 0)
    {
        postUri = new Uri("http://www.google.com/calendar/feeds/" + 
          ((CalendarEntry)(GoogleCalendar.SelectedItem)).SelfUri.ToString(
          ).Substring(((CalendarEntry)(
          GoogleCalendar.SelectedItem)).SelfUri.ToString(
          ).LastIndexOf("/") + 1) + "/private/full" );
    }
    GDataGAuthRequestFactory requestFactory = 
        (GDataGAuthRequestFactory)service.RequestFactory;
    IWebProxy iProxy = WebRequest.GetSystemWebProxy();
    WebProxy myProxy = new WebProxy();

    // potentially, setup credentials on the proxy here
    myProxy.Credentials = CredentialCache.DefaultCredentials;
    myProxy.UseDefaultCredentials = false;

    if (ProxyAddress.Text.Trim() != "" && ProxyPort.Text.Trim() != "")
    {
        myProxy.Address = new Uri("http://" + ProxyAddress.Text.Trim() + 
                                  ":" + ProxyPort.Text.Trim());
    }

    requestFactory.CreateRequest(GDataRequestType.Insert, postUri);// = myProxy;
    // Send the request and receive the response:
    AtomEntry insertedEntry = service.Insert(postUri, entry);

    MessageBox.Show("Event Successfully Added");
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message.ToString());
}
© . All rights reserved.