public AutoComplete()
 {
     APIClient     = new APIService();
     GoogleAPI     = new GoogleAPI();
     GoogleService = new GoogleService(GoogleAPI, APIClient);
     Algorithm     = new DistantBasedAlgorithm(GoogleService);
 }
        public async void SetupUI(string date)
        {
            //photoURIs = await GooglePhotoService.GetPhotos();

            try
            {
                foreach (List <string> list in App.User.photoURIs)
                {
                    string photoURI     = list[0];
                    string photoDate    = list[1];
                    string description  = list[2];
                    string creationTime = list[3];

                    if (date.Equals(photoDate))
                    {
                        Items.Add(new { Source = photoURI, Description = description, CreationTime = creationTime });
                    }
                }
            }
            catch (NullReferenceException e)
            {
                var googleService = new GoogleService();
                await googleService.RefreshToken();
            }
        }
        public async Task IPLocation(CommandContext ctx,
                                     [Description("IP Address")] string address)
        {
            if (string.IsNullOrWhiteSpace(address) || !IPAddress.TryParse(address, out IPAddress ip))
            {
                return;
            }
            var results = GoogleService.GetIPLocationAsync(ip).Result;

            if (results.Status != "success")
            {
                await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_LOCATION, EmbedType.Warning).ConfigureAwait(false);
            }
            else
            {
                var output = new DiscordEmbedBuilder()
                             .WithDescription($"Location: { results.City}, { results.Region}, { results.Country}")
                             .AddField("Longitude", results.Longitude.ToString(), true)
                             .AddField("Latitude", results.Latitude.ToString(), true)
                             .AddField("ISP", results.ISP)
                             .WithFooter($"IP: {results.Query}")
                             .WithColor(new DiscordColor("#4d2f63"));
                await ctx.RespondAsync(embed : output.Build()).ConfigureAwait(false);
            }
        }
        private static void SeedInitialDataEmployees(ShelterDbContext context)
        {
            var data = GoogleService.ReadEntries(Constants.SheetEmployees);

            if (data != null)
            {
                if (!context.Employees.Any())
                {
                    var employees = new List <Employee>();
                    var first     = true;

                    foreach (var row in data)
                    {
                        if (first)
                        {
                            first = false;
                            continue;
                        }

                        employees.Add(new Employee
                        {
                            Name        = row[0].ToString(),
                            Surname     = row[1].ToString(),
                            PhoneNumber = row[2].ToString(),
                            BirthDate   = DateTime.ParseExact(row[3].ToString(), "dd/MM/yyyy", CultureInfo.InvariantCulture),
                            Active      = row[4].Equals("1"),
                            Position    = Enum.Parse <Position>(row[5].ToString())
                        });
                    }

                    context.Employees.AddRange(employees);
                    context.SaveChanges();
                }
            }
        }
Beispiel #5
0
        public static async Task <IActionResult> Test1(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            string doc   = req.Query["doc"];
            string range = req.Query["range"];

            using var service = new GoogleService(doc);

            IList <IList <object> > list = new List <IList <object> >();

            list.Add(new List <object> {
                "A1", null, "C1"
            });
            list.Add(new List <object> {
                "A2", "B2", "C2"
            });

            try
            {
                var result = await service.WriteRange(range, list).ConfigureAwait(false);

                return(new OkObjectResult(result));
            }
            catch (Exception ex)
            {
                log.LogInformation(ex.ToString());
                return(new BadRequestObjectResult(ex.ToString()));
            }
        }
Beispiel #6
0
        public object GetAccounts(string userId)
        {
            AnalyticsConfig cfg = AnalyticsConfig.Current;

            AnalyticsConfigUser user = cfg.GetUserById(userId);

            if (user == null)
            {
                return(Request.CreateResponse(JsonMetaResponse.GetError(HttpStatusCode.NotFound, "User not found.")));
            }

            GoogleService google = GoogleService.CreateFromRefreshToken(
                user.Client.ClientId,
                user.Client.ClientSecret,
                user.RefreshToken
                );

            var response1 = google.Analytics.Management.GetAccounts(new AnalyticsGetAccountsOptions(1000));
            var response2 = google.Analytics.Management.GetWebProperties(new AnalyticsGetWebPropertiesOptions(1000));
            var response3 = google.Analytics.Management.GetProfiles(new AnalyticsGetProfilesOptions(1000));

            var accounts      = response1.Body.Items;
            var webProperties = response2.Body.Items;
            var profiles      = response3.Body.Items;

            var body = new Models.Api.Selector.UserModel(user, accounts, webProperties, profiles);

            return(body);
        }
Beispiel #7
0
        public StartPage(string _aToken)
        {
            InitializeComponent();

            if (_aToken == null)
            {
                token = App.Token;
            }
            else if (_aToken != null)
            {
                token = _aToken;
            }
            else
            {
                return;
            }
            google = GoogleService.DefaultGoogleInstance;
            FacebookButton.Clicked += ButtonClick;
            //Showing custom font in image button
            FacebookButton.Font = Font.OfSize("Open 24 Display St", 20);
            if (!VirtualizationManager.IsInitialized)
            {
                VirtualizationManager.Instance.UIThreadExcecuteAction = (a) => Xamarin.Forms.Device.BeginInvokeOnMainThread(a);
                Xamarin.Forms.Device.StartTimer(
                    TimeSpan.FromSeconds(1),
                    () => {
                    VirtualizationManager.Instance.ProcessActions(); return(true);
                });
            }

            this.BindingContext = new ButtonPageViewModel();
        }
Beispiel #8
0
 /// <summary>
 /// Creates GoogleService from the current saved account, using the config values stored as prevalues of the property editor
 /// </summary>
 /// <returns>GoogleService instance</returns>
 private static void EnsureGoogleService()
 {
     if (_googleService == null)
     {
         _googleService = GoogleService.CreateFromRefreshToken(Config.ClientIdFromPropertyEditor, Config.ClientSecretFromPropertyEditor, Config.RefreshTokenFromPropertyEditor);
     }
 }
Beispiel #9
0
        public static async Task <double> Average(this List <ViewStatistic> viewStatistic)
        {
            if (Token == null || Credentials == null)
            {
                throw new Exception("Token or credentials not found!");
            }

            double average = 0;

            if (viewStatistic != null && viewStatistic.Count > 0)
            {
                var googleService = new GoogleService(Credentials);
                googleService.SetToken(Token);

                var channel = await googleService.GetChannels();

                if (channel != null && channel.Items.Count > 0)
                {
                    var startDate = DateTime.ParseExact(viewStatistic.FirstOrDefault().Date, "yyyy-MM-dd", CultureInfo.InvariantCulture);
                    var endDate   = DateTime.ParseExact(viewStatistic.LastOrDefault().Date, "yyyy-MM-dd", CultureInfo.InvariantCulture);

                    var channelVideos = await googleService.GetChannelVideos(channel.Items.FirstOrDefault().Id, startDate, endDate);

                    if (channelVideos != null && channelVideos.PageInfo != null)
                    {
                        var totalVideos = channelVideos.PageInfo.TotalResults;
                        var totalViews  = viewStatistic.Sum(t => t.Value);

                        average = totalViews / totalVideos;
                    }
                }
            }

            return(average);
        }
        public override void RowSelected(UITableView tableView, Foundation.NSIndexPath indexPath)
        {
            tableView.Hidden = true;
            bgView.Hidden    = true;

            if (LocationRowSelectedEventAction != null)
            {
                LocationRowSelectedEventAction(lstLocations[indexPath.Row]);
                var locationData = lstLocations[indexPath.Row];

                rootVC.ShowLoadingView("Getting location details ...");

                Task runSync = Task.Factory.StartNew(async(object inputObj) =>
                {
                    var placeId = inputObj != null ? inputObj.ToString() : "";

                    if (!String.IsNullOrEmpty(placeId))
                    {
                        var data = await GoogleService.GetPlaceDetails(placeId);

                        rootVC.HideLoadingView();

                        rootVC.ItemModel.Location_Lat = data.result.geometry.location.lat;
                        rootVC.ItemModel.Location_Lnt = data.result.geometry.location.lng;
                        mCallback(data.result.geometry.location.lat, data.result.geometry.location.lng);
                    }
                }, locationData.place_id).Unwrap();
            }
            tableView.DeselectRow(indexPath, true);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            ILocalizedTextService textService = ApplicationContext.Services.TextService;

            // Get the state from the query string
            string state = Request.QueryString["state"];

            // Check whether the state is present
            if (string.IsNullOrWhiteSpace(state))
            {
                //Ouput an error message
                _content.Text += textService.Localize("pieman", new [] { "noAccess" });
                return;
            }

            // Get the session value

            // Has the session expire?
            if (!(Session["PieMan_" + state] is string session))
            {
                //Ouput an error message
                _content.Text += textService.Localize("pieman", new [] { "sorrySessionExpired" });
                return;
            }

            // Get the refresh token from the query string (kinda bad practice though)
            string refreshToken = Request.QueryString["token"];

            // Do we have a refresh token?
            if (string.IsNullOrWhiteSpace(refreshToken))
            {
                //Ouput an error message
                _content.Text += textService.Localize("pieman", new [] { "somethingWentWrong" });
                return;
            }

            // Initalize a new instance of the GoogleService class
            GoogleService service = GoogleService.CreateFromRefreshToken(Config.ClientIdFromPropertyEditor, Config.ClientSecretFromPropertyEditor, refreshToken);

            try
            {
                //Get the authenticated user
                GoogleUserInfo user = service.GetUserInfo().Body;

                //Set the refresh token in our config
                Config.RefreshTokenFromPropertyEditor = refreshToken;

                //Ouput some info about the user
                _content.Text  = "Hi there " + user.Name + ". We have saved your information to a config file, so Umbraco can pull stats from your Google Analytics account.";
                _content.Text += "<br /><br />Close this window and go grab a piping hot serve of stats - you'll need to reopen the settings panel and select an account and profile.";
            }
            catch
            {
                //Ouput an error message
                _content.Text += textService.Localize("pieman", new [] { "somethingWentWrong" });
            }

            // Clear the session state
            Session.Remove("PieMan_" + state);
        }
Beispiel #12
0
        //public ActionResult Stop()
        //{
        //    string username = Convert.ToString(Session["username"]);
        //    UserProfile user = _gService.GetUserVMDetail(username);
        //    _azService.Deallocate(Constant.Constant.resourceGroupName, user.machines[0]);
        //    var retVal = _azService.GetVMStatus(Constant.Constant.resourceGroupName, user.machines[0]);
        //    return Json(retVal, JsonRequestBehavior.AllowGet);
        //}

        public ActionResult Success()
        {
            GoogleService google   = new GoogleService();
            string        code     = Convert.ToString(Request.QueryString["code"]);
            string        token    = google.GetToken(code);
            UserProfile   userinfo = google.userProfile(token);

            Session["username"] = userinfo.email;
            if (string.IsNullOrEmpty(userinfo.email))
            {
                return(Content("Email not found"));
            }
            else
            {
                if (Constant.Constant.IsProduction)
                {
                    if (userinfo.email.Contains("@organizedgains.com"))
                    {
                        return(RedirectToAction("index"));
                    }
                    else
                    {
                        return(Redirect(GoogleContants.ExternalRedirection));
                    }
                }
                else
                {
                    return(RedirectToAction("index"));
                }
            }
        }
        public async Task Weather(CommandContext ctx,
                                  [Description("Location to retrieve weather data from")][RemainingText] string query)
        {
            if (!BotServices.CheckUserInput(query))
            {
                return;
            }
            var results = await GoogleService.GetWeatherDataAsync(query).ConfigureAwait(false);

            if (results.COD == 404)
            {
                await BotServices.SendEmbedAsync(ctx, Resources.NOT_FOUND_LOCATION, EmbedType.Missing).ConfigureAwait(false);
            }
            else
            {
                Func <double, double> format = GoogleService.CelsiusToFahrenheit;
                var output = new DiscordEmbedBuilder()
                             .WithTitle(":partly_sunny: Current weather in " + results.Name + ", " + results.Sys.Country)
                             .AddField("Temperature", $"{results.Main.Temperature:F1}°C / {format(results.Main.Temperature):F1}°F", true)
                             .AddField("Humidity", $"{results.Main.Humidity}%", true)
                             .AddField("Wind Speed", $"{results.Wind.Speed}m/s", true)
                             .WithUrl("https://openweathermap.org/city/" + results.ID)
                             .WithColor(SharedData.DefaultColor);
                await ctx.RespondAsync(embed : output.Build()).ConfigureAwait(false);
            }
        }
Beispiel #14
0
        public string Google2016(EngineInput engineInput)
        {
            _googleScrapper = new GoogleService(engineInput);
            _scrapFacade    = new ScrapFacade(_googleScrapper);

            return(_scrapFacade.GetResult());
        }
Beispiel #15
0
        private static void SeedInitialDataCustomers(ShelterDbContext context)
        {
            var data = GoogleService.ReadEntries(Constants.SheetCustomers);

            if (data != null)
            {
                if (!context.Customers.Any())
                {
                    var customers = new List <Customer>();
                    var first     = true;

                    foreach (var row in data)
                    {
                        if (first)
                        {
                            first = false;
                            continue;
                        }

                        customers.Add(new Customer
                        {
                            Name        = row[0].ToString(),
                            Surname     = row[1].ToString(),
                            PhoneNumber = row[2].ToString(),
                            BirthDate   = DateTime.ParseExact(row[3].ToString(), "dd/MM/yyyy", CultureInfo.InvariantCulture),
                        });
                    }

                    context.Customers.AddRange(customers);
                    context.SaveChanges();
                }
            }
        }
Beispiel #16
0
        public async Task google([Remainder] string keywords)
        {
            Search searchResults = GoogleService.Search(keywords).Result;
            var    eb            = new EmbedBuilder();

            if (searchResults.Items.Count < 1)
            {
                eb.WithTitle("Google Search");
                eb.WithColor(Color.Red);
                eb.WithDescription("No results were found.");
            }
            else
            {
                eb.WithTitle("Google Search");
                eb.WithColor(Color.Green);
                string description = "";
                foreach (Result result in searchResults.Items)
                {
                    string formattedResult = ConvertSearchToMessage(result);
                    if ((description + formattedResult).Length <= 2048)
                    {
                        description += formattedResult;
                    }
                }
                eb.WithDescription(description);
            }
            await Context.Channel.SendMessageAsync(embed : eb.Build());
        }
 public EventController(YelpService yelp, ApplicationDbContext db, GoogleService google, UserManager <IdentityUser> userManager)
 {
     _yelp        = yelp;
     _db          = db;
     _google      = google;
     _userManager = userManager;
 }
        public static async Task <IActionResult> Initialize(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "Initialize/{docId}")] HttpRequest req, string docId, ILogger log)
        {
            using var service = new GoogleService(docId);
            string body = await new StreamReader(req.Body).ReadToEndAsync().ConfigureAwait(false);

            // First, validate that we can access the document.
            try
            {
                var info = await service.GetSheetInfo().ConfigureAwait(false);

                if (!info.IsNewDocument())
                {
                    return(new BadRequestObjectResult(@"409: CONFLICT
To avoid overwriting data, only a brand new Google Sheet document may be initialized.
Please follow these steps:
1. Create a new Google Sheets document
2. Change the title of the document to the name of your election
3. Share the document with [email protected] granting Editor permissions
4. Retry the initialize command using the documentId of your new Google Sheets file
")
                    {
                        StatusCode = 409
                    });
                }

                var election = string.IsNullOrWhiteSpace(body) ? Election.DefaultValue() : JsonConvert.DeserializeObject <Election>(body);

                var result = await service.Initialize(election).ConfigureAwait(false);

                //TODO: What is the most useful return value?
                return(new OkObjectResult(result));
            }
            catch (GoogleApiException ex)
            {
                if (ex.HttpStatusCode == System.Net.HttpStatusCode.NotFound)
                {
                    return(new NotFoundObjectResult($@"404: NOT FOUND from Google API
Could not find a Google Sheets document with documentId: {docId}"));
                }
                if (ex.HttpStatusCode == System.Net.HttpStatusCode.Forbidden)
                {
                    return(new ObjectResult($@"403: NOT AUTHORIZED from Google API
This service has not been authorized to access documentId: {docId}
Please share your Google Sheets document with [email protected] and try again
Note that you must grant Editor access for the service to update your document")
                    {
                        StatusCode = 403
                    });
                }
                return(new BadRequestObjectResult(ex));
            }
            catch (Exception ex)
            {
                log.LogInformation(ex.GetType().AssemblyQualifiedName);
                log.LogInformation(ex.ToString());
                return(new BadRequestObjectResult(ex.ToString()));
            }
        }
        public void SetupTests()
        {
            //TODO: Put default couchdburl in appsettings and transform during CI/CD
            var settingsCollection = new CouchDbStore <ApplicationSettings>(ApplicationSettings.CouchDbUrl);
            var settings           = settingsCollection.FindAsync("9c3131ee7b9fb97491e8551211495381").GetAwaiter().GetResult();

            _googleService = new GoogleService(settings);
        }
 /// <summary>
 /// Returns the <see cref="PlacesHttpService"/> instance of the specified Google <paramref name="service"/>.
 /// </summary>
 /// <param name="service">The Google service.</param>
 /// <returns>An instance of <see cref="PlacesHttpService"/>.</returns>
 /// <remarks>
 /// The <see cref="GoogleService"/> instance keeps an internal registry ensuring that calling this method
 /// multiple times for the same <paramref name="service"/> will result in the same instance of
 /// <see cref="PlacesHttpService"/>.
 ///
 /// Specifically the <see cref="PlacesHttpService"/> instance will be created the first time this method is
 /// called, while any subsequent calls to this method will result in the instance saved registry being
 /// returned.
 /// </remarks>
 public static PlacesHttpService Places(this GoogleService service)
 {
     if (service == null)
     {
         throw new ArgumentNullException(nameof(service));
     }
     return(service.GetApiService(() => new PlacesHttpService(service)));
 }
 public static AnalyticsService Analytics(this GoogleService service)
 {
     if (service == null)
     {
         throw new ArgumentNullException(nameof(service));
     }
     return(service.GetApiService(() => new AnalyticsService(service)));
 }
Beispiel #22
0
        private void CarregarMapa(string endereco)
        {
            GoogleService google = new GoogleService();

            //Buscar latitude e longitude para montar o mapa conforme endereço de cada estabelecimento.
            google.PegarLatitudeLongitude(endereco);
            //Chamar a montagem do mapa
        }
        public void PegaServicoDoGoogle()
        {
            var googleService = new GoogleService();

            var driveService = googleService.GetDriveService();

            Assert.NotNull(driveService);
        }
    public async Task testAsync()
    {
        GoogleService googleS = new GoogleService();
        // use your token here
        var email = await googleS.GetEmailAsync("", "");

        Console.WriteLine(email);
    }
 /// <summary>
 /// Returns the <see cref="GeocodingService"/> instance of the specified Google <paramref name="service"/>.
 /// </summary>
 /// <param name="service">The Google service.</param>
 /// <returns>An instance of <see cref="GeocodingService"/>.</returns>
 /// <remarks>
 /// The <see cref="GoogleService"/> instance keeps an internal registry ensuring that calling this method
 /// multiple times for the same <paramref name="service"/> will result in the same instance of
 /// <see cref="GeocodingService"/>.
 ///
 /// Specifically the <see cref="GeocodingService"/> instance will be created the first time this method is
 /// called, while any subsequent calls to this method will result in the instance saved registry being
 /// returned.
 /// </remarks>
 public static GeocodingService Geocoding(this GoogleService service)
 {
     if (service == null)
     {
         throw new ArgumentNullException(nameof(service));
     }
     return(service.GetApiService(() => new GeocodingService(service)));
 }
        private async void OnGoogleAuthCompleted(object sender, AuthenticatorCompletedEventArgs e)
        {
            this.DismissViewController(true, null);

            var googleService = new GoogleService();
            var email         = await googleService.GetEmailAsync(e.Account.Properties["token_type"], e.Account.Properties["access_token"]);

            GoogleButton.SetTitle(email, UIControlState.Normal);
        }
Beispiel #27
0
        public async void OnAuthenticationCompleted(GoogleOAuthToken token)
        {
            // Retrieve the user's email address
            var googleService = new GoogleService();
            var email         = await googleService.GetEmailAsync(token.TokenType, token.AccessToken);

            ViewModel.ShowHomeViewModelCommand.Execute(null);
            ViewModel.AddUserToTable(email);
        }
Beispiel #28
0
        public async Task BadResponse()
        {
            MockHttp.When(BaseUrl)
            .Respond(System.Net.HttpStatusCode.BadRequest);

            var service = new GoogleService("SOME_KEY", MockHttp.ToHttpClient());

            await Assert.ThrowsAsync <GCException>(() => service.GetCoordinate("Good address"));
        }
        public AuthViewModel()
        {
            Title = "Sign In";
            FirebaseNotAuthorizedErrorMessage = "You are not authorized to access this application. " +
                                                "If you believe this is an error, please contact your administrator. " +
                                                "Once your administrator has fixed this problem, please restart the app.";

            _googleService = new GoogleService();
        }
 public HomeController(ILogger <HomeController> logger, LineService lineService, FBService fBService, GoogleService googleService, LinkedInService linkedService, MSService msService)
 {
     _logger        = logger;
     _lineService   = lineService;
     _fBService     = fBService;
     _googleService = googleService;
     _linkedService = linkedService;
     _msService     = msService;
 }
 internal AnalyticsEndpoint(GoogleService service) {
     Service = service;
 }
 internal AnalyticsEndpoint(GoogleService service) {
     Service = service;
     Management = new AnalyticsManagementEndpoint(this);
     Data = new AnalyticsDataEndpoint(this);
 }
 internal YouTubeEndpoint(GoogleService service) {
     Service = service;
 }