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);
        }
Esempio n. 2
0
        private void button1_Click(object sender, EventArgs e)
        {
            //////////////////////////////////////////////////////////////////////////////
            //// STEP 5: Make an OAuth authorized request to Google
            //////////////////////////////////////////////////////////////////////////////

            // Initialize the variables needed to make the request
            GOAuth2RequestFactory requestFactory =
                new GOAuth2RequestFactory(null, "TourTracking", parameters);
            SpreadsheetsService service = new SpreadsheetsService("TourTracking");
            service.RequestFactory = requestFactory;

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

            // Iterate through all of the spreadsheets returned
            foreach (SpreadsheetEntry entry in feed.Entries)
            {
                // Print the title of this spreadsheet to the screen
                MessageBox.Show(entry.Title.Text);
            }
        }
Esempio n. 3
0
 public SpreadsheetsService GetService()
 {
     GOAuth2RequestFactory requestFactory =
         new GOAuth2RequestFactory(null, "MySpreadsheetIntegration-v1", GetParameters());
     SpreadsheetsService service = new SpreadsheetsService("MySpreadsheetIntegration-v1");
     service.RequestFactory = requestFactory;
     return service;
 }
Esempio n. 4
0
 void printDocumentList(OAuth2Parameters parameters)
 {
     GOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory(null, "MyDocumentsListIntegration-v1", parameters);
     DocumentsService service = new DocumentsService("MyDocumentsListIntegration-v1");
     service.RequestFactory = requestFactory;
     DocumentsListQuery query = new DocumentsListQuery();
     DocumentsFeed feed = service.Query(query);
     foreach (DocumentEntry entry in feed.Entries)
     {
         Console.WriteLine(entry.Title.Text);
     }
     Console.ReadKey();
 }
Esempio n. 5
0
		public void Authenticate( string refreshToken, string spreadsheetName )
		{
			var authorizationUrl = OAuthUtil.CreateOAuth2AuthorizationUrl( oAuthParams );

			Console.WriteLine( authorizationUrl );

			/*if( !string.IsNullOrEmpty( accessCode ) )
			{
				oAuthParams.AccessCode = accessCode;
			}*/

			if( !string.IsNullOrEmpty( refreshToken ) )
			{
				oAuthParams.RefreshToken = refreshToken;

				OAuthUtil.RefreshAccessToken( oAuthParams );
			}
			else
			{
				OAuthUtil.GetAccessToken( oAuthParams );
			}

			var accessToken = oAuthParams.AccessToken;
			var requestFactory = new GOAuth2RequestFactory( null, applicationName, oAuthParams );

			_spreadsheetsService.RequestFactory = requestFactory;

			var spreadsheetFeed = _spreadsheetsService.Query( new SpreadsheetQuery() );

			_spreadsheetEntries.Clear();

			foreach( var entry in spreadsheetFeed.Entries )
			{
				var spreadsheetEntry = entry as SpreadsheetEntry;

				if( spreadsheetEntry == null )
				{
					continue;
				}

				_spreadsheetEntries.Add( spreadsheetEntry );

				if( spreadsheetName.Equals( spreadsheetEntry.Title.Text ) )
				{
					_currentEntry = spreadsheetEntry;
				}
			}
		}
Esempio n. 6
0
        public Dictionary<string, Tuple<string, string, string, bool>> SheetDownload(string IntegrationName, OAuth2Parameters paramaters, string SpreadSheetURI)
        {
            GOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory(null, IntegrationName, paramaters);
            SpreadsheetsService service = new SpreadsheetsService(IntegrationName);

            string accessToken = paramaters.AccessToken;
            service.RequestFactory = requestFactory;

            WorksheetEntry worksheet = this.GetWorksheet(paramaters, IntegrationName, SpreadSheetURI, service);

            Dictionary<string, Tuple<string, string, string, bool>> OnlineMapList = new Dictionary<string, Tuple<string, string, string, bool>>();

            string map = "MapNameError";
            string URL = "URL ERROR";
            string UserSteamID = "0";
            string Note = "No Notes";
            bool MapUploadStatus = false;

            AtomLink listFeedLink = worksheet.Links.FindService(GDataSpreadsheetsNameTable.ListRel, null);

            ListQuery listQuery = new ListQuery(listFeedLink.HRef.ToString());
            ListFeed listFeed = service.Query(listQuery);

            foreach (ListEntry row in listFeed.Entries)
            {

                map = row.Elements[1].Value;
                URL = row.Elements[2].Value;
                UserSteamID = row.Elements[3].Value;
                Note = row.Elements[4].Value;

                if (row.Elements[5].Value == "TRUE")
                {
                    MapUploadStatus = true;
                }
                else
                {
                    MapUploadStatus = false;
                }
                if (!OnlineMapList.ContainsKey(map))
                {
                    OnlineMapList.Add(map, new Tuple<string, string, string, bool>(URL, UserSteamID, Note, MapUploadStatus));
                }

            }
            return OnlineMapList;
        }
Esempio n. 7
0
        public SpreadSheetWrapper()
        {
            _parameters.ClientId = "471934575594.apps.googleusercontent.com";
            _parameters.ClientSecret = "Gr_MKJfuzKLYqnHCyl4m6aSP";
            _parameters.RedirectUri = "urn:ietf:wg:oauth:2.0:oob";

            /* 本来はGoogleDocs(Drive API)へのアクセス権限はいらないはず
             * スプレッドシートの作成は出来ると権限要求の説明には書いてある。
             * 
             * しかし、出来ない。Drive APIで作れとドキュメントにある。うそつき。
             */
//            parameters.Scope = "https://spreadsheets.google.com/feeds";
            _parameters.Scope = "https://spreadsheets.google.com/feeds https://www.googleapis.com/auth/drive.file";

            _requestFactory = new GOAuth2RequestFactory(null, _app_name,_parameters);

        }
Esempio n. 8
0
        public GoogleDocService()
        {
            var config = new Config();
            OAuth2Parameters parameters = new OAuth2Parameters();

            parameters.ClientId = config.Get("Google_Client_Id");
            parameters.ClientSecret = config.Get("Google_Client_Secret");
            parameters.Scope = config.Get("Google_Scope");

            parameters.AccessToken = config.Get("Google_Auth2_AccessToken");
            parameters.RefreshToken = config.Get("Google_Auth2_RefreshToken");


            GOAuth2RequestFactory requestFactory =
                new GOAuth2RequestFactory(null, "Sheet-bill", parameters);
            _spreadsheetService = new SpreadsheetsService("Sheet-bill");
            _spreadsheetService.RequestFactory = requestFactory;
        }
Esempio n. 9
0
        public string Init()
        {
            StringBuilder sb = new StringBuilder();

            lock (_lockObj)
            {
                if (null == SpreadsheetsService)
                {

                    ApiTraceManager.Inst.LogTrace("Init excel parser");
                    _parameters = new OAuth2Parameters();
                    _parameters.ClientId = ApiUtils.CLIENT_ID;
                    _parameters.ClientSecret = ApiUtils.CLIENT_SECRET;
                    _parameters.Scope = ApiUtils.SCOPE;
                    _parameters.RedirectUri = ApiUtils.REDIRECT_URL;
                    _parameters.TokenExpiry = DateTime.MaxValue;
                    _parameters.AccessType = "offline";
                    _parameters.AccessToken =
                        "ya29.IAK0DqyyBCLy1lNBPHM4ON0m74HiPnXdJnizHC2a7w5CIDndeLPuFbJm0u34HfKpiXZ8UQ";
                    _parameters.RefreshToken = "1/jWXrc6wJ4lUmWscyc3rozkWPKdFwvha43JfPCxMksus";

                    GOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory(null, "MySpreadsheetIntegration-v1",
                        _parameters);
                    SpreadsheetsService = new SpreadsheetsService("MySpreadsheetIntegration-v1");
                    SpreadsheetsService.RequestFactory = requestFactory;
                    sb.AppendFormat("<div>access code={0}</div>", _parameters.AccessCode);
                    sb.AppendFormat("<div>access token={0}</div>", _parameters.AccessToken);
                    sb.AppendFormat("<div>refresh token={0}</div>", _parameters.RefreshToken);

                    SpreadsheetsService service = SpreadsheetsService;
                    SpreadsheetQuery query = new SpreadsheetQuery();
                    SpreadsheetFeed feed = service.Query(query);

                    SpreadsheetEntry entry = GetSpreadsheetEntry(feed);
                    Debug.Assert(null != entry);
                    sb.Append("<h1>" + entry.Title.Text + "</h1>");
                    RenderWeek(entry,service);

                    this.IsInit = true;
                }
            }
            return sb.ToString();
        }
        public ActionResult ParseFile(string fileName)
        {
            if (HttpContext.Session[GlobalVariables.OAuthCodeKey] == null)
            {
                var model = new PSCoursesModel();
                return View(model);
            }
            else
            {
                var code = HttpContext.Session[GlobalVariables.OAuthCodeKey].ToString();

                var parameters = OAuthHelper.GetOAuthParameter();
                parameters.AccessCode = code;
                OAuthUtil.GetAccessToken(parameters);

                GOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory(null, GlobalVariables.GoogleSpreadSheetAppName, parameters);
                SpreadsheetsService service = new SpreadsheetsService(GlobalVariables.GoogleSpreadSheetAppName);
                service.RequestFactory = requestFactory;

                //Parsing
                var startTime = System.DateTime.Now;
                var readCourseService = new ReadCourseFromFile(fileName);
                var parser = new PSCourseParser(readCourseService, defaultStartTime);
                var currentCoursesModel = parser.ParseCourses();

                var googleHelper = new GoogleDriveHelper(defaultStartTime);
                googleHelper.Service = service;
                var oldCourses = googleHelper.FetchOldCourseSheet();
                parser.UpdateCourseStatus(currentCoursesModel, oldCourses);

                var success = googleHelper.AddDriveSpreadsheet(currentCoursesModel);

                var endTime = System.DateTime.Now;
                var processingTime = endTime - startTime;

                ViewData["StartTime"] = startTime;
                ViewData["EndTime"] = endTime;
                ViewData["ProcessTime"] = processingTime;

                return View(currentCoursesModel);
            }
        }
Esempio n. 11
0
        private void GetAccessCode(object sender, NavigationEventArgs e)
        {
            mshtml.IHTMLDocument2 doc = LoginBrowser.Document as mshtml.IHTMLDocument2;
            string accessCode = doc.title;
            if (accessCode.Substring(0, 7) == "Success")
            {
                accessCode = accessCode.Remove(0, 13);
                parameters.AccessCode = accessCode;// Key.Text;
                OAuthUtil.GetAccessToken(parameters);
                string accessToken = parameters.AccessToken;

                GOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory(null, "BoardGameStats", parameters);
                service.RequestFactory = requestFactory;

                if (service != null)
                {
                    DialogResult = true;
                }
                else
                {
                    DialogResult = false;
                }
            }
        }
        private bool CheckFileGS(string FileName, GoogleSheetsAccountSettings accountForTestGS)
        {
            bool result = false;
            SpreadsheetsService service = new SpreadsheetsService(Constants.googleSheetsAppName);
            GOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory(null, Constants.googleSheetsAppName, parameters);
            service.RequestFactory = requestFactory;
            SpreadsheetQuery query = new SpreadsheetQuery();
            SpreadsheetFeed feed = service.Query(query);
            SpreadsheetEntry spreadsheet;
            for (int i = 0; i < feed.Entries.Count; i++)
            {
                if (feed.Entries[i].Title.Text == FileName)
                {
                    spreadsheet = (SpreadsheetEntry)feed.Entries[i];
                    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 = service.Query(listQuery);
                    result = true;
                    break;
                }
                else
                {
                    result = false;
                }
            }

            //if (listFeed != null)
            //{
            //    //ShowMapping();
            //}

            return result;
        }
Esempio n. 13
0
        private void DrawLoginGUI()
        {
            if (Instance == null)
                Init();
            var loginFadeArea = InstanceData.Service == null
                ? MyGUILayout.BeginFadeArea(ShowLogin, LocalizationInfo.Localize(Localization.rowIds.ID_LABEL_LOGIN),
                    "login", MyGUILayout.OuterBox, MyGUILayout.OuterBoxHeader)
                : MyGUILayout.BeginFadeArea(ShowLogin,
                    LocalizationInfo.Localize(Localization.rowIds.ID_MESSAGE_LOGGED_IN_AS), "login",
                    MyGUILayout.OuterBox, MyGUILayout.OuterBoxHeader);
            ShowLogin = loginFadeArea.Open;
            Google2uGUIUtil.SetBool("ShowLogin", ShowLogin);
            if (loginFadeArea.Show())
            {
                var showLoginCredentialsArea = MyGUILayout.BeginFadeArea(ShowLoginCredentials,
                    LocalizationInfo.Localize(Localization.rowIds.ID_LABEL_CREDENTIALS), "credentials",
                    MyGUILayout.InnerBox, MyGUILayout.InnerBoxHeader);
                ShowLoginCredentials = showLoginCredentialsArea.Open;
                Google2uGUIUtil.SetBool("ShowLoginCredentials", ShowLoginCredentials);
                if (InstanceData.Commands.Contains(GFCommand.WaitForLogin))
                {
                    EditorGUILayout.LabelField(
                        LocalizationInfo.Localize(Localization.rowIds.ID_MESSAGE_PROCESSING_LOGIN) + Ellipses);
                }
                else if (InstanceData.Commands.Contains(GFCommand.WaitForRetrievingWorkbooks))
                {
                    EditorGUILayout.LabelField(
                        LocalizationInfo.Localize(Localization.rowIds.ID_MESSAGE_RETRIEVING_WORKBOOKS) + Ellipses);
                }
                else
                {
                    if (InstanceData.Service == null)
                    {
                        var content = new GUIContent(MyGUILayout.LoginButton);
                        if (!string.IsNullOrEmpty(TempTokenURL))
                        {
                            EditorGUILayout.BeginHorizontal();
                            TempToken = EditorGUILayout.TextField("OAuth Token: ", TempToken);
                            if (GUILayout.Button(content, GUILayout.Height(EditorGUILayoutEx.CredentialButtonHeight),
                                GUILayout.Width(EditorGUILayoutEx.CredentialButtonWidth)))
                            {
                                if (!string.IsNullOrEmpty(TempToken))
                                {
                                    _authParameters.AccessCode = TempToken;
                                    TempToken = string.Empty;

                                    OAuthUtil.GetAccessToken(_authParameters);

                                    if (!string.IsNullOrEmpty(_authParameters.AccessToken))
                                    {
                                        OAuthToken = _authParameters.AccessToken;
                                        RefreshToken = _authParameters.RefreshToken;
                                        RefreshTimeout = _authParameters.TokenExpiry;
                                        Google2uGUIUtil.SetString("OAuthToken", OAuthToken);
                                        Google2uGUIUtil.SetString("RefreshToken", RefreshToken);
                                        Google2uGUIUtil.SetString("RefreshTimeout", RefreshTimeout.ToString("O"));

                                        var requestFactory = new GOAuth2RequestFactory("structuredcontent",
                                            "Google2Unity", _authParameters);
                                        InstanceData.Service = new SpreadsheetsService("Google2Unity")
                                        {
                                            RequestFactory = requestFactory
                                        };

                                        if (!InstanceData.Commands.Contains(GFCommand.RetrieveWorkbooks))
                                            InstanceData.Commands.Add(GFCommand.RetrieveWorkbooks);
                                    }
                                }
                            }
                            EditorGUILayout.EndHorizontal();
                        }

                        content = new GUIContent(MyGUILayout.GoogleAuthButton);

                        if (GUILayout.Button(content, GUILayout.Height(EditorGUILayoutEx.GoogleButtonHeight),
                            GUILayout.Width(EditorGUILayoutEx.GoogleButtonWidth)))
                        {
                            if (_authParameters == null)
                                SetupParameters();
                            if (!string.IsNullOrEmpty(_authParameters.AccessToken))
                            {
                                OAuthToken = _authParameters.AccessToken;
                                Google2uGUIUtil.SetString("OAuthToken", OAuthToken);

                                var requestFactory = new GOAuth2RequestFactory("structuredcontent", "Google2Unity",
                                    _authParameters);
                                InstanceData.Service = new SpreadsheetsService("Google2Unity")
                                {
                                    RequestFactory = requestFactory
                                };

                                Thread.Sleep(100);

                                if (!InstanceData.Commands.Contains(GFCommand.RetrieveWorkbooks))
                                    InstanceData.Commands.Add(GFCommand.RetrieveWorkbooks);
                            }
                            else
                            {
                                OpenAuthWindow();
                            }
                        }

                        content = new GUIContent(MyGUILayout.ClearButton);
                        if (GUILayout.Button(content, GUILayout.Height(EditorGUILayoutEx.CredentialButtonHeight),
                            GUILayout.Width(EditorGUILayoutEx.CredentialButtonWidth)))
                        {
                            OAuthToken = string.Empty;
                            TempTokenURL = string.Empty;
                            _authParameters = null;
                            Google2uGUIUtil.SetString("OAuthToken", string.Empty);
                            InstanceData.AccountWorkbooks.Clear();
                            InstanceData.Service = null;
                        }
                    }
                    else
                    {
                        EditorGUILayout.BeginHorizontal();
                        var content = new GUIContent(MyGUILayout.LogoutButton,
                            LocalizationInfo.Localize(Localization.rowIds.ID_LABEL_LOGOUT));
                        if (GUILayout.Button(content, GUILayout.Height(EditorGUILayoutEx.CredentialButtonHeight),
                            GUILayout.Width(EditorGUILayoutEx.CredentialButtonWidth)))
                        {
                            if (!InstanceData.Commands.Contains(GFCommand.DoLogout))
                            {
                                InstanceData.Commands.Add(GFCommand.DoLogout);
                            }
                        }
                        EditorGUILayout.EndHorizontal();
                    }
                }

                MyGUILayout.EndFadeArea(); // End Credentials
            }
            MyGUILayout.EndFadeArea();
        }
Esempio n. 14
0
        /// <summary>
        /// Updates the online spreadsheet according the maps file
        /// </summary>
        /// 
        public static void SheetSync(bool ForceSync)
        {
            Bot.SteamFriends.SetPersonaName("[" + ImpMaster.Maplist.Count.ToString() + "] " + Bot.DisplayName);

            if ((GroupChatHandler.OnlineSync.StartsWith("true", StringComparison.OrdinalIgnoreCase) && !SyncRunning) || ForceSync)
            {
                SyncRunning = true;
                //Log.Interface ("Beginning Sync");
                OAuth2Parameters parameters = new OAuth2Parameters();
                parameters.ClientId = GroupChatHandler.CLIENT_ID;
                parameters.ClientSecret = GroupChatHandler.CLIENT_SECRET;
                parameters.RedirectUri = GroupChatHandler.REDIRECT_URI;
                parameters.Scope = GroupChatHandler.SCOPE;
                parameters.AccessType = "offline";
                parameters.RefreshToken = GroupChatHandler.GoogleAPI;
                OAuthUtil.RefreshAccessToken(parameters);
                string accessToken = parameters.AccessToken;

                GOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory(null, GroupChatHandler.IntegrationName, parameters);
                SpreadsheetsService service = new SpreadsheetsService(GroupChatHandler.IntegrationName);
                service.RequestFactory = requestFactory;
                SpreadsheetQuery query = new SpreadsheetQuery(SpreadSheetURI);
                SpreadsheetFeed feed = service.Query(query);
                SpreadsheetEntry spreadsheet = (SpreadsheetEntry)feed.Entries[0];
                WorksheetFeed wsFeed = spreadsheet.Worksheets;
                WorksheetEntry worksheet = (WorksheetEntry)wsFeed.Entries[0];

                worksheet.Cols = 5;
                worksheet.Rows = Convert.ToUInt32(ImpMaster.Maplist.Count + 1);

                worksheet.Update();

                CellQuery cellQuery = new CellQuery(worksheet.CellFeedLink);
                cellQuery.ReturnEmpty = ReturnEmptyCells.yes;
                CellFeed cellFeed = service.Query(cellQuery);
                CellFeed batchRequest = new CellFeed(cellQuery.Uri, service);

                int Entries = 1;

                foreach (var item in ImpMaster.Maplist)
                {
                    Entries = Entries + 1;
                    foreach (CellEntry cell in cellFeed.Entries)
                    {
                        if (cell.Title.Text == "A" + Entries.ToString())
                        {
                            cell.InputValue = item.Key;
                        }
                        if (cell.Title.Text == "B" + Entries.ToString())
                        {
                            cell.InputValue = item.Value.Item1;

                        }
                        if (cell.Title.Text == "C" + Entries.ToString())
                        {
                            cell.InputValue = item.Value.Item2.ToString();

                        }
                        if (cell.Title.Text == "D" + Entries.ToString())
                        {
                            cell.InputValue = item.Value.Item3.ToString();

                        }
                        if (cell.Title.Text == "E" + Entries.ToString())
                        {
                            cell.InputValue = item.Value.Item4.ToString();
                        }
                    }
                }

                cellFeed.Publish();
                CellFeed batchResponse = (CellFeed)service.Batch(batchRequest, new Uri(cellFeed.Batch));
                // Log.Interface("Completed Sync");
                SyncRunning = false;

            }
            else if (GroupChatHandler.OnlineSync.StartsWith("true", StringComparison.OrdinalIgnoreCase))
            {
                GroupChatHandler.SpreadsheetSync = true;
            }
        }
Esempio n. 15
0
 /// <summary>
 /// default constructor.
 /// </summary>
 internal GOAuth2Request(GDataRequestType type, Uri uriTarget, GOAuth2RequestFactory factory)
     : base(type, uriTarget, factory) {
     this.factory = factory;
 }
Esempio n. 16
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        // 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 = "641157605077-rr2l9ma85ps6n5grp031js3pccehfv5u.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 = "Gq-ekOvi9grFi9K3rznIpoT9";

        // 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.
        string REDIRECT_URI = "http://localhost:1918/oauth2callback";

        string TOKEN_TYPE = "refresh";

        ////////////////////////////////////////////////////////////////////////////
        // 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 = CLIENT_ID;

        // Set your OAuth 2.0 Client Secret, which can be obtained at
        // https://code.google.com/apis/console.
        parameters.ClientSecret = CLIENT_SECRET;

        // Set your Redirect URI, which can be registered at
        // https://code.google.com/apis/console.
        parameters.RedirectUri = REDIRECT_URI;

        ////////////////////////////////////////////////////////////////////////////
        // STEP 3: Get the Authorization URL
        ////////////////////////////////////////////////////////////////////////////

        // Set the scope for this particular service.
        parameters.Scope = SCOPE;

        parameters.AccessType = "offline"; // IMPORTANT and was missing in the original

        parameters.TokenType = TOKEN_TYPE; // IMPORTANT and was missing in the original

        string authorizationUrl = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);
        Response.Redirect(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...");
        parameters.AccessCode = Console.ReadLine();

        ////////////////////////////////////////////////////////////////////////////
        // 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.GetAccessToken(parameters);
        string accessToken = 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, "MySpreadsheetIntegration-v1", parameters);
        SpreadsheetsService service = new SpreadsheetsService("MySpreadsheetIntegration-v1");
        service.RequestFactory = requestFactory;

        // Make the request to Google
    }
        private void ReadGSFile()
        {
            SpreadsheetsService service = new SpreadsheetsService(Constants.googleSheetsAppName);
            GOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory(null, Constants.googleSheetsAppName, parameters);

            service.RequestFactory = requestFactory;

            SpreadsheetQuery query = new SpreadsheetQuery();
            SpreadsheetFeed feed = service.Query(query);

            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 = service.Query(listQuery);
        }
Esempio n. 18
0
        private void DoAuth()
        {
            ////////////////////////////////////////////////////////////////////////////
            // 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 = "906124997812-90jq6glur1kfjq5k0vdqj81t7ad214t0.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 = "";

            using (var sr = new StreamReader("../../../secret.txt"))
            {
                CLIENT_SECRET = sr.ReadLine();
            }

            // 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.
            string 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 = CLIENT_ID;

            // Set your OAuth 2.0 Client Secret, which can be obtained at
            // https://code.google.com/apis/console.
            parameters.ClientSecret = CLIENT_SECRET;

            // Set your Redirect URI, which can be registered at
            // https://code.google.com/apis/console.
            parameters.RedirectUri = REDIRECT_URI;

            ////////////////////////////////////////////////////////////////////////////
            // STEP 3: Get the Authorization URL
            ////////////////////////////////////////////////////////////////////////////

            // Set the scope for this particular service.
            parameters.Scope = SCOPE;

            bool needAuth = false;
            if (needAuth)
            {
                // 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...");
                parameters.AccessCode = "";// Console.ReadLine();

                ////////////////////////////////////////////////////////////////////////////
                // 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().
                try
                {
                    OAuthUtil.GetAccessToken(parameters);
                }
                catch (Exception ex)
                {

                }
                string accessToken = parameters.AccessToken;
                Console.WriteLine("OAuth Access Token: " + accessToken);

                using (var sw = new StreamWriter("../../../token.txt"))
                {
                    sw.WriteLine(parameters.AccessToken);
                    sw.WriteLine(parameters.RefreshToken);
                }
            }

            using (var sr = new StreamReader("../../../token.txt"))
            {
                parameters.AccessToken = sr.ReadLine();
                parameters.RefreshToken = sr.ReadLine();
            }

            ////////////////////////////////////////////////////////////////////////////
            // STEP 5: Make an OAuth authorized request to Google
            ////////////////////////////////////////////////////////////////////////////

            // Initialize the variables needed to make the request
            GOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory(null, "My Great Games!", parameters);
            _service = new SpreadsheetsService("My Great Games!");
            _service.RequestFactory = requestFactory;
        }
Esempio n. 19
0
        private void Init()
        {
            var lastChecked =
                Convert.ToDateTime(Google2uGUIUtil.GetString("Google2uLastCheckedForUpdate",
                    Convert.ToString(DateTime.MinValue)));
            if ((DateTime.Now - lastChecked).Days >= 1)
            {
                Google2uGUIUtil.SetString("Google2uLastCheckedForUpdate", Convert.ToString(DateTime.Now));
                var t = new Thread(CheckForUpdate);
                t.Start();
            }

            ShowDocsAtStartup = Google2uGUIUtil.GetBool("ShowDocsAtStartup", ShowDocsAtStartup);
            if (ShowDocsAtStartup)
                Google2uDocs.ShowWindow(MyGUILayout, LocalizationInfo);

            ServicePointManager.ServerCertificateValidationCallback = Validator;
            OAuthToken = Google2uGUIUtil.GetString("OAuthToken", OAuthToken);
            RefreshToken = Google2uGUIUtil.GetString("RefreshToken", RefreshToken);
            RefreshTimeout =
                DateTime.ParseExact(Google2uGUIUtil.GetString("RefreshTimeout", RefreshTimeout.ToString("O")), "O",
                    CultureInfo.InvariantCulture);

            if (InstanceData.Service == null && !string.IsNullOrEmpty(OAuthToken))
            {
                SetupParameters();

                _authParameters.AccessToken = OAuthToken;


                var requestFactory = new GOAuth2RequestFactory("structuredcontent", "Google2Unity", _authParameters);
                InstanceData.Service = new SpreadsheetsService("Google2Unity") {RequestFactory = requestFactory};

                Thread.Sleep(100);

                if (!InstanceData.Commands.Contains(GFCommand.RetrieveWorkbooks))
                    InstanceData.Commands.Add(GFCommand.RetrieveWorkbooks);
            }

            // Close lingering editor windows
            var ed = GetWindow<Google2uEditor>();
            if (ed != null)
                ed.Close();

            if (ObjDbExport == null)
                ObjDbExport = new List<Google2uObjDbExport>();

            Instance = this;
        }
Esempio n. 20
0
        /// <summary>
        /// Send authorized queries to a Service-based library
        /// </summary>
        /// <param name="service"></param>
        private static void RunGroupsSample(OAuth2Parameters parameters, string domain) {
            try {
                GOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory("apps", applicationName, parameters);

                GroupsService service = new GroupsService(domain, applicationName);
                service.RequestFactory = requestFactory;

                GroupFeed feed = service.RetrieveAllGroups();
                foreach (GroupEntry group in feed.Entries) {
                    Console.WriteLine(group.GroupName);
                }
            } catch (AppsException a) {
                Console.WriteLine("A Google Apps error occurred.");
                Console.WriteLine();
                Console.WriteLine("Error code: {0}", a.ErrorCode);
                Console.WriteLine("Invalid input: {0}", a.InvalidInput);
                Console.WriteLine("Reason: {0}", a.Reason);
            }
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {

            if (!IsPostBack)
            {

                OAuth2Parameters parameters_lst = oauthcredentials();
                GOAuth2RequestFactory requestFactory =
                  new GOAuth2RequestFactory(null, "Fusion-SpreadSheet", parameters_lst);
                SpreadsheetsService service = new SpreadsheetsService("Fusion-SpreadSheet");
                service.RequestFactory = requestFactory;

                SpreadsheetQuery query = new SpreadsheetQuery();

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

                // Iterate through all of the spreadsheets returned
                ddlexcellst.Items.Add("------------------- Select------------------");
                foreach (SpreadsheetEntry entry in feed.Entries)
                {
                    // Print the title of this spreadsheet to the screen

                    //Response.Write(entry.Title.Text);
                    ddlexcellst.Items.Add(entry.Title.Text);
                }

            }
        }
        catch (Exception)
        {

            Response.Redirect("Default.aspx");
        }
    }
    protected void ddlexcellst_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            if (ddlexcellst.SelectedIndex == 0) {
                Label2.Visible = true;
            }
            else
            {
                Label2.Visible = false;
                OAuth2Parameters parameters_lst = oauthcredentials();
                GOAuth2RequestFactory requestFactory =
                     new GOAuth2RequestFactory(null, "Fusion-SpreadSheet", parameters_lst);
                SpreadsheetsService service = new SpreadsheetsService("Fusion-SpreadSheet");
                service.RequestFactory = requestFactory;

                service.RequestFactory = requestFactory;

                // 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.
                }

                // TODO: Choose a spreadsheet more intelligently based on your
                // app's needs.
                SpreadsheetEntry spreadsheet = (SpreadsheetEntry)feed.Entries[Convert.ToInt32(ddlexcellst.SelectedIndex) - 1];
                //Response.Write(spreadsheet.Title.Text + "\n");

                // 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());
                listQuery.StartIndex = 0;
                ListFeed listFeed = service.Query(listQuery);

                // Iterate through each row, printing its cell values.

                List<category> chart_categories = new List<category>();
                ChartModels result = new ChartModels();
                categories final_categories = new categories();
                List<categories> list_categories = new List<categories>();
                List<dataset> collect_dataset = new List<dataset>();
                foreach (ListEntry row in listFeed.Entries)
                {
                    // Print the first column's cell value
                    TableRow tr = new TableRow();
                    //  Response.Write(row.Title.Text + "\n");
                    // Iterate over the remaining columns, and print each cell value
                    dataset final_dataset = new dataset();
                    List<data> collect_data = new List<data>();
                    foreach (ListEntry.Custom element in row.Elements)
                    {
                        if (row.Title.Text == "Row: 2")
                        {
                            category chart_category = new category();
                            chart_category.label = element.Value.ToString();
                            chart_categories.Add(chart_category);
                        }
                        else
                        {
                            data data_value = new data();
                            final_dataset.seriesname = row.Title.Text;
                            int n;
                            bool isNumeric = int.TryParse(element.Value, out n);
                            if (isNumeric)
                            {
                                data_value.value = element.Value.ToString();
                                collect_data.Add(data_value);
                            }
                        }
                        // Response.Write(element.Value + "\n");

                        TableCell tc = new TableCell();
                        if (row.Title.Text == "Row: 2")
                        {
                            tc.Text = "";
                        }
                        else
                            tc.Text = element.Value;
                        tr.Cells.Add(tc);
                    }
                    Table1.Rows.Add(tr);
                    if (collect_data.Count != 0)
                    {
                        final_dataset.data = collect_data;
                        collect_dataset.Add(final_dataset);
                    }
                }
                final_categories.category = chart_categories;
                result.dataset = collect_dataset;
                list_categories.Add(final_categories);
                result.categories = list_categories;

                JavaScriptSerializer js = new JavaScriptSerializer();
                string res = js.Serialize(result);
                string chartjson = JsonConvert.SerializeObject(result.categories);

                StringBuilder strJson = new StringBuilder();

                strJson.Append("{" +
                        "'chart': {" +
                              "'caption': 'Quarterly revenue'," +
                              "'subCaption':'Last year'," +
                              "'xAxisName':'Quarter (Click to drill down)'," +
                              "'subcaptionFontColor':'#0075c2'," +
                              "'numberPrefix': '$'," +
                              "'formatNumberScale': '1'," +
                              "'placeValuesInside': '1'," +
                              "'decimals': '0'" +
                                   "},");
                strJson.Append("'categories':");

                strJson.Append(chartjson);
                strJson.Append(",");
                strJson.Append("'dataset':");
                string chartdatajson = JsonConvert.SerializeObject(result.dataset);
                strJson.Append(chartdatajson);
                strJson.Append("}");

                // Initialize the chart.
                Chart sales = new Chart("mscolumn3d", "myChart", "600", "350", "json", strJson.ToString());

                // Render the chart.
                Label1.Text = sales.Render();
            }
        }
        catch (Exception)
        {
            Response.Redirect("Default.aspx");
        }
    }
 /// <summary>
 /// default constructor.
 /// </summary>
 internal GOAuth2Request(GDataRequestType type, Uri uriTarget, GOAuth2RequestFactory factory)
     : base(type, uriTarget, factory)
 {
     this.factory = factory;
 }
Esempio n. 24
0
        public Exception TestConnection()
        {
            logger.Debug("TestConnection");
            if (null != AuthParams && !NeedsAuthorization)
            {
                if (AuthParams.Scope.Contains("https://spreadsheets.google.com/feeds"))
                {
                    try
                    {
                        GOAuth2RequestFactory rfRequestFactory = new GOAuth2RequestFactory(null, "GoogleApiWrapper", AuthParams);
                        SpreadsheetsService ssSpreadesheetService = new SpreadsheetsService("GoogleApiWrapper");
                        ssSpreadesheetService.RequestFactory = rfRequestFactory;

                        // Instantiate a SpreadsheetQuery object to retrieve spreadsheets.
                        SpreadsheetQuery query = new SpreadsheetQuery();

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

                        if (null != feed)
                        {
                            return null;
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error(ex, "Test connection resulted in an error: {0}", ex.Message);
                        return ex;
                    }
                }
                else
                {
                    throw new NotImplementedException("Only the spreadsheet test is implemented! (Add that to the scope!)");
                }
            }

            return null;
        }
        private bool WriteToGoogleDrive(PSCourseParser parser, PSCoursesModel currentCoursesModel)
        {
            var code = HttpContext.Session[GlobalVariables.OAuthCodeKey].ToString();

            var parameters = OAuthHelper.GetOAuthParameter();
            parameters.AccessCode = code;
            OAuthUtil.GetAccessToken(parameters);

            GOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory(null, GlobalVariables.GoogleSpreadSheetAppName, parameters);
            SpreadsheetsService service = new SpreadsheetsService(GlobalVariables.GoogleSpreadSheetAppName);
            service.RequestFactory = requestFactory;

            var googleHelper = new GoogleDriveHelper(_startDate);
            googleHelper.Service = service;
            var oldCourses = googleHelper.FetchOldCourseSheet();
            parser.UpdateCourseStatus(currentCoursesModel, oldCourses);

            return googleHelper.AddDriveSpreadsheet(currentCoursesModel);
        }
Esempio n. 26
0
        public static void Go()
        {
            ////////////////////////////////////////////////////////////////////////////
                // 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 = "345296030463-604sndjpto5n8inaonllv89aga05aq7n.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 = "N-zSNIP1mkKrutG2yaBVPsY6";

                // 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.
                string 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 = CLIENT_ID;

                // Set your OAuth 2.0 Client Secret, which can be obtained at
                // https://code.google.com/apis/console.
                parameters.ClientSecret = CLIENT_SECRET;

                // Set your Redirect URI, which can be registered at
                // https://code.google.com/apis/console.
                parameters.RedirectUri = REDIRECT_URI;

                ////////////////////////////////////////////////////////////////////////////
                // STEP 3: Get the Authorization URL
                ////////////////////////////////////////////////////////////////////////////

                // Set the scope for this particular service.
                parameters.Scope = 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...");
                parameters.AccessCode = Console.ReadLine();

                ////////////////////////////////////////////////////////////////////////////
                // 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.GetAccessToken(parameters);
                string accessToken = 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, "MySpreadsheetIntegration-v1", parameters);
                SpreadsheetsService service = new SpreadsheetsService("MySpreadsheetIntegration-v1");
                service.RequestFactory = requestFactory;

                // 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.
            }

            // Iterate through all of the spreadsheets returned
            foreach (SpreadsheetEntry entry in feed.Entries)
            {
                // Print the title of this spreadsheet to the screen
                Console.WriteLine(entry.Title.Text);
            }

            // TODO: Choose a spreadsheet more intelligently based on your
            // app's needs.
            SpreadsheetEntry 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.
            WorksheetFeed 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;
                //int rowCount = entry.Rows;
                //int colCount = entry.Cols;

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

            // Make the request to Google
            // See other portions of this guide for code to put here...
            //   UserCredential credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
            //new ClientSecrets
            //{
            //    ClientId = "345296030463-604sndjpto5n8inaonllv89aga05aq7n.apps.googleusercontent.com",
            //    ClientSecret = "N-zSNIP1mkKrutG2yaBVPsY6",
            //},
            //new[] { DriveService.Scope.Drive }, "*****@*****.**",
            //CancellationToken.None).Result;

            //   var service = new DriveService(new BaseClientService.Initializer()
            //   {
            //       HttpClientInitializer = credential,
            //       ApplicationName = "docsync-1156",
            //   });
            //   //var response = service.Files.Get("MySheet").Execute();
            //foreach (var item in response.)
            //{
            //    Console.WriteLine(item.Title);
            //}
        }
Esempio n. 27
0
        private void Login_OAuth2()
        {
            ////////////////////////////////////////////////////////////////////////////
            // 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 = "563378205629.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 = "LTjwzC8lyx6gTcTR-yKvJojy";

            // 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.
            string 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 = CLIENT_ID;

            // Set your OAuth 2.0 Client Secret, which can be obtained at
            // https://code.google.com/apis/console.
            parameters.ClientSecret = CLIENT_SECRET;

            // Set your Redirect URI, which can be registered at
            // https://code.google.com/apis/console.
            parameters.RedirectUri = REDIRECT_URI;

            ////////////////////////////////////////////////////////////////////////////
            // STEP 3: Get the Authorization URL
            ////////////////////////////////////////////////////////////////////////////

            // Set the scope for this particular service.
            parameters.Scope = 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..."
            );

            //string authPage = WebUtil.Share().FetchWebPage(authorizationUrl);
            parameters.AccessCode = "4/XafgMCkzSYVgiFNBD9J0n9Kkp4X-.AuaA_wRiBmARgrKXntQAax0MeXZ4cQI";//Console.ReadLine();

            ////////////////////////////////////////////////////////////////////////////
            // 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.GetAccessToken(parameters);
            string accessToken = parameters.AccessToken;
            Console.WriteLine("OAuth Access Token: " + accessToken);

            // Initialize the variables needed to make the request
            GOAuth2RequestFactory requestFactory =
                new GOAuth2RequestFactory(null, "MySpreadsheetIntegration-v1", parameters);
            service = new SpreadsheetsService("MySpreadsheetIntegration-v1");
            service.RequestFactory = requestFactory;
        }
Esempio n. 28
0
    /// <summary>
    ///     Set the access code from Google
    /// </summary>
    /// <param name="accessCode">Access code</param>
    public void SetAccessCode(string accessCode)
    {
        oAuthParameters.AccessCode = accessCode;

        OAuthUtil.GetAccessToken(oAuthParameters);
        OAuthUtil.RefreshAccessToken(oAuthParameters);

        string accessToken = oAuthParameters.AccessToken;
        string refreshToken = oAuthParameters.RefreshToken;

        EditorPrefs.SetString("Datablocks_RefreshToken", refreshToken);
        EditorPrefs.SetString("Datablocks_AccessToken", accessToken);

        RefreshToken = refreshToken;
        AccessToken = accessToken;

        var requestFactory = new GOAuth2RequestFactory(null, "Datablocks for Unity", oAuthParameters);
        service.RequestFactory = requestFactory;
    }
Esempio n. 29
0
        private void Autoriace_recive_token(OAuth2Parameters parameters)
        {
            parameters.AccessCode = "";

              ////////////////////////////////////////////////////////////////////////////
              // 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.GetAccessToken(parameters);
              string accessToken = parameters.AccessToken;
              string refreshToken = parameters.RefreshToken;
              Console.WriteLine("OAuth Access Token: " + accessToken + "\n");
              Console.WriteLine("OAuth Refresh Token: " + refreshToken + "\n");

              ////////////////////////////////////////////////////////////////////////////
              // STEP 5: Make an OAuth authorized request to Google
              ////////////////////////////////////////////////////////////////////////////

              // Initialize the variables needed to make the request
              GOAuth2RequestFactory requestFactory =
                  new GOAuth2RequestFactory(null, _app_name, parameters);
              SpreadsheetsService service = new SpreadsheetsService(_app_name);
              service.RequestFactory = requestFactory;

              // Make the request to Google
              // See other portions of this guide for code to put here...

              // Instantiate a SpreadsheetQuery object to retrieve spreadsheets.
              Google.GData.Spreadsheets.SpreadsheetQuery query = new Google.GData.Spreadsheets.SpreadsheetQuery();

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

              // Iterate through all of the spreadsheets returned
              foreach (SpreadsheetEntry entry in feed.Entries)
              {
                // Print the title of this spreadsheet to the screen
                Console.WriteLine(entry.Title.Text);
              }
              Console.ReadLine();
        }
 public SpreadSheetManager(OAuth2Parameters parameters)
 {
     GOAuth2RequestFactory requestFactory =
       new GOAuth2RequestFactory(null, "MySpreadsheetIntegration-v1", parameters);
       service = new SpreadsheetsService("MySpreadsheetIntegration-v1");
       service.RequestFactory = requestFactory;
 }
Esempio n. 31
-1
    /// <summary>
    ///     Initilize sheets API with saved token
    /// </summary>
    public void Initilize()
    {
        PermissiveCert.Instate();
        RefreshToken = EditorPrefs.GetString("Datablocks_RefreshToken");
        AccessToken = EditorPrefs.GetString("Datablocks_AccessToken");

        Service = new SpreadsheetsService("Datablocks for Unity");

        // OAuth2Parameters holds all the parameters related to OAuth 2.0.
        oAuthParameters = new OAuth2Parameters();

        // Set your OAuth 2.0 Client Id (which you can register at
        oAuthParameters.ClientId = CLIENT_ID;

        // Set your OAuth 2.0 Client Secret, which can be obtained at
        oAuthParameters.ClientSecret = CLIENT_SECRET;

        // Set your Redirect URI, which can be registered at
        oAuthParameters.RedirectUri = REDIRECT_URI;

        // Set the scope for this particular service.
        oAuthParameters.Scope = SCOPE;

        if (!string.IsNullOrEmpty(RefreshToken))
        {
            oAuthParameters.RefreshToken = RefreshToken;
            oAuthParameters.AccessToken = AccessToken;

            var requestFactory = new GOAuth2RequestFactory(null, "Datablocks for Unity", oAuthParameters);
            Service.RequestFactory = requestFactory;
        }
    }