/// <summary> /// Shows the Google authentication web view so the user can authenticate /// </summary> async Task ShowGoogleAuthenticationView() { try { var api = new GoogleApi("google", Keys.GoogleApiClientId, Keys.GoogleClientSecret, new NativeMessageHandler()) { Scopes = Keys.GoogleScope.Split(' '), }; if (_doResetWebCache) { _doResetWebCache = false; api.ResetData(); } var account = await api.Authenticate(); if (account != null) { var oauthAccount = (OAuthAccount)account; App.AuthToken = "{0} {1}".Fmt(oauthAccount.TokenType, oauthAccount.Token); await Settings.Instance.Save(); } } catch (Exception e) { Console.WriteLine("**SPORT AUTHENTICATION ERROR**\n\n" + e.GetBaseException()); Insights.Report(e); } }
public async Task <IActionResult> OnGetAsync(string state, string code) { var antiForgery = HttpContext.Request.Cookies.FirstOrDefault(x => x.Key.StartsWith(".Login.Antiforgery")).Value; var stateDictionary = state.FromJsonEncoded(); var antiForgeryInState = (string)stateDictionary["AntiForgery"]; stateDictionary.Remove("AntiForgery"); // There might be + characters in the cookie to indicate a space, so we decode // it so it will match state (which would have already been decoded) // var antiForgeryDecoded = WebUtility.UrlDecode(antiForgery); if (antiForgeryInState != antiForgery) { return(Unauthorized()); } var(accessToken, _) = await GoogleApi.ValidateSignIn(code); HttpContext.Response.Cookies.Append(".google-token", accessToken, new CookieOptions { HttpOnly = true, Path = "/", Expires = DateTimeOffset.Now.AddHours(1), IsEssential = true }); return(RedirectToPage("Index", stateDictionary)); }
public override bool Add(SageLocation entity) { if (entity.Id == null) { entity.Id = ObjectId.GenerateNewId().ToString(); } if (workOrders == null) { var workOrderRepository = new MongoDbUnitOfWork().GetEntities <SageWorkOrder>(); workOrders = workOrderRepository.Get().Where(x => x.Status == "0").ToList(); } if (workOrders.Any(x => x.Location == entity.Location)) { System.Threading.Thread.Sleep(1000); var parametersSearch = entity.Address + " " + entity.City + " " + entity.ZIP + " " + entity.State; var location = GoogleApi.GetLocation(parametersSearch); if (location != null && location.result != null && location.result.Any()) { var geometry = location.result.FirstOrDefault().geometry; if (geometry != null && geometry.location != null) { entity.Latitude = geometry.location.lat; entity.Longitude = geometry.location.lng; } } } return(Collection.Insert(entity).HasLastErrorMessage); }
public SaveResult Save() { try { int count = 1; Trip.Steps.Add(new Step(AddressStart, TypeStep.Start, count++)); if (Steps != null) { foreach (var item in Steps) { Trip.Steps.Add(new Step(item, TypeStep.Step, count++)); } } Trip.Steps.Add(new Step(AddressEnd, TypeStep.End, count++)); Trip.Driver = SessionHelper.CurrentUser; Trip.DateStart = Date.AddHours(Hours.Hour).AddMinutes(Hours.Minute); Trip.RoundTrip = RoundTrip == "on"; Trip.Duration = new TimeSpan(0, 0, 0, Duration); var res = Trip.Save(); var json = GoogleApi.GetGoogleDirection(AddressStart, AddressEnd, Steps); Container.Manager.VoyageGuidageOperation.Add(Container.Manager.VoyageOperation.GetById(res.Id), json); Container.Manager.Save(); return(new SaveResult(true, Trip.Id)); } catch (Exception ex) { Logger.Error(ex, "TripViewModel.Save()"); return(new SaveResult(ex)); } }
Label warningLabel = new Label(); //выводится, если введены некорректные данные public Form2() { InitializeComponent(); this.Text = "Морской бой"; GoogleApi.Acsess(); StartGame(); }
public void Start(object sender, EventArgs e) { Warning(); sheetsArray = WriteToArray(); if (sheetsArray[0] == sheetsArray[1]) { warningLabel.Text = "Необходимо ввести разные таблицы для игрока и противника"; } else { if (ValidData(sheetsArray[0]) && ValidData(sheetsArray[1])) { GoogleApi.CreateEntry(); Form1.tern = Form1.StartMove(); GoogleApi.WrtiteTern(sheetsArray[0], Form1.tern); Hide(); Form1 myForm = new Form1(); myForm.ShowDialog(); myForm.UpdatePole(); } else { warningLabel.Text = "Проверьте правильность ввода листов таблицы"; } } }
public override ReferenceReader Initialize() { LoadCache(); if (!IsAllDataCached() || CardMakerInstance.ForceDataCacheRefresh) { var zSpreadsheet = new GoogleSpreadsheet(CardMakerInstance.GoogleInitializerFactory); try { zSpreadsheet.MakeSimpleSpreadsheetRequest(); } catch (GoogleApiException e) { if (GoogleApi.IsAuthorizationError(e)) { CardMakerInstance.GoogleCredentialsInvalid = true; } } catch (Exception e) { Logger.AddLogLine("Google Access Error: {0}".FormatString(e.Message)); } } return(this); }
public void WhoMove(Button pressedButton) //совершает выстрел и в зависимости от промаха/попадания записывает в таблицу игрока и в таблицу противника значения { int tern1, tern2; tern1 = ValueOfTern(0); bool shootData = Shoot(enemyMap, pressedButton); if (tern1 == 1) { if (shootData) { tern1 = 1; tern2 = 0; GoogleApi.WrtiteTern(Form2.sheetsArray[0], tern1); GoogleApi.WrtiteTern(Form2.sheetsArray[1], tern2); } else { tern1 = 0; tern2 = 1; GoogleApi.WrtiteTern(Form2.sheetsArray[0], tern1); GoogleApi.WrtiteTern(Form2.sheetsArray[1], tern2); } } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var googleApiConfig = new GoogleApi(); Configuration.GetSection("GoogleApi").Bind(googleApiConfig); services.Configure <CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddDbContext <InventoryContext>(options => { options.UseMySql(Configuration.GetConnectionString("DefaultConnection")); }); services.AddSession(options => { options.IdleTimeout = TimeSpan.FromSeconds(60); }); services.AddAuthentication(options => { options.DefaultAuthenticateScheme = "GoogleAuthMiddleware"; options.DefaultChallengeScheme = "GoogleAuthMiddleware"; }).AddCookie("GoogleAuthMiddleware", "GoogleAuthMiddleware", options => { options.LoginPath = "/auth/google-login"; options.AccessDeniedPath = "/home/beta"; }); services.AddSingleton <AssetLocator>(); services.AddSingleton(new GoogleApiConnector(googleApiConfig)); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); }
public override string AuthStartGetUrl(string redirectUrl, string state = "") { using (GoogleApi tmpApi = new GoogleApi(this.AppCredential.ClientId._NullCheck(), this.AppCredential.ClientSecret._NullCheck())) { return(tmpApi.AuthGenerateAuthorizeUrl(Consts.OAuthScopes.Google_Gmail, redirectUrl, state)); } }
public MarketViewModel(MonitorContext context) { Context = context; Context.Products.Load(); Context.Product.Load(); Context.Markets.Load(); if (Context.Markets.Count() == 0) { this.Fill(); } DispatcherTimer timer = new DispatcherTimer(); timer = new DispatcherTimer(); timer.Interval = new TimeSpan(0, 20, 0); timer.Tick += new EventHandler(this.DBUpdate); User = new User { LastUpdate = Properties.Settings.Default.LastUpdate }; Notify = new Notification(); // Start the timer. timer.Start(); try { GoogleApi api = new GoogleApi(Properties.Settings.Default.Token); User.Email = api.GetEmailPlus(); } catch { } }
public async System.Threading.Tasks.Task TestGetAutoCompleteAsync() { //localhost:9000/autocomplete?q=publix var _google = new GoogleApi(); var respList = await _google.GetAutoCompleteAsync("publix"); Assert.IsTrue(respList.Count > 0, "No records found"); }
public GoogleSheetOutput(string appName, string sheetId) { this.appName = appName; this.sheetId = sheetId; googleApi = new GoogleApi(appName, sheetId); storedIds = googleApi.GetIds(); }
public void Mapper_Should_Map_Book_To_Database_Model() { var googleBook = GoogleApi.FindBook("9780132350884"); var book = Mapper.ConvertModel <GoogleBookModel, Book>(googleBook); var databaseModel = Mapper.ConvertModel <Book, BookDB>(book); ValidateBook(book, databaseModel); }
public async Task LoginAsync(string provider) { var account = new SimpleAuth.Account(); switch (provider) { case Constants.Providers.Google: var clientId = Device.RuntimePlatform == Device.iOS ? Constants.ApiInfo.GoogleInfo.GoogleiOSClientId : Constants.ApiInfo.GoogleInfo.GoogleWebClientId; var clientSecret = Device.RuntimePlatform == Device.iOS ? null : Constants.ApiInfo.GoogleInfo.GoogleClientSecret; var googAuthenticator = new GoogleApi(Constants.Providers.Google, clientId, clientSecret) { Scopes = Constants.ApiInfo.GoogleInfo.GoogleScopes }; account = await googAuthenticator.Authenticate(); break; case Constants.Providers.Facebook: var facebookAuthenticator = new FacebookApi(Constants.Providers.Facebook, Constants.ApiInfo.FacebookInfo.FacebookAppId, Constants.ApiInfo.FacebookInfo.FacebookSecret); account = await facebookAuthenticator.Authenticate(); break; case Constants.Providers.Microsoft: var microsoftAuthenticator = new MicrosoftLiveConnectApi(Constants.Providers.Microsoft, Constants.ApiInfo.MicrosoftInfo.MicrosoftAppId, Constants.ApiInfo.MicrosoftInfo.MicrosoftSecret) { Scopes = Constants.ApiInfo.MicrosoftInfo.MicrosoftScopes }; account = await microsoftAuthenticator.Authenticate(); break; case Constants.Providers.Twitter: var twitterAuthenticator = new TwitterApi(Constants.Providers.Twitter, Constants.ApiInfo.TwitterInfo.TwitterAppId, Constants.ApiInfo.TwitterInfo.TwitterSecret) { RedirectUrl = new Uri("https://mobile.twitter.com/home") }; account = await twitterAuthenticator.Authenticate(); break; case Constants.Providers.Local: break; default: break; } var oauthAccount = account as SimpleAuth.OAuthAccount; if (!string.IsNullOrEmpty(oauthAccount.Token)) { await StoreToken(oauthAccount.Token); _navigation.NavigateToRoot <MainPageViewModel>(true, null); } return; }
public async System.Threading.Tasks.Task TestGetPlaceDetailsByIdAsync() { //localhost:9000/place?q=ChIJ5YQQf1GHhYARPKG7WLIaOko var id = "ChIJh7E5A2mA3YgR2IsjfOXPfx8"; var _google = new GoogleApi(); var dPlace = await _google.GetPlaceDetailsByIdAsync(id); Assert.IsTrue((dPlace != null && dPlace.Name != null), "Id was not found"); }
public void Init() { isPlaying = false; GoogleApi.Acsess(); GoogleApi.array = GoogleApi.ReadEntries(Form2.sheetsArray[0]); ConfigureShips(); ButtonStart(); enemy = new Enemy(enemyMap, myMap, enemyButtons, myButtons); }
public void GetFileMetadataUsingFileIdTest(string fileId) { // Act var actual = GoogleApi.GetFileMetadataUsingFileId(fileId); // Assert Assert.NotNull(actual); Debug.WriteLine(actual.ToString()); }
public void GetFileByFileIdTest(string fileId) { // Act var actual = GoogleApi.GetFileByFileId(fileId); // Assert Assert.NotNull(actual); Debug.WriteLine(actual); }
public SaveBookViewModel(IView view) { _view = view; _bookDal = new BookDal(); googleApi = new GoogleApi(); SaveButtonCommand = new RelayCommand(SaveButton, () => true); CloseWindowCommand = new RelayCommand <Window>(CloseWindow, window => true); GetBookFromAmazonCommand = new RelayCommand(GetBookFromAmazon, CanGetBookInformation); }
// Use this for initialization void Start() { googleScript = googleHolder.GetComponent <GoogleApi>(); raycastLine.positionCount = 2; raycastLine.material = new Material(Shader.Find("Particles/Multiply")); raycastLine.SetColors(Color.blue, Color.blue); raycastLine = Instantiate(raycastLine); houseMarker = Instantiate(houseMarker); }
public void UpdateFileTest(string newFileName, string fileId) { // Act var actual = GoogleApi.UpdateFile(newFileName, fileId); // Assert //Assert.NotNull(actual); //Assert.Equal(fileId, actual.Id); output.WriteLine(actual.Name, " ", actual.Id); }
public void CreateServiceTest() { // Arrange // Act var actual = GoogleApi.CreateService(); // Assert Assert.NotNull(actual); }
void Start() { leftController.GetComponent <VRTK_ControllerEvents>().TouchpadPressed += new ControllerInteractionEventHandler(TouchpadPressed); cam = GetComponent <Camera>(); googleScript = googleHolder.GetComponent <GoogleApi>(); currentMiddlelatitude = googleScript.lat; currentMiddlelongitude = googleScript.lon; zoomLevel = googleScript.zoom; dataloggerScript = dataLoggerHolder.GetComponent <DataLogger>(); }
public void UploadFileTest(string filename) { // Arrange // Act var actual = GoogleApi.UploadFile(filename); // Arrange Assert.NotNull(actual); }
public void GetUserCredentialTest() { // Arrange // Act var actual = GoogleApi.GetUserCredential(); // Assert Assert.NotNull(actual); }
public void CopyFileToNewLocationTest(string fromFolder, string toFolder, string fileName) { // Act var actual = GoogleApi.CopyFileToNewLocation(fromFolder, toFolder, fileName); // Assert Assert.NotNull(actual); Assert.True(actual.Result.Parents.Count > 1); Assert.Equal(fileName, actual.Result.Name); }
public void GetFileMetadataUsingFileNameTest(string fileName) { // Act var actual = GoogleApi.GetFileMetadataUsingFileName(fileName); // Assert Assert.NotNull(actual); Assert.Equal(fileName, actual.FileName); Debug.WriteLine(actual.ToString()); }
public MainViewModel() { bookDal = new BookDal(); BooksCollection = new ObservableCollection <Book>(bookDal.GetBooks()); googleApi = new GoogleApi(); AddBookCommand = new RelayCommand(AddBook, () => true); PurgeAllBooksCommand = new RelayCommand(PurgeAllDatabase, () => true); LoadDummyBooksCommand = new RelayCommand(LoadDummyBooks, () => true); ShutdownAppCommand = new RelayCommand(ShutDownApp, () => true); }
public void UploadFileToSpecificFolderTest(string folderName, string fileName) { // Arrange // Act var actual = GoogleApi.UploadFileToSpecificFolder(folderName, fileName); // Assert Assert.NotNull(actual); }
private bool getAccessToken(string authCode) { bool getSuccess = false; string accessToken=""; if(RefreshKey_saved == "") { consumer.ClientCredentialApplicator = ClientCredentialApplicator.PostParameter(clientSecret); IAuthorizationState grantedAccess1 = consumer.ProcessUserAuthorization(authCode); bool result=consumer.RefreshAuthorization(grantedAccess1, TimeSpan.FromHours(10)); accessToken = grantedAccess1.AccessToken; // save key iniParser parser = new iniParser(); String appStartPath = System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName); parser.IniParser(iniPath); string _r=grantedAccess1.AccessToken; //.RefreshToken; parser.AddSetting("Setup", "refreshkey", _r); parser.SaveSettings(); myTabControl.SelectedIndex = 0; } else { // change code immediately // consumer.RefreshAuthorization(grantedAccess1, TimeSpan.FromDays(30)); //accessToken = grantedAccess1.AccessToken; accessToken=RefreshKey_saved; myTabControl.SelectedIndex = 0; } try { GoogleApi api = new GoogleApi(accessToken); // string user = "******"; // api.GetEmail(); // GoogleApi api = new GoogleApi(accessToken); XmlDocument contacts = api.GetContacts(); XmlNamespaceManager nsmgr = new XmlNamespaceManager(contacts.NameTable); nsmgr.AddNamespace("gd", "http://schemas.google.com/g/2005"); nsmgr.AddNamespace("a", "http://www.w3.org/2005/Atom"); emailCount = 0; foreach (XmlNode contact in contacts.GetElementsByTagName("entry")) { XmlNode title = contact.SelectSingleNode("a:title", nsmgr); XmlNode email = contact.SelectSingleNode("gd:email", nsmgr); Console.WriteLine("{0}: {1}", title.InnerText, email.Attributes["address"].Value); mail_arr.Add(email.Attributes["address"].Value); emailCount++; // listbox1.Items.Add(title.InnerText + " , " + email.Attributes["address"].Value); } getSuccess = true; } catch (Exception err) { // MessageBox.Show("error: " + err.Message); Console.WriteLine("Error: " + err.Message); getSuccess = false; return getSuccess; } // everything is good, goto input : autocomplete contactData.inc(emailCount); int i = 0; foreach (string emailAddress in mail_arr) { contactData.States.SetValue(emailAddress, i); i++; } int where = contactData.States.Length; // AutoCompleteBox.ItemsSource = contactData.States; email_list.Items.Clear(); label_invalid.Visibility = Visibility.Collapsed; // myTabControl.SelectedIndex = 0; return getSuccess; //------------------------ try { // get inbox mail content // #region get InBox string user = "******"; // api.GetEmail(); using (Imap imap = new Imap()) { imap.ConnectSSL("imap.gmail.com"); imap.LoginOAUTH2(user, accessToken); imap.SelectInbox(); List<long> uids = imap.Search(Flag.Unseen); foreach (long uid in uids) { string eml = imap.GetMessageByUID(uid); IMail email = new MailBuilder().CreateFromEml(eml); // listbox1.Items.Add(email.From); } imap.Close(); } } catch (Exception err) { MessageBox.Show("error: " + err.Message); } }