Exemple #1
0
        private void createNewCalendar(CalendarService service)
        {
            CalendarEntry calendar = new CalendarEntry();
            calendar.Title.Text = textBox1.Text;//"Little League Schedule";
            calendar.Summary.Text = "This calendar contains the practice schedule and game times.";
            calendar.TimeZone = "America/Los_Angeles";
            calendar.Hidden = false;
            calendar.Color = "#2952A3";
            calendar.Location = new  Where("", "", "Oakland");

            Uri postUri = new Uri("https://www.google.com/calendar/feeds/default/owncalendars/full");
            CalendarEntry createdCalendar = (CalendarEntry)service.Insert(postUri, calendar);
            refreshCalendar();
        }
        public Calendar(CalendarEntry calendar)
        {
            Title = calendar.Title.Text;

            //System.Windows.Media.Color color = (System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString(calendar.Color);
            //color.A = 225;

            //Color = color;

            Color = calendar.Color;
            CalendarUri = calendar.Content.AbsoluteUri;

            IsMine = IsSelected = String.Compare(calendar.AccessLevel, "owner") == 0;

            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("IsMine"));
            }
        }
        public void OAuth3LeggedAuthenticationTest() {
            Tracing.TraceMsg("Entering OAuth3LeggedAuthenticationTest");

            CalendarService service = new CalendarService("OAuthTestcode");

            OAuthParameters parameters = new OAuthParameters() {
                ConsumerKey = this.oAuthConsumerKey,
                ConsumerSecret = this.oAuthConsumerSecret,
                Token = this.oAuthToken,
                TokenSecret = this.oAuthTokenSecret,
                Scope = this.oAuthScope,
                SignatureMethod = this.oAuthSignatureMethod
            };

            GOAuthRequestFactory requestFactory = new GOAuthRequestFactory("cl", "OAuthTestcode", parameters);
            service.RequestFactory = requestFactory;

            CalendarEntry calendar = new CalendarEntry();
            calendar.Title.Text = "Test OAuth";

            Uri postUri = new Uri("https://www.google.com/calendar/feeds/default/owncalendars/full");
            CalendarEntry createdCalendar = (CalendarEntry)service.Insert(postUri, calendar);

            // delete the new entry
            createdCalendar.Delete();
        }
        public void OAuth2LeggedAuthenticationTest() {
            Tracing.TraceMsg("Entering OAuth2LeggedAuthenticationTest");

            CalendarService service = new CalendarService("OAuthTestcode");

            GOAuthRequestFactory requestFactory = new GOAuthRequestFactory("cl", "OAuthTestcode");
            requestFactory.ConsumerKey = this.oAuthConsumerKey;
            requestFactory.ConsumerSecret = this.oAuthConsumerSecret;
            requestFactory.UseSSL = true;
            service.RequestFactory = requestFactory;

            CalendarEntry calendar = new CalendarEntry();
            calendar.Title.Text = "Test OAuth";

            OAuthUri postUri = new OAuthUri("https://www.google.com/calendar/feeds/default/owncalendars/full",
                this.oAuthUser,
                this.oAuthDomain);
            CalendarEntry createdCalendar = (CalendarEntry)service.Insert(postUri, calendar);
        }
        /////////////////////////////////////////////////////////////////////////////


        /// <summary>
        /// Test to check creating/updating/deleting a secondary calendar.
        /// </summary>
        [Test] public void CalendarOwnCalendarsTest()
        {
            Tracing.TraceMsg("Enterting CalendarOwnCalendarsTest");

            CalendarService service = new CalendarService(this.ApplicationName);

            if (this.defaultOwnCalendarsUri != null)
            {
                if (this.userName != null)
                {
                    service.Credentials = new GDataCredentials(this.userName, this.passWord);
                }

                service.RequestFactory = this.factory;

                CalendarEntry newCalendar = new CalendarEntry();
                newCalendar.Title.Text = "new calendar" + Guid.NewGuid().ToString();
                newCalendar.Summary.Text = "some unique summary" + Guid.NewGuid().ToString();
                newCalendar.TimeZone = "America/Los_Angeles";
                newCalendar.Hidden = false;
                newCalendar.Selected = true;
                newCalendar.Color = "#2952A3";
                newCalendar.Location = new Where("", "", "Test City");

                Uri postUri = new Uri(this.defaultOwnCalendarsUri);
                CalendarEntry createdCalendar = (CalendarEntry) service.Insert(postUri, newCalendar);

                Assert.IsNotNull(createdCalendar, "created calendar should be returned.");

                Assert.AreEqual(newCalendar.Title.Text, createdCalendar.Title.Text, "Titles should be equal");
                Assert.AreEqual(newCalendar.Summary.Text, createdCalendar.Summary.Text, "Summaries should be equal");
                Assert.AreEqual(newCalendar.TimeZone, createdCalendar.TimeZone, "Timezone should be equal");
                Assert.AreEqual(newCalendar.Hidden, createdCalendar.Hidden, "Hidden property should be equal");
                Assert.AreEqual(newCalendar.Color, createdCalendar.Color, "Color property should be equal");
                Assert.AreEqual(newCalendar.Location.ValueString, createdCalendar.Location.ValueString, "Where should be equal");

                createdCalendar.Title.Text = "renamed calendar" + Guid.NewGuid().ToString();
                createdCalendar.Hidden = true;
                CalendarEntry updatedCalendar = (CalendarEntry) createdCalendar.Update();

                Assert.AreEqual(createdCalendar.Title.Text, updatedCalendar.Title.Text, "entry should have been updated");

                updatedCalendar.Delete();

                CalendarQuery query = new CalendarQuery();
                query.Uri = postUri;

                CalendarFeed calendarList = service.Query(query);

                foreach (CalendarEntry entry in calendarList.Entries)
                {
                    Assert.IsTrue(entry.Title.Text != updatedCalendar.Title.Text, "Calendar should have been removed");
                }


                service.Credentials = null;
            }

        }
Exemple #6
0
 public GDataTypes.GDataCalendarEntry CreateCalendarEntry(CalendarEntry calendarEntry)
 {
     var _gDataCalendarEntry = new GDataTypes.GDataCalendarEntry();
     if (calendarEntry.Title.Text != null)
     {
         _gDataCalendarEntry.Name = calendarEntry.Title.Text;
     }
     if (calendarEntry.Color != null)
     {
         _gDataCalendarEntry.Color = calendarEntry.Color;
     }
     if (calendarEntry.Summary != null)
     {
         _gDataCalendarEntry.Description = calendarEntry.Summary.Text;
     }
     if (calendarEntry.Location != null)
     {
         _gDataCalendarEntry.Location = calendarEntry.Location.ValueString;
     }
     _gDataCalendarEntry.Hidden = calendarEntry.Hidden;
     _gDataCalendarEntry.Selected = calendarEntry.Selected;
     if (calendarEntry.TimeZone != null)
     {
         _gDataCalendarEntry.TimeZone = calendarEntry.TimeZone;
     }
     if (calendarEntry.AccessLevel != null)
     {
         _gDataCalendarEntry.AccessLevel = calendarEntry.AccessLevel;
     }
     if (calendarEntry.SelfUri.ToString() != null)
     {
         _gDataCalendarEntry.SelfUri = calendarEntry.SelfUri.ToString();
     }
     return _gDataCalendarEntry;
 }
        public static void AddMenuButton()
        {
            //string googleAcc = "*****@*****.**", googlePWD = "<Cg4&YYN";
            string googleAcc = "*****@*****.**", googlePWD = "A123456&";

            var accessHelper = new FISCA.UDT.AccessHelper();
            var ribbonBarItem = K12.Presentation.NLDPanels.Course.RibbonBarItems["課程行事曆"];
            var syncButton = ribbonBarItem["同步修課學生"];

            Catalog button_syncCalendar = RoleAclSource.Instance["課程"]["功能按鈕"];
            button_syncCalendar.Add(new RibbonFeature("Sync_Course_Calendar_Student", "同步修課學生"));
            bool isEnabled = UserAcl.Current["Sync_Course_Calendar_Student"].Executable;

            syncButton.Enable = isEnabled;
            K12.Presentation.NLDPanels.Course.SelectedSourceChanged += delegate(object sender, EventArgs e)
            {
                syncButton.Enable = ((K12.Presentation.NLDPanels.Course.SelectedSource.Count > 0) && isEnabled);
            };

            //syncButton.Enable = false;
            //K12.Presentation.NLDPanels.Course.SelectedSourceChanged += delegate(object sender, EventArgs e)
            //{
            //    syncButton.Enable = K12.Presentation.NLDPanels.Course.SelectedSource.Count > 0;
            //};
            syncButton.Click += delegate
            {
                bool hasFaild = false;
                FISCA.Presentation.MotherForm.SetStatusBarMessage("修課學生行事曆同步中...", 0);
                List<string> selectedSource = new List<string>(K12.Presentation.NLDPanels.Course.SelectedSource);
                BackgroundWorker bkw = new System.ComponentModel.BackgroundWorker() { WorkerReportsProgress = true };
                bkw.ProgressChanged += delegate(object sender, ProgressChangedEventArgs e)
                {
                    FISCA.Presentation.MotherForm.SetStatusBarMessage("修課學生行事曆同步中...", e.ProgressPercentage);
                };
                bkw.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e)
                {
                    SectionSyncColumn.Reload();
                    FISCA.Presentation.MotherForm.SetStatusBarMessage("修課學生行事曆同步完成");
                    if (hasFaild)
                    {
                        FISCA.Presentation.Controls.MsgBox.Show("修課學生行事曆同步完成,其中部分資同步失敗,請稍後再試。");
                    }
                };
                bkw.DoWork += delegate
                {
                    int count = 0;
                    int syncedSections = 0;
                    Dictionary<string, List<string>> courseAttend = new Dictionary<string, List<string>>();

                    //foreach (var item in K12.Data.SCAttend.SelectByCourseIDs(selectedSource))

                    AccessHelper helper = new AccessHelper();
                    string condition2 = "ref_course_id in (";
                    foreach (string key in selectedSource)
                    {
                        if (condition2 != "ref_course_id in (")
                            condition2 += ",";
                        condition2 += "'" + key + "'";
                    }
                    condition2 += ")";

                    foreach (var item in helper.Select<SCAttendExt>(condition2))
                    {
                        if (!courseAttend.ContainsKey(item.CourseID.ToString()))
                            courseAttend.Add(item.CourseID.ToString(), new List<string>());
                        courseAttend[item.CourseID.ToString()].Add(item.StudentID.ToString());
                        count++;
                    }

                    Dictionary<string, Calendar> courseCalendar = new Dictionary<string, Calendar>();
                    string condition = "RefCourseID in (";
                    foreach (string key in selectedSource)
                    {
                        if (condition != "RefCourseID in (")
                            condition += ",";
                        condition += "'" + key + "'";
                    }
                    condition += ")";
                    foreach (Calendar cal in accessHelper.Select<Calendar>(condition))
                    {
                        if (!courseCalendar.ContainsKey(cal.RefCourseID))
                            courseCalendar.Add(cal.RefCourseID, cal);
                    }
                    bkw.ReportProgress(5);
                    CalendarService myService = new CalendarService("ischool.CourseCalendar");
                    myService.setUserCredentials(googleAcc, googlePWD);
                    bkw.ReportProgress(20);
                    foreach (K12.Data.CourseRecord course in K12.Data.Course.SelectByIDs(courseAttend.Keys))
                    {
                        Calendar targetCal = null;
                        try
                        {
                            if (!courseCalendar.ContainsKey(course.ID))
                            {
                                #region 建立新Calender
                                string[] colorLists = new string[]{"#A32929","#B1365F","#7A367A","#5229A3","#29527A","#2952A3","#1B887A",
                            "#28754E","#0D7813","#528800","#88880E","#AB8B00","#BE6D00","#B1440E",
                            "#865A5A","#705770","#4E5D6C","#5A6986","#4A716C","#6E6E41","#8D6F47"};
                                CalendarEntry newCal = new CalendarEntry();
                                newCal.Title.Text = course.Name;
                                newCal.Summary.Text = "科目:" + course.Subject
                                    + "\n學年度:" + course.SchoolYear
                                    + "\n學期:" + course.Semester
                                    + "\n學分數:" + course.Credit;
                                newCal.TimeZone = "Asia/Taipei";
                                //targetCalender.Hidden = false;
                                newCal.Color = colorLists[new Random(DateTime.Now.Millisecond).Next(0, colorLists.Length)];
                                Uri postUri = new Uri("http://www.google.com/calendar/feeds/default/owncalendars/full");
                                newCal = (CalendarEntry)myService.Insert(postUri, newCal);
                                #endregion
                                String calendarURI = newCal.Id.Uri.ToString();
                                String calendarID = calendarURI.Substring(calendarURI.LastIndexOf("/") + 1);
                                targetCal = new Calendar() { RefCourseID = course.ID, GoogleCalanderID = calendarID };
                                targetCal.Save();
                                courseCalendar.Add(course.ID, targetCal);
                            }
                            else
                            {
                                targetCal = courseCalendar[course.ID];
                            }
                        }
                        catch { hasFaild = true; }
                        if (targetCal != null)
                        {
                            List<string> aclList = new List<string>(targetCal.ACLList.Split("%".ToCharArray(), StringSplitOptions.RemoveEmptyEntries));
                            foreach (var student in K12.Data.Student.SelectByIDs(courseAttend[course.ID]))
                            {
                                try
                                {
                                    if (student.SALoginName != "" && !aclList.Contains(student.SALoginName))
                                    {
                                        #region 新增分享
                                        AclEntry entry = new AclEntry();
                                        entry.Scope = new AclScope();
                                        entry.Scope.Type = AclScope.SCOPE_USER;
                                        entry.Scope.Value = student.SALoginName;
                                        entry.Role = AclRole.ACL_CALENDAR_READ;
                                        try
                                        {
                                            AclEntry insertedEntry = myService.Insert(new Uri("https://www.google.com/calendar/feeds/" + targetCal.GoogleCalanderID + "/acl/full"), entry);
                                        }
                                        catch (GDataRequestException gex)
                                        {
                                            if (!gex.InnerException.Message.Contains("(409)"))
                                                throw;
                                        }
                                        #endregion
                                        aclList.Add(student.SALoginName);
                                        targetCal.ACLList += (targetCal.ACLList == "" ? "" : "%") + student.SALoginName;
                                    }
                                }
                                catch
                                {
                                    hasFaild = true;
                                }
                                syncedSections++;
                                int p = syncedSections * 80 / count + 20;
                                if (p > 100) p = 100;
                                if (p < 0) p = 0;
                                bkw.ReportProgress(p);
                            }
                        }
                    }
                    courseCalendar.Values.SaveAll();
                };
                bkw.RunWorkerAsync();
            };
        }
Exemple #8
0
 /// <summary>
 /// Solve conflict by comparing last modified time
 /// </summary>
 /// <param name="addToLocal">List of GGItems to be added to local GGList</param>
 /// <param name="removeFromLocal">List of GGItems to be removed from local GGList</param>
 /// <param name="GGService">Google calendar service object</param>
 /// <param name="GGCalendar">GG calendar</param>
 /// <param name="ggItem">The local GGItem to be compared</param>
 /// <param name="theEvent">The Google event to be compared</param>
 private void SolveConflict(List<GGItem> addToLocal, List<GGItem> removeFromLocal, CalendarService GGService, CalendarEntry GGCalendar, GGItem ggItem, AtomEntry theEvent)
 {
     if (theEvent.Updated.CompareTo(ggItem.GetLastModifiedTime()) < 0)
     {   // Local is the latest version : delete on server, then add the latest one
         Log("Local is the latest");
         theEvent.Delete();
         Log("Delete on server");
         ggItem.SetEventAbsoluteUrl(AddGGEvent(GGService, GGCalendar, ggItem));
         Log("Add to server: " + ggItem.ToString());
     }
     else
     {   // Server is the latest version : delete on local, then add the latest one
         Log("Server is the latest");
         EventEntry e = (EventEntry)theEvent;
         GGItem newGGItem = new GGItem(e.Title.Text, e.Times[0].EndTime, ExtractTagFromContents(e.Content.Content), DateTime.Parse(e.Updated.ToLongTimeString()), e.Id.AbsoluteUri, ExtractPathFromContents(e.Content.Content));
         removeFromLocal.Add(ggItem);
         addToLocal.Add(newGGItem);
         Log("Update to lsocal: " + newGGItem.ToString());
     }
 }
Exemple #9
0
        /// <summary>
        /// Sync local GGItem to GG calendar
        /// </summary>
        /// <param name="addToLocal">List of GGItems to be added to local GGList</param>
        /// <param name="removeFromLocal">List of GGItems to be removed from local GGList</param>
        /// <param name="GGService">Google calendar service object</param>
        /// <param name="GGCalendar">GG calendar</param>
        /// <param name="GGEvents">Google event query results</param>
        /// <param name="server">List of bools to indicate if a Google event has a local version</param>
        /// <param name="ggItem">The local GGItem to be synced</param>
        private void SyncFromLocalToServer(List<GGItem> addToLocal, List<GGItem> removeFromLocal, CalendarService GGService, CalendarEntry GGCalendar, EventFeed GGEvents, List<bool> server, GGItem ggItem)
        {
            if (ggItem.GetEventAbsoluteUrl() == String.Empty)
            {   // Not synced : add to GG Calendar
                Log("Never synced");
                ggItem.SetEventAbsoluteUrl(AddGGEvent(GGService, GGCalendar, ggItem));
                Log("Add to server: " + ggItem.ToString());
            }
            else
            {   // Synced before
                Log("Synced before");
                string id = ggItem.GetEventAbsoluteUrl();

                // Find the coresponding Google event
                AtomEntry theEvent = FindGoogleEvent(GGEvents, server, id);

                if (theEvent == null)
                {   // Not found: deleted on GG calendar : remove from local list
                    Log("Event is deleted on server");
                    removeFromLocal.Add(ggItem);
                    Log("Removed in local list");
                }
                else
                {   // Found
                    SolveConflict(addToLocal, removeFromLocal, GGService, GGCalendar, ggItem, theEvent);
                }
            }
        }
Exemple #10
0
        /// <summary>
        /// Create GG calendar
        /// </summary>
        /// <param name="GGService">Google calendar service object</param>
        /// <returns>created GG calendar</returns>
        private CalendarEntry CreateGGCalendar(CalendarService GGService)
        {
            // Create a new calendar object and specify details
            CalendarEntry calendar = new CalendarEntry();
            calendar.Title.Text = GG_CALENDAR_TITLE;
            calendar.Summary.Text = GG_CALENDAR_SUMMARY;
            calendar.TimeZone = GG_CALENDAR_TIMEZONE;
            calendar.Hidden = GG_CALENDAR_HIDDEN;
            calendar.Color = GG_CALENDAR_COLOR;
            calendar.Location = new Where("", "", GG_CALENDAR_LOCATION);

            // Create on Google Calendar
            Uri postUri = new Uri(CALENDAR_QUERY_URL);
            CalendarEntry createdCalendar = (CalendarEntry)GGService.Insert(postUri, calendar);

            Log("Create calendar: " + createdCalendar.Title.Text + "\n");

            // return created calendar
            return createdCalendar;
        }
Exemple #11
0
        /// <summary>
        /// Prepare for synchronization
        /// </summary>
        /// <param name="ggList">Local GGList</param>
        /// <param name="addToLocal">List of GGItems to be added to local GGList</param>
        /// <param name="removeFromLocal">List of GGItems to be removed from local GGList</param>
        /// <param name="GGService">Google calendar service object</param>
        /// <param name="GGCalendar">GG calendar</param>
        /// <param name="GGEvents">Google event query results</param>
        /// <param name="server">List of bools to indicate if a Google event has a local version</param>
        /// <param name="toBeSyncedList">List of GGItems to be synced</param>
        /// <param name="toBeDeletedList">List of GGItems to be deleted on Google calendar</param>
        private void PrepareForSync(GGList ggList, out List<GGItem> addToLocal, out List<GGItem> removeFromLocal, out CalendarService GGService, out CalendarEntry GGCalendar, out EventFeed GGEvents, out List<bool> server, out List<GGItem> toBeSyncedList, out List<GGItem> toBeDeletedList)
        {
            // List of GGItems to be add to local GGList
            addToLocal = new List<GGItem>();
            // List of GGItems to be removed from local GGList
            removeFromLocal = new List<GGItem>();

            // Create Google calendar service object
            GGService = new CalendarService("GG");
            // Set credentials
            GGService.setUserCredentials(username, password);

            // Select GG calendar, create one if not exists
            GGCalendar = SelectGGCalendar(GGService);
            if (GGCalendar == null)
            {
                GGCalendar = CreateGGCalendar(GGService);
            }

            Log("operate on calender: " + GGCalendar.Title.Text);

            // Query and get all events on GG calendar
            EventQuery q = new EventQuery();
            q.Uri = new Uri("https://www.google.com/calendar/feeds/" + GGCalendar.Id.AbsoluteUri.Substring(63) + "/private/full");
            GGEvents = GGService.Query(q);

            // True if a Google event has a coresponding GGItem
            server = new List<bool>();
            for (int i = 0; i < GGEvents.Entries.Count; i++)
            {
                server.Add(false);
            }

            toBeSyncedList = ggList.GetInnerList();
            toBeDeletedList = ggList.GetDeletedList();
        }
Exemple #12
0
        /// <summary>
        /// Add a local event to Google Calendar
        /// </summary>
        /// <param name="GGService">Google calendar service object</param>
        /// <param name="GGCalendar">GG calendar object</param>
        /// <param name="myGGItem">GGItem object to be added to GG calendar</param>
        /// <returns>Google event's ID</returns>
        private string AddGGEvent(CalendarService GGService, CalendarEntry GGCalendar, GGItem myGGItem)
        {
            // Create a event object
            EventEntry entry = new EventEntry();

            // Use description as event title (necessary)
            entry.Title.Text = myGGItem.GetDescription();
            // Use tag as event content (optional)
            entry.Content.Content = myGGItem.GetTag() + " | " + myGGItem.GetPath();

            // Set event start and end time
            if (myGGItem.GetEndDate().CompareTo(GGItem.DEFAULT_ENDDATE) != 0)
            {   // Specified endDate
                // Use endDate - 2hours as start time and endDate as end time
                When eventTime = new When(myGGItem.GetEndDate().AddHours(-2), myGGItem.GetEndDate());
                entry.Times.Add(eventTime);
            }
            else
            {   // Default endDate
                // Treat as tasks, set due date as 3 days later
                When eventTime = new When(DateTime.Today, DateTime.Today.AddDays(3));
                entry.Times.Add(eventTime);
            }

            // Log(entry.Updated.ToLongDateString());

            // Set email reminder: 15 minutes before end time
            Reminder GGReminder = new Reminder();
            GGReminder.Minutes = 15;
            GGReminder.Method = Reminder.ReminderMethod.email;
            entry.Reminders.Add(GGReminder);

            // Create the event on Google Calendar
            Uri postUri = new Uri("https://www.google.com/calendar/feeds/" + GGCalendar.Id.AbsoluteUri.Substring(63) + "/private/full");
            AtomEntry insertedEntry = GGService.Insert(postUri, entry);

            // Return the event's ID
            return insertedEntry.Id.AbsoluteUri;
        }
 private static string addNewCalender(string refid)
 {
     CalendarService myService = new CalendarService("ischool.CourseCalendar");
     myService.setUserCredentials(googleAcc, googlePWD);
     #region 建立新Calender
     string[] colorLists = new string[]{"#A32929","#B1365F","#7A367A","#5229A3","#29527A","#2952A3","#1B887A",
                     "#28754E","#0D7813","#528800","#88880E","#AB8B00","#BE6D00","#B1440E",
                     "#865A5A","#705770","#4E5D6C","#5A6986","#4A716C","#6E6E41","#8D6F47"};
     CalendarEntry newCal = new CalendarEntry();
     newCal.Title.Text = "TEST" + DateTime.Now.ToShortTimeString();
     newCal.TimeZone = "Asia/Taipei";
     newCal.Color = colorLists[new Random(DateTime.Now.Millisecond).Next(0, colorLists.Length)];
     Uri postUri = new Uri("http://www.google.com/calendar/feeds/default/owncalendars/full");
     newCal = (CalendarEntry)myService.Insert(postUri, newCal);
     #endregion
     String calendarURI = newCal.Id.Uri.ToString();
     String calendarID = calendarURI.Substring(calendarURI.LastIndexOf("/") + 1);
     return calendarID;
 }
Exemple #14
0
            protected override void ProcessRecord()
            {
                var _domain = dgcGoogleCalendarService.GetDomain(service.CalendarService);

                var _calendar = new CalendarEntry();
                _calendar.Title.Text = calendarName;

                if (description != null)
                {
                    _calendar.Summary.Text = description;
                }
                if (timeZone != null)
                {
                    _calendar.TimeZone = timeZone;
                }
                try
                {
                    if (service.Oauth == null)
                    {
                        throw new Exception("User -ConsumerKey/-ConsumerSecret in New-GdataService");
                    }
                    if (service.OauthCalendarService == null)
                    {
                        throw new Exception("User -ConsumerKey/-ConsumerSecret in New-GdataService");
                    }
                    var _postUri = new Uri("http://www.google.com/calendar/feeds/default/owncalendars/full");
                    var _oAuth2LeggedAuthenticator = new OAuth2LeggedAuthenticator("GDataCmdLet", service.Oauth.ConsumerKey, service.Oauth.ConsumerSecret, id, _domain);
                    var _oAuthUri = _oAuth2LeggedAuthenticator.ApplyAuthenticationToUri(_postUri);

                    var _createdCalendar = (CalendarEntry)service.OauthCalendarService.Insert(_oAuthUri, _calendar);
                    var _calendarEntry = dgcGoogleCalendarService.CreateCalendarEntry(_createdCalendar);
                    WriteObject(_calendarEntry);

                } catch (Exception _exception)
                {
                    WriteObject(_exception);
                }
            }
        public static void AddMenuButton()
        {
            var accessHelper = new FISCA.UDT.AccessHelper();
            var ribbonBarItem = K12.Presentation.NLDPanels.Course.RibbonBarItems["課程行事曆"];
            var syncButton = ribbonBarItem["同步行事曆"];

            Catalog button_syncCalendar = RoleAclSource.Instance["課程"]["功能按鈕"];
            button_syncCalendar.Add(new RibbonFeature("Sync_Course_Calendar", "同步課程行事曆"));
            bool isEnabled = UserAcl.Current["Sync_Course_Calendar"].Executable;

            syncButton.Enable = ((K12.Presentation.NLDPanels.Course.SelectedSource.Count > 0) && isEnabled);
            K12.Presentation.NLDPanels.Course.SelectedSourceChanged += delegate(object sender, EventArgs e)
            {

                syncButton.Enable = ((K12.Presentation.NLDPanels.Course.SelectedSource.Count > 0) && isEnabled);
            };
            syncButton.Click += delegate
            {
                bool hasFaild = false;
                FISCA.Presentation.MotherForm.SetStatusBarMessage("課程行事曆同步中...", 0);
                List<string> selectedSource = new List<string>(K12.Presentation.NLDPanels.Course.SelectedSource);
                BackgroundWorker bkw = new System.ComponentModel.BackgroundWorker() { WorkerReportsProgress = true };
                bkw.ProgressChanged += delegate(object sender, ProgressChangedEventArgs e)
                {
                    FISCA.Presentation.MotherForm.SetStatusBarMessage("課程行事曆同步中...", e.ProgressPercentage);
                };
                bkw.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e)
                {
                    SectionSyncColumn.Reload();
                    FISCA.Presentation.MotherForm.SetStatusBarMessage("課程行事曆同步完成");
                    if (hasFaild)
                    {
                        FISCA.Presentation.Controls.MsgBox.Show("課程行事曆同步完成,其中部分資料同步失敗,請稍後再試。");
                    }
                };
                bkw.DoWork += delegate(object sender, DoWorkEventArgs e)
                {
                    Dictionary<string, Calendar> calendars = new Dictionary<string, Calendar>();
                    Dictionary<string, List<string>> courseAttend = new Dictionary<string, List<string>>();
                    Dictionary<string, List<Section>> publishItems = new Dictionary<string, List<Section>>();
                    Dictionary<string, string> studentLoginAccount = new Dictionary<string, string>();
                    List<string> syncCourses = new List<string>();
                    int count = 0;
                    string condition = "RefCourseID in (";
                    foreach (string key in selectedSource)
                    {
                        if (condition != "RefCourseID in (")
                            condition += ",";
                        condition += "'" + key + "'";
                    }
                    condition += ")";
                    string condition2 = "ref_course_id in (";
                    foreach (string key in selectedSource)
                    {
                        if (condition2 != "ref_course_id in (")
                            condition2 += ",";
                        condition2 += "'" + key + "'";
                    }
                    condition2 += ")";
                    bkw.ReportProgress(3);
                    foreach (Section section in accessHelper.Select<Section>(condition))
                    {
                        if (!section.IsPublished || section.Removed)
                        {
                            if (!publishItems.ContainsKey(section.RefCourseID))
                                publishItems.Add(section.RefCourseID, new List<Section>());
                            publishItems[section.RefCourseID].Add(section);
                            count++;
                        }
                    }
                    foreach (Calendar cal in accessHelper.Select<Calendar>(condition))
                    {
                        if (!calendars.ContainsKey(cal.RefCourseID))
                            calendars.Add(cal.RefCourseID, cal);
                    }
                    syncCourses.AddRange(publishItems.Keys);
                    foreach (var item in accessHelper.Select<SCAttendExt>(condition2))
                    {
                        if (!courseAttend.ContainsKey(item.CourseID.ToString()))
                            courseAttend.Add(item.CourseID.ToString(), new List<string>());
                        courseAttend[item.CourseID.ToString()].Add(item.StudentID.ToString());
                        if (!studentLoginAccount.ContainsKey(item.StudentID.ToString()))
                            studentLoginAccount.Add(item.StudentID.ToString(), "");
                        count++;
                    }
                    foreach (string key in selectedSource)
                    {
                        if (!courseAttend.ContainsKey(key))
                            courseAttend.Add(key, new List<string>());
                    }
                    foreach (var student in K12.Data.Student.SelectByIDs(studentLoginAccount.Keys))
                    {
                        if (student.SALoginName != "")
                        {
                            studentLoginAccount[student.ID] = student.SALoginName.ToLower();
                        }
                    }
                    foreach (string calid in courseAttend.Keys)
                    {
                        if (calendars.ContainsKey(calid))
                        {
                            Calendar cal = calendars[calid];
                            List<string> aclList = new List<string>(cal.ACLList.Split("%".ToCharArray(), StringSplitOptions.RemoveEmptyEntries));
                            List<string> attentAccounts = new List<string>();
                            foreach (string sid in courseAttend[calid])
                            {
                                if (studentLoginAccount[sid] != "")
                                    attentAccounts.Add(studentLoginAccount[sid]);
                            }
                            if (aclList.Count != attentAccounts.Count)
                            {
                                if (!syncCourses.Contains(calid))
                                    syncCourses.Add(calid);
                            }
                            else
                            {
                                foreach (string acc in aclList)
                                {
                                    if (!attentAccounts.Contains(acc.ToLower()))
                                    {
                                        if (!syncCourses.Contains(calid))
                                            syncCourses.Add(calid);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    bkw.ReportProgress(5);
                    CalendarService myService = new CalendarService("ischool.CourseCalendar");
                    myService.setUserCredentials(googleAcc, googlePWD);
                    bkw.ReportProgress(20);
                    List<Section> syncedSections = new List<Section>();
                    foreach (K12.Data.CourseRecord course in K12.Data.Course.SelectByIDs(syncCourses))
                    {
                        //CalendarEntry targetCalender = null;
                        Calendar targetCal = null;
                        try
                        {
                            if (!calendars.ContainsKey(course.ID))
                            {
                                #region 建立新Calender
                                string[] colorLists = new string[]{"#A32929","#B1365F","#7A367A","#5229A3","#29527A","#2952A3","#1B887A",
                            "#28754E","#0D7813","#528800","#88880E","#AB8B00","#BE6D00","#B1440E",
                            "#865A5A","#705770","#4E5D6C","#5A6986","#4A716C","#6E6E41","#8D6F47"};
                                CalendarEntry newCal = new CalendarEntry();
                                newCal.Title.Text = course.Name;
                                newCal.Summary.Text = "科目:" + course.Subject
                                    + "\n學年度:" + course.SchoolYear
                                    + "\n學期:" + course.Semester
                                    + "\n學分數:" + course.Credit;
                                newCal.TimeZone = "Asia/Taipei";
                                //targetCalender.Hidden = false;
                                newCal.Color = colorLists[new Random(DateTime.Now.Millisecond).Next(0, colorLists.Length)];
                                Uri postUri = new Uri("http://www.google.com/calendar/feeds/default/owncalendars/full");
                                newCal = (CalendarEntry)myService.Insert(postUri, newCal);
                                #endregion
                                String calendarURI = newCal.Id.Uri.ToString();
                                String calendarID = calendarURI.Substring(calendarURI.LastIndexOf("/") + 1);
                                targetCal = new Calendar() { RefCourseID = course.ID, GoogleCalanderID = calendarID };
                                targetCal.Save();
                            }
                            else
                            {
                                targetCal = calendars[course.ID];
                            }
                        }
                        catch
                        {
                            hasFaild = true;
                        }
                        if (targetCal != null)
                        {
                            try
                            {
                                #region ACL
                                if (courseAttend.ContainsKey(course.ID))
                                {
                                    List<string> aclList = new List<string>(targetCal.ACLList.Split("%".ToCharArray(), StringSplitOptions.RemoveEmptyEntries));
                                    for (int i = 0; i < aclList.Count; i++)
                                    {
                                        aclList[i] = aclList[i].ToLower();
                                    }
                                    List<string> attentAccounts = new List<string>();
                                    foreach (string sid in courseAttend[course.ID])
                                    {
                                        if (studentLoginAccount[sid] != "")
                                            attentAccounts.Add(studentLoginAccount[sid]);
                                    }
                                    foreach (string acc in attentAccounts)
                                    {
                                        if (!aclList.Contains(acc))
                                        {
                                            try
                                            {
                                                #region 新增分享
                                                AclEntry entry = new AclEntry();
                                                entry.Scope = new AclScope();
                                                entry.Scope.Type = AclScope.SCOPE_USER;
                                                entry.Scope.Value = acc;
                                                entry.Role = AclRole.ACL_CALENDAR_READ;
                                                try
                                                {
                                                    AclEntry insertedEntry = myService.Insert(new Uri("https://www.google.com/calendar/feeds/" + targetCal.GoogleCalanderID + "/acl/full"), entry);
                                                }
                                                catch (GDataRequestException gex)
                                                {
                                                    if (!gex.InnerException.Message.Contains("(409)"))
                                                        throw;
                                                }
                                                #endregion
                                                aclList.Add(acc);
                                            }
                                            catch
                                            {
                                                hasFaild = true;
                                            }
                                        }
                                    }
                                    List<string> removeList = new List<string>();
                                    if (aclList.Count != attentAccounts.Count)
                                    {
                                        #region 移除分享
                                        AtomFeed calFeed = myService.Query(new FeedQuery("https://www.google.com/calendar/feeds/" + targetCal.GoogleCalanderID + "/acl/full"));
                                        foreach (string acc in aclList)
                                        {
                                            if (!attentAccounts.Contains(acc))
                                            {
                                                try
                                                {
                                                    foreach (AtomEntry atomEntry in calFeed.Entries)
                                                    {
                                                        if (atomEntry is AtomEntry)
                                                        {
                                                            AclEntry aclEntry = (AclEntry)atomEntry;
                                                            if (aclEntry.Scope.Value.ToLower() == acc)
                                                            {
                                                                aclEntry.Delete();
                                                                break;
                                                            }
                                                        }
                                                    }
                                                    removeList.Add(acc);
                                                }
                                                catch
                                                {
                                                    hasFaild = true;
                                                }
                                            }
                                        }
                                        #endregion
                                    }
                                    foreach (string acc in removeList)
                                    {
                                        if (aclList.Contains(acc)) aclList.Remove(acc);
                                    }
                                    targetCal.ACLList = "";
                                    foreach (string acc in aclList)
                                    {
                                        targetCal.ACLList += (targetCal.ACLList == "" ? "" : "%") + acc;
                                    }
                                }
                                #endregion
                                #region Events
                                if (publishItems.ContainsKey(course.ID))
                                {
                                    EventFeed feed = myService.Query(new EventQuery("https://www.google.com/calendar/feeds/" + targetCal.GoogleCalanderID + "/private/full"));
                                    AtomFeed batchFeed = new AtomFeed(feed);
                                    foreach (Section section in publishItems[course.ID])
                                    {
                                        if (!section.Removed)
                                        {
                                            #region 新增Event
                                            Google.GData.Calendar.EventEntry eventEntry = new Google.GData.Calendar.EventEntry();

                                            eventEntry.Title.Text = course.Name;
                                            //eventEntry
                                            Where eventLocation = new Where();
                                            eventLocation.ValueString = section.Place;
                                            eventEntry.Locations.Add(eventLocation);
                                            eventEntry.Notifications = true;
                                            eventEntry.Times.Add(new When(section.StartTime, section.EndTime));
                                            eventEntry.Participants.Add(new Who()
                                            {
                                                ValueString = googleAcc,
                                                Attendee_Type = new Who.AttendeeType() { Value = Who.AttendeeType.EVENT_REQUIRED },
                                                Attendee_Status = new Who.AttendeeStatus() { Value = Who.AttendeeStatus.EVENT_ACCEPTED },
                                                Rel = Who.RelType.EVENT_ATTENDEE
                                            });
                                            eventEntry.BatchData = new GDataBatchEntryData(section.UID, GDataBatchOperationType.insert);
                                            batchFeed.Entries.Add(eventEntry);
                                            #endregion
                                        }
                                        else
                                        {
                                            #region 刪除Event

                                            EventEntry toDelete = (EventEntry)feed.Entries.FindById(new AtomId(feed.Id.AbsoluteUri + "/" + section.EventID));
                                            if (toDelete != null)
                                            {
                                                toDelete.Id = new AtomId(toDelete.EditUri.ToString());
                                                toDelete.BatchData = new GDataBatchEntryData(section.UID, GDataBatchOperationType.delete);
                                                batchFeed.Entries.Add(toDelete);
                                            }
                                            else
                                            {
                                                section.Deleted = true;
                                                syncedSections.Add(section);
                                            }
                                            #endregion
                                        }
                                        int p = syncedSections.Count * 80 / count + 20;
                                        if (p > 100) p = 100;
                                        if (p < 0) p = 0;
                                        bkw.ReportProgress(p);
                                    }
                                    EventFeed batchResultFeed = (EventFeed)myService.Batch(batchFeed, new Uri(feed.Batch));
                                    foreach (Section section in publishItems[course.ID])
                                    {
                                        if (syncedSections.Contains(section)) continue;
                                        #region 儲存Section狀態
                                        bool match = false;
                                        if (section.Removed)
                                        {
                                            foreach (EventEntry entry in batchResultFeed.Entries)
                                            {
                                                if (entry.BatchData.Status.Code == 200)
                                                {
                                                    if (section.UID == entry.BatchData.Id)
                                                    {
                                                        section.Deleted = true;
                                                        match = true;
                                                        syncedSections.Add(section);
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                        else
                                        {
                                            foreach (EventEntry entry in batchResultFeed.Entries)
                                            {
                                                if (entry.BatchData.Status.Code == 201)
                                                {
                                                    if (section.UID == entry.BatchData.Id)
                                                    {
                                                        section.IsPublished = true;
                                                        match = true;
                                                        section.EventID = entry.EventId;
                                                        syncedSections.Add(section);
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                        if (!match)
                                            hasFaild = true;
                                        #endregion
                                    }
                                }
                                #endregion
                            }
                            catch
                            {
                                hasFaild = true;
                            }
                            targetCal.Save();
                        }
                    }
                    syncedSections.SaveAll();
                };
                bkw.RunWorkerAsync();
            };
        }
        public void OAuth3LeggedAuthenticationTest()
        {
            Tracing.TraceMsg("Entering OAuth3LeggedAuthenticationTest");

            CalendarService service = new CalendarService("OAuthTestcode");

            GOAuthRequestFactory requestFactory = new GOAuthRequestFactory("cl", "OAuthTestcode");
            requestFactory.ConsumerKey = this.oAuthConsumerKey;
            requestFactory.ConsumerSecret = this.oAuthConsumerSecret;
            requestFactory.Token = this.oAuthToken;
            requestFactory.TokenSecret = this.oAuthTokenSecret;
            service.RequestFactory = requestFactory;

            CalendarEntry calendar = new CalendarEntry();
            calendar.Title.Text = "Test OAuth";

            Uri postUri = new Uri("https://www.google.com/calendar/feeds/default/owncalendars/full");
            CalendarEntry createdCalendar = (CalendarEntry)service.Insert(postUri, calendar);

            // delete the guy again

            createdCalendar.Delete();


        }