public MapLocation GetGeoLocation(string address) { var xdoc = GoogleAPI.GeolocationRequest(address); var geolocation = GoogleAPI.ManageGeolocationResponse(xdoc); return(geolocation); }
async Task CallGetEvents() { string valid = await GetEvents(); if (valid == "FAILURE") { Debug.WriteLine("Need to refresh token"); //We want to get a new token in this case string refresh = account.refreshToken; bool new_tokens = await GoogleAPI.RefreshToken(refresh); if (new_tokens == false) { //Navigate back to login page Application.Current.MainPage = new LogInPage(); } //Otherwise, we simply call getEvents again valid = await GetEvents(); if (valid == "SUCCESS") { Debug.WriteLine("Successfully got events!"); } else { Debug.WriteLine("Error getting refresh tokens"); } } }
private async Task HandleCommandAsync(SocketMessage messageParam) { var message = messageParam as SocketUserMessage; SocketCommandContext context; int argPos = 0; // Delimiteur commande/parametres string[] imagesUrl = { ".jpg", ".png" }; // Verifie que ce soit un message d'utilisateur, et adressé au bot if (message == null || !(message.HasCharPrefix('!', ref argPos)) || message.HasMentionPrefix(_client.CurrentUser, ref argPos) || message.Author.IsBot) { if (messageParam.Attachments.Count > 0) { List <Attachment> images = message.Attachments .Where(x => imagesUrl .Any(y => x.Url.EndsWith(y))) .ToList(); string channelID = messageParam.Channel.Id.ToString(); foreach (var image in images) { GoogleAPI.UploadImageFromLink(channelID, image.Url); } } return; } // Detecte puis execute la commande context = new SocketCommandContext(_client, message); await _commands.ExecuteAsync(context, argPos, null); }
public AutoComplete() { APIClient = new APIService(); GoogleAPI = new GoogleAPI(); GoogleService = new GoogleService(GoogleAPI, APIClient); Algorithm = new DistantBasedAlgorithm(GoogleService); }
public ActionResult Index() { GoogleAPI googleReport = new GoogleAPI(); googleReport.GenerateReport(); return(View(googleReport)); //New to MVC not sure if this is how to instantiate my class? }
public void TestGeo2() { float Lat = 51.25137F; float Long = 7.778971F; string result = GoogleAPI.GetAdress(Lat, Long); Assert.IsNotNull(result); Assert.IsTrue(result != ""); }
public void JsonToItems_JsonWithNoItems_EmptyItemsList() { // Arrange StreamReader reader = new StreamReader(Path.Combine(resourcesPath, "noSearchResults.json")); dynamic jsonData = JsonConvert.DeserializeObject(reader.ReadToEnd()); // Act List <Items> items = GoogleAPI.jsonToItems(jsonData); // Assert Assert.AreEqual(0, items.Count); }
private async Task SendToGoogle(ImageFormat format) { using (var imageStream = new MemoryStream()) { ExportService.ExportWithoutSaving(Canvas, format, imageStream); string feedback = await GoogleAPI.SaveOnGoogleDrive(imageStream, ".png", AuthService.GoogleAccessToken); ToastsService.Pop("Google Drive Sharing", feedback, Constants.DriveIconUri); if (AuthService.IsLoggedIn) { await AchievementsService.Increment(AuthService.CurrentUser.Id, AchievementMetrics.SharesOnDrive); } } }
public void jsonToGoogleUrl_FilledJson_GoogleUrl() { // Arrange StreamReader reader = new StreamReader(Path.Combine(resourcesPath, "configTest.json")); dynamic jsonData = JsonConvert.DeserializeObject(reader.ReadToEnd()); List <string> query = new List <string>(new string[] { "Legislative", "Executive", "Judicial" }); // Act string googleUrl = GoogleAPI.jsonToGoogleUrl(jsonData, query); // Assert Assert.AreEqual( "https://customsearch.googleapis.com/customsearch/v1?key=ABCDEFGHIJKLMNOPQRSTUVWXYZ&cx=0123456789&q=Legislative%20Executive%20Judicial&searchType=image&num=5&imgSize=xxlarge" , googleUrl); }
static async Task <IWorkbook> ReadExcel() { String filePath = "../../data/data.xls"; String sheetName = "Cluster"; String fileExt = System.IO.Path.GetExtension(filePath); FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read); IWorkbook workbook = null; if (fileExt == ".xls") { workbook = new HSSFWorkbook(file); } else if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(file); } if (workbook != null) { ISheet sheet = workbook.GetSheet(sheetName); if (sheet != null) { for (int i = 1; i <= sheet.LastRowNum; i++) // skip header { IRow row = sheet.GetRow(i); if (row != null) //null is when the row only contains empty cells { String lat = row.GetCell(1).ToString().Trim(); String lng = row.GetCell(2).ToString().Trim(); String result = await GoogleAPI.GetNearestRoad(lat, lng); if (result != null) { String[] items = result.Split('\n'); ICell cell = row.GetCell(3) != null?row.GetCell(3) : row.CreateCell(3); cell.SetCellValue(items[0]); cell = row.GetCell(4) != null?row.GetCell(4) : row.CreateCell(4); cell.SetCellValue(items[1]); } } } } } file.Close(); return(workbook); }
// Use this for initialization void Awake() { if (s != null && s != this) { Destroy(this.gameObject); return; } else { s = this; } Application.targetFrameRate = 60; DontDestroyOnLoad(this.gameObject); }
/// <summary> /// Initializes the G-mail service asynchronous. /// </summary> public async Task InitializeGmailServiceAsync() { try { GoogleAPI = new GoogleAPI(); await GoogleAPI.CreateUserCredentialAsync(); UsersResource = GoogleAPI.GetGmailUserResource(); GoogleServiceInitialized = true; } catch (Exception ex) { LogError(ex); GoogleServiceInitialized = false; throw; } }
public void JsonToItems_JsonWith1Item_Item() { // Arrange StreamReader reader = new StreamReader(Path.Combine(resourcesPath, "oneSearchResult.json")); dynamic jsonData = JsonConvert.DeserializeObject(reader.ReadToEnd()); // Act List <Items> items = GoogleAPI.jsonToItems(jsonData); // Assert Assert.AreEqual("Banana bread tops the list of most searched for recipes in ...", items[0].title); Assert.AreEqual("https://i.dailymail.co.uk/1s/2020/05/08/16/28165848-0-image-a-51_1588951482497.jpg", items[0].link); Assert.AreEqual("Banana bread tops the list of most searched for recipes in ...", items[0].snippet); Assert.AreEqual("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSNlrx0wzJ7YfD5cVIIQvOnrEirC-lfVesmhILv4T1D2WyNTHonIHAX&s", items[0].thumbnailLink); Assert.AreEqual(70, items[0].thumbnailHeight); Assert.AreEqual(117, items[0].thumbnailWidth); }
public void JsonToItems_JsonWith5Items_5Items() { // Arrange StreamReader reader = new StreamReader(Path.Combine(resourcesPath, "fiveSearchResults.json")); dynamic jsonData = JsonConvert.DeserializeObject(reader.ReadToEnd()); // Act List <Items> items = GoogleAPI.jsonToItems(jsonData); // Assert Assert.AreEqual("Google Slides: Free Online Presentations for Personal Use", items[0].title); Assert.AreEqual("https://blogs.shu.ac.uk/shutel/files/2014/08/GSlides.png", items[0].link); Assert.AreEqual("Google Slides: Free Online Presentations for Personal Use", items[0].snippet); Assert.AreEqual("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTJD2kAqjGymXR2mNOk4StjJQavh1nwHdkRrFCOuLYrhgkJVz-8JRhbcA&s", items[0].thumbnailLink); Assert.AreEqual(116, items[0].thumbnailHeight); Assert.AreEqual(116, items[0].thumbnailWidth); Assert.AreEqual("Google", items[1].title); Assert.AreEqual("https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_160x56dp.png", items[1].link); Assert.AreEqual("googlelogo_color_160x56dp.png", items[1].snippet); Assert.AreEqual("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQu7ggDqQyXuxqO0_rzP-_dRCIY-Ul34jHadQSgkoV-z2gcxrj5rYO0Wg&s", items[1].thumbnailLink); Assert.AreEqual(41, items[1].thumbnailHeight); Assert.AreEqual(118, items[1].thumbnailWidth); Assert.AreEqual("Google Input Tools", items[2].title); Assert.AreEqual("https://www.google.com/inputtools/images/hero-video.jpg", items[2].link); Assert.AreEqual("Google Input Tools", items[2].snippet); Assert.AreEqual("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSt9y6Ig6Uxvz5Y_zTtBIkVNnvihzlrABhf-GQiwBsfHbSkQKpgHhN3&s", items[2].thumbnailLink); Assert.AreEqual(75, items[2].thumbnailHeight); Assert.AreEqual(122, items[2].thumbnailWidth); Assert.AreEqual("30th Anniversary of PAC-MAN", items[3].title); Assert.AreEqual("https://www.google.com/logos/2002/dilberttwo.gif", items[3].link); Assert.AreEqual("30th Anniversary of PAC-MAN", items[3].snippet); Assert.AreEqual("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSnhk3QXrOnD9DHoRYrgiKbK1zOZxfA3UgG-e1EAge5cGPsXH4kxAqCDVc&s", items[3].thumbnailLink); Assert.AreEqual(31, items[3].thumbnailHeight); Assert.AreEqual(133, items[3].thumbnailWidth); Assert.AreEqual("Google Slides: Free Online Presentations for Personal Use", items[4].title); Assert.AreEqual("https://lh3.ggpht.com/9rwhkrvgiLhXVBeKtScn1jlenYk-4k3Wyqt1PsbUr9jhGew0Gt1w9xbwO4oePPd5yOM=w300", items[4].link); Assert.AreEqual("Google Slides: Free Online Presentations for Personal Use", items[4].snippet); Assert.AreEqual("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRf6eeLn_JMfOKbyBwUtVCJLBqnL08o7jw-nx4ocjUmeZOwqa0N5q9WlA&s", items[4].thumbnailLink); Assert.AreEqual(116, items[4].thumbnailHeight); Assert.AreEqual(116, items[4].thumbnailWidth); }
public async Task <IResponse> GoogleRegister([FromBody] GoogleRegisterModel googleRegisterModel) { ExternalLoginResponse externalLoginResponse = new ExternalLoginResponse(); externalLoginResponse.IsModelValid = ModelState.IsValid; if (ModelState.IsValid) { GoogleDataModel googleData = await GoogleAPI.GetUserLoginData(googleRegisterModel.AccessToken); ExternalLoginInfo info = CustomExternalLoginInfo.FromLoginModel("Google", googleData); Account account = new Account { UserName = googleRegisterModel.Username, Email = googleData.Email }; var result = await _userManager.CreateAsync(account); if (result.Succeeded) { result = await _userManager.AddLoginAsync(account, info); account.SetUpPoints(_context); await _context.SaveChangesAsync(); if (result.Succeeded) { await _signInManager.SignInAsync(account, true); } } externalLoginResponse.CreateResult = result; externalLoginResponse.Errors = result.Errors.Select(x => x.Description); } else { externalLoginResponse.Errors = ModelState.Values.SelectMany(v => v.Errors.Select(b => b.ErrorMessage)); } return(externalLoginResponse); }
public async Task <IResponse> GoogleSignIn([FromBody] GoogleLoginModel googleLoginModel) { ExternalLoginResponse externalLoginResponse = new ExternalLoginResponse(); externalLoginResponse.IsModelValid = ModelState.IsValid; if (ModelState.IsValid) { GoogleDataModel googleData = await GoogleAPI.GetUserLoginData(googleLoginModel.AccessToken); ExternalLoginInfo info = CustomExternalLoginInfo.FromLoginModel("Google", googleData); var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, true); externalLoginResponse.IsRegistered = result.Succeeded; externalLoginResponse.Result = result; } else { externalLoginResponse.Errors = ModelState.Values.SelectMany(v => v.Errors.Select(b => b.ErrorMessage)); } return(externalLoginResponse); }
public async void NavigatedHandler(object sender, NavigationEventArgs e) { if (e.Uri.Host.Equals("www.facebook.com") && e.Uri.Fragment.Contains("access_token=")) { Visibility = Visibility.Hidden; FacebookConnected?.Invoke(this, new ConnectedEventArgs(ParseGetParameter(e.Uri.Fragment, "access_token"))); return; } if (e.Uri.Host.Equals("accounts.google.com")) { dynamic doc = ConnectionBrowser.Document; var htmlText = doc.documentElement.InnerHtml; Regex codeRegex = new Regex(@"<title>Success\scode=[a-zA-Z\d_\-\/~\.]{57}<\/title>"); Match codeMatch = codeRegex.Match(htmlText); if (codeMatch.Success) { Visibility = Visibility.Hidden; string code = codeMatch.Value.Substring(20, 57); string token = await GoogleAPI.GetGoogleAccessToken(code); GoogleConnected?.Invoke(this, new ConnectedEventArgs(token)); } } }
public ActionResult Index() { return(View(GoogleAPI.GetDriveFilesCustom("0B4MIqD5-aiTKY3N0QmU3UUNVaFk"))); }
public DistanceMatrix() { APIClient = new APIService(); GoogleAPI = new GoogleAPI(); GoogleService = new GoogleService(GoogleAPI, APIClient); }
public async Task SaveImageLink(string channelID, string imageLink) => await new Task(() => GoogleAPI.UploadImageFromLink(channelID, imageLink));
public GoogleAPI() { Instance = this; Debug.Log("Google API Construct"); }
static async Task <int> GetDistanceDuration(List <Station> stations, int[,] distance, int[,] duration) { String[] key = //"AIzaSyBfzSI0fxi2LfMLS2gBHuT0Uj3PNtg6kpY", // "AIzaSyCMixsUHVQxCI1lRjeuYlnw44rguIIVu78", // "AIzaSyAcrvPKrL7lpUlSeCawDZWylN58IoZJrt4", // "AIzaSyCI23HUoG4zqAvSwheflDAXaoYDX0cB96c", //"AIzaSyBoZywSXF5v6bvmQq5ACe2IrOfu7VdVQPU", { "AIzaSyD_jz_Q6UiqssRaKcZIRmcA1JE5tlivVeY", "AIzaSyChlnIf1epCPc0nqACdXO0CC2lzGqluhS0", "AIzaSyAgf7HvMzFeCFAI4pP5_DhqGp5zNexaIbw", "AIzaSyAS6jMX07dsiFHKbfKU_UKZHC6WxPy3FG4", "AIzaSyDtjztULpIl_uufAZv9h0osmmOc21MDpeI" /* "AIzaSyAdVXcc4W_tCZpKpNLeEmXeD2e0DJyCY1k", * "AIzaSyDUuKbQJ3-6fhXcCTU2euSxagTywNSD_EI", * "AIzaSyD9GVedngtNwQD49lmWQ6OGzKsZUIXHT4I", * "AIzaSyAy21E9OQPqVT9TCt2iH6aMowlI6yJ37O0"*/ }; int indexKey = 0; int size = stations.Count; int count = 0; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { if (i == j) { distance[i, j] = 0; duration[i, j] = 0; } else// if (distance[i, j] == -1 && duration[i, j] == -1) { Station stationI = stations[i]; Station stationJ = stations[j]; // if(stationI.NStudent!=0&&stationJ.NStudent!=0) { count++; if (count % 2000 == 0) { indexKey++; } String result = await GoogleAPI.GetDistanceDuration(stationI.Latitude.ToString(), stationI.Longitude.ToString(), stationJ.Latitude.ToString(), stationJ.Longitude.ToString(), key[indexKey]); if (result != null) { String[] items = result.Split('\n'); distance[i, j] = int.Parse(items[0]); duration[i, j] = int.Parse(items[1]); // distance[j, i] = distance[i, j]; // duration[j, i] = duration[i, j]; } else { Console.WriteLine("BI NULL: " + stationI.ID + "-" + stationJ.ID); } } } } Console.WriteLine(count); } // for DEBUG /*for (int i = 0; i < size; i++) * { * for (int j = 0; j < size; j++) * { * Console.WriteLine(i + " - " + j + ": " + distance[i, j] + " - " + duration[i, j]); * } * }*/ return(0); }
public async void SetContentGoogle(GoogleSignInAccount acct) { try { //Successful log in hooray!! if (acct != null) { progressBar.Visibility = ViewStates.Visible; Btn_Login.Visibility = ViewStates.Gone; G_AccountName = acct.Account.Name; G_AccountType = acct.Account.Type; G_displayName = acct.DisplayName; G_firstName = acct.GivenName; G_lastName = acct.FamilyName; G_profileId = acct.Id; G_email = acct.Email; G_Img = acct.PhotoUrl.Path; G_Idtoken = acct.IdToken; G_ServerCode = acct.ServerAuthCode; var api = new GoogleAPI(); G_accessToken = await api.GetAccessTokenAsync(G_ServerCode); if (!string.IsNullOrEmpty(G_accessToken)) { var(apiStatus, settingsResult) = await WoWonder_API.Current.GetSettings(); if (apiStatus == 200) { if (settingsResult is GetSiteSettingsObject.Config res) { var PushID = res.pushId; if (OneSignalNotification.OneSignalAPP_ID == "") { OneSignalNotification.OneSignalAPP_ID = PushID; if (AppSettings.ShowNotification) { OneSignalNotification.RegisterNotificationDevice(); } } string key = IMethods.IApp.GetValueFromManifest(this, "com.google.android.geo.API_KEY"); var(Api_status, respond) = await Global.Get_SocialLogin(G_accessToken, "google", key); if (Api_status == 200) { if (respond is AuthObject auth) { Current.AccessToken = auth.access_token; UserDetails.Username = UsernameEditext.Text; UserDetails.Full_name = UsernameEditext.Text; UserDetails.Password = PasswordEditext.Text; UserDetails.access_token = auth.access_token; UserDetails.User_id = auth.user_id; UserDetails.Status = "Active"; UserDetails.Cookie = auth.access_token; UserDetails.Email = UsernameEditext.Text; //Insert user data to database var user = new DataTables.LoginTB() { UserID = UserDetails.User_id, access_token = UserDetails.access_token, Cookie = UserDetails.Cookie, Username = UsernameEditext.Text, Password = PasswordEditext.Text, Status = "Active", Lang = "" }; Classes.DataUserLoginList.Add(user); var dbDatabase = new SqLiteDatabase(); dbDatabase.InsertRow(user); dbDatabase.Dispose(); if (AppSettings.Show_WalkTroutPage) { StartActivity(new Intent(this, typeof(AppIntroWalkTroutPage))); } else { StartActivity(new Intent(this, typeof(Tabbed_Main_Page))); //Get data profile var data = API_Request.Get_MyProfileData_Api(this).ConfigureAwait(false); } Finish(); } } else if (Api_status == 400) { if (respond is ErrorObject error) { var errortext = error._errors.Error_text; if (errortext.Contains("Invalid or expired access_token")) { API_Request.Logout(this); } } } else if (Api_status == 404) { var error = respond.ToString(); } progressBar.Visibility = ViewStates.Gone; Btn_Login.Visibility = ViewStates.Visible; } } } } } catch (Exception exception) { progressBar.Visibility = ViewStates.Gone; Btn_Login.Visibility = ViewStates.Visible; IMethods.DialogPopup.InvokeAndShowDialog(this, GetText(Resource.String.Lbl_Security), exception.Message, GetText(Resource.String.Lbl_Ok)); Console.WriteLine(exception); } }
static void RunArbitragem() { nRun++; Console.WriteLine("\nExecução: {0} - {1}\n", nRun, DateTime.Now); passo = "RunArbitragem"; try { #region GetPriceData //Cotações double quantidade = amountDefault; string amount = quantidade.ToString(cultureInfoUS); //Console.WriteLine("\nBUY"); List <Ticker> tickerBuy = AirSwapAPI.GetTickers("buy", asset, amount); //Console.WriteLine("\nSELL"); List <Ticker> tickerSell = AirSwapAPI.GetTickers("sell", asset, amount); #endregion //Encontrar a menor compra a mercado e a maior venda a mercado Ticker menorCompra = new Ticker(); Ticker maiorVenda = new Ticker(); double spreadGain = Convert.ToDouble(configuration["spreadGain"], cultureInfoUS); if (Program.debug) { Console.WriteLine("Spread lucro: {0:0.00} %", spreadGain * 100); } //Calcula menor compra Console.WriteLine("\nBUY"); foreach (Ticker p in tickerBuy) { //Lista todas as cotações encontradas if (Program.debug) { Console.WriteLine("{0:0.000000000000000000}\t {1}", p.avgPrice, p.exchangeName); } if ((p.avgPrice < menorCompra.avgPrice) || (menorCompra.avgPrice == 0)) { menorCompra.exchangeName = p.exchangeName; menorCompra.totalPrice = p.totalPrice; menorCompra.tokenAmount = p.tokenAmount; menorCompra.tokenSymbol = p.tokenSymbol; menorCompra.avgPrice = p.avgPrice; menorCompra.timestamp = p.timestamp; menorCompra.error = p.error; } } if (menorCompra.exchangeName == null) { Console.WriteLine("Exchange de compra não encontrada"); return; } //Calcula maior Venda Console.WriteLine("\nSELL"); foreach (Ticker p in tickerSell) { if (Program.debug) { Console.WriteLine("{0:0.000000000000000000}\t {1}", p.avgPrice, p.exchangeName); } if ((p.avgPrice > maiorVenda.avgPrice) && (p.exchangeName != menorCompra.exchangeName)) { maiorVenda.exchangeName = p.exchangeName; maiorVenda.totalPrice = p.totalPrice; maiorVenda.tokenAmount = p.tokenAmount; maiorVenda.tokenSymbol = p.tokenSymbol; maiorVenda.avgPrice = p.avgPrice; maiorVenda.timestamp = p.timestamp; maiorVenda.error = p.error; } } if (maiorVenda.exchangeName == null) { Console.WriteLine("Exchange de venda não encontrada"); return; } //Lucro double lucro = maiorVenda.avgPrice - menorCompra.avgPrice; if (Program.debug) { Console.WriteLine("\nlucro: {0:0.00000000}", lucro); } double gainPerc = (maiorVenda.avgPrice / menorCompra.avgPrice) - 1; Console.WriteLine("Compra:\t{0:0.000000000000000000}\t{1}", menorCompra.avgPrice, menorCompra.exchangeName); Console.WriteLine("Venda:\t{0:0.000000000000000000}\t{1}", maiorVenda.avgPrice, maiorVenda.exchangeName); Console.WriteLine("Calculo - Compra em {0} por {1:0.000000000000000000} - Venda em {2} por {3:0.000000000000000000}\nLucro: {4:0.000000000000000000} ({5:0.0000}%)" , menorCompra.exchangeName, menorCompra.avgPrice, maiorVenda.exchangeName, maiorVenda.avgPrice, lucro, gainPerc * 100); Console.WriteLine(); DateTime dateTime = DateTime.Now; if (gainPerc > spreadGain) { Console.WriteLine("PROFIT FOUND"); double gainAmount = lucro * quantidade; string alert = string.Format("{0}\tCompra em\t{1}\t{2:0.00000000}\tpor\t{3:0.000000000000000000}\nVenda em\t{4}\t{5:0.00000000}\tpor\t{6:0.000000000000000000}\nLucro:\t{7:0.000000000000000000}\t-\t{8:0.0000}%" , dateTime, menorCompra.exchangeName, quantidade, menorCompra.avgPrice, maiorVenda.exchangeName, quantidade, maiorVenda.avgPrice, gainAmount, gainPerc * 100); Console.WriteLine("{0}\tCompra:\t{1}\tpor\t{2:0.000000000000000000}", menorCompra.exchangeName, quantidade, menorCompra.avgPrice); Console.WriteLine("{0}\tVenda:\t{1}\tpor\t{2:0.000000000000000000}", maiorVenda.exchangeName, quantidade, maiorVenda.avgPrice); Console.WriteLine("Lucro lote: {0:0.000000000000000000}\n", gainAmount); GoogleAPI.UpdateTrade(dateTime, quantidade, menorCompra.exchangeName, menorCompra.avgPrice, maiorVenda.exchangeName, maiorVenda.avgPrice, gainAmount, gainPerc); } //lucro > spreadGain return; } catch (Exception ex) { erro = new StringBuilder(); erro.AppendLine(ex.Message); if (ex.InnerException != null) { erro.AppendLine(ex.InnerException.ToString()); } Console.WriteLine("\nERRO {0}\n{1}", passo, erro.ToString()); } }
public async void SetContentGoogle(GoogleSignInAccount acct) { try { //Successful log in hooray!! if (acct != null) { progressBar.Visibility = ViewStates.Visible; mButtonViewSignIn.Visibility = ViewStates.Gone; G_AccountName = acct.Account.Name; G_AccountType = acct.Account.Type; G_displayName = acct.DisplayName; G_firstName = acct.GivenName; G_lastName = acct.FamilyName; G_profileId = acct.Id; G_email = acct.Email; G_Img = acct.PhotoUrl.Path; G_Idtoken = acct.IdToken; G_ServerCode = acct.ServerAuthCode; var api = new GoogleAPI(); G_accessToken = await api.GetAccessTokenAsync(G_ServerCode); if (!string.IsNullOrEmpty(G_accessToken)) { Current.CurrentInstance.SetWebsiteURL(st.WebsiteUrl, st.ServerKey); var settingsResult = await Current.GetWoWonder_Settings(st, "WoWonder_Native_Android"); if (settingsResult != null) { string PushID = ""; try { PushID = settingsResult["push_id_2"].ToString(); } catch (Exception e) { Console.WriteLine(e); } if (OneSignalNotification.OneSignalAPP_ID == "") { OneSignalNotification.OneSignalAPP_ID = PushID; if (Settings.ShowNotification) { OneSignalNotification.RegisterNotificationDevice(); } } string key = IMethods.IApp.GetValueFromManifest(this, "com.google.android.geo.API_KEY"); var(Api_status, respond) = await Client.Global.Get_SocialLogin(st, G_accessToken, "google", key); if (Api_status == 200) { if (respond is Auth_Object auth) { WoWonder_API.Client.WebsiteUrl = st.WebsiteUrl; Current.CurrentInstance.ServerKey = st.ServerKey; Current.CurrentInstance.Access_token = auth.access_token; UserDetails.Username = mEditTextEmail.Text; UserDetails.Full_name = mEditTextEmail.Text; UserDetails.Password = mEditTextPassword.Text; UserDetails.access_token = auth.access_token; UserDetails.User_id = auth.user_id; UserDetails.Status = "Active"; UserDetails.Cookie = auth.access_token; UserDetails.Email = mEditTextEmail.Text; //Insert user data to database var user = new DataTables.LoginTB { UserID = UserDetails.User_id, access_token = UserDetails.access_token, Cookie = UserDetails.Cookie, Username = mEditTextEmail.Text, Password = mEditTextPassword.Text, Status = "Active", Lang = "", Device_ID = UserDetails.Device_ID, }; Classes.DataUserLoginList.Add(user); var dbDatabase = new SqLiteDatabase(); dbDatabase.InsertRow(user); dbDatabase.Dispose(); StartActivity(new Intent(this, typeof(AppIntroWalkTroutPage))); } } else if (Api_status == 400) { if (respond is Error_Object error) { var errortext = error._errors.Error_text; //Toast.MakeText(this, errortext, ToastLength.Short).Show(); if (errortext.Contains("Invalid or expired access_token")) { API_Request.Logout(this); } } } else if (Api_status == 404) { var error = respond.ToString(); //Toast.MakeText(this, error, ToastLength.Short).Show(); } progressBar.Visibility = ViewStates.Gone; mButtonViewSignIn.Visibility = ViewStates.Visible; Finish(); } } } } catch (Exception exception) { progressBar.Visibility = ViewStates.Gone; mButtonViewSignIn.Visibility = ViewStates.Visible; IMethods.DialogPopup.InvokeAndShowDialog(this, GetText(Resource.String.Lbl_Security), exception.Message, GetText(Resource.String.Lbl_Ok)); Crashes.TrackError(exception); } }
static async Task <List <Cluster> > ReadExcel() { List <Cluster> clusters = new List <Cluster>(); String filePath = "../../data/data.xls"; String sheetName = "Cluster"; String fileExt = System.IO.Path.GetExtension(filePath); FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read); IWorkbook workbook = null; if (fileExt == ".xls") { workbook = new HSSFWorkbook(file); } else if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(file); } if (workbook != null) { ISheet sheet = workbook.GetSheet(sheetName); if (sheet != null) { for (int i = 1; i <= sheet.LastRowNum; i++) // skip header { IRow row = sheet.GetRow(i); if (row != null) //null is when the row only contains empty cells { Cluster cluster = new Cluster(); cluster.ID = int.Parse(row.GetCell(0).ToString().Trim()); cluster.Latitude = double.Parse(row.GetCell(1).ToString().Trim()); cluster.Longitude = double.Parse(row.GetCell(2).ToString().Trim()); cluster.Nb = int.Parse(row.GetCell(3).ToString().Trim()); int radius = 500; String result = await GoogleAPI.NearbySearchPlaces(cluster.Latitude.ToString(), cluster.Longitude.ToString(), radius); if (result != null) { List <GPlace> places = new List <GPlace>(); result = result.Trim(); String[] items = result.Split('\n'); foreach (String item in items) { String[] items2 = item.Split('$'); if (items2.Length >= 5) { GPlace place = new GPlace(); place.ID = items2[0].Trim(); place.Name = items2[1].Trim(); place.Address = items2[2].Trim(); place.Latitude = double.Parse(items2[3].Trim()); place.Longitude = double.Parse(items2[4].Trim()); GeoCoordinate sCoord = new GeoCoordinate(cluster.Latitude, cluster.Longitude); GeoCoordinate eCoord = new GeoCoordinate(place.Latitude, place.Longitude); place.Distance = sCoord.GetDistanceTo(eCoord); places.Add(place); } } List <GPlace> sortedPlaces = places.OrderBy(o => o.Distance).ToList(); // sort by Distance cluster.Places = sortedPlaces; } clusters.Add(cluster); } } } } file.Close(); return(clusters); }
static async Task <List <Student> > ReadExcel() { List <Student> students = new List <Student>(); String filePath = "../../data/data.xls"; String sheetName = "TH KIM DONG"; String fileExt = System.IO.Path.GetExtension(filePath); FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read); IWorkbook workbook = null; if (fileExt == ".xls") { workbook = new HSSFWorkbook(file); } else if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(file); } if (workbook != null) { ISheet sheet = workbook.GetSheet(sheetName); if (sheet != null) { for (int i = 2; i <= sheet.LastRowNum; i++) // skip header { IRow row = sheet.GetRow(i); if (row != null) //null is when the row only contains empty cells { Student student = new Student(); student.ID = int.Parse(row.GetCell(0).ToString().Trim()); student.Address = row.GetCell(4).ToString().Trim(); if (student.Address != "") { // parse Address String[] items = student.Address.Split(','); foreach (String item in items) { if (item.Trim().Contains("Q. ")) { student.Quan = item.Trim().Substring(item.Trim().IndexOf("Q. ")); } if (item.Trim().Contains("P. ")) { student.Phuong = item.Trim().Substring(item.Trim().IndexOf("P. ")); } if (item.Trim().Contains("KP. ")) { student.KhuPho = item.Trim().Substring(item.Trim().IndexOf("KP. ")); } if (item.Trim().Contains("Tổ ")) { student.To = item.Trim().Substring(item.Trim().IndexOf("Tổ ")); } } // geocode Address String geocode = await GoogleAPI.Geocode(student.Address); if (geocode != null) { items = geocode.Split('\n'); student.Latitude = double.Parse(items[0]); student.Longitude = double.Parse(items[1]); student.GoogleAddress = items[2]; } } students.Add(student); } } } } file.Close(); return(students); }