Example #1
2
        private static GoogleMailSettingsService CreateGoogleMailService()
        {
            // Get your service account email from Google Developer's Console
            // Read more: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
            const string SERVICE_ACCT_EMAIL = "<YOUR SERVICE KEY>@developer.gserviceaccount.com";
            //Generate your .p12 key in the Google Developer Console and associate it with your project.
            var certificate = new X509Certificate2("Key.p12", "notasecret", X509KeyStorageFlags.Exportable);

            var serviceAccountCredentialInitializer = new ServiceAccountCredential.Initializer(SERVICE_ACCT_EMAIL)
            {
                User = "******", // A user with administrator access.
                Scopes = new[] { "https://apps-apis.google.com/a/feeds/emailsettings/2.0/" }
            }.FromCertificate(certificate);

            var credential = new ServiceAccountCredential(serviceAccountCredentialInitializer);
            if (!credential.RequestAccessTokenAsync(System.Threading.CancellationToken.None).Result)
                throw new InvalidOperationException("Access token failed.");

            var requestFactory = new GDataRequestFactory(null);
            requestFactory.CustomHeaders.Add("Authorization: Bearer " + credential.Token.AccessToken);

            // Replace the name of your domain and the Google Developer project you created...
            GoogleMailSettingsService service = new GoogleMailSettingsService("vuwall.com", "signatures");
            service.RequestFactory = requestFactory;

            return service;
        }
Example #2
0
 /// <summary>default constructor</summary>
 internal GDataRequest(GDataRequestType type, Uri uriTarget, GDataRequestFactory factory)
 {
     this.type      = type;
     this.targetUri = uriTarget;
     this.factory   = factory;
     this.useGZip   = this.factory.UseGZip; // use gzip setting from factory
 }
Example #3
0
 //////////////////////////////////////////////////////////////////////
 /// <summary>default constructor</summary> 
 //////////////////////////////////////////////////////////////////////
 internal GR(GDataRequestType type, Uri uriTarget, GDataRequestFactory factory)
 {
     this.type = type;
     this.targetUri = uriTarget;
     this.factory = factory;
     this.useGZip = this.factory.UseGZip; // use gzip setting from factory
 }
 public void UserAgentTest()
 {
     string userAgent = "TestValue"; // TODO: Initialize to an appropriate value
     GDataRequestFactory target = new GDataRequestFactory(userAgent); // TODO: Initialize to an appropriate value
     string expected = "TestValue";            string actual;
     target.UserAgent = expected;
     actual = target.UserAgent;
     Assert.AreEqual(expected, actual);
 }
        private DataFeed ReturnGoogleAnalyticsDataFeed(DataQuery dataQuery)
        {
            string userName = ConfigurationManager.AppSettings["GoogleUsername"];
            string passWord = ConfigurationManager.AppSettings["GooglePassword"];

            var service = new AnalyticsService(ConfigurationManager.AppSettings["ApplicationName"]);

            GDataRequestFactory f = new GDataRequestFactory(ConfigurationManager.AppSettings["UserAgent"]);
            if (_proxyProvider != null)
            {
                var proxy = _proxyProvider.CreateProxy();
                f.Proxy = proxy;
            }

            service.RequestFactory = f;

            service.setUserCredentials(userName, passWord);

            return service.Query(dataQuery);

        }
        public PicasaService GetPicasaService(bool recreate = false)
        {
            if (recreate)
            {
                //Recreate service
                _picasaService = null;
                //Get google drive about to sync autorization
                //Because unknown problems in picasa autorization
                var drive = new GoogleDriveClient();
                drive.GetAbout();
            }

            if (_picasaService == null)
            {
                var creditals = GoogleDriveClient.GetCreditals();

                var requestFactory = new GDataRequestFactory(null);
                requestFactory.CustomHeaders.Add("Authorization: Bearer " + creditals.Token.AccessToken);
                requestFactory.CustomHeaders.Add("Gdata-version: 2");
                _picasaService = new PicasaService("api-project");
                _picasaService.RequestFactory = requestFactory;
            }
            return _picasaService;
        }
        //////////////////////////////////////////////////////////////////////
        /// <summary>default constructor</summary> 
        //////////////////////////////////////////////////////////////////////
        internal GDataRequest(GDataRequestType type, Uri uriTarget, GDataRequestFactory factory) {
            this.type = type;
            this.targetUri = uriTarget;
			if (uriTarget.OriginalString.StartsWith("http:"))
			{
				factory.UseSSL = false;	
			}
            this.factory = factory;
            this.useGZip = this.factory.UseGZip; // use gzip setting from factory
        }
 public void GDataRequestFactoryConstructorTest()
 {
     string userAgent = "TestValue"; // TODO: Initialize to an appropriate value
     GDataRequestFactory target = new GDataRequestFactory(userAgent);
     Assert.IsNotNull(target);
 }
 public void CustomHeadersTest()
 {
     string userAgent = "TestValue"; // TODO: Initialize to an appropriate value
     GDataRequestFactory target = new GDataRequestFactory(userAgent); // TODO: Initialize to an appropriate value
     List<string> actual;
     actual = target.CustomHeaders;
     Assert.IsNotNull(actual);
     Assert.IsTrue(actual.Count == 0); 
 }
 public void KeepAliveTest()
 {
     string userAgent = "TestValue"; // TODO: Initialize to an appropriate value
     GDataRequestFactory target = new GDataRequestFactory(userAgent); // TODO: Initialize to an appropriate value
     bool expected = false; // TODO: Initialize to an appropriate value
     bool actual;
     target.KeepAlive = expected;
     actual = target.KeepAlive;
     Assert.AreEqual(expected, actual);
 }
 public void ProxyTest()
 {
     string userAgent = "TestValue"; // TODO: Initialize to an appropriate value
     GDataRequestFactory target = new GDataRequestFactory(userAgent); // TODO: Initialize to an appropriate value
     IWebProxy expected = new WebProxy();
     IWebProxy actual;
     target.Proxy = expected;
     actual = target.Proxy;
     Assert.AreEqual(expected, actual);
 }
 public void TimeoutTest()
 {
     string userAgent = "TestValue"; // TODO: Initialize to an appropriate value
     GDataRequestFactory target = new GDataRequestFactory(userAgent); // TODO: Initialize to an appropriate value
     int expected = 250000; // TODO: Initialize to an appropriate value
     int actual;
     target.Timeout = expected;
     actual = target.Timeout;
     Assert.AreEqual(expected, actual);
 }
Example #13
0
        /////////////////////////////////////////////////////////////////////////////


        //////////////////////////////////////////////////////////////////////
        /// <summary>Inserts an AtomBase entry against a Uri. The overloaded
        /// version here will check if this is an AbstractEntry and if it has
        /// a media property set. If so, it will create a mime multipart envelope</summary>
        /// <param name="feedUri">the uri for the feed this object should be posted against</param>
        /// <param name="baseEntry">the entry to be inserted</param>
        /// <param name="type">the type of request to create</param>
        /// <param name="data">the async data payload</param>
        /// <returns> the response as a stream</returns>
        //////////////////////////////////////////////////////////////////////
        internal override Stream EntrySend(Uri feedUri, AtomBase baseEntry, GDataRequestType type, AsyncSendData data)
        {
            if (feedUri == null)
            {
                throw new ArgumentNullException("feedUri");
            }
            Tracing.Assert(baseEntry != null, "baseEntry should not be null");
            if (baseEntry == null)
            {
                throw new ArgumentNullException("baseEntry");
            }

            AbstractEntry entry = baseEntry as AbstractEntry;

            // if the entry is not an abstractentry or if no media is set, do the default
            if (entry == null || entry.MediaSource == null)
            {
                return(base.EntrySend(feedUri, baseEntry, type, data));
            }

            Stream outputStream = null;
            Stream inputStream  = null;

            try
            {
                IGDataRequest request = this.RequestFactory.CreateRequest(type, feedUri);
                request.Credentials = this.Credentials;

                GDataRequest r = request as GDataRequest;

                if (r != null)
                {
                    r.ContentType = MediaService.MimeContentType;
                    r.Slug        = entry.MediaSource.Name;

                    GDataRequestFactory f = this.RequestFactory as GDataRequestFactory;
                    if (f != null)
                    {
                        f.CustomHeaders.Add("MIME-version: 1.0");
                    }
                }

                if (data != null)
                {
                    GDataGAuthRequest gr = request as GDataGAuthRequest;
                    if (gr != null)
                    {
                        gr.AsyncData = data;
                    }
                }


                outputStream = request.GetRequestStream();
                inputStream  = entry.MediaSource.GetDataStream();
                StreamWriter w = new StreamWriter(outputStream);

                w.WriteLine("Media multipart posting");
                CreateBoundary(w, GDataRequestFactory.DefaultContentType);
                baseEntry.SaveToXml(outputStream);
                w.WriteLine();
                CreateBoundary(w, entry.MediaSource.ContentType);
                WriteInputStreamToRequest(inputStream, outputStream);
                w.WriteLine();
                w.WriteLine("--" + MediaService.MimeBoundary + "--");
                w.Flush();
                request.Execute();
                outputStream.Close();
                outputStream = null;
                return(request.GetResponseStream());
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (outputStream != null)
                {
                    outputStream.Close();
                }
                if (inputStream != null)
                {
                    inputStream.Close();
                }
            }
        }
Example #14
0
    private async Task Run(Boolean refresh)
    {
      UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
        new ClientSecrets
        {
          ClientId = CLIENT_ID,
          ClientSecret = CLIENT_SECRET
        },
        new[] { SCOPE },
        "user",
        CancellationToken.None, new FileDataStore("Spreadsheet.aboveTradera"));

      if (refresh)
      {
        refresh = credential.RefreshTokenAsync(CancellationToken.None).Result;
      }
      var requestFactory = new GDataRequestFactory("My App User Agent");
      requestFactory.CustomHeaders.Add(string.Format("Authorization: Bearer {0}", credential.Token.AccessToken));

      var service = new SpreadsheetsService("MySpreadsheetIntegration-v1");
      service.RequestFactory = requestFactory;

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

      main.UseWaitCursor = false;
      
      var query = new SpreadsheetQuery();
      query.Title = "Samling";
      query.Exact = true;

      // Make a request to the API and get all spreadsheets.
      var feed = service.Query(query);

      var spreadsheet = (SpreadsheetEntry)feed.Entries[0];
      // Console.WriteLine(spreadsheet.Title.Text);

      // Make a request to the API to fetch information about all
      // worksheets in the spreadsheet.
      var wsFeed = spreadsheet.Worksheets;

      // Iterate through each worksheet in the spreadsheet.
      foreach (WorksheetEntry entry in wsFeed.Entries)
      {
        // Get the worksheet's title, row count, and column count.
        string title = entry.Title.Text;
        uint rowCount = entry.Rows;
        uint colCount = entry.Cols;

        // Print the fetched information to the screen for this worksheet.
        // Console.WriteLine(title + "- rows:" + rowCount + " cols: " + colCount);
      }

      var worksheet = (WorksheetEntry)wsFeed.Entries[0];
      var listFeedLink = worksheet.Links.FindService(GDataSpreadsheetsNameTable.ListRel, null);

      // Fetch the list feed of the worksheet.
      var listQuery = new ListQuery(listFeedLink.HRef.ToString());
      var listFeed = service.Query(listQuery);

      database = Database.Load();

      if (database == null)
      {
        database = new Database();
      }

      // Download all stamps there is in Östergötland.
      Database newDatabase = new Database();
      DatabaseRow databaseRow = new DatabaseRow();
      newDatabase.Add(databaseRow);
      foreach (ListEntry row in listFeed.Entries)
      {
        if (row.Title.Text.StartsWith("Row:"))
        {
          databaseRow.Add(row);
        }
        else
        {
          databaseRow = new DatabaseRow(row);
          newDatabase.Add(databaseRow);
        }
      }

      var request = drive.Children.List("root");
      ChildList children = request.Execute();
      Google.Apis.Drive.v2.Data.File frimärken = null;
      foreach (var folder in children.Items)
      {
        frimärken = drive.Files.Get(folder.Id).Execute();
        if (frimärken.Title == "Frimärken")
        {
          break;
        }
      }

      // Download a File descriptor for all stamps in my collection.
      List<aboveTradera.DatabaseRowEntry.KeyValuePair<String, List<Google.Apis.Drive.v2.Data.File>>> images = new List<aboveTradera.DatabaseRowEntry.KeyValuePair<string, List<Google.Apis.Drive.v2.Data.File>>>();

      ChildrenResource.ListRequest folderCommand = drive.Children.List(frimärken.Id);
      folderCommand.MaxResults = 1000;
      // main.ToolStripProgressBar.Maximum = orter.Items.Count;
      int counter = 0;
      List<Google.Apis.Drive.v2.Data.File> folders = new List<Google.Apis.Drive.v2.Data.File>();
      const string collectingHeading = "Found images for ";
      do
      {
        try
        {
          ChildList orter = folderCommand.Execute();
          foreach (var ort in orter.Items)
          {
            Google.Apis.Drive.v2.Data.File folder = drive.Files.Get(ort.Id).Execute();
            if (backgroundGoogleDrive.CancellationPending) return;
            if (folder.Kind != "drive#file") continue;
            if (folder.Title.StartsWith("New")) continue;
            backgroundGoogleDrive.ReportProgress(++counter, collectingHeading + folder.Title);
            folders.Add(folder);
          }
          folderCommand.PageToken = orter.NextPageToken;
        }
        catch (Exception e)
        {
          Console.WriteLine("An error occurred: " + e.Message);
          folderCommand.PageToken = null;
        }
      } while (!String.IsNullOrEmpty(folderCommand.PageToken)); 

      counter = 0;
      const string heading = "Downloading images for ";
      Thread.CurrentThread.CurrentCulture = new CultureInfo("sv-SE");
      foreach (var stampFolder in folders.OrderBy(p => p.Title))
      {
        var list = new List<Google.Apis.Drive.v2.Data.File>();
        if (backgroundGoogleDrive.CancellationPending) return;
        backgroundGoogleDrive.ReportProgress(++counter, heading + stampFolder.Title);
        var stampImageRequest = drive.Children.List(stampFolder.Id).Execute();
        foreach (var image in stampImageRequest.Items)
        {
          Google.Apis.Drive.v2.Data.File imageFile = drive.Files.Get(image.Id).Execute();
          list.Add(imageFile);
          //DownloadImage(drive, imageFile);
        }
        var keyvaluePair = new aboveTradera.DatabaseRowEntry.KeyValuePair<string, List<Google.Apis.Drive.v2.Data.File>>(stampFolder.Title.ToUpper(), list);
        images.Add(keyvaluePair);
      }
      if (backgroundGoogleDrive.CancellationPending) return;
      backgroundGoogleDrive.ReportProgress(100, "Analyzing...");

      // Let's do a check that I've correctly mark a stamp as my and that I've scanned the stamp.
      // I have all stamps marks with a "z" - link'em with the scanned image File descriptor.
      // Print a report of those images that's missing and those that's extra.

      // First we check that we have a image 4 all stamps we have logged as ours i.e. all "z"'d should have an image.
      string fileName = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());

      using (TextWriter writer = System.IO.File.CreateText(fileName))
      {
        bool anything2report = false;
        foreach (var row in newDatabase.Rows)
        {
          if (row.Town == null) continue;
          foreach (DatabaseRowEntry entry in row.Entries)
          {
            if (entry.IsOwned)
            {
              String cancelletion = DatabaseRow.Cancellation(entry.Start);
              try
              {
                foreach(var image in images.Find(s => s.Key == row.Town).Value.FindAll(t => t.Title.StartsWith(cancelletion))){
                  entry.Images.Add(new aboveTradera.DatabaseRowEntry.KeyValuePair<string, string>(image.Id, image.DownloadUrl));
                }
              }
              catch (Exception)
              {
                anything2report = true;
                writer.WriteLine("Missing image {0} ({1})", row.Town, cancelletion);
              }
            }
          }
        }
        // Then we check that we don't have an image that is not checked with a "z"
        foreach (var image in images)
        {
          foreach (var file in image.Value)
          {
            foreach (var row in newDatabase.Rows.FindAll(s => s.Town == image.Key))
            {
              try
              {
                var entry = row.Entries.Find(s => DatabaseRow.Cancellation(file.Title).StartsWith(DatabaseRow.Cancellation(s.Start)));
                if (entry == null) throw new Exception();
                if (!entry.IsOwned)
                {
                  entry.ExtraImages.Add(new aboveTradera.DatabaseRowEntry.KeyValuePair<string, string>(file.Id, file.DownloadUrl));
                  throw new Exception();
                }
              }
              catch (Exception)
              {
                anything2report = true;
                writer.WriteLine("Stamp not marked as owned {0} ({1})", row.Town, file.Title);
              }
            }
          }
        }
        if (anything2report)
        {
          Process.Start("notepad.exe", fileName);
        }
      }
      newDatabase.Save();
      if (backgroundGoogleDrive.CancellationPending) return;
      backgroundGoogleDrive.ReportProgress(0, "");
      database = newDatabase;
    }
Example #15
0
        public static void doThatThing(Form1 f)
        {
            f.text("Querying MySQL");
            var appData = getAppDataFromMySQL();
            f.text("MySQL Query Complete");
            string serviceAccountEmail = "*****@*****.**";
            f.text("Creating X509 Cert");
            var certificate = new X509Certificate2(@"C:\\Users\\Joey\\Desktop\\dmmsapi.p12", "notasecret", X509KeyStorageFlags.Exportable);
            f.text("Creating Google Credential");
            ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail) {
                Scopes = new[] { "https://spreadsheets.google.com/feeds" }
            }.FromCertificate(certificate));
            credential.RequestAccessTokenAsync(System.Threading.CancellationToken.None).Wait();
            f.text("initializing spreadsheetservice");
            SpreadsheetsService service = new SpreadsheetsService("Dalmarko-Master-Sheet");
            var requestFactory = new GDataRequestFactory("Dalmarko-Master-Sheet");
            requestFactory.CustomHeaders.Add(string.Format("Authorization: Bearer {0}", credential.Token.AccessToken));
            service.RequestFactory = requestFactory;
            f.text("preparing html");
            string html = "<html><table border=1><tr>";
            Console.WriteLine("before ssq");
            f.text("initializing spreadsheetquery");
            SpreadsheetQuery query = new SpreadsheetQuery();
            SpreadsheetFeed ssf = service.Query(query);
            foreach(SpreadsheetEntry sse in ssf.Entries) {
                Console.WriteLine(sse.Title.Text);
                WorksheetFeed wf = sse.Worksheets;
                foreach(WorksheetEntry we in wf.Entries) {
                    f.text("total entries: " + we.Rows);
                    f.max((int) we.Rows);
                    /*AtomLink listFeedLink = we.Links.FindService(GDataSpreadsheetsNameTable.ListRel, null);
                    ListQuery listQuery = new ListQuery(listFeedLink.HRef.ToString());
                    ListFeed listFeed = service.Query(listQuery);
                    foreach(ListEntry row in listFeed.Entries) {
                        html = html + "</tr><tr>";
                        foreach(ListEntry.Custom element in row.Elements) {
                            html = html + "<td>" + element.Value + "</td>";
                        }
                    }*/
                    int cols = (int) we.Cols;
                    int coliterator = 0;
                    CellQuery cq = new CellQuery(we.CellFeedLink);
                    cq.ReturnEmpty = ReturnEmptyCells.yes;
                    CellFeed cf = service.Query(cq);

                    Boolean headerCellsDone = false;
                    int rows = 1;

                    foreach(CellEntry cell in cf.Entries) {
                        if(!headerCellsDone) {
                            if(cell.Value != null) {
                                html = html + "<th>" + cell.Value + "</th>";
                                if(cell.Value.ToString().Contains("Parsed Sku")) {
                                    headerCellsDone = true;
                                    html = html + "</tr><tr>";
                                    rows++;
                                }
                            } else {
                                html = html + "<td></td>";
                            }
                        } else {
                            coliterator++;
                            if(coliterator == 1) {
                                CellQuery ncq = new CellQuery(we.CellFeedLink);
                                ncq.MinimumRow = (uint) rows;
                                ncq.MaximumColumn = (uint) cols;
                                ncq.MinimumColumn = (uint) cols;
                                try {
                                    CellFeed ncf = service.Query(ncq);
                                    string imgsrc = "http://dalmarkodesigns.com/master-images/";
                                    CellEntry ce = (CellEntry) ncf.Entries[0];
                                    if(ce.Value != null)
                                        imgsrc = imgsrc + ce.Value + ".jpg";
                                    else
                                        imgsrc = imgsrc + "default.jpg";

                                    html = html + "<td><img src='" + imgsrc + "' height=200 width=200/></td>";
                                } catch(Exception e) {
                                    string imgsrc = "http://dalmarkodesigns.com/master-images/default.jpg";
                                    html = html + "<td><img src='" + imgsrc + "' height=200 width=200/></td>";
                                }

                            } else {
                                if(cell.Value != null)
                                    html = html + "<td>" + cell.Value + "</td>";
                                else
                                    html = html + "<td></td>";
                            }

                            if(coliterator == cols) {
                                html = html + "</tr><tr>";
                                rows++;
                                f.prog(rows);
                                f.text("processing entry " + rows + " of " + we.Rows);
                                f.percent(rows, (int) we.Rows);
                                coliterator = 0;
                            }
                        }
                    }
                }
            }
            html = html + "</tr></table></html>";
            File.WriteAllText("C:\\Users\\Joey\\Desktop\\index.html", html);
            alreadyRunning = false;
        }
 public GDataAuthenticator(string accessToken)
 {
     requestFactory = new GDataRequestFactory ("PicasaWebSync");
     requestFactory.CustomHeaders.Add (string.Format ("Authorization: Bearer {0}", accessToken));
 }