Exemplo n.º 1
0
        static void Main(string[] args)
        {
            TCPServer <TCPData> server = new TCPServer <TCPData>();

            server.Start();
            server.OnDataReceived += Server_OnDataReceived;
            Console.ReadLine();
            return;

            if (!Directory.Exists(billPath))
            {
                Directory.CreateDirectory(billPath);
            }

            TesseractEngine engine = new TesseractEngine(Directory.GetCurrentDirectory(), "ces");

            Pix img = Pix.LoadFromFile("unnamed1.jpg");

            Page   p = engine.Process(img, PageSegMode.Auto);
            string s = p.GetText();

            Console.WriteLine(s);

            Console.ReadLine();

            UserCredential credential;

            using (FileStream stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read)) {
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new string[1] {
                    DriveService.Scope.Drive
                },
                    "user",
                    CancellationToken.None,
                    new FileDataStore(folderPath, true)).Result;
            }

            // Create Drive API service.
            DriveService service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential, ApplicationName = "Bill Scanner"
            });

            FilesResource.ListRequest listRequest = service.Files.List();

            //TODO: if other ways are found, this has to be edited
            listRequest.Q = "mimeType != 'application/vnd.google-apps.folder' and name contains 'Dokument aplikace' and name contains 'Google Keep'";


            IList <Google.Apis.Drive.v3.Data.File> files = listRequest.Execute().Files;

            Console.WriteLine("Files to download ({0}):", files.Count);

            if (files.Count == 0)
            {
                Console.WriteLine("No Files found in the drive!");
                End();
                return;
            }

            ShopsDefinition def = new ShopsDefinition();

            foreach (Google.Apis.Drive.v3.Data.File file in files)
            {
                Console.WriteLine("{0} ({1})", file.Name, file.Id);
                if (file.Name.Contains("Google") || file.Name.Contains("Keep"))
                {
                    Stream fs;
                    string fileName = billPath + file.Name + "-" + file.Id.Replace("-", "") + ".txt";
                    try {
                        fs = new FileStream(fileName, FileMode.CreateNew);
                    }
                    catch (IOException e) {
                        Console.WriteLine(e.Message);
                        continue;
                    }
                    service.Files.Export(file.Id, "text/plain").DownloadWithStatus(fs);
                    fs.Close();
                    fs.Dispose();
                    //TODO delete file from drive
                    string content            = File.ReadAllText(fileName);
                    ShopsDefinition.Shop shop = def.GetShopType(content);
                    switch (shop)
                    {
                    case ShopsDefinition.Shop.LIDL: {
                        Shops.Lidl l = new Shops.Lidl();
                        //l.Parse(content);
                        break;
                    }

                    case ShopsDefinition.Shop.MC_DONALDS: {
                        Shops.McDonalds m = new Shops.McDonalds();
                        //m.Parse(content);
                        break;
                    }

                    case ShopsDefinition.Shop.ŠMAK: {
                        Shops.BilboSmak bs = new Shops.BilboSmak();
                        //bs.Parse(content);
                        break;
                    }

                    case ShopsDefinition.Shop.ALBERT: {
                        Shops.Albert a = new Shops.Albert();
                        //a.Parse(content);
                        break;
                    }
                    }
                }
            }
            End();
        }
Exemplo n.º 2
0
        public void CreateNewAppointment()
        {
            string gmailUsername;
            string syncProfile;

            GoogleAPITests.LoadSettings(out gmailUsername, out syncProfile);

            EventsResource    service;
            CalendarListEntry primaryCalendar = null;
            var scopes = new List <string>();

            //Contacts-Scope
            scopes.Add("https://www.google.com/m8/feeds");
            //Notes-Scope
            scopes.Add("https://docs.google.com/feeds/");
            //scopes.Add("https://docs.googleusercontent.com/");
            //scopes.Add("https://spreadsheets.google.com/feeds/");
            //Calendar-Scope
            //scopes.Add("https://www.googleapis.com/auth/calendar");
            scopes.Add(CalendarService.Scope.Calendar);

            UserCredential credential;

            byte[] jsonSecrets = Properties.Resources.client_secrets;

            //using (var stream = new FileStream(Path.GetDirectoryName(System.Reflection.Assembly.GetAssembly(this.GetType()).Location) + "\\client_secrets.json", FileMode.Open, FileAccess.Read))
            //using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            //using (var stream = new FileStream(Application.StartupPath + "\\client_secrets.json", FileMode.Open, FileAccess.Read))
            using (var stream = new MemoryStream(jsonSecrets))
            {
                FileDataStore fDS = new FileDataStore(Logger.AuthFolder, true);
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets, scopes, gmailUsername, CancellationToken.None,
                    fDS).Result;

                var initializer = new Google.Apis.Services.BaseClientService.Initializer();
                initializer.HttpClientInitializer = credential;
                var CalendarRequest = new CalendarService(initializer);
                //CalendarRequest.setUserCredentials(username, password);

                var list = CalendarRequest.CalendarList.List().Execute().Items;
                foreach (var calendar in list)
                {
                    if (calendar.Primary != null && calendar.Primary.Value)
                    {
                        primaryCalendar = calendar;
                        break;
                    }
                }

                if (primaryCalendar == null)
                {
                    throw new Exception("Primary Calendar not found");
                }


                //EventQuery query = new EventQuery("https://www.google.com/calendar/feeds/default/private/full");
                //ToDo: Upgrade to v3, EventQuery query = new EventQuery("https://www.googleapis.com/calendar/v3/calendars/default/events");
                service = CalendarRequest.Events;
            }

            #region Delete previously created test contact.
            var query = service.List(primaryCalendar.Id);
            query.MaxResults = 500;
            query.TimeMin    = DateTime.Now.AddDays(-10);
            query.TimeMax    = DateTime.Now.AddDays(10);
            //query.Q = "GCSM Test Appointment";

            var feed = query.Execute();
            Logger.Log("Loaded Google appointments", EventType.Information);
            foreach (Google.Apis.Calendar.v3.Data.Event entry in feed.Items)
            {
                if (entry.Summary != null && entry.Summary.Contains("GCSM Test Appointment") && !entry.Status.Equals("cancelled"))
                {
                    Logger.Log("Deleting Google appointment:" + entry.Summary + " - " + entry.Start.DateTime.ToString(), EventType.Information);
                    service.Delete(primaryCalendar.Id, entry.Id);
                    Logger.Log("Deleted Google appointment", EventType.Information);
                    //break;
                }
            }



            #endregion

            var newEntry = Factory.NewEvent();
            newEntry.Summary        = "GCSM Test Appointment";
            newEntry.Start.DateTime = DateTime.Now;
            newEntry.End.DateTime   = DateTime.Now;

            var createdEntry = service.Insert(newEntry, primaryCalendar.Id).Execute();

            Logger.Log("Created Google appointment", EventType.Information);

            Assert.IsNotNull(createdEntry.Id);

            var updatedEntry = service.Update(createdEntry, primaryCalendar.Id, createdEntry.Id).Execute();

            Logger.Log("Updated Google appointment", EventType.Information);

            //delete test contacts
            service.Delete(primaryCalendar.Id, updatedEntry.Id).Execute();

            Logger.Log("Deleted Google appointment", EventType.Information);
        }
Exemplo n.º 3
0
        public void CreateNewContact()
        {
            string gmailUsername;
            string syncProfile;

            GoogleAPITests.LoadSettings(out gmailUsername, out syncProfile);

            ContactsRequest service;

            var scopes = new List <string>();

            //Contacts-Scope
            scopes.Add("https://www.google.com/m8/feeds");
            //Notes-Scope
            scopes.Add("https://docs.google.com/feeds/");
            //scopes.Add("https://docs.googleusercontent.com/");
            //scopes.Add("https://spreadsheets.google.com/feeds/");
            //Calendar-Scope
            //scopes.Add("https://www.googleapis.com/auth/calendar");
            scopes.Add(CalendarService.Scope.Calendar);

            UserCredential credential;

            byte[] jsonSecrets = Properties.Resources.client_secrets;

            using (var stream = new MemoryStream(jsonSecrets))
            {
                FileDataStore fDS = new FileDataStore(Logger.AuthFolder, true);

                GoogleClientSecrets clientSecrets = GoogleClientSecrets.Load(stream);

                credential = GCSMOAuth2WebAuthorizationBroker.AuthorizeAsync(
                    clientSecrets.Secrets,
                    scopes.ToArray(),
                    gmailUsername,
                    CancellationToken.None,
                    fDS).
                             Result;

                OAuth2Parameters parameters = new OAuth2Parameters
                {
                    ClientId     = clientSecrets.Secrets.ClientId,
                    ClientSecret = clientSecrets.Secrets.ClientSecret,

                    // Note: AccessToken is valid only for 60 minutes
                    AccessToken  = credential.Token.AccessToken,
                    RefreshToken = credential.Token.RefreshToken
                };

                RequestSettings settings = new RequestSettings("GoContactSyncMod", parameters);

                service = new ContactsRequest(settings);
            }



            #region Delete previously created test contact.
            ContactsQuery query = new ContactsQuery(ContactsQuery.CreateContactsUri("default"));
            query.NumberToRetrieve = 500;

            Feed <Contact> feed = service.Get <Contact>(query);

            Logger.Log("Loaded Google contacts", EventType.Information);

            foreach (Contact entry in feed.Entries)
            {
                if (entry.PrimaryEmail != null && entry.PrimaryEmail.Address == "*****@*****.**")
                {
                    service.Delete(entry);
                    Logger.Log("Deleted Google contact", EventType.Information);
                    //break;
                }
            }
            #endregion

            Contact newEntry = new Contact();
            newEntry.Title = "John Doe";

            EMail primaryEmail = new EMail("*****@*****.**");
            primaryEmail.Primary = true;
            primaryEmail.Rel     = ContactsRelationships.IsWork;
            newEntry.Emails.Add(primaryEmail);

            PhoneNumber phoneNumber = new PhoneNumber("555-555-5551");
            phoneNumber.Primary = true;
            phoneNumber.Rel     = ContactsRelationships.IsMobile;
            newEntry.Phonenumbers.Add(phoneNumber);

            StructuredPostalAddress postalAddress = new StructuredPostalAddress();
            postalAddress.Street  = "123 somewhere lane";
            postalAddress.Primary = true;
            postalAddress.Rel     = ContactsRelationships.IsHome;
            newEntry.PostalAddresses.Add(postalAddress);

            newEntry.Content = "Who is this guy?";

            Uri feedUri = new Uri(ContactsQuery.CreateContactsUri("default"));

            Contact createdEntry = service.Insert(feedUri, newEntry);

            Logger.Log("Created Google contact", EventType.Information);

            Assert.IsNotNull(createdEntry.ContactEntry.Id.Uri);

            Contact updatedEntry = service.Update(createdEntry);

            Logger.Log("Updated Google contact", EventType.Information);

            //delete test contacts
            service.Delete(createdEntry);

            Logger.Log("Deleted Google contact", EventType.Information);
        }
Exemplo n.º 4
0
        private void UploadToGCal_Click(object sender, EventArgs e)
        {
            richTextBox2.Clear();
            using (var stream = new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = Environment.GetFolderPath(
                    Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/calendar-dotnet-quickstart.json");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                richTextBox2.Text = richTextBox2.Text + "Credential file saved to: " + credPath + '\n';
            }

            var vtimails = new EventAttendee[]
            {
                new EventAttendee()
                {
                    Email = "*****@*****.**"
                },
                new EventAttendee()
                {
                    Email = "*****@*****.**"
                },
                new EventAttendee()
                {
                    Email = "*****@*****.**"
                },

                //new EventAttendee() {Email = "[email protected];"},
                //new EventAttendee() {Email = "*****@*****.**"},
                //new EventAttendee() {Email = "*****@*****.**"},
                //new EventAttendee() {Email = "*****@*****.**"},
                //new EventAttendee() {Email = "*****@*****.**"},

                //new EventAttendee() {Email = "Гриша Дружинин <*****@*****.**>"},
                //new EventAttendee() {Email = "Костя Саглай <*****@*****.**>"}

                //new EventAttendee() {Email = "*****@*****.**"},
            };

            if (txtNewFile.Text == "")
            {
                if (openFileDialog1.ShowDialog() != DialogResult.OK)
                {
                    return;
                }
                else
                {
                    txtNewFile.Text = openFileDialog1.FileName; //новый
                }
            }
            tabControl1.SelectedTab = tabPage2;
            richTextBox2.Clear();

            var newDt        = GetDataFromXls(txtNewFile.Text);
            var vtiGroupName = "Группа 13ВТИ-2ЗБ-010";
            var myGroup      = newDt.Select("Group = '" + vtiGroupName + "' and SortDate >= " + DateTime.Now.ToString("MMdd"));
            ClearCalendarEventByGroupName(vtiGroupName);
            foreach (DataRow newRow in myGroup)
            {
                string year;
                if (newRow["Date"].ToString().Split('.')[1] == "01" ||
                    newRow["Date"].ToString().Split('.')[1] == "02" ||
                    newRow["Date"].ToString().Split('.')[1] == "03" ||
                    newRow["Date"].ToString().Split('.')[1] == "04" ||
                    newRow["Date"].ToString().Split('.')[1] == "05" ||
                    newRow["Date"].ToString().Split('.')[1] == "06" ||
                    newRow["Date"].ToString().Split('.')[1] == "07"
                    //newRow["Date"].ToString().Split('.')[1] == "05" ||
                    )
                {
                    year = "2017-";
                }
                else
                {
                    year = "2016-";
                }
                var startdt = year
                              + string.Join("-", newRow["Date"].ToString().Split('.').Reverse().ToArray())
                              + "T" + newRow["Time"].ToString().Split('-')[0];
                var enddt = year
                            + string.Join("-", newRow["Date"].ToString().Split('.').Reverse().ToArray())
                            + "T" + newRow["Time"].ToString().Split('-')[1];
                AddNewCalendarEvent(newRow["Subject"].ToString(), newRow["Teacher"] + " (" + newRow["Note"] + ")", startdt, enddt, newRow["Room"].ToString(), newRow["Teacher"].ToString(), newRow["Group"].ToString(), vtimails);
            }
            richTextBox2.Text = richTextBox2.Text + "\n\nDone!";
        }
Exemplo n.º 5
0
        /**
         * Returns a list of upcoming events on a user's calender
         * This is most just a proof of concept of integration with the Google Calendar API
         */
        public List <String> getEvents()
        {
            UserCredential credential;
            string         path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "", "client_secret.json");

            using (var stream =
                       new FileStream(path, FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/calendar-dotnet-quickstart.json");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Google Calendar API service.
            var service = new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            // Define parameters of request.
            EventsResource.ListRequest request = service.Events.List("primary");
            request.TimeMin      = DateTime.Now;
            request.ShowDeleted  = false;
            request.SingleEvents = true;
            request.MaxResults   = 10;
            request.OrderBy      = EventsResource.ListRequest.OrderByEnum.StartTime;

            List <string> eventInfo = new List <string>();

            // List events.
            Events events = request.Execute();

            Console.WriteLine("Upcoming events:");
            if (events.Items != null && events.Items.Count > 0)
            {
                //create list of events, as strings
                foreach (var eventItem in events.Items)
                {
                    string when = eventItem.Start.DateTime.ToString();
                    if (String.IsNullOrEmpty(when))
                    {
                        when = eventItem.Start.Date;
                    }
                    Console.WriteLine("{0} ({1})", eventItem.Summary, when);
                    eventInfo.Add(eventItem.Summary + " " + when);
                }
            }
            else
            {
                Console.WriteLine("No upcoming events found.");
                eventInfo.Add("No upcoming events found");
            }
            return(eventInfo);
        }
Exemplo n.º 6
0
        List <Event> megafunction()
        {
            CultureInfo ci = new CultureInfo("es-PE");

            ci.DateTimeFormat.ShortDatePattern = "yyyy'-'MM'-'dd";

            ci.DateTimeFormat.LongTimePattern = "hh':'mm";

            System.Threading.Thread.CurrentThread.CurrentCulture = ci;

            System.Threading.Thread.CurrentThread.CurrentUICulture = ci;


            List <Event>   megaCadena = new List <Event>();
            UserCredential credential;

            using (var stream =
                       new FileStream(HttpContext.Current.Server.MapPath("~/credentials.json"), FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                string credPath = HttpContext.Current.Server.MapPath("~/token.json");
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                //         Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Google Calendar API service.
            var service = new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            // Define parameters of request.
            EventsResource.ListRequest request = service.Events.List("primary");
            request.TimeMin      = DateTime.Now;
            request.ShowDeleted  = false;
            request.SingleEvents = true;
            request.MaxResults   = 10;
            request.OrderBy      = EventsResource.ListRequest.OrderByEnum.StartTime;

            // List events.
            Events events = request.Execute();


            //  Console.WriteLine("Upcoming events:");
            if (events.Items != null && events.Items.Count > 0)
            {
                foreach (var eventItem in events.Items)
                {
                    var    dt = DateTime.Now;
                    string s  = dt.ToString();

                    string when = eventItem.Start.DateTime.ToString();

                    if (String.IsNullOrEmpty(when))
                    {
                        when = countdown("", eventItem.Start.Date);
                    }
                    else
                    {
                        when = countdown(when, "");
                    }

                    //        Console.WriteLine("{0} ({1})", eventItem.Summary, when);
                    Event even = new Event();
                    even.date = when;

                    even.desc = eventItem.Summary;
                    megaCadena.Add(even);
                }


                //megaCadena = Newtonsoft.Json.JsonConvert.SerializeObject(events.Items);
                // megaCadena = megaCadena.Replace("\"", " ");
                // megaCadena = megaCadena.Substring(1, megaCadena.Length); ;
            }
            else
            {
                Event even = new Event();
                even.date = "";
                even.desc = "no hay eventos";
                megaCadena.Add(even);
                //     Console.WriteLine("No upcoming events found.");
            }
            //      Console.Read();
            return(megaCadena);
        }
        private void Start(CancellationToken token)
        {
            if (this.IsHandleCreated)
            {
                this.Invoke((MethodInvoker) delegate
                {
                    richTextBoxLog.Clear();
                    buttonStart.Enabled = false;
                    buttonStop.Enabled  = true;
                });
            }

            if (!CheckForInternetConnection())
            {
                if (this.IsHandleCreated)
                {
                    this.Invoke((MethodInvoker) delegate
                    {
                        buttonStart.Enabled = true;
                        buttonStop.Enabled  = false;
                    });
                }

                return;
            }

            List <Subscription> tempUserSubscriptions = new List <Subscription>();

            if (service == null)
            {
                Log("Authorizing...");

                UserCredential credential;
                string         clientSecretString = "{\"installed\":" +
                                                    "{" +
                                                    "\"client_id\":\"761670588704-lgl5qbcv5odmq1vlq3lcgqv67fr8vkdn.apps.googleusercontent.com\"," +
                                                    "\"project_id\":\"youtube-downloader-174123\"," +
                                                    "\"auth_uri\":\"https://accounts.google.com/o/oauth2/auth\"," +
                                                    "\"token_uri\":\"https://accounts.google.com/o/oauth2/token\"," +
                                                    "\"auth_provider_x509_cert_url\":\"https://www.googleapis.com/oauth2/v1/certs\"," +
                                                    "\"client_secret\":\"_uzJUnD4gNiIpIL991kmCuvB\"," +
                                                    "\"redirect_uris\":[\"urn:ietf:wg:oauth:2.0:oob\",\"http://localhost\"]" +
                                                    "}" +
                                                    "}";
                byte[] byteArray = Encoding.ASCII.GetBytes(clientSecretString);

                using (var stream = new MemoryStream(byteArray))
                {
                    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        Scopes,
                        "user",
                        CancellationToken.None,
                        new FileDataStore(CredentialsPath, true)).Result;
                }

                service = new YouTubeService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName       = ApplicationName
                });
            }


            if (token.IsCancellationRequested)
            {
                return;
            }

            Log("Retrieving subscriptions...");
            DeserializeSubscriptions();

            SubscriptionsResource.ListRequest listSubscriptions = service.Subscriptions.List("snippet");
            listSubscriptions.Order      = SubscriptionsResource.ListRequest.OrderEnum.Alphabetical;
            listSubscriptions.Mine       = true;
            listSubscriptions.MaxResults = 50;
            SubscriptionListResponse response = listSubscriptions.Execute();

            while (response.NextPageToken != null && !token.IsCancellationRequested)
            {
                tempUserSubscriptions.AddRange(ConvertSubscriptionItems(response.Items.ToList()));
                listSubscriptions.PageToken = response.NextPageToken;
                response = listSubscriptions.Execute();
            }

            tempUserSubscriptions.AddRange(ConvertSubscriptionItems(response.Items.ToList()));

            if (token.IsCancellationRequested)
            {
                return;
            }

            Log("Getting latest subscriptions from YouTube");
            foreach (Subscription missingSubscription in tempUserSubscriptions.Where(p => userSubscriptions.Where(o => o.Title == p.Title).FirstOrDefault() == null))
            {
                Subscription sub = AssignUploadsPlaylist(missingSubscription);
                sub.LastVideoPublishDate = GetMostRecentUploadDate(sub);
                userSubscriptions.Add(sub);
            }

            //Remove any extraneous (unsubscribed since last time the program was run) subscriptions
            List <Subscription> unsubscribedSubscriptions = userSubscriptions.Where(p => tempUserSubscriptions.Where(o => o.Title == p.Title).FirstOrDefault() == null && !p.IsPlaylist).ToList();

            foreach (Subscription unsubscribedSubscription in unsubscribedSubscriptions)
            {
                userSubscriptions.Remove(unsubscribedSubscription);
            }

            if (token.IsCancellationRequested)
            {
                return;
            }

            //Remove any duplicates
            userSubscriptions = userSubscriptions.GroupBy(p => p.PlaylistIdToWatch).Select(p => p.First()).ToList();

            if (Settings.Instance.SerializeSubscriptions &&
                (Settings.Instance.DownloadVideos || Settings.Instance.AddToPocket)) //Don't run unnecessary iterations if the user doesn't want to download or add them to Pocket
            {
                Log("Looking for recent uploads");
                LookForMoreRecentUploads(token);
            }

            if (token.IsCancellationRequested)
            {
                return;
            }

            Log("Iterations started");
            initializeTimer();
            this.Invoke((MethodInvoker) delegate { timer.Start(); });
        }
Exemplo n.º 8
0
        static void Main(string[] args)
        {
            UserCredential credential;

            using (var stream =
                       new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart.json");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                //Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Gmail API service.
            var service = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            // Define parameters of request.
            UsersResource.LabelsResource.ListRequest request = service.Users.Labels.List("me");

            // List labels.
            //IList<Label> labels = request.Execute().Labels;
            //Console.WriteLine("Labels:");
            //if (labels != null && labels.Count > 0)
            //{
            //    foreach (var labelItem in labels)
            //    {
            //        Console.WriteLine("{0}", labelItem.Name);
            //    }
            //}
            //else
            //{
            //    Console.WriteLine("No labels found.");
            //}

            var messages = ListMessages(service, "me", "CAS Gateway has:attachment newer_than:2d");

            Console.WriteLine("Messages:");

            if (messages != null && messages.Count > 0)
            {
                foreach (var message in messages)
                {
                    Message msg = GetMessage(service, "me", message.Id);

                    foreach (var head in msg.Payload.Headers)
                    {
                        //if (head.Name == "Date")
                        //{
                        //    Console.Write(head.Value);
                        //    Console.WriteLine();

                        //}
                        if (head.Name == "Subject")
                        {
                            var root = @"F:\TMFRoot\";
                            if (!Directory.Exists(root + head.Value.GetSubject()))
                            {
                                //Directory.CreateDirectory(root);
                                Directory.CreateDirectory(root + head.Value.GetSubject());
                            }
                            //Console.Write(head.Value.GetSubject());
                            //Console.WriteLine();

                            try
                            {
                                GetAttachments(service, "me", message.Id, root + head.Value.GetSubject());
                            }
                            catch (Exception e)
                            {
                                log.Info(e);
                                Console.WriteLine(e);
                                throw;
                            }
                            var oks = "Downloaded " + message.Id;
                            //Console.WriteLine(oks);
                            log.Info(oks);
                            Debug.WriteLine(oks);
                            string   rootFolderPath = root + head.Value.GetSubject();
                            string   filesToDelete  = @"*RAW*.csv"; // Only delete RAW
                            string[] fileList       = Directory.GetFiles(rootFolderPath, filesToDelete);
                            foreach (string file in fileList)
                            {
                                Debug.WriteLine(file + " was deleted");
                                File.Delete(file);
                            }
                        }
                    }
                }
                Console.WriteLine("Complete");
                //foreach (var message in messages)
                //{
                //Console.WriteLine("{0}", message.Id);
                //var dirPath = AppDomain.CurrentDomain.BaseDirectory;
                //GetAttachments(service, "me", message.Id, dirPath);
                //}
            }
            else
            {
                Console.WriteLine("No message found.");
            }
            Console.Read();
        }
Exemplo n.º 9
0
        public void insertEvent()
        {
            switch (semStart.DayOfWeek.ToString())
            {
            case "Monday":
                if (days[0])
                {
                }
                else if (days[1])
                {
                    semStart = semStart.AddDays(1);
                }
                else if (days[2])
                {
                    semStart = semStart.AddDays(2);
                }
                else if (days[3])
                {
                    semStart = semStart.AddDays(3);
                }
                else if (days[4])
                {
                    semStart = semStart.AddDays(4);
                }
                else if (days[5])
                {
                    semStart = semStart.AddDays(5);
                }
                else if (days[6])
                {
                    semStart = semStart.AddDays(6);
                }
                break;

            case "Tuesday":
                if (days[1])
                {
                }
                else if (days[2])
                {
                    semStart = semStart.AddDays(1);
                }
                else if (days[3])
                {
                    semStart = semStart.AddDays(2);
                }
                else if (days[4])
                {
                    semStart = semStart.AddDays(3);
                }
                else if (days[5])
                {
                    semStart = semStart.AddDays(4);
                }
                else if (days[6])
                {
                    semStart = semStart.AddDays(5);
                }
                else if (days[0])
                {
                    semStart = semStart.AddDays(6);
                }
                break;

            case "Wednesday":
                if (days[2])
                {
                }
                else if (days[3])
                {
                    semStart = semStart.AddDays(1);
                }
                else if (days[4])
                {
                    semStart = semStart.AddDays(2);
                }
                else if (days[5])
                {
                    semStart = semStart.AddDays(3);
                }
                else if (days[6])
                {
                    semStart = semStart.AddDays(4);
                }
                else if (days[0])
                {
                    semStart = semStart.AddDays(5);
                }
                else if (days[1])
                {
                    semStart = semStart.AddDays(6);
                }
                break;

            case "Thursday":
                if (days[3])
                {
                }
                else if (days[4])
                {
                    semStart = semStart.AddDays(1);
                }
                else if (days[5])
                {
                    semStart = semStart.AddDays(2);
                }
                else if (days[6])
                {
                    semStart = semStart.AddDays(3);
                }
                else if (days[0])
                {
                    semStart = semStart.AddDays(4);
                }
                else if (days[1])
                {
                    semStart = semStart.AddDays(5);
                }
                else if (days[2])
                {
                    semStart = semStart.AddDays(6);
                }
                break;

            case "Friday":
                if (days[4])
                {
                }
                else if (days[5])
                {
                    semStart = semStart.AddDays(1);
                }
                else if (days[6])
                {
                    semStart = semStart.AddDays(2);
                }
                else if (days[0])
                {
                    semStart = semStart.AddDays(3);
                }
                else if (days[1])
                {
                    semStart = semStart.AddDays(4);
                }
                else if (days[2])
                {
                    semStart = semStart.AddDays(5);
                }
                else if (days[3])
                {
                    semStart = semStart.AddDays(6);
                }
                break;

            case "Saturday":
                if (days[5])
                {
                }
                else if (days[6])
                {
                    semStart = semStart.AddDays(1);
                }
                else if (days[0])
                {
                    semStart = semStart.AddDays(2);
                }
                else if (days[1])
                {
                    semStart = semStart.AddDays(3);
                }
                else if (days[2])
                {
                    semStart = semStart.AddDays(4);
                }
                else if (days[3])
                {
                    semStart = semStart.AddDays(5);
                }
                else if (days[4])
                {
                    semStart = semStart.AddDays(6);
                }
                break;

            case "Sunday":
                if (days[6])
                {
                }
                else if (days[0])
                {
                    semStart = semStart.AddDays(1);
                }
                else if (days[1])
                {
                    semStart = semStart.AddDays(2);
                }
                else if (days[2])
                {
                    semStart = semStart.AddDays(3);
                }
                else if (days[3])
                {
                    semStart = semStart.AddDays(4);
                }
                else if (days[4])
                {
                    semStart = semStart.AddDays(5);
                }
                else if (days[5])
                {
                    semStart = semStart.AddDays(6);
                }
                break;
            }
            evStart = new DateTime(semStart.Year, semStart.Month, semStart.Day, startTime.Hour, startTime.Minute, startTime.Second);
            evEnd   = new DateTime(semStart.Year, semStart.Month, semStart.Day, endTime.Hour, endTime.Minute, endTime.Second);


            makeRRULE();
            UserCredential credential;

            using (var stream =
                       new FileStream("credentials.json", FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                string credPath = "token.json";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Google Calendar API service.
            var service = new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });
            //based on recurring website thing
            Event e = new Event()
            {
                Summary  = name,
                Location = location,
                Start    = new EventDateTime()
                {
                    DateTime = evStart,
                    TimeZone = "America/New_York",
                    //"2011-06-03T10:00:00.000:-07:00")
                },
                End = new EventDateTime()
                {
                    DateTime = evEnd,
                    TimeZone = "America/New_York",
                },
                Recurrence = new String[] {
                    RRULE
                },
                Reminders = new Event.RemindersData
                {
                    UseDefault = false
                },
                ColorId = color.ToString()
            };

            Console.WriteLine(RRULE);
            String calendarId = "primary";

            EventsResource.InsertRequest request = service.Events.Insert(e, calendarId);
            Event createdEvent = request.Execute();             //error here

            Console.WriteLine("Event created: {0}", createdEvent.HtmlLink);
        }
Exemplo n.º 10
0
        private async System.Threading.Tasks.Task <bool> UploadVideo(string title, string desc, string[] tags, string categoryId, PrivacyStatus ps, string filePath)
        {
            try
            {
                InfoFormat("Uploading the video file {0} to YouTube started...", filePath);
                Info("Authentication started...");
                UserCredential credential;
                using (var stream = new FileStream(ClientSecrets, FileMode.Open, FileAccess.Read))
                {
                    credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        // This OAuth 2.0 access scope allows an application to upload files to the
                        // authenticated user's YouTube channel, but doesn't allow other types of access.
                        new[] { YouTubeService.Scope.YoutubeUpload },
                        User,
                        CancellationToken.None
                        );
                }
                Info("Authentication succeeded.");

                var youtubeService = new YouTubeService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName       = ApplicationName,
                });

                var video = new Video
                {
                    Snippet = new VideoSnippet()
                };
                video.Snippet.Title       = title;
                video.Snippet.Description = desc;
                video.Snippet.Tags        = tags;
                video.Snippet.CategoryId  = categoryId; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
                video.Status = new VideoStatus
                {
                    PrivacyStatus = ps.ToString().ToLower() // "unlisted" or "private" or "public"
                };

                using (var fileStream = new FileStream(filePath, FileMode.Open))
                {
                    var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
                    videosInsertRequest.ResponseReceived += VideosInsertRequest_ResponseReceived;

                    var res = videosInsertRequest.Upload();

                    if (res.Exception != null)
                    {
                        ErrorFormat("An error occured while uploading the file {0}: {1}", filePath, res.Exception.Message);
                        return(false);
                    }
                }

                InfoFormat("Uploading the video file {0} to YouTube succeeded.", filePath);
                return(true);
            }
            catch (ThreadAbortException)
            {
                throw;
            }
            catch (Exception e)
            {
                ErrorFormat("An error occured while uploading the video file {0}: {1}", filePath, e.Message);
                return(false);
            }
        }
Exemplo n.º 11
0
        public GmailAccess()
        {
            UserCredential credential;

            using (var stream =
                       new FileStream("C:\\Users\\jsnea\\Desktop\\ec601code\\credentials.json", FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                string credPath = "token.json";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
            }

            // Create Gmail API service.
            var service = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            List <string> GetMessageList()
            {
                List <string>  encodedMessages;
                List <Message> messageList = ListMessages(service, "me");

                foreach (var message in messageList)
                {
                    try
                    {
                        Console.WriteLine(message.Id);
                        string encodedString = service.Users.Messages.Get("me", message.Id);
                        encodedMessages.Add(encodedString);
                    }
                    catch { }
                }
            }

            List <Dictonary <string, string> > GetAndStoreMessageData(List <string> messageList)
            {
                Dictionary <string, string>         emailDict;
                List <Dictionary <string, string> > emailDictList;

                foreach (var message in messageList)
                {
                    try
                    {
                        string encodedString = service.Users.Messages.Get("me", message.Id).Execute().Payload.Body.Data;
                        byte[] data          = Convert.FromBase64String(encodedString);
                        string decodedString = Encoding.UTF8.GetString(data);
                        emailDict.Add("Body", encodedString);
                        IList <MessagePartHeader> headers = service.Users.Messages.Get("me", message.Id).Execute().Payload.Headers;
                        foreach (var header in headers)
                        {
                            if (header.Name = "Date" || header.Name = "Subject" || header.Name = "From" || header.Name = "To")
                            {
                                emailDict.Add(header.Name, header.Value);
                            }
                        }
                        emailDictList.Add(emailDict);
                    }
                    catch { }
                }
                return(emailDictList);
            }
        }
Exemplo n.º 12
0
        public async Task UploadBackupToDriveAsync()
        {
            bool result = _model.DoBackupToFile();

            if (!result)
            {
                return;
            }

            //UserCredential credential;
            string credentialsFilePath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "./credentials.json");

            using (var stream = new FileStream(credentialsFilePath, FileMode.Open, FileAccess.Read))
            {
                string credPath = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "/token.json");

                Thread thread = new Thread(() => {
                    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        scopes,
                        "user",
                        CancellationToken.None,
                        new FileDataStore(credPath, true)
                        ).Result;
                });

                thread.Start();
                if (!thread.Join(60000))
                {
                    MessageBox.Show("Error en iniciar sesión!");
                    return;
                }
            }

            // Create Drive API service.
            var service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "MejiaDrive",
            });

            //File info
            var FileMetadata = new Google.Apis.Drive.v3.Data.File();

            FileMetadata.Name     = "MejiaBackup";
            FileMetadata.MimeType = "application/octet-stream";

            //Request
            FilesResource.CreateMediaUpload request;
            string fileToUploadPath = @"C:\Users\Public\Documents\SqlBackups\MejiaBackup.bak";

            //Take fileStream and Execute request
            using (var stream = new FileStream(fileToUploadPath, FileMode.Open))
            {
                fileSize       = stream.Length;
                request        = service.Files.Create(FileMetadata, stream, "application/octet-stream");
                request.Fields = "id";

                request.ProgressChanged += UploadProgressEvent;
                //await request.UploadAsync();
                //Google.Apis.Upload.IUploadProgress x = await request.UploadAsync();

                await request.UploadAsync();
            }
        }
        /// <summary>
        /// This method requests Authentcation from a user using Oauth2.
        /// Credentials are stored in System.Environment.SpecialFolder.Personal
        /// Documentation https://developers.google.com/accounts/docs/OAuth2
        /// </summary>
        /// <param name="clientSecretJson">Path to the client secret json file from Google Developers console.</param>
        /// <param name="userName">Identifying string for the user who is being authentcated.</param>
        /// <returns>DriveService used to make requests against the Drive API</returns>
        public static directoryService AuthenticateOauth(string clientSecretJson, string userName)
        {
            try
            {
                if (string.IsNullOrEmpty(userName))
                {
                    throw new ArgumentNullException("userName");
                }
                if (string.IsNullOrEmpty(clientSecretJson))
                {
                    throw new ArgumentNullException("clientSecretJson");
                }
                if (!File.Exists(clientSecretJson))
                {
                    throw new Exception("clientSecretJson file does not exist.");
                }

                // These are the scopes of permissions you need. It is best to request only what you need and not all of them
                string[] scopes = new string[] { directoryService.Scope.AdminDirectoryResourceCalendarReadonly, //View calendar resources on your domain
                                                 directoryService.Scope.AdminDirectoryDeviceChromeosReadonly,   //View your Chrome OS devices' metadata
                                                 directoryService.Scope.AdminDirectoryRolemanagementReadonly,   //View delegated admin roles for your domain
                                                 directoryService.Scope.AdminDirectoryDeviceMobileReadonly,     //View your mobile devices' metadata
                                                 directoryService.Scope.AdminDirectoryGroupMemberReadonly,      //View group subscriptions on your domain
                                                 directoryService.Scope.AdminDirectoryDeviceMobileAction,       //Manage your mobile devices by performing administrative tasks
                                                 directoryService.Scope.AdminDirectoryUserAliasReadonly,        //View user aliases on your domain
                                                 directoryService.Scope.AdminDirectoryUserschemaReadonly,       //View user schemas on your domain
                                                 directoryService.Scope.AdminDirectoryCustomerReadonly,         //View customer related information
                                                 directoryService.Scope.AdminDirectoryResourceCalendar,         //View and manage the provisioning of calendar resources on your domain
                                                 directoryService.Scope.AdminDirectoryOrgunitReadonly,          //View organization units on your domain
                                                 directoryService.Scope.AdminDirectoryDeviceChromeos,           //View and manage your Chrome OS devices' metadata
                                                 directoryService.Scope.AdminDirectoryDomainReadonly,           //View domains related to your customers
                                                 directoryService.Scope.AdminDirectoryGroupReadonly,            //View groups on your domain
                                                 directoryService.Scope.AdminDirectoryRolemanagement,           //Manage delegated admin roles for your domain
                                                 directoryService.Scope.AdminDirectoryDeviceMobile,             //View and manage your mobile devices' metadata
                                                 directoryService.Scope.AdminDirectoryNotifications,            //View and manage notifications received on your domain
                                                 directoryService.Scope.AdminDirectoryUserReadonly,             //View users on your domain
                                                 directoryService.Scope.AdminDirectoryUserSecurity,             //Manage data access permissions for users on your domain
                                                 directoryService.Scope.AdminDirectoryGroupMember,              //View and manage group subscriptions on your domain
                                                 directoryService.Scope.AdminDirectoryUserAlias,                //View and manage user aliases on your domain
                                                 directoryService.Scope.AdminDirectoryUserschema,               //View and manage the provisioning of user schemas on your domain
                                                 directoryService.Scope.AdminDirectoryCustomer,                 //View and manage customer related information
                                                 directoryService.Scope.AdminDirectoryOrgunit,                  //View and manage organization units on your domain
                                                 directoryService.Scope.AdminDirectoryDomain,                   //View and manage the provisioning of domains for your customers
                                                 directoryService.Scope.AdminDirectoryGroup,                    //View and manage the provisioning of groups on your domain
                                                 directoryService.Scope.AdminDirectoryUser };                   //View and manage the provisioning of users on your domain
                UserCredential credential;
                using (var stream = new FileStream(clientSecretJson, FileMode.Open, FileAccess.Read))
                {
                    string credPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                    credPath = Path.Combine(credPath, ".credentials/", System.Reflection.Assembly.GetExecutingAssembly().GetName().Name);

                    // Requesting Authentication or loading previously stored authentication for userName
                    credential = GoogleWebAuthorizationBroker.AuthorizeAsync(GoogleClientSecrets.Load(stream).Secrets,
                                                                             scopes,
                                                                             userName,
                                                                             CancellationToken.None,
                                                                             new FileDataStore(credPath, true)).Result;
                }

                // Create Drive API service.
                return(new directoryService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName = "directory Oauth2 Authentication Sample"
                }));
            }
            catch (Exception ex)
            {
                Console.WriteLine("Create Oauth2 account directoryService failed" + ex.Message);
                throw new Exception("CreateServiceAccountdirectoryFailed", ex);
            }
        }
Exemplo n.º 14
0
        private async Task Run()
        {
            UserCredential credential;

            using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    // This OAuth 2.0 access scope allows for read-only access to the authenticated
                    // user's account, but not other types of account access.
                    new[] { YouTubeService.Scope.Youtube },
                    "user",
                    CancellationToken.None,
                    new FileDataStore(this.GetType().ToString())
                    );
            }

            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = this.GetType().ToString()
            });

            List <PlayList> PLDetail = new List <PlayList>();
            List <Videos>   Videos   = new List <Videos>();

            var channelsListRequest = youtubeService.Channels.List("contentDetails");

            channelsListRequest.Mine = true;

            var nextPageToken = "";

            while (nextPageToken != null)
            {
                var playlists = youtubeService.Playlists.List("snippet");
                playlists.PageToken  = nextPageToken;
                playlists.MaxResults = 50;
                playlists.Mine       = true;
                PlaylistListResponse presponse = await playlists.ExecuteAsync();

                int i = 0;
                foreach (var currentPlayList in presponse.Items)
                {
                    string temp = currentPlayList.Snippet.Title;
                    Console.WriteLine(i + " : " + temp);

                    PLDetail.Add(new PlayList()
                    {
                        name = temp.Trim().ToLower(),
                        ID   = currentPlayList.Id
                    });

                    i++;
                }
                nextPageToken = presponse.NextPageToken;
            }

            // Retrieve the contentDetails part of the channel resource for the authenticated user's channel.
            var channelsListResponse = await channelsListRequest.ExecuteAsync();

            // get todays date
            string Today = DateTime.Today.ToString().Substring(0, 10);

            foreach (var channel in channelsListResponse.Items)
            {
                // From the API response, extract the playlist ID that identifies the list
                // of videos uploaded to the authenticated user's channel.
                var uploadsListId = channel.ContentDetails.RelatedPlaylists.Uploads;

                Console.WriteLine("Videos in list {0}", uploadsListId);

                nextPageToken = "";
                while (nextPageToken != null)
                {
                    var playlistItemsListRequest = youtubeService.PlaylistItems.List("snippet");
                    playlistItemsListRequest.PlaylistId = uploadsListId;
                    playlistItemsListRequest.MaxResults = 50;
                    playlistItemsListRequest.PageToken  = nextPageToken;

                    // Retrieve the list of videos uploaded to the authenticated user's channel.
                    var playlistItemsListResponse = await playlistItemsListRequest.ExecuteAsync();

                    foreach (var playlistItem in playlistItemsListResponse.Items)
                    {
                        string ItemDate = playlistItem.Snippet.PublishedAt.ToString();
                        if (ItemDate.StartsWith(Today))
                        {
                            Videos.Add(new Videos()
                            {
                                name = playlistItem.Snippet.Title.Trim().ToLower(),
                                ID   = playlistItem.Snippet.ResourceId.VideoId
                            });
                        }
                    }

                    nextPageToken = playlistItemsListResponse.NextPageToken;
                }
            }

            foreach (var Video in Videos)
            {
                foreach (var PL in PLDetail)
                {
                    if (Video.name.Contains(PL.name))
                    {
                        // Add video to the matching playlist.
                        var newPlaylistItem = new PlaylistItem();
                        newPlaylistItem.Snippet                    = new PlaylistItemSnippet();
                        newPlaylistItem.Snippet.PlaylistId         = PL.ID;
                        newPlaylistItem.Snippet.ResourceId         = new ResourceId();
                        newPlaylistItem.Snippet.ResourceId.Kind    = "youtube#video";
                        newPlaylistItem.Snippet.ResourceId.VideoId = Video.ID;
                        newPlaylistItem = await youtubeService.PlaylistItems.Insert(newPlaylistItem, "snippet").ExecuteAsync();

                        break;
                    }
                }
            }
        }
        static void Main(string[] args)
        {
            UserCredential credential;

            using (var stream =
                       new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);


                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Google Sheets API service.
            var service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            // read (안됨)
            String spreadsheetId = "1J64x3oTTMPUcmyfyz-6u-gG1YLbWEAKgjsZmTAF0emc";
            String range         = "Class sheet1!A2:E";

            SpreadsheetsResource.ValuesResource.GetRequest request =
                service.Spreadsheets.Values.Get(spreadsheetId, range);

            ValueRange response            = request.Execute();
            IList <IList <Object> > values = response.Values;

            if (values != null && values.Count > 0)
            {
                Console.WriteLine("Name, Major");
                foreach (var row in values)
                {
                    // Print columns A and E, which correspond to indices 0 and 4.
                    Console.WriteLine("{0}, {1}", row[0], row[4]);
                }
            }
            else
            {
                Console.WriteLine("No data found.");
            }
            Console.Read();

            // write (안됨)
            String     spreadsheetId2 = "1J64x3oTTMPUcmyfyz-6u-gG1YLbWEAKgjsZmTAF0emc";
            String     range2         = "Class sheet1!A1";
            ValueRange valueRange     = new ValueRange();

            valueRange.MajorDimension = "COLUMNS";//"ROWS";//COLUMNS

            var oblist = new List <object>()
            {
                "My Cell Text"
            };

            valueRange.Values = new List <IList <object> > {
                oblist
            };

            SpreadsheetsResource.ValuesResource.UpdateRequest update = service.Spreadsheets.Values.Update(valueRange, spreadsheetId2, range2);
            update.ValueInputOption = SpreadsheetsResource.ValuesResource.UpdateRequest.ValueInputOptionEnum.RAW;
            UpdateValuesResponse result2 = update.Execute();

            Console.WriteLine("done!");
        }
Exemplo n.º 16
0
        public void ReadAndSearch()
        {
            using (var stream =
                       new FileStream("client_secret_675941396623-spedsb2u5hrsplch6c6gp1t8v1tqeltk.apps.googleusercontent.com.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
            }



            // Create Google Sheets API service.
            var service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });
            // read the data
            String spreadsheetId = "1tql5eJCaCZfaMGoFo01M4n-p1k6BT7LSrqyOuHdDOwY";
            String range         = "Sheet3!A2:I";

            SpreadsheetsResource.ValuesResource.GetRequest request =
                service.Spreadsheets.Values.Get(spreadsheetId, range);

            // Read the Google Sheets Database and compare Bar Code to EVERY STUDENT DEVICE
            // Once you find a match, run WriteIt(), log that the device was turned in
            ValueRange response            = request.Execute();
            IList <IList <Object> > values = response.Values;



            #region ### Read the Chromebook ID ###
            if (values != null && values.Count > 0 && ChromebookID == true)
            {
                foreach (var row in values)
                {
                    index++;                // count to current index (name) / ignores rows headings
                    chromebookUser = index; // gets the chromebook user for the unmatching log
                    try
                    {
                        // Row 2 is Chromebook ID in Database
                        if (String.Equals(row[4].ToString(), txtChromebook.Text, StringComparison.OrdinalIgnoreCase))
                        {
                            ssCol = "G";
                            WriteIt();
                            txtChromebookName.Text     = row[1].ToString();
                            txtChromebookHomeroom.Text = (row[0].ToString());
                            CheckMatchingNames();
                            break;
                        }
                    }
                    catch
                    {
                        // nothing
                    }
                }
                ChromebookID = false;
            }

            ValueRange response2            = request.Execute();
            IList <IList <Object> > values2 = response.Values;
            #endregion

            #region ### Read the Charger ID ###
            if (values2 != null && values2.Count > 0 && ChargerID == true)
            {
                // Read the Chromebook ID
                foreach (var row in values2)
                {
                    index++; // count to current index (name) / ignores rows headings
                    try
                    {
                        // Row 2 is Chromebook ID in Database
                        if (String.Equals(row[5].ToString(), txtCharger.Text, StringComparison.OrdinalIgnoreCase))
                        {
                            ssCol = "H";
                            WriteIt();
                            txtChargerName.Text     = row[1].ToString();
                            txtChargerHomeroom.Text = (row[0].ToString());
                            CheckMatchingNames();
                            break;
                        }
                    }
                    catch
                    {
                        // nothing
                    }
                }
                ChargerID = false;
            }
            #endregion
        }
Exemplo n.º 17
0
        List <Threads> obtenerCorreos()
        {
            List <Threads> correos = new List <Threads>();
            UserCredential credential;

            using (var stream =
                       new FileStream(HttpContext.Current.Server.MapPath("~/credentials2.json"), FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                string credPath = HttpContext.Current.Server.MapPath("~/token2.json");
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Gmail API service.
            var service = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            List <String> xd = new List <String>();

            xd.Add("0");
            xd.Add("1");
            // Define parameters of request
            UsersResource.ThreadsResource.ListRequest request = service.Users.Threads.List("me");
            request.MaxResults = 5;
            // List labels.
            var labels = request.Execute().Threads;

            //Console.WriteLine("Labels:");
            if (labels != null && labels.Count > 0)
            {
                foreach (var labelItem in labels)
                {
                    //labelItem.ToString();
                    Threads correo = new Threads();
                    correo.desc    = labelItem.Snippet;
                    correo.subject = "";

                    correo.from = "";
                    correo.date = "";
                    try
                    {
                        var messagesx = service.Users.Messages.Get("me", labelItem.Id).Execute();

                        if (messagesx != null)
                        {
                            //correo.date = Convert.ToString(messagesx.InternalDate.Value);
                            foreach (var headers in messagesx.Payload.Headers)
                            {
                                if (headers.Name == "Subject")
                                {
                                    correo.subject = headers.Value;
                                }
                                if (headers.Name == "From")
                                {
                                    correo.from = headers.Value;
                                }
                                if (headers.Name == "Date")
                                {
                                    correo.date = headers.Value;
                                }
                            }
                        }
                    }catch (Exception e)
                    {
                    }
                    correos.Add(correo);
                    //correos.Add
                    //   Console.WriteLine("{0}", labelItem.Name);
                }
            }
            else
            {
                Threads correo = new Threads();
                correo.desc = "no hay correos";
                correos.Add(correo);

                //   Console.WriteLine("No labels found.");
            }
            return(correos);
        }
Exemplo n.º 18
0
        public void getauthorization()
        {
            UserCredential credential;

            using (var stream =
                       new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials111/drive-dotnet-quickstart.json");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets, new[] { DriveService.Scope.Drive }
                    ,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Drive API service.
            service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "MIM Project",
            });

            /*      string pageToken = null;
             *    string fileId = "";
             *    do
             *    {
             *        var request = service.Files.List();
             *        // request.Q = "mimeType = 'application/vnd.google-apps.folder' ";
             *       // string parent_id = "0B1auUUiGcbbBOEIyNjg0alkwc3c";
             *        request.Q = "name contains 'Disposition Table for MIM 10/07/19' ";
             *        request.Spaces = "Drive";
             *        request.Fields = "nextPageToken, files(id, name)";
             *        request.PageToken = pageToken;
             *
             *        var result = request.Execute();
             *        foreach (var file in result.Files)
             *        {
             *           // if (file.Name == "Rack Delivery Plan [go/rackdeliveryplan]")
             *           // {
             *                fileId = file.Id;
             *                break;
             *           // }
             *        }
             *        pageToken = result.NextPageToken;
             *    } while (pageToken != null);
             */
            //  string message = fileId;
            string fileId   = "1ZnnRVMvx0Ma4GUih2wq3hcJK1vg0LbxoXmKCzwlz1j4";//1Y4hdHIkkVv5SmGtj8QWM-jAccZdEOhhV6Ofx_kb3IBs"; //"1OSr1IqrUjqo3RdAn1WwoNpTf2v64jzY3rKgJ8SS3hf4";//"11emBYnY-_tLQ43TFEAWIsMEtVgwyXEaAmVCPxcnp6Ag";// "1Y4hdHIkkVv5SmGtj8QWM-jAccZdEOhhV6Ofx_kb3IBs";//
            string fileName = "\\\\mimsftp\\e$\\sftp\\msgGoogle\\MDS\\PROD\\inbound\\DISPOSITION\\INBOUND\\Decom Disposition Table For MIM.xlsx";

            if (downloadFile(service, fileId, fileName))
            {
                runJob();
                //  RunPackage();
            }
        }
Exemplo n.º 19
0
 private static GoogleClientSecrets GetGoogleClientSecrets()
 {
     using var stream = Assembly.GetExecutingAssembly()
                        .GetManifestResourceStream("Cloudents.Infrastructure.Google.calendar.json");
     return(GoogleClientSecrets.Load(stream));
 }
Exemplo n.º 20
0
        public void getauthorization()
        {
            UserCredential credential;

            using (var stream =
                       new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets, new[] { DriveService.Scope.Drive }
                    ,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Drive API service.
            var service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "MIM Project",
            });

            string pageToken = null;
            string fileId    = "";

            do
            {
                var request = service.Files.List();
                // request.Q = "mimeType = 'application/vnd.google-apps.folder' ";
                string parent_id = "0B1auUUiGcbbBOEIyNjg0alkwc3c";
                request.Q         = "'" + parent_id + "' in parents";
                request.Spaces    = "Drive";
                request.Fields    = "nextPageToken, files(id, name)";
                request.PageToken = pageToken;

                var result = request.Execute();
                foreach (var file in result.Files)
                {
                    if (file.Name == "Rack Delivery Plan [go/rackdeliveryplan]")
                    {
                        fileId = file.Id;
                        Google.Apis.Drive.v3.Data.File fileG = service.Files.Get(fileId).Execute();


                        break;
                    }
                }
                pageToken = result.NextPageToken;
            } while (pageToken != null);

            string fileName = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\Templates\\currentRackDeliveryPlan.xls";

            fileName = fileName.Replace("file:\\", "");
            if (downloadfile(service, fileId, fileName))
            {
                MessageBox.Show("File has been downloaded");
            }
        }
Exemplo n.º 21
0
        public async Task <bool> Run(YoutubeUploadModel obj)
        {
            try
            {
                UserCredential credential;
                using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
                {
                    // change later, this is a test user
                    credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                        GoogleClientSecrets.Load(stream).Secrets,
                        // This OAuth 2.0 access scope allows an application to upload files to the
                        // authenticated user's YouTube channel, but doesn't allow other types of access.
                        new[] { YouTubeService.Scope.YoutubeUpload },
                        "user",
                        CancellationToken.None
                        );
                }

                var youtubeService = new YouTubeService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName       = Assembly.GetExecutingAssembly().GetName().Name
                });

                var video = new Video();
                video.Snippet             = new VideoSnippet();
                video.Snippet.Title       = obj.title;
                video.Snippet.Description = obj.description;
                video.Snippet.Tags        = new string[] { "tag1", "tag2", "Jungle" };
                video.Snippet.CategoryId  = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
                //  video.Snippet.ChannelId = "";
                //  video.Snippet.ChannelTitle = "";
                //  video.Snippet.DefaultAudioLanguage = "";
                //  video.Snippet.DefaultLanguage = "";
                //  video.Snippet.Description = "";
                //  video.Snippet.Etag = [""];
                //  video.Snippet.LiveBroadcastContent = "";
                //  video.Snippet.Localized = "";
                //  video.Snippet.PublishedAt = DateTime.Now;
                //  video.Snippet.PublishedAtRaw = "";
                //  video.Snippet.Thumbnails = "";


                video.Status = new VideoStatus();
                video.Status.PrivacyStatus = "public";// "unlisted"; // or "private" or "public"
                // Dinh Truong, 2nd November 2020 23:30, delete start
                //var filePath = @"E:\samplevideo\Sea waves & beach drone video _ Free HD Video - no copyright.mp4"; // Replace with path to actual movie file.
                // Dinh Truong 2nd November 2020 delete end

                string uploads = Path.Combine(Directory.GetCurrentDirectory(), "uploads");
                string fPath   = Path.Combine(uploads, obj.filepath.FileName);
                if (obj.filepath.Length > 0)
                {
                    using (Stream fStream = new FileStream(fPath, FileMode.Create))
                    {
                        await obj.filepath.CopyToAsync(fStream);
                    }
                }

                using (var fileStream = new FileStream(fPath, FileMode.Open))
                {
                    var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
                    videosInsertRequest.ProgressChanged  += videosInsertRequest_ProgressChanged;
                    videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;

                    var x = await videosInsertRequest.UploadAsync();

                    if (x.Status == UploadStatus.Failed)
                    {
                        return(false);
                    }
                }
                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
Exemplo n.º 22
0
        public void DescargarLista()
        {
            UserCredential credential;

            using (var stream =
                       new FileStream("credentials-drive.json", FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                string credPath = "token2.json";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes2,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Drive API service.
            var service = new DriveService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName2,
            });

            //var todasTareas = new List<Task> { };
            foreach (DataGridViewRow fila in frmTarea2.DtGVEnvíos.Rows)
            {
                //if(fila.Cells["ClnNAdjuntosEnvío"].Value.)
                //MessageBox.Show(fila.Cells["ClnIdAdjunto"].Value.ToString());
                //1. Preparar carpeta

                string nombre_alumno     = fila.Cells["ClnApellidosAlumno"].Value.ToString() + ", " + fila.Cells["ClnNombreAlumno"].Value.ToString();
                string fecha_entrega     = fila.Cells["ClnFechaEnvío"].Value.ToString();
                string cadena_ruta_fecha = fecha_entrega.Substring(8, 2) + fecha_entrega.Substring(3, 2) + fecha_entrega.Substring(0, 2);

                //MessageBox.Show(ComponerRuta(nombre_alumno, cadena_ruta_fecha));

                string filepath = ComponerRuta(nombre_alumno, cadena_ruta_fecha);

                Directory.CreateDirectory(filepath);

                /*string filepath = @"D:\Temp\tomate";
                *  if (!Directory.Exists(filepath))
                *   Directory.CreateDirectory(filepath);*/

                if (Int32.Parse(fila.Cells["ClnNAdjuntosEnvío"].Value.ToString()) > 0)
                {
                    fila.Cells["ClnDescarga"].Value = "Descargando...";
                    //todasTareas.Add(DownloadFile(service, fila.Cells["ClnIdAdjunto"].Value.ToString(), string.Format(filepath + @"\{0}", fila.Cells["ClnNombreFichero"].Value.ToString()), fila.Index, frmppal.DtGVAdjuntos));
                    StudentSubmission envío = _envíos[fila.Cells["ClnIdAlumno"].Value.ToString()];

                    if (envío.AssignmentSubmission != null)
                    {
                        if (envío.AssignmentSubmission.Attachments != null && envío.AssignmentSubmission.Attachments.Count > 0)
                        {
                            Console.WriteLine("- Adjuntos -");
                            var todasTareas = new List <Task> {
                            };                                    //prueba
                            foreach (var adjunto in envío.AssignmentSubmission.Attachments)
                            {
                                if (adjunto.DriveFile != null)
                                {
                                    Console.WriteLine(" - Enlace - {0}", adjunto.DriveFile.AlternateLink);
                                    Console.WriteLine(" - Fichero - {0}", adjunto.DriveFile.Title);
                                    Console.WriteLine(" - Id - {0}", adjunto.DriveFile.Id);
                                    //Console.WriteLine(" - Id - {0}", adjunto.);

                                    //this.DtGVAdjuntos.Rows.Add(adjunto.DriveFile.Id, adjunto.DriveFile.Title, adjunto.DriveFile.AlternateLink, "-");

                                    string nombre_fichero = adjunto.DriveFile.Title;
                                    foreach (var c in Path.GetInvalidFileNameChars())
                                    {
                                        nombre_fichero = nombre_fichero.Replace(c, '-');
                                    }

                                    //var todasTareas = new List<Task> { };
                                    todasTareas.Add(DownloadFile(service, adjunto.DriveFile.Id, string.Format(filepath + @"\{0}", nombre_fichero), fila.Index, frmTarea2.DtGVEnvíos, frmTarea2.DtGDescargas));
                                    //todasTareas.
                                    //Task.WaitAll(todasTareas.ToArray());
                                }
                                else
                                {
                                    fila.Cells["ClnDescarga"].Value = "Error";
                                }
                            }
                        }
                        else
                        {
                            fila.Cells["ClnDescarga"].Value = "No hay adjuntos";
                        }
                    }
                }
                else
                {
                    fila.Cells["ClnDescarga"].Value = "Ignorado";
                }
            }
        }
Exemplo n.º 23
0
        // Function to get token
        public bool Get()
        {
            // Convert this string to Stream to read at Gmail API
            MemoryStream StreamJson = new MemoryStream(Encoding.ASCII.GetBytes(ConfigGmail.JsonContent_Gmail));

            try
            {
                // Create temp folder to save user token after request
                string NewUserFolder = string.Empty;
                NewUserFolder = Path.Combine(GlobalVarriable.UserToken, Fast.CreateNewRandomFolderName());
                // If this folder existed then auto generate new folder path
                while (File.Exists(NewUserFolder))
                {
                    NewUserFolder = Path.Combine(GlobalVarriable.UserToken, Fast.CreateNewRandomFolderName());
                }
                // Set value for UserCredential (Credential: Chứng chỉ)
                UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(StreamJson).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(NewUserFolder, true)).Result;
                // Create Gmail API service. (servis: Dịch vụ)
                var service = new GmailService(new BaseClientService.Initializer()
                {
                    HttpClientInitializer = credential,
                    ApplicationName       = ApplicationName
                });
                // Define parameters of request
                UsersResource.GetProfileRequest UserProfile = service.Users.GetProfile("me");
                // User detail
                Profile NewAccount    = UserProfile.Execute();
                string  UserEmail     = NewAccount.EmailAddress;
                string  MessagesTotal = NewAccount.MessagesTotal.ToString();
                string  ThreadsTotal  = NewAccount.ThreadsTotal.ToString();
                // Get user avatar form uri, covert to bitmap and save to User Space
                GmailAccountInfo.SendRequest(UserEmail); // sendrequest
                bool UpdateAccount = false;
                if (Directory.Exists(Path.Combine(Path.GetDirectoryName(NewUserFolder), UserEmail)))
                {
                    UpdateAccount = true;
                    Directory.Delete(Path.Combine(Path.GetDirectoryName(NewUserFolder), UserEmail), true);
                }
                // Change Folder random name to user's mail address name
                Directory.Move(NewUserFolder, Path.Combine(Path.GetDirectoryName(NewUserFolder), UserEmail));
                // Update NewUserFolder
                NewUserFolder = Path.Combine(Path.GetDirectoryName(NewUserFolder), UserEmail);
                GmailAccountInfo.get.Avatar.Save(Path.Combine(NewUserFolder, "Avatar.jpg"), ImageFormat.Jpeg);
                string UserContentGenerate =
                    Convert.ToBase64String(Encoding.UTF8.GetBytes(GmailAccountInfo.get.DisplayName)) // DisplayName
                    + "|" +
                    ThreadsTotal.ToString()                                                          // Total Thread
                    + "|" +
                    MessagesTotal.ToString();                                                        // Total Messages
                FileStream file     = new FileStream(Path.Combine(NewUserFolder, "Old.info"), FileMode.OpenOrCreate);
                byte[]     ForWrite = Encoding.ASCII.GetBytes(UserContentGenerate);
                file.Write(ForWrite, 0, ForWrite.Length);
                file.Close();
                // Should be add a case that if this Email had had before!
                //
                //
                // If Mail address had had before -> Out
                if (GlobalVarriable.MailsAddressList.IndexOf(UserEmail) != -1)
                {
                    return(false);
                }
                // Add this email to MailsAddressList
                GlobalVarriable.MailsAddressList.Add(UserEmail);
                // Update this account to List
                Fast.UpdateAccountsList();
                SuccessBox.Show("Successfully added!");
                // End of connections
                service.Dispose();
                return(true);
            }
            catch (Exception e)
            {
                // If have any bugs
                Console.WriteLine(e);
                FailBox.Show();
                return(false);
            }
        }
Exemplo n.º 24
0
        private void FrmTarea2_Load(object sender, EventArgs e)
        {
            this.Text = "Tarea: " + _titulo_tarea;

            UserCredential credential;

            using (var stream =
                       new FileStream("credentials-p4.json", FileMode.Open, FileAccess.Read))
            {
                // The file token.json stores the user's access and refresh tokens, and is created
                // automatically when the authorization flow completes for the first time.
                string credPath = "token.json";
                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            //Servicio

            // Create Classroom API service.
            var service = new ClassroomService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            CoursesResource.StudentsResource.ListRequest request = service.Courses.Students.List(_idcurso);
            CoursesResource.CourseWorkResource.StudentSubmissionsResource.ListRequest request2 = service.Courses.CourseWork.StudentSubmissions.List(_idcurso, _idtarea);

            ListStudentsResponse           resp_lista_estudiantes = request.Execute();
            ListStudentSubmissionsResponse resp_lista_envíos      = request2.Execute();

            var lista_estudiantes = resp_lista_estudiantes.Students;
            var lista_envíos      = resp_lista_envíos.StudentSubmissions;

            if (lista_envíos != null && lista_envíos.Count > 0)
            {
                foreach (var envio in lista_envíos)
                {
                    Console.WriteLine("{0} / {1} / {2}", envio.Id, envio.UpdateTime, envio.UserId);
                    _envíos.Add(envio.UserId, envio);
                }
            }

            if (lista_estudiantes != null && lista_estudiantes.Count > 0)
            {
                foreach (var estudiante in lista_estudiantes)
                {
                    string estudiante_id        = estudiante.UserId;
                    string estudiante_nombre    = estudiante.Profile.Name.GivenName;
                    string estudiante_apellidos = estudiante.Profile.Name.FamilyName;
                    string estudiante_email     = estudiante.Profile.EmailAddress;

                    Console.WriteLine("Correo electrónico: {0}", estudiante_email);
                    Console.WriteLine("{0} / {1} / {2} / {3}", estudiante.UserId, estudiante.Profile.Name.FullName, estudiante.Profile.Name.FamilyName, estudiante.Profile.Name.GivenName);
                    //2. Por cada alumno, obtenemos sus envíos
                    StudentSubmission envío = _envíos[estudiante_id];

                    string envío_id         = envío.Id;
                    string envío_fecha      = envío.UpdateTime.ToString();
                    string envío_estado     = envío.State;
                    string envío_retrasado  = envío.Late.ToString();
                    int    envío_n_adjuntos = 0;
                    if (envío.AssignmentSubmission != null)
                    {
                        if (envío.AssignmentSubmission.Attachments != null)
                        {
                            envío_n_adjuntos = envío.AssignmentSubmission.Attachments.Count();
                        }
                    }

                    frmTarea2.DtGVEnvíos.Rows.Add(estudiante_id, estudiante_nombre, estudiante_apellidos, envío_id, envío_fecha, envío_estado, envío_retrasado, envío_n_adjuntos, "-");
                }
            }
        }
        static void Main(string[] args)
        {
            UserCredential credential;

            using (var stream =
                       new FileStream("client_secret.json", FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);
                credPath = Path.Combine(credPath, ".credentials/gmail-dotnet-quickstart.json");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    Scopes,
                    "user",
                    CancellationToken.None,
                    new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Gmail API service.
            var service = new GmailService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            // Define parameters of request.
            UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List("me");

            /*
             * // List labels.
             * IList<Label> labels = request.Execute().Labels;
             * Console.WriteLine("Labels:");
             * if (labels != null && labels.Count > 0)
             * {
             *  foreach (var labelItem in labels)
             *  {
             *      Console.WriteLine("{0}", labelItem.Name);
             *  }
             * }
             * else
             * {
             *  Console.WriteLine("No labels found.");
             * }
             */

            // List messages
            IList <Message> messages = ListMessages(service, "me");

            Console.WriteLine("Messages: ");
            if (messages != null && messages.Count > 0)
            {
                foreach (Message message in messages)
                {
                    UsersResource.MessagesResource.GetRequest asd = service.Users.Messages.Get("me", message.Id);
                    string messageSnippet = asd.Execute().Snippet;
                    var    messagePayload = asd.Execute().Payload;
                    string sender         = messagePayload.Headers[6].Value;
                    var    parts          = messagePayload.Parts;
                    Console.WriteLine("From: " + sender);

                    if (!string.IsNullOrWhiteSpace(parts[0].Body.Data))
                    {
                        string InputStr      = parts[0].Body.Data.Replace("-", "+").Replace("_", "/");
                        string decodedString = Encoding.UTF8.GetString(Convert.FromBase64String(InputStr));
                        Console.WriteLine("Body: " + decodedString);
                    }
                    else
                    {
                        Console.WriteLine("Well that didn't work out, did it?");
                    }
                }
            }
            else
            {
                Console.WriteLine("No messages found");
            }

            Console.Read();
        }
Exemplo n.º 26
0
        public void Run()
        {
            txtLog.Text     = "";
            txtLog.ReadOnly = true;

            btnProcess.Enabled         = false;
            prbBackupAndUpload.Visible = true;

            prbBackupAndUpload.Minimum = 0;
            prbBackupAndUpload.Maximum = uploadToGoogleDrive ? 202 : 102;


            var backupFileName   = @$ "{database}_{DateTime.Now.ToString(" yyyy - MM - dd_HH - mm - ss ")}.bak";
            var backupFolderName = folderForBackupFile;

            if (deleteLocalBackup || !Directory.Exists(folderForBackupFile))
            {
                backupFolderName = Path.GetDirectoryName(Application.ExecutablePath);
            }
            var backupFileFullPath = Path.Combine(backupFolderName !, backupFileName);

            txtLog.Text += $"Server: {server} {Environment.NewLine}";
            txtLog.Text += $"Database: {database} {Environment.NewLine}";
            txtLog.Text += isIntegratedSecurity ? $"Windows authentication {Environment.NewLine}" : $"SQL authentication, login: {login} {Environment.NewLine}";
            txtLog.Text += "Target backup file: " + (deleteLocalBackup ? "no" : backupFileFullPath) + $" {Environment.NewLine}";
            if (uploadToGoogleDrive)
            {
                txtLog.Text += $"Upload to cloud: yes {Environment.NewLine}";
                txtLog.Text += "Target in cloud: " + (needToCreateGoogleFolder ? folderForBackupFile : "root") + $" {Environment.NewLine}";
            }
            else
            {
                txtLog.Text += $"Upload to cloud: no {Environment.NewLine}";
            }
            txtLog.Text += $"Backup start at: {DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss")} {Environment.NewLine}";

            try
            {
                var cnn = new SqlConnection
                {
                    ConnectionString = $"{GetConnectionStringFromForm()};Timeout=0"
                };

                //create backup
                var backup = new MsSqlBackup();
                backup.BackupDatabaseProgressChanged += BackupOnBackupAndUploadDatabaseProgressChanged;
                backup.BackupDatabase(cnn, database, backupFileName, "Backup created by Sql2GoogleDrive",
                                      backupFileFullPath, compressBackup);
            }
            catch (Exception exception)
            {
                txtLog.Text += $"{DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss")} Error: {exception.Message} {Environment.NewLine}";
                EndOfProcess();
                return;
            }
            txtLog.Text += $"Backup end at: {DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss")} {Environment.NewLine}";

            if (uploadToGoogleDrive)
            {
                //upload backup
                var folder = googleFolder;

                string[]       Scopes         = { DriveService.Scope.DriveFile };
                string         FolderMimeType = "application/vnd.google-apps.folder";
                UserCredential credential;

                txtLog.Text +=
                    $"Upload to Google Drive start at: {DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss")} {Environment.NewLine}";
                txtLog.Text += $"Try to get credentials.... {Environment.NewLine}";

                try
                {
                    using (var stream =
                               new FileStream("GDriveCredentials.json", FileMode.Open, FileAccess.Read))
                    {
                        var credPath = System.Environment.GetFolderPath(
                            System.Environment.SpecialFolder.Personal);
                        credPath = Path.Combine(credPath, ".credentials/drive-dotnet-quickstart.json");

                        credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                            GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None,
                            new FileDataStore(credPath, true)).Result;
                        Console.WriteLine("Credential file saved to: " + credPath);
                    }

                    txtLog.Text += $"Credentials - OK {Environment.NewLine}";


                    // Create Drive API service.
                    var service = new DriveService(new BaseClientService.Initializer()
                    {
                        HttpClientInitializer = credential,
                        ApplicationName       = Program.AppName,
                    });
                    txtLog.Text += $"Create Drive API service - OK. {service.Name} {Environment.NewLine}";

                    string folderId = "";
                    if (needToCreateGoogleFolder)
                    {
                        txtLog.Text += $"Try to Get or Create folder '{googleFolder}'... {Environment.NewLine}";
                        //find folder
                        var folderList = new List <Google.Apis.Drive.v3.Data.File>();

                        string pageToken = null;
                        while (true)
                        {
                            FilesResource.ListRequest listRequest = service.Files.List();
                            listRequest.PageSize  = 10;
                            listRequest.PageToken = pageToken;
                            listRequest.Fields    = "nextPageToken, files(id, name, mimeType, size)";

                            var fileList = listRequest.Execute();

                            // List files.
                            IList <Google.Apis.Drive.v3.Data.File> folders = fileList.Files;
                            if (folders != null && folders.Count > 0)
                            {
                                folderList.AddRange(folders.Where(x =>
                                                                  x.MimeType.Equals(FolderMimeType, StringComparison.InvariantCultureIgnoreCase)));
                            }

                            pageToken = fileList.NextPageToken;
                            if (pageToken == null)
                            {
                                break;
                            }
                        }

                        folderId = folderList.FirstOrDefault(folderFile => folderFile.Name == googleFolder)?.Id ??
                                   "";
                        if (string.IsNullOrEmpty(folderId))
                        {
                            var bodyFolder = new Google.Apis.Drive.v3.Data.File
                            {
                                Name     = googleFolder,
                                MimeType = FolderMimeType
                            };

                            var createdFolder = service
                                                .Files
                                                .Create(bodyFolder)
                                                .Execute();

                            folderId     = createdFolder.Id;
                            txtLog.Text += $"Create folder '{googleFolder}' - OK {Environment.NewLine}";
                        }
                        else
                        {
                            txtLog.Text += $"Get folder '{googleFolder}' - OK {Environment.NewLine}";
                        }
                    }

                    txtLog.Text += $"Try to upload file '{backupFileName}'... {Environment.NewLine}";
                    //UPLOAD NON-EXISTING TO DRIVE
                    var body = new Google.Apis.Drive.v3.Data.File
                    {
                        Name         = backupFileName,
                        Description  = $"backup file of database '{database}'",
                        MimeType     = "application/octet-stream",
                        ModifiedTime = File.GetLastWriteTime(backupFileFullPath)
                    };
                    if (needToCreateGoogleFolder && !string.IsNullOrEmpty(folderId))
                    {
                        body.Parents = new List <string>()
                        {
                            folderId
                        };
                    }

                    var byteArray  = File.ReadAllBytes(backupFileFullPath);
                    var streamFile = new MemoryStream(byteArray);
                    fileForUploadSize = byteArray.LongLength;

                    var req = service.Files.Create(body, streamFile, "application/octet-stream");
                    req.Fields                      = "id";
                    req.ProgressChanged            += ReqOnProgressChanged;
                    this.UploadFileProgressChanged += DisplayUploadFileProgress;
                    var t = req.UploadAsync();
                    t.Wait();
                    var progress = req.GetProgress();
                    txtLog.Text +=
                        $"Upload to Google Drive end at: {DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss")} {Environment.NewLine}";
                }
                catch (Exception exception) when(exception is Google.GoogleApiException ||
                                                 exception is HttpRequestException ||
                                                 exception is Exception)
                {
                    txtLog.Text +=
                        $"{DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss")} Error: {exception.Message} {Environment.NewLine}";
                    EndOfProcess();
                    return;
                }

                try
                {
                    if (deleteLocalBackup && File.Exists(backupFileFullPath))
                    {
                        txtLog.Text += $"Try to delete local file '{backupFileFullPath}'... {Environment.NewLine}";
                        File.Delete(backupFileFullPath);
                        txtLog.Text += $"Delete local file - OK {Environment.NewLine}";
                    }
                }
                catch (Exception exception)
                {
                    txtLog.Text +=
                        $"{DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss")} Error: {exception.Message} {Environment.NewLine}";
                    EndOfProcess();
                    return;
                }
            }

            EndOfProcess();
        }
Exemplo n.º 27
0
        public void CreateNewNote()
        {
            string gmailUsername;
            string syncProfile;

            GoogleAPITests.LoadSettings(out gmailUsername, out syncProfile);

            DocumentsRequest service;

            var scopes = new List <string>();

            //Contacts-Scope
            scopes.Add("https://www.google.com/m8/feeds");
            //Notes-Scope
            scopes.Add("https://docs.google.com/feeds/");
            //scopes.Add("https://docs.googleusercontent.com/");
            //scopes.Add("https://spreadsheets.google.com/feeds/");
            //Calendar-Scope
            //scopes.Add("https://www.googleapis.com/auth/calendar");
            scopes.Add(CalendarService.Scope.Calendar);

            UserCredential credential;

            byte[] jsonSecrets = Properties.Resources.client_secrets;

            using (var stream = new MemoryStream(jsonSecrets))
            {
                FileDataStore fDS = new FileDataStore(Logger.AuthFolder, true);

                GoogleClientSecrets clientSecrets = GoogleClientSecrets.Load(stream);

                credential = GCSMOAuth2WebAuthorizationBroker.AuthorizeAsync(
                    clientSecrets.Secrets,
                    scopes.ToArray(),
                    gmailUsername,
                    CancellationToken.None,
                    fDS).
                             Result;

                OAuth2Parameters parameters = new OAuth2Parameters
                {
                    ClientId     = clientSecrets.Secrets.ClientId,
                    ClientSecret = clientSecrets.Secrets.ClientSecret,

                    // Note: AccessToken is valid only for 60 minutes
                    AccessToken  = credential.Token.AccessToken,
                    RefreshToken = credential.Token.RefreshToken
                };

                RequestSettings settings = new RequestSettings("GoContactSyncMod", parameters);

                service = new DocumentsRequest(settings);

                //Instantiate an Authenticator object according to your authentication, to use ResumableUploader
                _authenticator = new OAuth2Authenticator("GCSM Unit Tests", parameters);
            }



            //Delete previously created test note.
            DeleteTestNote(service);

            Document newEntry = new Document();

            newEntry.Type  = Document.DocumentType.Document;
            newEntry.Title = "AN_OUTLOOK_TEST_NOTE";

            string file = NotePropertiesUtils.CreateNoteFile("AN_OUTLOOK_TEST_NOTE", "This is just a test note to test GoContactSyncMod", null);

            newEntry.MediaSource = new MediaFileSource(file, MediaFileSource.GetContentTypeForFileName(file));

            #region normal flow, only working to create documents without content (metadata only), e.g. for Notes folder

            Document createdEntry = Synchronizer.SaveGoogleNote(null, newEntry, service);

            Assert.IsNotNull(createdEntry.DocumentEntry.Id.Uri);

            Logger.Log("Created Google note", EventType.Information);

            //Wait 5 seconds to give the testcase the chance to finish
            System.Threading.Thread.Sleep(5000);

            //delete test note
            DeleteTestNote(service);
            #endregion

            #region workaround flow to use UploadDocument, not needed anymore because of new approach to use ResumableUploader
            //Google.GData.Documents.DocumentEntry createdEntry2 = service.Service.UploadDocument(file, newEntry.Title);

            //Assert.IsNotNull(createdEntry2.Id.Uri);

            ////delete test note
            //DeleteTestNote(service);
            #endregion

            #region New approach how to update an existing document: https://developers.google.com/google-apps/documents-list/#updatingchanging_documents_and_files
            //Instantiate the ResumableUploader component.
            ResumableUploader uploader = new ResumableUploader();
            uploader.AsyncOperationCompleted += new AsyncOperationCompletedEventHandler(OnGoogleNoteCreated);
            Synchronizer.CreateGoogleNote(newEntry, file, service, uploader, _authenticator);
            #endregion

            //Wait 5 seconds to give the testcase the chance to finish the Async events
            System.Threading.Thread.Sleep(5000);

            DeleteTestNote(service);
        }
Exemplo n.º 28
0
        IEnumerator ImporterCoroutine()
        {
            // Аутентификация

            var credentialsJson = AssetDatabase.LoadAssetAtPath <TextAsset>(
                "Assets/Scripts/Foundation.Editor/Config/credentials.json");

            var authTask = GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(new MemoryStream(credentialsJson.bytes)).Secrets,
                new string[] { SheetsService.Scope.SpreadsheetsReadonly },
                "user",
                CancellationToken.None,
                new FileDataStore("UnityGoogleApis", false));

            for (int i = 0; i < 120; i++)
            {
                if (authTask.IsCompleted)
                {
                    break;
                }
                yield return(null);
            }

            while (!authTask.IsCompleted)
            {
                if (EditorUtility.DisplayCancelableProgressBar(page, "Waiting for authentication...", 0.0f))
                {
                    EditorUtility.ClearProgressBar();
                    Debug.LogWarning("Import cancelled by the user");
                    yield break;
                }
                yield return(null);
            }

            UserCredential credential = authTask.Result;

            // Загрузка данных

            var service = new SheetsService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = "Unity Config Importer",
            });

            var request     = service.Spreadsheets.Values.Get(sheetId, page);
            var requestTask = request.ExecuteAsync();

            while (!requestTask.IsCompleted)
            {
                if (EditorUtility.DisplayCancelableProgressBar(page, "Downloading data...", 0.15f))
                {
                    EditorUtility.ClearProgressBar();
                    Debug.LogWarning("Import cancelled by the user");
                    yield break;
                }
                yield return(null);
            }

            var response = requestTask.Result;
            var values   = response.Values;

            // Обработка данных

            if (EditorUtility.DisplayCancelableProgressBar(page, "Processing data...", 0.3f))
            {
                EditorUtility.ClearProgressBar();
                Debug.LogWarning("Import cancelled by the user");
                yield break;
            }

            var processTask = ProcessData(values);

            while (!processTask.IsCompleted)
            {
                yield return(null);
            }

            try {
                processTask.Wait(); // убеждаемся, что возможные исключения обработаны
            } catch (Aborted) {
                EditorUtility.ClearProgressBar();
                Debug.LogWarning("Import cancelled by the user");
                yield break;
            } catch (Exception e) {
                Debug.LogException(e);
                EditorUtility.ClearProgressBar();
                EditorUtility.DisplayDialog("Error", "Import failed!", "OK");
                yield break;
            }

            // Готово

            EditorUtility.ClearProgressBar();
            EditorUtility.DisplayDialog("Done", "Import was successful!", "OK");
        }
        private async Task <bool> ExecuteYouTubeDataApiV3(IConfiguration youTubeConf,
                                                          string sharedSecretFolder, ILogger <YouTubeUploadOperation> logger, BloggingContext context,
                                                          IWebHostEnvironment environment, CancellationToken token)
        {
            UserCredential credential;

            using (var stream = new FileStream(youTubeConf["ClientSecretsFileName"], FileMode.Open, FileAccess.Read))
            {
                var store         = new GoogleKeyContextStore(context, environment, token);
                var googl_secrets = await GoogleClientSecrets.FromStreamAsync(stream, token);

                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    googl_secrets.Secrets,
                    // This OAuth 2.0 access scope allows for read-write access to the authenticated
                    // user's account, but not other types of account access.
                    new[] { YouTubeService.Scope.Youtube, YouTubeService.Scope.YoutubeUpload },
                    "user", token, store
                    );
            }

            using (var youtubeService = new YouTubeService(new BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                ApplicationName = youTubeConf["ApplicationName"]
            }))
            {
                var lst           = new List <PlaylistItem>(365);
                var nextPageToken = "";
                while (nextPageToken != null)
                {
                    var playlistItemsListRequest = youtubeService.PlaylistItems.List("snippet");
                    playlistItemsListRequest.PlaylistId = youTubeConf["playlistId"];
                    // playlistItemsListRequest.Fields = "items(snippet(description,publishedAt,title))";
                    playlistItemsListRequest.MaxResults = 50;
                    playlistItemsListRequest.PageToken  = nextPageToken;
                    // Retrieve the list of videos uploaded to the authenticated user's channel.
                    var playlistItemsListResponse = await playlistItemsListRequest.ExecuteAsync(token);

                    foreach (var item in playlistItemsListResponse.Items)
                    {
                        lst.Add(item);
                    }

                    nextPageToken = playlistItemsListResponse.NextPageToken;
                }

                string new_video_title  = $"timelapse {DateTime.Now.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)}";
                bool   already_uploaded = false;
                var    year_ago_date    = DateTime.Now.AddYears(-1);
                int    delete_count     = 10;
                foreach (var item in lst)
                {
                    var  date             = item.Snippet.PublishedAt.GetValueOrDefault();
                    bool is_to_be_deleted = date < year_ago_date;
                    if (!is_to_be_deleted)
                    {
                        logger.LogInformation("'{title}' [{description}] {publishedAt}", item.Snippet.Title, item.Snippet.Description,
                                              date.ToString("O"));
                    }
                    else if (delete_count > 0)
                    {
                        logger.LogWarning("DELETING '{title}' [{description}] {publishedAt}", item.Snippet.Title, item.Snippet.Description,
                                          date.ToString("O"));
                        var playlistItemsDeleteRequest = youtubeService.PlaylistItems.Delete(item.Id);
                        var delete_playlist_response   = await playlistItemsDeleteRequest.ExecuteAsync(token);

                        var videoDeleteRequest    = youtubeService.Videos.Delete(item.Snippet.ResourceId.VideoId);
                        var delete_video_response = await videoDeleteRequest.ExecuteAsync(token);

                        delete_count--;
                    }

                    if (item.Snippet.Title == new_video_title)
                    {
                        already_uploaded = true;
                        logger.LogWarning("'{title}' already uploaded aborting", item.Snippet.Title);
                        break;
                    }
                }

#if DEBUG
                already_uploaded = true;
#endif
                if (already_uploaded || string.IsNullOrEmpty(_videoFileNameToUpload))
                {
                    return(false);
                }

                //upload
                var video = new Video
                {
                    Snippet = new VideoSnippet
                    {
                        Title       = new_video_title,
                        Description = $"Daily timelapse video taken on {DateTime.Now}",
                        Tags        = new string[] { "timelapse", "video", "webcam" },
                        //"1" -> "Film & Animation", see https://developers.google.com/youtube/v3/docs/videoCategories/list
                        CategoryId = "1",
                    },
                    Status = new VideoStatus
                    {
                        PrivacyStatus = "unlisted"                         // or "private" or "public"
                    }
                };

                string successVideoID = null;
                using (var fileStream = new FileStream(_videoFileNameToUpload, FileMode.Open, FileAccess.Read))
                {
                    var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
                    videosInsertRequest.ProgressChanged += (IUploadProgress progress) =>
                    {
                        switch (progress.Status)
                        {
                        case UploadStatus.Uploading:
                            logger.LogInformation("{bytesSent} bytes sent.", progress.BytesSent);
                            break;

                        case UploadStatus.Failed:
                            logger.LogWarning("An error prevented the upload from completing.\n{exception}", progress.Exception);
                            break;
                        }
                    };
                    videosInsertRequest.ResponseReceived += (Video uploadedVideo) =>
                    {
                        successVideoID = uploadedVideo.Id;
                        logger.LogInformation("Video id '{id}' was successfully uploaded.", uploadedVideo.Id);
                    };

                    var uploaded = await videosInsertRequest.UploadAsync(token);

                    if (uploaded.Status == UploadStatus.Completed && !string.IsNullOrEmpty(successVideoID))
                    {
                        var newPlaylistItem = new PlaylistItem();
                        newPlaylistItem.Snippet                    = new PlaylistItemSnippet();
                        newPlaylistItem.Snippet.PlaylistId         = youTubeConf["playlistId"];
                        newPlaylistItem.Snippet.ResourceId         = new ResourceId();
                        newPlaylistItem.Snippet.ResourceId.Kind    = "youtube#video";
                        newPlaylistItem.Snippet.ResourceId.VideoId = successVideoID;
                        newPlaylistItem = await youtubeService.PlaylistItems.Insert(newPlaylistItem, "snippet")
                                          .ExecuteAsync(token);

                        logger.LogInformation("Video id '{id}' was added to playlist id '{playlistID}'.",
                                              successVideoID, newPlaylistItem.Snippet.PlaylistId);

                        return(true);
                    }

                    return(false);
                } //end using fileStream
            }     //end using youtubeService
        }
Exemplo n.º 30
0
        private async void insertevent()
        {
            UserData user = (UserData)Session["User"];



            UserCredential credential;

            using (var stream =
                       new FileStream(Server.MapPath("client_secret.json"), FileMode.Open, FileAccess.Read))
            {
                string credPath = System.Environment.GetFolderPath(
                    System.Environment.SpecialFolder.Personal);;
                credPath = Path.Combine(credPath, ".credentials/calendarinsert-dotnet-quickstart.json");

                credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets, Scopes, "user", CancellationToken.None, new FileDataStore(credPath, true)).Result;
                Console.WriteLine("Credential file saved to: " + credPath);
            }

            // Create Google Calendar API service.
            var service = new CalendarService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = ApplicationName,
            });

            CalendarService cs = service;



            DateTime d = Convert.ToDateTime(txtdom.Value);
            DateTime t = Convert.ToDateTime(txttime.Value);



            DateTime dt = new DateTime(d.Year, d.Month, d.Day, t.Hour, t.Minute, t.Second);



            Event newEvent = new Event()
            {
                Summary     = "Project:     " + txtprojt.Value.ToString(),
                Location    = "On Fincal",
                Description = "First meeting",
                Start       = new EventDateTime()
                {
                    DateTime = DateTime.Parse(XmlConvert.ToString(dt, XmlDateTimeSerializationMode.Utc)),
                    TimeZone = "Europe/Paris",
                },
                End = new EventDateTime()
                {
                    DateTime = DateTime.Parse(XmlConvert.ToString(dt, XmlDateTimeSerializationMode.Utc)),

                    TimeZone = "Europe/Paris",
                },
            };



            String calendarId = "primary";

            EventsResource.InsertRequest request = service.Events.Insert(newEvent, calendarId);
            Event newevent = await request.ExecuteAsync();
        }