private void DoListInsert() { String[] commaSplit = this.listAddTextBox.Text.Split(','); ListEntry entry = new ListEntry(); for (int i = 0; i < commaSplit.Length; i++) { String[] pair = commaSplit[i].Split('='); ListEntry.Custom custom = new ListEntry.Custom(); custom.LocalName = pair[0]; custom.Value = pair[1]; entry.Elements.Add(custom); } AtomEntry retEntry = service.Insert(new Uri(this.worksheetListView.SelectedItems[0].SubItems[2].Text), entry); }
private string ToGoogleTable() { WorksheetFeed wsFeed = TargetTable.Worksheets; WorksheetEntry worksheet = (WorksheetEntry)wsFeed.Entries[0]; // Define the URL to request the list feed of the worksheet. AtomLink listFeedLink = worksheet.Links.FindService(GDataSpreadsheetsNameTable.ListRel, null); // Fetch the list feed of the worksheet. ListQuery listQuery = new ListQuery(listFeedLink.HRef.ToString()); ListFeed listFeed = service.Query(listQuery); CellQuery cellQuery = new CellQuery(worksheet.CellFeedLink); CellFeed cellFeed = service.Query(cellQuery); CellEntry cellEntry = new CellEntry(1, 1, "oid"); cellFeed.Insert(cellEntry); cellEntry = new CellEntry(1, 2, "value"); cellFeed.Insert(cellEntry); cellEntry = new CellEntry(1, 3, "type"); cellFeed.Insert(cellEntry); ProgressBarSetStartParams(progressBar1, ListData[ListData.Count - 1].Count); tabControlShow(progressBar1); tabControlShow(label3); for (int i = 0; i < ListData[ListData.Count - 1].Count; i++) { IncrementProgressbar(progressBar1); IncrementGeneralLabel(string.Format("Выполнено {0}/{1}", i + 1, ListData[ListData.Count - 1].Count)); service.Insert(listFeed, ListData[ListData.Count - 1].GetCustom(i)); } tabControlShow(progressBar1, false); tabControlShow(label3, false); return("Данные записаны"); }
private static void EnviarFilas(string filas, SpreadsheetsService servicio, string url) { const string tipoDelContenido = "application/atom+xml"; // Convierte el contenido de la fila en stream var filaEnArregloDeBytes = Encoding.UTF8.GetBytes(filas); var filaEnStream = new MemoryStream(filaEnArregloDeBytes); // Inserta la fila en la hoja Historial (Google) servicio.Insert(new Uri(url), filaEnStream, tipoDelContenido, ""); //servicio.StreamSend(new Uri(url), filaEnStream, GDataRequestType.Batch, tipoDelContenido, "", ""); }
public ActionResult Document(int?rowNumber, string docName, string workName) { var model = ConfigurationController.GoogleDocuments; if (model != null && model.GoogleAPIAccess != null) { GOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory(null, "MySpreadsheetIntegration-v1", model.GoogleAPIAccess); SpreadsheetsService service = new SpreadsheetsService("MySpreadsheetIntegration-v1"); service.RequestFactory = requestFactory; model.RowActive = rowNumber; if (rowNumber != null) { //add row to save table model.RowActiveSave = (ListEntry)service.Insert(model.TableSave, (ListEntry)model.Table[(int)rowNumber]); model.RowActiveSave.Elements.Add(new ListEntry.Custom() { LocalName = "workdate", Value = DateTime.Now.ToString() }); model.RowActiveSave.Elements.Add(new ListEntry.Custom() { LocalName = "hours", Value = "0" }); model.RowActiveSave.Update(); } else { GetSaveTable(); ListEntry lastRow = (ListEntry)model.TableSave.Entries.Last(); var lastRowCells = (ListEntry.CustomElementCollection)lastRow.Elements; DateTime startDate = DateTime.Now; foreach (ListEntry.Custom cell in lastRowCells) { if (cell.LocalName.Equals("workdate")) { startDate = DateTime.Parse(cell.Value); } if (cell.LocalName.Equals("hours")) { cell.Value = ((double)(DateTime.Now - startDate).Seconds / 60.0 / 60.0).ToString(); } } lastRow.Update(); } //timer.Interval = 10000; //10 sec //timer.Elapsed += timer_Elapsed; //timer.Start(); } return(RedirectToAction("Document", new { docName = docName, workName = workName })); }
}//function static bool AddRow(ListFeed feed, string[] content) { if (content.Length != ssCOLUMNS.Length) return false; ListEntry row = new ListEntry(); //fill row from content for (int i = 0; i < ssCOLUMNS.Length; i++) { row.Elements.Add(new ListEntry.Custom() { LocalName = ssCOLUMNS[i], Value = content[i] }); //Log.Add("debug " + row.ToString()); }//for //insert row service.Insert(feed, row); return true; }//function
public void InsertSMSIntoSpreadsheet(WorksheetEntry worksheet, Sms sms) { // Loop through rows in worksheet if (worksheet != null) { // Define the URL to request the list feed of the worksheet. AtomLink listFeedLink = worksheet.Links.FindService(GDataSpreadsheetsNameTable.ListRel, null); // Fetch the list feed of the worksheet. ListQuery listQuery = new ListQuery(listFeedLink.HRef.ToString()); ListFeed listFeed = _service.Query(listQuery); // Create a local representation of the new row. ListEntry row = new ListEntry(); row.Elements.Add(new ListEntry.Custom() { LocalName = "number", Value = sms.PhoneNumber }); row.Elements.Add(new ListEntry.Custom() { LocalName = "message", Value = sms.Body }); row.Elements.Add(new ListEntry.Custom() { LocalName = "date", Value = sms.Date.ToString() }); if (sms.Address != null) { row.Elements.Add(new ListEntry.Custom() { LocalName = "address", Value = sms.Address.ToString() }); } // Send the new row to the API for insertion. _service.Insert(listFeed, row); } }
public override void Log(LoggingEntery LE) { IniFile Ini = new IniFile(Path.Combine(Environment.CurrentDirectory, "GoogleDocs.ini")); // nir start //////////////////////////////////////////////////////////////////////////// // STEP 1: Configure how to perform OAuth 2.0 //////////////////////////////////////////////////////////////////////////// // TODO: Update the following information with that obtained from // https://code.google.com/apis/console. After registering // your application, these will be provided for you. //string CLIENT_ID = "339569043085-6k0io9kdubi7a3g3jes4m76t614fkccr.apps.googleusercontent.com"; // This is the OAuth 2.0 Client Secret retrieved // above. Be sure to store this value securely. Leaking this // value would enable others to act on behalf of your application! //string CLIENT_SECRET = "wWC4Wcb12RbQg4YuGWJtkh4j"; // Space separated list of scopes for which to request access. //string SCOPE = "https://spreadsheets.google.com/feeds https://docs.google.com/feeds"; // This is the Redirect URI for installed applications. // If you are building a web application, you have to set your // Redirect URI at https://code.google.com/apis/console. //tring REDIRECT_URI = "urn:ietf:wg:oauth:2.0:oob"; //////////////////////////////////////////////////////////////////////////// // STEP 2: Set up the OAuth 2.0 object //////////////////////////////////////////////////////////////////////////// // OAuth2Parameters holds all the parameters related to OAuth 2.0. OAuth2Parameters parameters = new OAuth2Parameters(); // Set your OAuth 2.0 Client Id (which you can register at // https://code.google.com/apis/console). parameters.ClientId = Ini.IniReadValue(ConnectSection, "ClientID"); // Set your OAuth 2.0 Client Secret, which can be obtained at // https://code.google.com/apis/console. parameters.ClientSecret = Ini.IniReadValue(ConnectSection, "ClientSecret"); // Set your Redirect URI, which can be registered at // https://code.google.com/apis/console. parameters.RedirectUri = Ini.IniReadValue(ConnectSection, "RedirectURI"); // Set your refresh token parameters.RefreshToken = Ini.IniReadValue(ConnectSection, "RefreshToken"); parameters.AccessToken = Ini.IniReadValue(ConnectSection, "LastAccessToken"); // Set the scope for this particular service. parameters.Scope = Ini.IniReadValue(ConnectSection, "Scope"); // Get the authorization url. The user of your application must visit // this url in order to authorize with Google. If you are building a // browser-based application, you can redirect the user to the authorization // url. //string authorizationUrl = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters); //Console.WriteLine(authorizationUrl); //Console.WriteLine("Please visit the URL above to authorize your OAuth " // + "request token. Once that is complete, type in your access code to " // + "continue..."); //////////////////////////////////////////////////////////////////////////// // STEP 4: Get the Access Token //////////////////////////////////////////////////////////////////////////// // Once the user authorizes with Google, the request token can be exchanged // for a long-lived access token. If you are building a browser-based // application, you should parse the incoming request token from the url and // set it in OAuthParameters before calling GetAccessToken(). OAuthUtil.RefreshAccessToken(parameters);//parameters.AccessToken; Ini.IniWriteValue(ConnectSection, "LastAccessToken", parameters.AccessToken); // Console.WriteLine("OAuth Access Token: " + accessToken); //////////////////////////////////////////////////////////////////////////// // STEP 5: Make an OAuth authorized request to Google //////////////////////////////////////////////////////////////////////////// // Initialize the variables needed to make the request GOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory(null, "OctoTipPlus", parameters); SpreadsheetsService myService = new SpreadsheetsService("OctoTipPlus"); myService.RequestFactory = requestFactory; // nir end string User = Ini.IniReadValue("UserLogin", "User"); string Password = Ini.IniReadValue("UserLogin", "Password"); // SpreadsheetsService myService = new SpreadsheetsService("MySpreadsheetIntegration-v1"); //myService.setUserCredentials(User,Password); SpreadsheetQuery Squery = new SpreadsheetQuery(); string Sender = LE.Sender; Squery.Title = Sender; Squery.Exact = true; SpreadsheetFeed Sfeed; try { Sfeed = myService.Query(Squery); } catch (Google.GData.Client.InvalidCredentialsException e) { throw(new Exception(string.Format("Credentials error in google acount for user:{0}", User), e)); } if (Sfeed.Entries.Count == 0) { //DriveService service1 = new DriveService(); //service.SetAuthenticationToken(parameters.AccessToken);//.setUserCredentials(User,Password); //Google.GData.Client.GOAuth2RequestFactory requestf = new Google.GData.Client.GOAuth2RequestFactory(null, "OctoTipPlus",parameters); OAuthUtil.RefreshAccessToken(parameters); //parameters.AccessToken; Ini.IniWriteValue(ConnectSection, "LastAccessToken", parameters.AccessToken); Google.GData.Documents.DocumentsService service = new Google.GData.Documents.DocumentsService("OctoTipPlus"); GOAuth2RequestFactory requestFactory2 = new GOAuth2RequestFactory(null, "OctoTipPlus", parameters); service.RequestFactory = requestFactory2; //service.RequestFactory=requestf; // Instantiate a DocumentEntry object to be inserted. Google.GData.Documents.DocumentEntry entry = new Google.GData.Documents.DocumentEntry(); // Set the document title entry.Title.Text = LE.Sender; // Add the document category entry.Categories.Add(Google.GData.Documents.DocumentEntry.SPREADSHEET_CATEGORY); // Make a request to the API and create the document. Google.GData.Documents.DocumentEntry newEntry = service.Insert( Google.GData.Documents.DocumentsListQuery.documentsBaseUri, entry); Squery = new SpreadsheetQuery(); Squery.Title = Sender; Squery.Exact = true; Sfeed = myService.Query(Squery); } SpreadsheetEntry spreadsheet = (SpreadsheetEntry)Sfeed.Entries[0]; WorksheetEntry ProtocolWorksheetEntry = null; AtomLink link = spreadsheet.Links.FindService(GDataSpreadsheetsNameTable.WorksheetRel, null); WorksheetQuery Wquery = new WorksheetQuery(link.HRef.ToString()); WorksheetFeed Wfeed = myService.Query(Wquery); foreach (WorksheetEntry worksheet in Wfeed.Entries) { if (worksheet.Title.Text == LE.SubSender) { ProtocolWorksheetEntry = worksheet; } } if (ProtocolWorksheetEntry == null) { // cteate new worksheet WorksheetEntry worksheet = new WorksheetEntry(); worksheet.Title.Text = LE.SubSender; worksheet.Cols = 3; worksheet.Rows = 5; // Send the local representation of the worksheet to the API for // creation. The URL to use here is the worksheet feed URL of our // spreadsheet. WorksheetFeed wsFeed = spreadsheet.Worksheets; ProtocolWorksheetEntry = myService.Insert(wsFeed, worksheet); CellFeed cellFeed = ProtocolWorksheetEntry.QueryCellFeed(); CellEntry cellEntry = new CellEntry(1, 1, DateHeader); cellFeed.Insert(cellEntry); cellEntry = new CellEntry(1, 2, MessageHeader); cellFeed.Insert(cellEntry); } // Define the URL to request the list feed of the worksheet. AtomLink listFeedLink = ProtocolWorksheetEntry.Links.FindService(GDataSpreadsheetsNameTable.ListRel, null); // Fetch the list feed of the worksheet. ListQuery listQuery = new ListQuery(listFeedLink.HRef.ToString()); ListFeed listFeed = myService.Query(listQuery); string Message = string.Format("{0}\n{1}", LE.Title, LE.Message); // Create a local representation of the new row. ListEntry row = new ListEntry(); row.Elements.Add(new ListEntry.Custom() { LocalName = DateHeader, Value = DateTime.Now.ToString() }); row.Elements.Add(new ListEntry.Custom() { LocalName = MessageHeader, Value = Message }); // Send the new row to the API for insertion. myService.Insert(listFeed, row); }
// this method updates a row in the google spreadsheet // MySpreadsheetIntegration-v1 public static void AddRowToGoogleSpreadsheet() { try { clsUtransEditorStaticClass.AuthorizeRequestGoogleSheetsAPI(); SpreadsheetEntry spreadsheet = null; //string docKey = "1A5be20hhg2fe2AGWe6BpeJmtdI-_ITcTSF1WiIVbyTY"; //string gDocsURL = "https://docs.google.com/spreadsheet/ccc?key={0}"; //string docURL = String.Format(gDocsURL, docKey); //FeedQuery singleQuery = new FeedQuery(); //singleQuery.Uri = new Uri(docKey); //AtomFeed newFeed = service.Query(singleQuery); //AtomEntry retrievedEntry = newFeed.Entries[0]; //MessageBox.Show(retrievedEntry.Title.Text); ////SpreadsheetsService service = new SpreadsheetsService("MySpreadsheetIntegration-v1"); // TODO: Authorize the service object for a specific user (see other sections) // Instantiate a SpreadsheetQuery object to retrieve spreadsheets. SpreadsheetQuery query = new SpreadsheetQuery(); // Make a request to the API and get all spreadsheets. SpreadsheetFeed feed = service.Query(query); if (feed.Entries.Count == 0) { // TODO: There were no spreadsheets, act accordingly. MessageBox.Show("google didn't find any spreadsheets."); } // TODO: Choose a spreadsheet more intelligently based on your // app's needs. ////SpreadsheetEntry spreadsheet = (SpreadsheetEntry)feed.Entries[0]; ////MessageBox.Show(spreadsheet.Title.Text); //Console.WriteLine(spreadsheet.Title.Text); //loop through the feeds to find the spreadsheet with the correct name for (int i = 0; i < feed.Entries.Count; i++) { spreadsheet = (SpreadsheetEntry)feed.Entries[i]; if (spreadsheet.Title.Text == "UtransEditorCountyNotificationList") { //MessageBox.Show("found it!!!"); break; } else { //MessageBox.Show("Didn't find a spreadsheet with the name UtransEditorCountyNotificationList. The info was not saved to a google spreadsheet."); } } // Get the first worksheet of the first spreadsheet. // TODO: Choose a worksheet more intelligently based on your // app's needs. WorksheetFeed wsFeed = spreadsheet.Worksheets; WorksheetEntry worksheet = (WorksheetEntry)wsFeed.Entries[0]; // Define the URL to request the list feed of the worksheet. AtomLink listFeedLink = worksheet.Links.FindService(GDataSpreadsheetsNameTable.ListRel, null); // Fetch the list feed of the worksheet. ListQuery listQuery = new ListQuery(listFeedLink.HRef.ToString()); ListFeed listFeed = service.Query(listQuery); // Create a local representation of the new row. ListEntry row = new ListEntry(); row.Elements.Add(new ListEntry.Custom() { LocalName = "logdate", Value = DateTime.Now.ToString("d") }); row.Elements.Add(new ListEntry.Custom() { LocalName = "countyid", Value = clsGlobals.strCountyID }); row.Elements.Add(new ListEntry.Custom() { LocalName = "agrcnotes", Value = clsGlobals.strUserInputForSpreadsheet.ToString().Trim() }); row.Elements.Add(new ListEntry.Custom() { LocalName = "agrcsegment", Value = clsGlobals.strAgrcSegment.ToString().Trim() }); row.Elements.Add(new ListEntry.Custom() { LocalName = "cntysegment", Value = clsGlobals.strCountySegmentTrimed }); row.Elements.Add(new ListEntry.Custom() { LocalName = "leftfrom", Value = clsGlobals.strCountyL_F_Add }); row.Elements.Add(new ListEntry.Custom() { LocalName = "leftto", Value = clsGlobals.strCountyL_T_Add }); row.Elements.Add(new ListEntry.Custom() { LocalName = "rightfrom", Value = clsGlobals.strCountyR_F_Add }); row.Elements.Add(new ListEntry.Custom() { LocalName = "rightto", Value = clsGlobals.strCountyR_T_Add }); row.Elements.Add(new ListEntry.Custom() { LocalName = "city", Value = clsGlobals.strGoogleSpreadsheetCityField }); // Send the new row to the API for insertion. service.Insert(listFeed, row); } catch (Exception ex) { clsGlobals.logger.Error(Environment.NewLine + "Error Message: " + ex.Message + Environment.NewLine + "Error Source: " + ex.Source + Environment.NewLine + "Error Location:" + ex.StackTrace + Environment.NewLine + "Target Site: " + ex.TargetSite); MessageBox.Show("Error Message: " + Environment.NewLine + ex.Message + Environment.NewLine + Environment.NewLine + "Error Source: " + Environment.NewLine + ex.Source + Environment.NewLine + Environment.NewLine + "Error Location:" + Environment.NewLine + ex.StackTrace, "UTRANS Editor tool error!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } }
public void MergeSheet(string cellsFeedURI, string listFeedURI, IList <IntelDataRow> rows) { //make sure our column headers are set to known values since the list feed depends on them SetColumnHeaders(cellsFeedURI, "Team", "Stats"); ListFeed feed = service.Query(new ListQuery(listFeedURI)); //treat all data as text, escape = and numbers foreach (var r in rows) { r.Team = EscapeCellValue(r.Team); r.Stats = EscapeCellValue(r.Stats); } //NOTE: LocalName is the ColumnHeader value except it MUST use lower case AND replace spaces with _ string[][] values = { new string[] { "team", "" }, new string[] { "stats", "" } }; int i = 0; //update existing rows for (; i < feed.Entries.Count && i < rows.Count; ++i) { ListEntry entry = (ListEntry)feed.Entries[i]; IntelDataRow r = rows[i]; values[0][1] = r.Team; values[1][1] = r.Stats; bool update = false; foreach (ListEntry.Custom el in entry.Elements) { foreach (var kv in values) { if (el.LocalName == kv[0] && el.Value != kv[1]) { update = true; el.Value = kv[1]; } } } if (update) { entry.Update(); } } //delete the remaining rows for (; i < feed.Entries.Count; ++i) { ListEntry entry = (ListEntry)feed.Entries[i]; entry.Delete(); } //or add the remaining intel for (; i < rows.Count; ++i) { var r = rows[i]; var entry = new ListEntry(); entry.Elements.Add(new ListEntry.Custom() { LocalName = "team", Value = r.Team }); entry.Elements.Add(new ListEntry.Custom() { LocalName = "stats", Value = r.Stats }); service.Insert(new Uri(listFeedURI), entry); } }
static void Main(string[] args) { try { string Profile = (args.Length > 0) ? args[0] : "default"; Console.WriteLine(Profile); Logfile = Profile + "_google.log"; Inifile = Profile + ".ini"; if (File.Exists(Inifile) == false) throw new ArgumentException("Profile is not found - " + Inifile); Props prop = new Props(); prop.Load(Inifile); #region get settings string LOGIN = prop.Get("login"); string PASSWORD = prop.Get("password"); string SPREADSHEET = prop.Get("spreadsheet"); string WORKSHEET = prop.Get("worksheet"); string CSV = prop.Get("csv"); string COLUMNS = prop.Get("columns"); #endregion #region test settings if (LOGIN == string.Empty) throw new ArgumentException(@"Setting 'login' is not found in profile"); if (PASSWORD == string.Empty) throw new ArgumentException(@"Setting 'password' is not found in profile"); if (SPREADSHEET == string.Empty) throw new ArgumentException(@"Setting 'spreadsheet' is not found in profile"); if (WORKSHEET == string.Empty) throw new ArgumentException(@"Setting 'worksheet' is not found in profile"); if (CSV == string.Empty) throw new ArgumentException(@"Setting 'csv' is not found in profile"); if (COLUMNS == string.Empty) throw new ArgumentException(@"Setting 'columns' is not found in profile"); if (File.Exists(CSV) == false) throw new ArgumentException("CSV is not found - " + Inifile); #endregion #region spreadsheet get service = new SpreadsheetsService("SynesisIntegration-v1"); service.setUserCredentials(LOGIN, PASSWORD); SpreadsheetEntry spreadsheet = null; SpreadsheetFeed feed = service.Query(new SpreadsheetQuery()); foreach (SpreadsheetEntry item in feed.Entries) { if (item.Title.Text == SPREADSHEET) { Log.Add("SPREADSHEET is found - " + SPREADSHEET); spreadsheet = item; //spreadsheet.SaveToXml(new FileStream("spreadsheet.xml", FileMode.Create)); break; }//if }//for if (spreadsheet == null) throw new ArgumentException("SPREADSHEET is not found - " + SPREADSHEET); #endregion #region worksheet get WorksheetEntry worksheet = null; WorksheetFeed wsFeed = spreadsheet.Worksheets; foreach (WorksheetEntry entry in wsFeed.Entries) { if (entry.Title.Text == WORKSHEET) { worksheet = entry; Log.Add("WORKSHEET is found - " + WORKSHEET); break; }//if }//for if (worksheet == null) { Log.Add("WORKSHEET is not found - " + WORKSHEET); worksheet = new WorksheetEntry(); worksheet.Title.Text = WORKSHEET; service.Insert(wsFeed, worksheet); Log.Add("WORKSHEET is added - " + WORKSHEET); }//if #endregion //CLEAR worksheet worksheet.Rows = 1; worksheet.Update(); // Fetch the list feed of the worksheet. AtomLink listFeedLink = worksheet.Links.FindService(GDataSpreadsheetsNameTable.ListRel, null); ListQuery listQuery = new ListQuery(listFeedLink.HRef.Content); ListFeed listFeed = service.Query(listQuery); //delimiter on extension char Delim = ';'; if (CSV.EndsWith(".tsv")) Delim = '\t'; //columns ssCOLUMNS = COLUMNS.Split(';'); for (int i = 0; i < ssCOLUMNS.Length; i++) ssCOLUMNS[i] = ssCOLUMNS[i].ToLower(); #region input rows string[] input = File.ReadAllLines(CSV); Log.Add("CSV " + CSV + " has " + input.Length + " items"); int CountAdded = 0; foreach (string s in input) { if (AddRow(listFeed, s.Split(Delim))) CountAdded++; else Log.Add("Row is not compatible - " + s); }//for Log.Add("Rows inserted - " + CountAdded.ToString()); #endregion }//try catch (Exception e) { Log.Add(e.Message); }//catch finally { File.WriteAllLines(Logfile, Log.ToArray()); }//finally }//function
protected void Button2_Click(object sender, EventArgs e) { OAuth2Parameters parameters = new OAuth2Parameters(); parameters.ClientId = clientID.Text.Trim(); parameters.ClientSecret = clientSecret.Text.Trim(); parameters.RedirectUri = REDIRECT_URI; parameters.Scope = SCOPE; parameters.AccessCode = aToken.Text.Trim(); try { //dealing with slack; string urlWithAccessToken = sToken.Text.Trim(); SlackClient client = new SlackClient(urlWithAccessToken); client.PostMessage(username: owner.Text.Trim(), text: uStory.Text.Trim(), channel: "#" + cID.Text.Trim()); //Now Deal with spreadsheet. OAuthUtil.GetAccessToken(parameters); string accessToken = parameters.AccessToken; GOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory(null, "MySpreadsheetIntegration-v1", parameters); SpreadsheetsService service = new SpreadsheetsService("MySpreadsheetIntegration-v1"); service.RequestFactory = requestFactory; SpreadsheetQuery query = new SpreadsheetQuery(); query.Title = sID.Text.Trim(); // Make a request to the API and get the spreadsheet; SpreadsheetFeed feed = service.Query(query); if (feed.Entries.Count != 1) { msg.Text = "The Mentioned Spreadsheet does not exist"; return; } SpreadsheetEntry spreadsheet = (SpreadsheetEntry)feed.Entries[0]; WorksheetFeed wsFeed = spreadsheet.Worksheets; WorksheetEntry worksheet = (WorksheetEntry)wsFeed.Entries[0]; AtomLink listFeedLink = worksheet.Links.FindService(GDataSpreadsheetsNameTable.ListRel, null); ListQuery listQuery = new ListQuery(listFeedLink.HRef.ToString()); ListFeed listFeed = service.Query(listQuery); // Create a local representation of the new row. ListEntry row = new ListEntry(); row.Elements.Add(new ListEntry.Custom() { LocalName = "userstory", Value = uStory.Text.Trim() }); row.Elements.Add(new ListEntry.Custom() { LocalName = "owner", Value = owner.Text.Trim() }); try { // Send the new row to the API for insertion. service.Insert(listFeed, row); //Disable button 1 and enable button 2. Button1.Visible = true; Button2.Visible = false; //disable all text boxes except for the access token. uStory.Enabled = true; owner.Enabled = true; clientID.Enabled = true; clientSecret.Enabled = true; sID.Enabled = true; sToken.Enabled = true; cID.Enabled = true; aToken.Enabled = true; //clear all textboxes uStory.Text = owner.Text = sToken.Text = ""; msg.Text = "Submitted Successfully"; } catch (Exception) { msg.Text = "Error while sending data to spreadsheet."; } } catch (Exception) { msg.Text = "Some error occured."; } }
public void method1() { OAuth2Parameters parameters = (OAuth2Parameters)Session["para"]; if (!string.IsNullOrEmpty(Request.QueryString["Code"])) { parameters.AccessCode = Request.QueryString["Code"].ToString();// = Console.ReadLine(); OAuthUtil.GetAccessToken(parameters); // //parameters.AccessToken= credential.Token.AccessToken; // string accessToken = parameters.AccessToken; Console.WriteLine("OAuth Access Token: " + accessToken); GOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory(null, "MySpreadsheetIntegration-v1", parameters); SpreadsheetsService service = new SpreadsheetsService("MySpreadsheetIntegration-v1"); service.RequestFactory = requestFactory; SpreadsheetQuery query = new SpreadsheetQuery(); SpreadsheetFeed feed = service.Query(query); //foreach (SpreadsheetEntry entry in feed.Entries) //{ // Console.WriteLine(entry.Title.Text); //} //SpreadsheetEntry spreadsheet = (SpreadsheetEntry)feed.Entries[0]; if (feed.Entries.Where(x => x.Title.Text == "testSS").First() != null) { SpreadsheetEntry spreadsheet = (SpreadsheetEntry)feed.Entries.Where(x => x.Title.Text == "testSS").First(); //SpreadsheetEntry spreadsheet = (SpreadsheetEntry)feed.CreateFeedEntry(); //Console.WriteLine(spreadsheet.Title.Text); //AtomTextConstruct at = new AtomTextConstruct(AtomTextConstructElementType.Title); //at.Text = "test"; //spreadsheet.Title = at; // spreadsheet.Worksheets.AddExtension(requestFactory); var t = (Home.JSONClass)Session["UserDataGet"]; List <object> lists = new List <object>() { t.email, t.name, t.given_name, t.family_name, t.picture, t.Gender, t.locale }; // Get the first worksheet of the first spreadsheet. // TODO: Choose a worksheet more intelligently based on your // app's needs. WorksheetFeed wsFeed = spreadsheet.Worksheets; WorksheetEntry worksheet = (WorksheetEntry)wsFeed.Entries[0]; // Define the URL to request the list feed of the worksheet. AtomLink listFeedLink = worksheet.Links.FindService(GDataSpreadsheetsNameTable.ListRel, null); // Fetch the list feed of the worksheet. ListQuery listQuery = new ListQuery(listFeedLink.HRef.ToString()); ListFeed listFeed = service.Query(listQuery); CellQuery cellQuery = new CellQuery(worksheet.CellFeedLink); CellFeed cellFeed = service.Query(cellQuery); CellEntry cellEntry = new CellEntry(1, 1, "email"); cellFeed.Insert(cellEntry); cellEntry = new CellEntry(1, 2, "name"); cellFeed.Insert(cellEntry); cellEntry = new CellEntry(1, 3, "givenname"); cellFeed.Insert(cellEntry); cellEntry = new CellEntry(1, 4, "familyname"); cellFeed.Insert(cellEntry); cellEntry = new CellEntry(1, 5, "picture"); cellFeed.Insert(cellEntry); cellEntry = new CellEntry(1, 6, "gender"); cellFeed.Insert(cellEntry); cellEntry = new CellEntry(1, 7, "locale"); cellFeed.Insert(cellEntry); // Create a local representation of the new row. ListEntry row = new ListEntry(); row.Elements.Add(new ListEntry.Custom() { LocalName = "email", Value = t.email }); row.Elements.Add(new ListEntry.Custom() { LocalName = "name", Value = t.name }); row.Elements.Add(new ListEntry.Custom() { LocalName = "givenname", Value = t.given_name }); row.Elements.Add(new ListEntry.Custom() { LocalName = "familyname", Value = t.family_name }); row.Elements.Add(new ListEntry.Custom() { LocalName = "picture", Value = t.picture }); row.Elements.Add(new ListEntry.Custom() { LocalName = "gender", Value = t.Gender }); row.Elements.Add(new ListEntry.Custom() { LocalName = "locale", Value = t.locale }); // Send the new row to the API for insertion. service.Insert(listFeed, row); } Response.Redirect("Home.aspx?access_token=" + Session["access_token"].ToString()); } }
private static bool AddLinkInfo(WorksheetEntry wsEntry, List <LinkInfo> linkToAdd) { bool added = false; try { AtomLink listFeedLink = wsEntry.Links.FindService(GDataSpreadsheetsNameTable.ListRel, null); ListQuery listQuery = new ListQuery(listFeedLink.HRef.ToString()); ListFeed listFeed = sheetsService.Query(listQuery); foreach (LinkInfo info in linkToAdd) { ListEntry row = new ListEntry(); row.Elements.Add(new ListEntry.Custom() { LocalName = "itemtype", Value = info.ItemType.ToString() }); row.Elements.Add(new ListEntry.Custom() { LocalName = "sourcename", Value = info.SourceModelName }); row.Elements.Add(new ListEntry.Custom() { LocalName = "sourcepath", Value = info.SourceModelPath }); row.Elements.Add(new ListEntry.Custom() { LocalName = "sourcemodelid", Value = info.SourceModelId }); row.Elements.Add(new ListEntry.Custom() { LocalName = "destinationpath", Value = info.DestModelPath }); row.Elements.Add(new ListEntry.Custom() { LocalName = "itemsourceid", Value = info.SourceItemId.ToString() }); row.Elements.Add(new ListEntry.Custom() { LocalName = "itemsourcename", Value = info.SourceItemName }); row.Elements.Add(new ListEntry.Custom() { LocalName = "itemdestinationid", Value = info.DestItemId.ToString() }); row.Elements.Add(new ListEntry.Custom() { LocalName = "itemdestinationname", Value = info.DestItemName }); row.Elements.Add(new ListEntry.Custom() { LocalName = "itemdestinationimage1", Value = info.DestImagePath1 }); row.Elements.Add(new ListEntry.Custom() { LocalName = "itemdestinationimage2", Value = info.DestImagePath2 }); row.Elements.Add(new ListEntry.Custom() { LocalName = "linkmodified", Value = info.LinkModified }); row.Elements.Add(new ListEntry.Custom() { LocalName = "linkmodifiedby", Value = info.LinkModifiedBy }); sheetsService.Insert(listFeed, row); } } catch (Exception ex) { MessageBox.Show("Failed to add the link information.\n" + ex.Message, "Add Link Information", MessageBoxButton.OK, MessageBoxImage.Warning); } return(added); }
public static void Main(string[] args) { Console.WriteLine("Working..."); long bukow = 50217665; // bukowskaii's player id Region bRegion = new Region(Region.Regions.NA); Console.WriteLine("Getting List of all champions..."); List <ChampionDto> allChampions = ChampionAPI.RetrieveAllChampions(bRegion.ChampionRegion); Console.WriteLine("Getting masteries for Bukowskaii..."); List <ChampionMasteryDto> myMasteries = ChampionMasteryAPI.GetAllChampionMastery(bRegion.ChampionMasteryRegion, bukow); Console.WriteLine("Getting Dictionary of champion Ids and champion metadata..."); Dictionary <long, ChampionMetaData> championLookup = StaticDataAPI.GetChampionMetaData(bRegion.ChampionRegion); Console.WriteLine("Writing info to file..."); List <long> loggedIds = new List <long>(); StringBuilder sb = new StringBuilder(); foreach (ChampionMasteryDto mastery in myMasteries) { string champName = championLookup[mastery.ChampionId].Name; string champTitle = championLookup[mastery.ChampionId].Title; sb.AppendLine(champName + " -- " + champTitle + "," + mastery.ChampionId + "," + mastery.ChestGranted + "," + mastery.TokensEarned + "," + UnixTimeStampToDateTime(mastery.LastPlayTime) + "," + mastery.ChampionLevel + "," + mastery.ChampionPoints); loggedIds.Add(mastery.ChampionId); } foreach (ChampionDto champion in allChampions) { if (!loggedIds.Contains(champion.Id)) { string champName = championLookup[champion.Id].Name; string champTitle = championLookup[champion.Id].Title; sb.AppendLine(champName + " - " + champTitle + "," + champion.Id + "," + "False," + "0," + "0," + "0," + "0"); } } //File.WriteAllText(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "LeagueData.csv"), sb.ToString()); //Console.WriteLine("Done! -- Press any key to exit."); //Thread.Sleep(100); //Console.ReadKey(false); //Thread.Sleep(100); const string ClientId = "376250057781-pud8thtu2qrku59p4jkusf5o97d0nc1e.apps.googleusercontent.com"; string ClientSecret = "WAIKheO-M3YQ6RVlDrK0DC8i"; string scope = "https://spreadsheets.google.com/feeds"; string redirect = "urn:ietf:wg:oauth:2.0:oob"; OAuth2Parameters parameters = new OAuth2Parameters(); parameters.ClientId = ClientId; parameters.ClientSecret = ClientSecret; parameters.RedirectUri = redirect; parameters.Scope = scope; string authorizationUrl = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters); Process.Start(authorizationUrl); Console.WriteLine("Paste your authorization code:"); parameters.AccessCode = Console.ReadLine(); //parameters.AccessCode = "4/6op1327wcvTW8eMwFm4D4ZETIS2JCDSas8oifd1OD9M"; OAuthUtil.GetAccessToken(parameters); string accessToken = parameters.AccessToken; Console.WriteLine("OAuthAccessToken: " + accessToken); GOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory(null, "LoL Crate Parse", parameters); SpreadsheetsService service = new SpreadsheetsService("LoL Crate Parse"); service.RequestFactory = requestFactory; SpreadsheetQuery query = new SpreadsheetQuery(); SpreadsheetFeed feed = service.Query(query); if (feed.Entries.Count > 0) { SpreadsheetEntry selectedEntry = new SpreadsheetEntry(); foreach (SpreadsheetEntry entry in feed.Entries) { if (entry.Title.Text == "LoL Crates") { selectedEntry = entry; } } WorksheetFeed wFeed = selectedEntry.Worksheets; WorksheetEntry worksheet = (WorksheetEntry)wFeed.Entries[0]; AtomLink listFeedLink = worksheet.Links.FindService(GDataSpreadsheetsNameTable.ListRel, null); ListQuery listQuery = new ListQuery(listFeedLink.HRef.ToString()); ListFeed listFeed = service.Query(listQuery); int entries = listFeed.Entries.Count; int remaining = 0; ListEntry existingRow; do { existingRow = (ListEntry)listFeed.Entries[0]; existingRow.Delete(); listFeed = service.Query(listQuery); remaining++; Console.WriteLine(string.Format("Deleting {0} of {1} complete", remaining, entries)); } while (listFeed.Entries.Count > 0); string[] rows = sb.ToString().Trim('\n').Split('\n'); entries = rows.Length; remaining = 0; foreach (string row in rows) { Console.WriteLine(string.Format("Inserting {0} of {1} complete", remaining, entries)); string[] elements = row.Split(','); ListEntry toAdd = new ListEntry(); toAdd.Elements.Add(new ListEntry.Custom() { LocalName = "champion", Value = elements[0] }); toAdd.Elements.Add(new ListEntry.Custom() { LocalName = "id", Value = elements[1] }); toAdd.Elements.Add(new ListEntry.Custom() { LocalName = "chest", Value = elements[2] }); toAdd.Elements.Add(new ListEntry.Custom() { LocalName = "tokensearned", Value = elements[3] }); toAdd.Elements.Add(new ListEntry.Custom() { LocalName = "lastplayed", Value = elements[4] }); toAdd.Elements.Add(new ListEntry.Custom() { LocalName = "champlevel", Value = elements[5] }); toAdd.Elements.Add(new ListEntry.Custom() { LocalName = "masterypoints", Value = elements[6] }); service.Insert(listFeed, toAdd); remaining++; } } Console.WriteLine("Done! -- Press any key to exit."); Thread.Sleep(100); Console.ReadKey(false); }