Пример #1
0
 public bool Insert(Task task)
 {
     EventEntry eventEntry = new EventEntry
                             {
                                 Title = {Text = task.Head},
                                 Content = {Content = task.Description,},
                                 Locations = {new Where("", "", task.Location)},
                                 Times = {new When(task.StartDate, task.StopDate)},
                             };
     Log.InfoFormat("Inserting new entry to google : [{0}]", task.ToString());
     CalendarService service = new CalendarService("googleCalendarInsert");
     service.setUserCredentials(task.AccountInfo.Username, task.AccountInfo.Password);
     Uri postUri = new Uri("https://www.google.com/calendar/feeds/default/private/full");
     ErrorMessage = String.Empty;
     try
     {
         EventEntry createdEntry = service.Insert(postUri, eventEntry);
         return createdEntry != null;
     }
     catch (Exception exception)
     {
         Log.ErrorFormat(exception.Message);
         Log.ErrorFormat(exception.ToString());
         ErrorMessage = exception.Message;
     }
     return false;
 }
Пример #2
0
 public bool Delete(Task task)
 {
     ErrorMessage = String.Empty;
     CalendarService service = new CalendarService("googleCalendar");
     service.setUserCredentials(task.AccountInfo.Username, task.AccountInfo.Password);
     Log.InfoFormat("Fetching google account : [{0}]", task.AccountInfo.ToString());
     string queryUri = String.Format(CultureInfo.InvariantCulture,
                                     "http://www.google.com/calendar/feeds/{0}/private/full",
                                     service.Credentials.Username);
     Log.DebugFormat("Query='{0}'", queryUri);
     EventQuery eventQuery = new EventQuery(queryUri);
     try
     {
         EventFeed eventFeed = service.Query(eventQuery);
         foreach (EventEntry eventEntry in eventFeed.Entries.Cast<EventEntry>())
         {
             if (eventEntry.Times.Count > 0)
             {
                 if (eventEntry.EventId == task.Id)
                 {
                     Log.InfoFormat("Deleting : [{0}]-[{1}]", eventEntry.EventId, eventEntry.Title);
                     eventEntry.Delete();
                     return true;
                 }
             }
         }
     }
     catch (Exception exception)
     {
         Log.ErrorFormat(exception.Message);
         Log.ErrorFormat(exception.ToString());
         ErrorMessage = exception.Message;
     }
     return false;
 }
Пример #3
0
 public CalendarManager(string email, string password)
 {
     _userID = email;
     _password = password;
     _myService = new CalendarService("Bruce's Application");
     _myService.setUserCredentials(_userID, _password);
 }
Пример #4
0
        public void googlecalendarSMSreminder(string sendstring)
        {
            CalendarService service = new CalendarService("exampleCo-exampleApp-1");
            service.setUserCredentials(UserName.Text, Password.Text);

            EventEntry entry = new EventEntry();

            // Set the title and content of the entry.
            entry.Title.Text = sendstring;
            entry.Content.Content = "Nadpis Test SMS.";
            // Set a location for the event.
            Where eventLocation = new Where();
            eventLocation.ValueString = "Test sms";
            entry.Locations.Add(eventLocation);

            When eventTime = new When(DateTime.Now.AddMinutes(3), DateTime.Now.AddHours(1));
            entry.Times.Add(eventTime);

            //Add SMS Reminder
            Reminder fiftyMinReminder = new Reminder();
            fiftyMinReminder.Minutes = 1;
            fiftyMinReminder.Method = Reminder.ReminderMethod.sms;
            entry.Reminders.Add(fiftyMinReminder);

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

            // Send the request and receive the response:
            AtomEntry insertedEntry = service.Insert(postUri, entry);
        }
Пример #5
0
 public BookThemAllSample(string domain, string admin, string password)
 {
     apps = new AppsService(domain, admin, password);
     calendar = new CalendarService("BookThemAll");
     calendar.setUserCredentials(admin, password);
     this.admin = admin;
 }
Пример #6
0
 public GoogleCalendar()
 {
     this.userName = GoogleUsername;
     this.userPassword = GooglePassword;
     calendarService = new CalendarService("webcsm");
     calendarService.setUserCredentials(userName, userPassword);
 }
Пример #7
0
        public void Authenticate(string account, string password)
        {
            _calendarService = new Google.GData.Calendar.CalendarService("");
            _calendarService.setUserCredentials(account, password);

            _calendarUri = new Uri(string.Format("https://www.google.com/calendar/feeds/{0}/private/full", account));
            _isAuthenticated = true;
        }
Пример #8
0
        public PostableEvents GetPostableEvents(string calendarId)
        {
            var result = new PostableEvents();

            var service = new CalendarService("WascherCom.Auto.CalendarToBlog");

            if (!string.IsNullOrWhiteSpace(UserId))
            {
                service.setUserCredentials(UserId, Password);
            }

            var query = new EventQuery
                {
                    Uri = new Uri(string.Format(GOOGLE_URI, calendarId)),
                    StartTime = StartDate.AddDays(-DaysForPastEvents),
                    EndTime = StartDate.AddDays(DaysForCurrentEvents + DaysForFutureEvents)
                };

            var eventFeed = service.Query(query);

            if (eventFeed == null || eventFeed.Entries.Count == 0)
            {
                return result;
            }

            foreach (EventEntry entry in eventFeed.Entries)
            {
                foreach (var time in entry.Times)
                {
                    var calEvent = new CalendarEvent
                        {
                            Title = entry.Title.Text,
                            Description = string.Empty,
                            StartDateTime = time.StartTime,
                            EndDateTime = time.EndTime,
                            IsAllDay = time.AllDay
                        };

                    if (calEvent.StartDateTime < StartDate)
                    {
                        result.PastEvents.Add(calEvent);
                    }
                    else if (calEvent.StartDateTime > StartDate.AddDays(DaysForCurrentEvents))
                    {
                        result.FutureEvents.Add(calEvent);
                    }
                    else
                    {
                        result.CurrentEvents.Add(calEvent);
                    }

                    Console.WriteLine(string.Format("{0}: {1} All Day: {2}", entry.Title.Text, time.StartTime, time.AllDay));
                }
            }

            return result;
        }
Пример #9
0
        public bool Init(string user, string password)
        {
            service = new CalendarService("GTrello");
            service.setUserCredentials(user, password);

            if (!LoadMapping())
            {
                return false;
            }
            return CollectEntries();
        }
Пример #10
0
        // Validates a username/pass by attempting to login to calendar
        public static bool checkPw(string username, string password)
        {
            GDataGAuthRequestFactory authFactory = new GDataGAuthRequestFactory("cl", "Seadragon");
            authFactory.AccountType = "HOSTED";

            CalendarService client = new CalendarService(authFactory.ApplicationName);
            client.RequestFactory = authFactory;
            client.setUserCredentials(username + "@" + DOMAIN, password);

            try
            {
                client.QueryClientLoginToken(); // Authenticate the user immediately
            }
            catch (WebException)     // Invalid login
            {
                return false;
            }

            return true;
        }
Пример #11
0
        public static void export(string email, string password, List<LeadTask> tasks)
        {
            CalendarService myService = new CalendarService("exportToGCalendar");
            myService.setUserCredentials(email, password);

            foreach (LeadTask task in tasks) {
                EventEntry entry = new EventEntry();

                // Set the title and content of the entry.
                entry.Title.Text = task.text;
                entry.Content.Content = task.details;

                When eventTime = new When((DateTime)task.start_date, (DateTime)task.end_date);
                entry.Times.Add(eventTime);

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

                // Send the request and receive the response:
                Google.GData.Client.AtomEntry insertedEntry = myService.Insert(postUri, entry);
            }
        }
Пример #12
0
        public async Task Delete(Guid userId, string eventId)
        {
            try
            {
                var item = _iSysUserService.GetById(userId);

                if (string.IsNullOrEmpty(item.GoogleUserName) || string.IsNullOrEmpty(item.GooglePassword)) return;
                var myService = new CalendarService(item.GoogleUserName);
                myService.setUserCredentials(item.GoogleUserName, item.GooglePassword);

                var calendar =
                    myService.Get("https://www.google.com/calendar/feeds/default/private/full/" + eventId);

                foreach (var item1 in calendar.Feed.Entries)
                {
                    item1.Delete();
                }
            }
            catch
            {
            }
        }
Пример #13
0
        public  async Task<string> Insert(Guid userId, string title, string content, DateTime start, DateTime end)
        {
            try
            {
                //同步到Google日历
                var item = _iSysUserService.GetById(userId);

                if (string.IsNullOrEmpty(item.GoogleUserName) || string.IsNullOrEmpty(item.GooglePassword)) return "";

                var myService = new CalendarService(item.GoogleUserName);
                myService.setUserCredentials(item.GoogleUserName, item.GooglePassword);

                // Set the title and content of the entry.
                var entry = new EventEntry
                {
                    Title = { Text = "云集 " + title },
                    Content = { Content = content }
                };

                //计划时间
                var eventTime = new When(start, end);

                //判断是否为全天计划
                if (start.Date != end.Date)
                    eventTime.AllDay = true;

                entry.Times.Add(eventTime);

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

                // Send the request and receive the response:
                var eventEntry = myService.Insert(postUri, entry);
                return eventEntry.EventId;
            }
            catch
            {
                return "";
            }
        }
Пример #14
0
        static void Main(string[] args)
        {
            //
            // TODO: Add code to start application here
            //
            if (args.Length != 1 && args.Length != 3)
            {
                Console.WriteLine("Not enough parameters. Usage is Sample <uri> <username> <password>");
                return;
            }

            string calendarURI = args[0];

            string userName = args.Length == 3 ? args[1] : null;
            string passWord = args.Length == 3 ? args[2] : null;

            EventQuery query = new EventQuery();
            CalendarService service = new CalendarService(ApplicationName);

            if (userName != null)
            {
                service.setUserCredentials(userName, passWord);
            }

            query.Uri = new Uri(calendarURI);
            EventFeed calFeed = service.Query(query) as EventFeed;

            Console.WriteLine("");
            Console.WriteLine("Query Feed Test " + query.Uri);

            Console.WriteLine("Post URI is:  " + calFeed.Post); 

            foreach (EventEntry feedEntry in calFeed.Entries)
            {
                DumpEventEntry(feedEntry);
            }
        }
Пример #15
0
        static void Main(string[] args)
        {
            //
            // TODO: Add code to start application here
            //
            if (args.Length < 3)
            {
                Console.WriteLine("Not enough parameters. Usage is Sample <uri> <username> <password>");
                return;
            }

            string calendarURI = args[0];
            string userName = args[1];
            string passWord = args[2];

            EventQuery query = new EventQuery();
            CalendarService service = new CalendarService(ApplicationName);

            if (userName != null)
            {
                service.setUserCredentials(userName, passWord);
            }

            query.Uri = new Uri(calendarURI);
            EventFeed calFeed = service.Query(query);

            EventEntry insertedEntry = InsertEvent(calFeed, "Conference www2006",
                "Frank Mantek", DateTime.Now, 
                                DateTime.Now.AddDays(1), 
                                true,
                                "Edinburgh");

            if (insertedEntry != null) 
            {
                DumpEventEntry(insertedEntry);
            }
        }
Пример #16
0
        static void Main(string[] args)
        {
            //
            // TODO: Add code to start application here
            //
            if (args.Length < 3)
            {
                Console.WriteLine("Not enough parameters. Usage is Sample <uri> <username> <password>");
                return;
            }

            string calendarURI = args[0];
            string userName = args[1];
            string passWord = args[2];

            EventQuery query = new EventQuery();
            CalendarService service = new CalendarService(ApplicationName);

            if (userName != null)
            {
                service.setUserCredentials(userName, passWord);
            }

            query.Uri = new Uri(calendarURI);
            EventFeed calFeed = service.Query(query) as EventFeed;

 			foreach (EventEntry entry in calFeed.Entries)
            {
            	if (entry.Title.Text == "Conference www2006") 
            	{
                	entry.Content.Content = "The conference was fun... ";
                	entry.Update();
                	Console.WriteLine("Updated the Conference entry"); 
                }
            }
        }
        private CalendarService GetCalendarService(EventQuery query, string eventId, DateTime startDateTime, DateTime endDateTime)
        {
            query.Uri = CalendarUri;
            query.Uri = new Uri(string.Concat(query.Uri.ToString(), !string.IsNullOrEmpty(eventId) ? string.Concat("/", eventId) : string.Empty));

            query.StartTime = startDateTime;
            query.EndTime = endDateTime;

            var calendarService = new CalendarService(_applicationName);
            calendarService.setUserCredentials(_googleUsername, _googlePassword);
            calendarService.QueryClientLoginToken();
            return calendarService;
        }
Пример #18
0
        private void RefreshFeed()
        {
            string calendarURI = this.CalendarURI.Text;
            string userName =    this.UserName.Text;
            string passWord =    this.Password.Text;

            this.entryList = new ArrayList(50);
            ArrayList dates = new ArrayList(50);
            EventQuery query = new EventQuery();
            CalendarService service = new CalendarService("CalendarSampleApp");

            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);

            query.StartTime = DateTime.Now.AddDays(-28);
            query.EndTime = DateTime.Now.AddMonths(6);

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

            // now populate the calendar
            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;
        }
        protected override void ProcessRecord()
        {
            Log.Debug("Get-OSAGCalendar - ProcessRecord - Started");

            CalendarService service = new CalendarService("OSA");
            service.setUserCredentials(Username, Password);

            EventQuery query = new EventQuery();
            query.Uri = new Uri("http://www.google.com/calendar/feeds/" + Username + "/private/full");

            if (FromDate != DateTime.MinValue) query.StartTime = fromDate;

            query.RecurrenceStart = DateTime.Now;

            if (ToDate != DateTime.MinValue) query.EndTime = ToDate;

            if (FutureEvents)
            {
                Log.Debug("Only looking for future events");
                query.FutureEvents = true;
            }
            else
                query.FutureEvents = false;

            query.SortOrder = CalendarSortOrder.ascending;
            query.ExtraParameters = "orderby=starttime";

            // Tell the service to query:
            EventFeed calFeed = service.Query(query);

            List<CalendarEvent> events = new List<CalendarEvent>();

            foreach (var entry in calFeed.Entries)
            {
               Log.Debug("Found Entry: " + entry.ToString());
               EventEntry eventEntry = entry as Google.GData.Calendar.EventEntry;
               if (eventEntry != null)
               {
                   if (!eventEntry.Status.Value.Contains("event.canceled"))
                   {
                       Log.Debug("Entry is an EventEntry");
                       CalendarEvent c = new CalendarEvent();
                       c.Title = eventEntry.Title.Text;
                       c.Content = eventEntry.Content.Content;

                       if (eventEntry.Times.Count > 0)
                       {
                           c.Start = eventEntry.Times[0].StartTime;
                           c.End = eventEntry.Times[0].EndTime;
                       }

                       events.Add(c);
                   }
                }
            }
            WriteObject(events);
        }
Пример #20
0
        /// <summary>
        /// Runs the methods above to demonstrate usage of the .NET
        /// client library.  The methods that add, update, or remove
        /// users on access control lists will not run by default.
        /// </summary>
        static void RunSample()
        {
            CalendarService service = new CalendarService("exampleCo-exampleApp-1");
            service.setUserCredentials(userName, userPassword);

            // Demonstrate retrieving a list of the user's calendars.
            PrintUserCalendars(service);

            // Demonstrate various feed queries.
            PrintAllEvents(service);
            FullTextQuery(service, "Tennis");
            DateRangeQuery(service, new DateTime(2007, 1, 5), new DateTime(2007, 1, 7));

            // Demonstrate creating a single-occurrence event.
            EventEntry singleEvent = CreateSingleEvent(service, "Tennis with Mike");
            Console.WriteLine("Successfully created event {0}", singleEvent.Title.Text);

            // Demonstrate creating a recurring event.
            AtomEntry recurringEvent = CreateRecurringEvent(service, "Tennis with Dan");
            Console.WriteLine("Successfully created recurring event {0}", recurringEvent.Title.Text);

            // Demonstrate updating the event's text.
            singleEvent = UpdateTitle(singleEvent, "Important meeting");
            Console.WriteLine("Event's new title is {0}", singleEvent.Title.Text);

            // Demonstrate adding a reminder.  Note that this will only work on a primary
            // calendar.
            singleEvent = AddReminder(singleEvent, 15);
            Console.WriteLine("Set a {0}-minute reminder for the event.", singleEvent.Reminder.Minutes);

            // Demonstrate adding an extended property.
            AddExtendedProperty(singleEvent);

            // Demonstrate deleting the item.
            singleEvent.Delete();

            // Demonstrate retrieving access control lists for all calendars.
            RetrieveAcls(service);
        }
Пример #21
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();
        }
Пример #22
0
        public void googlecalendarSMSreminder(string sendstring)
        {
            CalendarService service = new CalendarService("exampleCo-exampleApp-1");
            service.setUserCredentials("*****@*****.**", "joneson55");

            EventEntry entry = new EventEntry();

            // Set the title and content of the entry.
            entry.Title.Text = sendstring;
            entry.Content.Content = "Lockerz Login Page Check.";
            // Set a location for the event.
            Where eventLocation = new Where();
            eventLocation.ValueString = "Lockerz Login";
            entry.Locations.Add(eventLocation);

            When eventTime = new When(DateTime.Now.AddMinutes(3), DateTime.Now.AddHours(1));
            entry.Times.Add(eventTime);

            if (checkBox1.Checked == true)  //Reminder ON/OFF
            {
                //Add SMS Reminder
                Reminder fiftyMinReminder = new Reminder();
                fiftyMinReminder.Minutes = 1;
                fiftyMinReminder.Method = Reminder.ReminderMethod.sms;
                entry.Reminders.Add(fiftyMinReminder);
            }
            else
            {
            }

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

            // Send the request and receive the response:
            AtomEntry insertedEntry = service.Insert(postUri, entry);
        }
        protected String GetCalendarEvents()
        {
            var calendarService = new CalendarService("WesternWakeFarmersMarket");

            calendarService.setUserCredentials(
                ConfigurationManager.AppSettings["FROMEMAIL"], 
                ConfigurationManager.AppSettings["FROMPWD"]);

            var query = new EventQuery
            {
                Uri = new Uri("http://www.google.com/calendar/feeds/westernwakefarmersmarket.org_m0pmqcck35r6n8ag45vifsc4oo%40group.calendar.google.com/public/full")
            };

            var stringBuilder = new StringBuilder("<dl id=\"eventCalendar\">");

            try
            {
                var calendarFeed = calendarService.Query(query);

                var eventDates = (from EventEntry e in calendarFeed.Entries
                                  where (e.Times.Count > 0)
                                  where (e.Times[0].StartTime.CompareTo(DateTime.Today) > 0)
                                  where (!String.IsNullOrWhiteSpace(e.Title.Text))
                                  orderby e.Times[0].StartTime
                                  select e.Times[0].StartTime.Date).Distinct();

                foreach (var eventDate in eventDates)
                {
                    stringBuilder.AppendFormat("<dt>{0}</dt>", eventDate.Date.ToString("MMM d"));

                    var currentDate = eventDate.Date;

                    var eventsOnDate = from EventEntry e in calendarFeed.Entries
                                       where e.Times.Count > 0
                                       where e.Times[0].StartTime.Date.Equals(currentDate)
                                       where !String.IsNullOrWhiteSpace(e.Title.Text)
                                       orderby e.Times[0].StartTime
                                       select e;

                    stringBuilder.AppendFormat("<dd class=\"vcalendar\">");

                    foreach (var e in eventsOnDate)
                    {
                        stringBuilder.AppendFormat("<span class=\"vevent\"><abbr class=\"dtstart\" title=\"{0}\">{1}</abbr> : <span class=\"summary\">{2}</span></span><br />",
                            e.Times[0].StartTime.ToString("s"),
                            e.Times[0].StartTime.ToString("h tt"),
                            e.Title.Text);
                    }

                    stringBuilder.AppendFormat("</dd>");
                }
            }
            catch (WebException)
            {
            }
            catch (GDataRequestException)
            {
            }
            finally
            {
                stringBuilder.AppendLine("</dl>");
            }

            return stringBuilder.ToString();
        }
        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();
            };
        }
        /// <summary>
        /// 同期
        /// </summary>
        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            //各設定保存
            XML xl = new XML();
            DataSet ds = new DataSet();
            DataTable dtb;

            dtb = ds.Tables.Add("data");
            dtb.Columns.Add("cal1",Type.GetType("System.String"));
            dtb.Columns.Add("cal2", Type.GetType("System.String"));
            dtb.Columns.Add("id", Type.GetType("System.String"));
            dtb.Columns.Add("pass", Type.GetType("System.String"));
            dtb.Rows.Add(new object[] {tbCal1.Text,tbCal2.Text,tbID.Text,tbPASS.Text});
            xl.Save(System.Environment.CurrentDirectory + "/data.xml", ds);

            // カレンダーサービスを作成
            CalendarService service = new CalendarService("companyName-applicationName-1");

            // 認証設定
            service.setUserCredentials(tbID.Text, tbPASS.Text);

            // 認証結果の確認
            try
            {
                // ここで例外がthrowされなければOK
                // 処理に少し時間がかかる
                var token = service.QueryClientLoginToken();
            }
            catch (InvalidCredentialsException ex)
            {
                // 認証に失敗している
                MessageBox.Show(ex.Message);
                service = null;
            }

            // 取得条件設定
            for (int year = 2014; year < 2021; year++)
            {
                //ファイルを開く
                EXCEL EX = new EXCEL();
                EX.Open(year.ToString());

                for (int calNo = 1; calNo < 3; calNo++)
                {
                    EventQuery query = new EventQuery();
                    if (calNo == 1)
                    {
                        query.Uri = new Uri("https://www.google.com/calendar/feeds/" + tbCal1.Text + "/private/full");
                    }
                    else
                    {
                        query.Uri = new Uri("https://www.google.com/calendar/feeds/" + tbCal2.Text + "/private/full");
                    }

                    query.StartTime = new DateTime(year, 1, 1);
                    query.EndTime = new DateTime(year, 12, 31);
                    query.SortOrder = CalendarSortOrder.descending;
                    //query.SingleEvents = true;

                    // 取得して表示
                    EventFeed feeds = service.Query(query);
                    IEnumerable<EventEntry> entries = feeds.Entries.Cast<EventEntry>();
                    foreach (EventEntry entry in entries)
                    {
                        //ファイルに書き込み
                        EX.Write(entry.Times.First().StartTime.Month, entry.Times.First().StartTime.Day,
                            entry.Times.First().StartTime.TimeOfDay.ToString(), entry.Locations.First().ValueString, entry.Title.Text, calNo);
                    }
                }

                //ファイル保存
                EX.Save(year.ToString());
                //ファイルを閉じる
                EX.Close();
            }
        }
 private static Google.GData.Calendar.CalendarService CreateCalendarService()
 {
     var calendar = new Google.GData.Calendar.CalendarService("WestHill3Peaks");
     calendar.setUserCredentials("*****@*****.**", "3PWestHill24");
     return calendar;
 }
Пример #27
0
        // TODO: dynamically generate study time based on credit hours of each class
        private void generateBtn_Click(object sender, EventArgs e)
        {
            timeSlots.Clear();

            String report = "";

            if (username == "" || password == "" || calendarUrl == "")
            {
                MessageBox.Show("Please add Google login and password information.");
            }
            else
            {
                foreach (ClassGroupBox g in groupBoxList)
                {
                    firstDayOfClass = assignClassStartDay(g.getDays()[0], startOfSemester);

                    String recursionString = "DTSTART;TZID=US/Eastern:" + startOfSemester.Year
                        + startOfSemester.Month.ToString("00") + firstDayOfClass.ToString()
                        + "T" + g.getStartHour() + g.getStartMin()
                        + "00" + "\r\nDTEND;TZID=US/Eastern:" + startOfSemester.Year
                        + startOfSemester.Month.ToString("00") + startOfSemester.Day.ToString("00")
                        + "T" + g.getEndHour() + g.getEndMin() + "00"
                        + "\r\n" + "RRULE:FREQ=WEEKLY;BYDAY=" + buildDayString(g.getDays()) + ";UNTIL="
                        + endOfSemester.Year + endOfSemester.Month.ToString("00")
                        + endOfSemester.Day.ToString("00") + "\r\n";

                    Recurrence recurrence = new Recurrence();
                    recurrence.Value = recursionString;
                    Console.Out.WriteLine(recursionString);

                    CalendarService service = new CalendarService("ggco-purdueScheduler-0.01");
                    Uri postUri = new Uri("https://www.google.com/calendar/feeds/" + calendarUrl + "/private/full");

                    service.setUserCredentials(username, password);
                    EventEntry calendarEntry = new EventEntry();
                    calendarEntry.Title.Text = g.getCourseName();
                    calendarEntry.Recurrence = recurrence;

                    report += buildDayReport(g);

                    try
                    {
                        AtomEntry insertedEntry = service.Insert(postUri, calendarEntry);
                        resultLbl.Text = "SUCCESS";
                        resultLbl.ForeColor = Color.White;
                        resultLbl.BackColor = Color.Green;
                    }
                    catch
                    {
                        resultLbl.Text = "FAILURE";
                        resultLbl.ForeColor = Color.White;
                        resultLbl.BackColor = Color.Red;
                    }

                    //// BASELINE - used to ensure no overlap in a given day
                    //DateTime start = new DateTime(DateTime.Now.Year, DateTime.Now.Month,
                    //    DateTime.Now.Day, int.Parse(g.getStartHour()), int.Parse(g.getStartMin()), 0);
                    //DateTime end = new DateTime(DateTime.Now.Year, DateTime.Now.Month,
                    //    DateTime.Now.Day, int.Parse(g.getEndHour()), int.Parse(g.getEndMin()), 0);

                    //if (groupBoxList.Count == 0)
                    //{
                    //    timeSlots.Add(new TimeSlot(start, end));
                    //}
                    //else
                    //{
                    //    foreach (TimeSlot t in timeSlots)
                    //    {
                    //        if (start <= t.getStartTime() && end > t.getStartTime())
                    //        {
                    //            MessageBox.Show("Classes overlap - one ends after another starts.");
                    //        }
                    //        else if (start >= t.getStartTime() && start < t.getEndTime())
                    //        {
                    //            MessageBox.Show("Classes overlap - one starts before another ends.");
                    //        }
                    //        else
                    //        {
                    //            MessageBox.Show("No errors");
                    //        }
                    //    }
                    //    timeSlots.Add(new TimeSlot(start, end));
                    //}
                }
            }
            reportRichTxt.Text = report;
        }
Пример #28
0
            protected override void ProcessRecord()
            {
                adminUser = credentials.UserName;
                adminPassword = new Dgc.ConvertToUnsecureString(credentials.Password).PlainString;
                var _domain = dgcGoogleAppsService.GetDomain(adminUser);

                try
                {
                    //AppsService
                    service.AppsService = new AppsService(_domain, adminUser, adminPassword);

                    //CalendarService
                    var _calendarService = new CalendarService("Calendar");
                    _calendarService.setUserCredentials(adminUser, adminPassword);
                    service.CalendarService = _calendarService;

                    //OauthCalendarService
                    if (consumerKey != null)
                    {
                        if (consumerSecret == null)
                        {
                            throw new Exception("-ConsumerSecret can't be null");
                        }
                        var _oauthCalendarService = new CalendarService("Calendar");
                        var _oauth = new GDataTypes.Oauth();
                        _oauth.ConsumerKey = consumerKey;
                        _oauth.ConsumerSecret = consumerSecret;
                        service.Oauth = _oauth;
                        GOAuthRequestFactory _requestFactory = new GOAuthRequestFactory("cl", "GDataCmdLet");
                        _requestFactory.ConsumerKey = _oauth.ConsumerKey;
                        _requestFactory.ConsumerSecret = _oauth.ConsumerSecret;
                        _oauthCalendarService.RequestFactory = _requestFactory;
                        service.OauthCalendarService = _oauthCalendarService;
                    }

                    //MailSettingsService
                    var _googleMailSettingsService = new GoogleMailSettingsService(_domain, "GMailSettingsService");
                    _googleMailSettingsService.setUserCredentials(adminUser, adminPassword);
                    service.GoogleMailSettingsService = _googleMailSettingsService;

                    //ProfileService
                    var _dgcGoogleProfileService = new Dgc.GoogleProfileService();
                    service.ProfileService = _dgcGoogleProfileService.GetAuthToken(adminUser, adminPassword);

                    //ResourceService
                    var _dgcGoogleResourceService = new Dgc.GoogleResourceService();
                    service.ResourceService = _dgcGoogleResourceService.GetAuthToken(adminUser, adminPassword);

                    //ContactsService
                    var _contactService = new ContactsService("GData");
                    _contactService.setUserCredentials(adminUser, adminPassword);
                    service.ContactsService = _contactService;

                    WriteObject(service);
                }
                catch (AppsException _exception)
                {
                    WriteObject(_exception, true);
                }
            }
Пример #29
0
 public Calendar()
 {
     _service = new CalendarService("ClearCanvas-Workstation-1.0");
     _service.setUserCredentials("clearcanvas.demo", "clearcanvas1");
 }
Пример #30
0
 private CalendarService getService()
 {
     // Create a CalenderService and authenticate
     CalendarService googleCalendarService = new CalendarService("rpcwc-rpcwcorg-2");
     googleCalendarService.setUserCredentials("*****@*****.**", "Vert1go");
     return googleCalendarService;
 }