public ActionResult <PlaceResponse> GetPlace(int zipcode)
        {
            PlaceResponse result = null;

            var place = _context.Places
                        .Where(place => place.Zipcode == zipcode)
                        .FirstOrDefault();

            // if entered zipcode is valid, then calculate the distance from mindgrub
            if (place != null)
            {
                result           = new PlaceResponse();
                result.City      = place.City;
                result.State     = place.State;
                result.Zipcode   = place.Zipcode;
                result.Longitude = place.Longitude;
                result.Latitude  = place.Latitude;

                // get latitude and longitute of mindgrub's location
                var mindGrub = _context.Places
                               .Where(place => place.Zipcode == MINDGRUB_ZIP)
                               .FirstOrDefault();

                result.DistanceFromMindGrub =
                    DistanceHelper.haversine(mindGrub.Latitude, mindGrub.Longitude, place.Latitude, place.Longitude);
            }

            return(result);
        }
 public IObjectConverter <Place, PlaceResponse> GetPlaceConverter(
     PlaceResponse response)
 {
     return(new InstaPlaceConverter {
         SourceObject = response
     });
 }
示例#3
0
        private static void FullAppendage(PlaceResponse rs, int projectId, string type, List <LNKPAppendage> lList)
        {
            if (rs.status == "0" && rs.total > 0)
            {
                foreach (var item in rs.results)
                {
                    LNKPAppendage inkpa = new LNKPAppendage();
                    inkpa.AppendageCode = GetCode(type);
                    inkpa.P_AName       = item.name;
                    inkpa.Distance      = item.detail_info.distance;
                    inkpa.ProjectId     = projectId;
                    inkpa.Address       = item.address;
                    inkpa.x             = item.location.lng;
                    inkpa.y             = item.location.lat;
                    inkpa.Uid           = item.uid;
                    inkpa.CityId        = GetCityIdBylocation(item.location);

                    var list = lList.Where(m => m.Uid == inkpa.Uid);
                    if (list.Count() < 1)
                    {
                        lList.Add(inkpa);
                    }
                }
            }
        }
示例#4
0
        private double FindClosestPlace(PlaceResponse response, IList <Miejsce> places, out Miejsce closestPlace)
        {
            decimal lat = response.Latitude;
            decimal lon = response.Longitude;

            closestPlace = places.OrderBy(p => DistanceInKmBetweenEarthCoordinates(p.SzerokoscGeograficzna, lat, p.DlugoscGeograficzna, lon)).First();
            var distance = DistanceInKmBetweenEarthCoordinates(closestPlace.SzerokoscGeograficzna, lat, closestPlace.DlugoscGeograficzna, lon);

            return(distance);
        }
示例#5
0
        /// <summary>
        /// Process exchange to storage sync.
        /// </summary>
        /// <returns>A task that represents the work queued to execute.</returns>
        public async Task ExchangeToStorageExportAsync()
        {
            // 1. Get list of buildings from Microsoft Graph API.
            // 2. Create batch of 10 buildings. (Useful for parallel execution)
            // 3. For every building in batch do:
            //    - Get records from table storage matching building email id.
            //    - Get rooms from Microsoft Graph API associated with building email id.
            //    - Check which rooms got deleted by comparing rooms from Azure table storage and rooms Microsoft Graph API
            //          - Set IsDeleted flag to true in RoomCollection table for rooms which got deleted.
            //    - Update or insert rooms received from Microsoft Graph API in RoomCollection table.
            this.telemetryClient.TrackTrace("Exchange sync started");

            string token = await this.GetApplicationAccessTokenAsync().ConfigureAwait(false);

            if (token == null)
            {
                this.telemetryClient.TrackTrace("Exchange sync - Application access token is null.");
                return;
            }

            PlaceResponse buildings           = new PlaceResponse();
            var           httpResponseMessage = await this.apiHelper.GetAsync(this.graphAPIAppFindRoomList, token).ConfigureAwait(false);

            var content = await httpResponseMessage.Content.ReadAsStringAsync();

            if (httpResponseMessage.IsSuccessStatusCode)
            {
                buildings = JsonConvert.DeserializeObject <PlaceResponse>(content);
            }
            else
            {
                var errorResponse = JsonConvert.DeserializeObject <ErrorResponse>(content);
                this.telemetryClient.TrackTrace($"Exchange sync - Graph API failure- url: {this.graphAPIAppFindRoomList}, response-code: {errorResponse.Error.StatusCode}, response-content: {errorResponse.Error.ErrorMessage}, request-id: {errorResponse.Error.InnerError.RequestId}", SeverityLevel.Warning);
            }

            this.telemetryClient.TrackTrace($"Exchange sync - Building count: {buildings?.PlaceDetails?.Count}");

            var buildingsPerBatch = 10;

            if (buildings?.PlaceDetails?.Count > 0)
            {
                int count = (int)Math.Ceiling((double)buildings.PlaceDetails.Count / buildingsPerBatch);
                for (int i = 0; i < count; i++)
                {
                    var buildingsBatch = buildings.PlaceDetails.Skip(i * buildingsPerBatch).Take(buildingsPerBatch);
                    await Task.WhenAll(buildingsBatch.Select(building => this.ProcessBuildingAsync(building))).ConfigureAwait(false);
                }
            }
            else
            {
                this.telemetryClient.TrackTrace("Exchange sync- Buildings count is 0");
            }

            await this.searchService.InitializeAsync();
        }
示例#6
0
        public bool CreateCustomRoute(CustomRouteRequest route, out IList <RouteResponse> result)
        {
            var routes = _context.GradedRoutesWithIncludedRelatedData();
            var places = FindPlacesFromRoutes(routes);

            PlaceResponse start = route.Start;
            PlaceResponse end   = route.End;

            double distanceFromStart = FindClosestPlace(start, places, out Miejsce closestToStart);
            double distanceFromEnd   = FindClosestPlace(end, places, out Miejsce closestToEnd);

            if (distanceFromStart <= MAXIMUM_DISTANCE && distanceFromEnd <= MAXIMUM_DISTANCE)
            {
                var mountainGroup     = FindMountainGroup(closestToStart);
                var mountainGroupName = _context.GrupaGorska.First(m => m.Id == mountainGroup).Nazwa;
                routes = routes.Where(r => r.GrupaGorskaId == mountainGroup).ToList();
                places = FindPlacesFromRoutes(routes);

                //create graph from locations in a mountain group
                var graph = new BidirectionalGraph <PlaceVertex, Edge <PlaceVertex> >();
                var edgeCostDictionary = new Dictionary <Edge <PlaceVertex>, int>();
                PopulateGraph(graph, edgeCostDictionary, places, routes);

                //find path between start location and end location using A* Algorithm
                AStarShortestPathAlgorithm <PlaceVertex, Edge <PlaceVertex> > astar = new AStarShortestPathAlgorithm <PlaceVertex, Edge <PlaceVertex> >(graph, x => edgeCostDictionary[x], x => 0);
                var startVertex = new PlaceVertex(closestToStart.Id);
                var endVertex   = new PlaceVertex(closestToEnd.Id);

                if (astar.ComputeDistanceBetween(startVertex, endVertex, out var path))
                {
                    result = new List <RouteResponse>();
                    if (distanceFromStart >= MINIMUM_DISTANCE)
                    {
                        result.Add(RouteResponse.CreateCustomRoute(start, PlaceResponse.BuildFromModel(closestToStart), mountainGroupName, distanceFromStart));
                    }
                    result = result.Concat(CreateResponseListFromPath(path)).ToList();
                    if (distanceFromEnd >= MINIMUM_DISTANCE)
                    {
                        result.Add(RouteResponse.CreateCustomRoute(PlaceResponse.BuildFromModel(closestToEnd), end, mountainGroupName, distanceFromEnd));
                    }
                    return(true);
                }
                else
                {
                    result = new List <RouteResponse>();
                    return(false);
                }
            }
            else
            {
                result = new List <RouteResponse>();
                return(false);
            }
        }
示例#7
0
        public static void Run(
            [QueueTrigger("wug-tweets-que", Connection = "AzureWebJobsStorage")] string myQueueItem,
            [Table("TweetLocation", Connection = "AzureWebJobsStorage")] ICollector <TweetLocationTable> locationTable,
            TraceWriter log,
            ExecutionContext context)
        {
            try
            {
                log.Info($"C# Queue trigger function processed: {myQueueItem}");

                // 環境変数を読み込む
                var config = new ConfigurationBuilder()
                             .SetBasePath(context.FunctionAppDirectory)
                             .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                             .AddEnvironmentVariables()
                             .Build();

                // 環境変数からキーを取得する
                string consumerKey       = config["ConsumerKey"];
                string consumerSecret    = config["ConsumerSecret"];
                string accessToken       = config["AccessToken"];
                string accessTokenSecret = config["AccessTokenSecret"];

                if (string.IsNullOrEmpty(consumerKey) || string.IsNullOrEmpty(consumerSecret) || string.IsNullOrEmpty(accessToken) || string.IsNullOrEmpty(accessTokenSecret))
                {
                    log.Error("can't read configuration about token.");
                    return;
                }

                // アクセストークン
                var tokens = Tokens.Create(consumerKey, consumerSecret, accessToken, accessTokenSecret);
                // log.Info($"twitter token created: {tokens.ToString()}");

                // ツイートを取得
                var task   = tokens.Statuses.ShowAsync(id => myQueueItem);
                var status = task.Result;

                PlaceResponse place = null;
                if (status.Place != null)
                {
                    var task2 = tokens.Geo.IdAsync(status.Place.Id);
                    place = task2.Result;
                }

                var register = new TweetRegister();
                // ツイートを記録する
                register.InsertRecord(locationTable, status, place, log);
            }
            catch (Exception ex)
            {
                log.Error($"{ex.Message}");
                log.Error($"{ex.StackTrace}");
            }
        }
示例#8
0
        /// <summary>
        /// Process each building sync operation.
        /// </summary>
        /// <param name="building">Building object.</param>
        /// <returns>A task that represents the work queued to execute.</returns>
        private async Task ProcessBuildingAsync(PlaceInfo building)
        {
            await retryPolicy.ExecuteAsync(async() =>
            {
                string token = await this.GetApplicationAccessTokenAsync().ConfigureAwait(false);
                if (token == null)
                {
                    this.telemetryClient.TrackTrace("Exchange sync - Application access token is null.");
                    return;
                }

                var roomsFromStorage = await this.roomCollectionStorageProvider.GetAsync(building.EmailAddress).ConfigureAwait(false);

                // Get rooms from graph api (max 100 rooms returned per building).
                var rooms = new PlaceResponse();
                var httpResponseMessage = await this.apiHelper.GetAsync(this.graphAPIAppFindRooms.Replace("{buildingAlias}", building.EmailAddress, StringComparison.OrdinalIgnoreCase), token).ConfigureAwait(false);
                var content             = await httpResponseMessage.Content.ReadAsStringAsync();

                if (httpResponseMessage.IsSuccessStatusCode)
                {
                    rooms = JsonConvert.DeserializeObject <PlaceResponse>(content);
                }
                else
                {
                    var errorResponse = JsonConvert.DeserializeObject <ErrorResponse>(content);
                    this.telemetryClient.TrackTrace($"Graph API failure- url: {this.graphAPIAppFindRooms}, response-code: {errorResponse.Error.StatusCode}, response-content: {errorResponse.Error.ErrorMessage}, request-id: {errorResponse.Error.InnerError.RequestId}", SeverityLevel.Warning);
                }

                this.telemetryClient.TrackTrace($"Exchange sync - Building {building.DisplayName}, rooms count: {rooms?.PlaceDetails?.Count}");

                // Delete existing rooms of building from storage.
                if (roomsFromStorage?.Count > 0)
                {
                    this.telemetryClient.TrackTrace($"Exchange sync - Building {building.DisplayName}, deleting rooms from storage");

                    // Get room email IDs which got removed from Microsoft Exchange.
                    var roomsToRemoveEmails = roomsFromStorage.Select(room => room.RowKey).Except(rooms.PlaceDetails.Select(room => room.EmailAddress));
                    var roomsToRemove       = roomsFromStorage.Where(room => roomsToRemoveEmails.Contains(room.RowKey)).ToList();

                    // Set isDeleted flag to true for entity received from Azure table storage.
                    roomsToRemove.ForEach(room => room.IsDeleted = true);

                    // Update deleted rooms.
                    await this.roomCollectionStorageProvider.UpdateDeletedRoomsAsync(roomsToRemove).ConfigureAwait(false);
                }

                // Add or update rooms received from Microsoft Exchange.
                var allRooms = await this.AddOrReplaceRoomsAsync(building, rooms?.PlaceDetails).ConfigureAwait(false);

                this.telemetryClient.TrackTrace($"Exchange Sync - Building {building.DisplayName}, deleting rooms from user favorites");
            }).ConfigureAwait(false);
        }
        public PlaceResponse UpdatePlace(PutRequest <Place> request)
        {
            var validator = new Response();
            var response  = new PlaceResponse();

            try
            {
                validator = new UpdatePlaceValidator(_placeRepository).Validate(request).ToResponse();
            }
            catch (Exception ex)
            {
                _logger.Error(ExceptionMessages.UpdatePlaceException, ex);
                response.Result = false;
                response.Errors.Add(new ResponseError {
                    Name = "UpdatePlaceException", Error = ExceptionMessages.UpdatePlaceException
                });
                return(response);
            }

            if (!validator.Result)
            {
                return new PlaceResponse {
                           Errors = validator.Errors, Result = false
                }
            }
            ;

            try
            {
                response = _placeRepository.UpdatePlace(request);
            }
            catch (Exception ex)
            {
                _logger.Error(ExceptionMessages.UpdatePlaceException, ex);
                response.Result = false;
                response.Errors.Add(new ResponseError {
                    Name = "UpdateEventException", Error = ExceptionMessages.UpdatePlaceException
                });
                return(response);
            }

            if (response.Result)
            {
                _logger.Information($"The Place with Id: {response.Place.Id} has been successfully updated.");
            }

            return(response);
        }
示例#10
0
        /// <summary>
        /// Process each building sync operation.
        /// </summary>
        /// <param name="building">Building object.</param>
        /// <returns>A task that represents the work queued to execute.</returns>
        private async Task ProcessBuildingAsync(PlaceInfo building)
        {
            await retryPolicy.ExecuteAsync(async() =>
            {
                string token = await this.GetApplicationAccessTokenAsync().ConfigureAwait(false);
                if (token == null)
                {
                    this.telemetryClient.TrackTrace("Exchange sync - Application access token is null.");
                    return;
                }

                var roomsFromStorage = await this.roomCollectionStorageProvider.GetAsync(building.EmailAddress).ConfigureAwait(false);

                // Get rooms from graph api (max 100 rooms returned per building).
                var rooms = new PlaceResponse();
                var httpResponseMessage = await this.apiHelper.GetAsync(this.graphAPIAppFindRooms.Replace("{buildingAlias}", building.EmailAddress, StringComparison.OrdinalIgnoreCase), token).ConfigureAwait(false);
                var content             = await httpResponseMessage.Content.ReadAsStringAsync();

                if (httpResponseMessage.IsSuccessStatusCode)
                {
                    rooms = JsonConvert.DeserializeObject <PlaceResponse>(content);
                }
                else
                {
                    var errorResponse = JsonConvert.DeserializeObject <ErrorResponse>(content);
                    this.telemetryClient.TrackTrace($"Graph API failure- url: {this.graphAPIAppFindRooms}, response-code: {errorResponse.Error.StatusCode}, response-content: {errorResponse.Error.ErrorMessage}, request-id: {errorResponse.Error.InnerError.RequestId}", SeverityLevel.Warning);
                }

                this.telemetryClient.TrackTrace($"Exchange sync - Building {building.DisplayName}, rooms count: {rooms?.PlaceDetails?.Count}");

                // Delete existing rooms of building from storage.
                if (roomsFromStorage?.Count > 0)
                {
                    this.telemetryClient.TrackTrace($"Exchange sync - Building {building.DisplayName}, deleting rooms from storage");
                    await this.roomCollectionStorageProvider.DeleteAsync(roomsFromStorage).ConfigureAwait(false);
                }

                // Add new rooms to storage.
                var allRooms = await this.AddRoomsToStorageAsync(building, rooms?.PlaceDetails).ConfigureAwait(false);

                this.telemetryClient.TrackTrace($"Exchange Sync - Building {building.DisplayName}, deleting rooms from user favorites");

                // Remove deleted rooms from user favourites.
                await this.RemoveFromFavoritesAsync(roomsFromStorage, allRooms, building.EmailAddress).ConfigureAwait(false);
            }).ConfigureAwait(false);
        }
示例#11
0
        public PlaceResponse GetPlace(PlaceIdRequest request)
        {
            var response  = new PlaceResponse();
            var validator = new Response();

            try
            {
                validator = new PlaceIdRequestValidator(_placeRepository).Validate(request).ToResponse();
            }
            catch (Exception ex)
            {
                _logger.Error(ExceptionMessages.GetPlaceException, ex);
                response.Result = false;
                response.Errors.Add(new ResponseError {
                    Name = "GetPlaceException", Error = ExceptionMessages.GetPlaceException
                });
                return(response);
            }

            if (!validator.Result)
            {
                return new PlaceResponse()
                       {
                           Errors = validator.Errors
                       }
            }
            ;

            try
            {
                response = _placeRepository.GetPlace(request);
            }
            catch (Exception ex)
            {
                _logger.Error(ExceptionMessages.GetPlaceException, ex);
                response.Result = false;
                response.Errors.Add(new ResponseError {
                    Name = "GetPlaceException", Error = ExceptionMessages.GetPlaceException
                });
                return(response);
            }

            return(response);
        }
示例#12
0
        /// <summary>
        /// 获取所有兴趣点
        /// </summary>
        /// <param name="location"></param>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public static List <LNKPAppendage> GetAllAppendage(string location, int projectId)
        {
            loadData();

            list = SYSCityApi.GetAllCity();

            //rq.location = "22.55932,114.04508";
            List <LNKPAppendage> lnkpaList = new List <LNKPAppendage>();

            try
            {
                rq.location = location;
                string[] queryArray = rq.query.Split('$');
                for (int t = 0; t < queryArray.Length; t++)
                {
                    rq.page_num = 0;
                    rq.query    = queryArray[t];

                    //分页获取
                    PlaceResponse rs = BaiduAPI.PlaceAPIManger.SearchPOI(rq);
                    BaiduApiManager.FullAppendage(rs, projectId, rq.query, lnkpaList);
                    if (rs.total > 20)
                    {
                        int pageTotal = rs.total / 20;
                        for (int i = 1; i < pageTotal + 1; i++)
                        {
                            rq.page_num = i;
                            PlaceResponse rs2 = BaiduAPI.PlaceAPIManger.SearchPOI(rq);
                            BaiduApiManager.FullAppendage(rs2, projectId, rq.query, lnkpaList);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
                lnkpaList = new List <LNKPAppendage>();
            }

            return(lnkpaList);
        }
示例#13
0
        public PlaceResponse CreatePlace(PostRequest <Place> request)
        {
            var response = new PlaceResponse();

            if (request.Payload != null)
            {
                var validator = new PlacesValidator().Validate(request.Payload).ToResponse();

                if (!validator.Result)
                {
                    return new PlaceResponse {
                               Errors = validator.Errors, Result = false
                    }
                }
                ;

                try
                {
                    return(_placeRepository.CreatePlace(request));
                }
                catch (Exception ex)
                {
                    _logger.Error(ExceptionMessages.CreatePlaceException, ex);
                    response.Result = false;
                    response.Errors.Add(new ResponseError {
                        Name = "CreatePlaceException", Error = ExceptionMessages.CreatePlaceException
                    });
                    return(response);
                }
            }

            _logger.Information(ExceptionMessages.NullObject);
            response.Result = false;
            response.Errors.Add(new ResponseError()
            {
                Name = "NullObject", Error = ExceptionMessages.NullObject
            });
            return(response);
        }
示例#14
0
        // TODO: delete once we have actual data in place
        private static PlaceResponse GenerateFakeResponse()
        {
            var resp = new PlaceResponse
            {
                Id          = 12345,
                Name        = "Name",
                Description = "This is a description",
                Locations   = new List <PlaceLocationsResponse>
                {
                    new PlaceLocationsResponse
                    {
                        Id        = 123456,
                        Latitude  = 123.12,
                        Longitude = 123.12,
                        Features  = new PlaceLocationFeaturesResponse
                        {
                            Ramps      = {},
                            Lighting   = {},
                            Parking    = {},
                            NoiseLevel = {}
                        },
                        Reviews = new List <PlaceLocationReviewsResponse>
                        {
                            new PlaceLocationReviewsResponse
                            {
                                Id     = 1234567,
                                Text   = "Some text",
                                Rating = 5
                            }
                        }
                    }
                }
            };

            return(resp);
        }
示例#15
0
        public PlaceResponse UpdatePlace(PutRequest <Place> request)
        {
            using (var db = new EventSourceDbContext(_contextOptions))
            {
                var response = new PlaceResponse();
                var _place   = db.Places.Find(request.Id);

                if (_place != null)
                {
                    _place.Description = !string.IsNullOrEmpty(request.Payload.Description) ? request.Payload.Description : _place.Description;
                    _place.City        = !string.IsNullOrEmpty(request.Payload.City) ? request.Payload.City.ToLower() : _place.City;
                    _place.Capacity    = request.Payload.Capacity > 0 ? request.Payload.Capacity : _place.Capacity;
                    _place.Name        = !string.IsNullOrEmpty(request.Payload.Name) ? request.Payload.Name.ToLower() : _place.Name;
                    _place.Location    = !string.IsNullOrEmpty(request.Payload.Location) ? request.Payload.Location.ToLower() : _place.Location;

                    db.Places.Attach(_place);
                    db.SaveChanges();
                    response.Place = _place;
                    return(response);
                }
                response.Result = false;
                return(response);
            }
        }
示例#16
0
        /// <summary>
        /// Inserts the record.
        /// </summary>
        public void InsertRecord(ICollector <TweetLocationTable> locationTable,
                                 Status status,
                                 PlaceResponse placeResponse,
                                 TraceWriter log)
        {
            string location  = "";
            double latitude  = 0.0;
            double longitude = 0.0;
            string placeID   = "";

            try
            {
                if (status.Coordinates != null)
                {
                    latitude  = status.Coordinates.Latitude;
                    longitude = status.Coordinates.Longitude;
                }

                if (placeResponse != null)
                {
                    location = placeResponse.FullName;
                    placeID  = placeResponse.Id;
                    if (placeResponse.Centroid != null && placeResponse.Centroid.Length >= 2)
                    {
                        latitude  = placeResponse.Centroid[1];
                        longitude = placeResponse.Centroid[0];
                    }

                    if (placeResponse.Geometry != null)
                    {
                        latitude  = placeResponse.Geometry.Latitude;
                        longitude = placeResponse.Geometry.Longitude;
                    }
                }

                var place = status.Place;
                if (place != null)
                {
                    location = place.FullName;
                    placeID  = place.Id;

                    if (place.Centroid != null && place.Centroid.Length >= 2)
                    {
                        latitude  = place.Centroid[1];
                        longitude = place.Centroid[0];
                    }
                    if (place.Geometry != null)
                    {
                        latitude  = place.Geometry.Latitude;
                        longitude = place.Geometry.Longitude;
                    }
                }

                /*
                 * // RowKeyの重複回避のためランダムな文字列を生成する
                 * Random random = new Random();
                 * string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
                 * string randomStr = new string(Enumerable.Repeat(chars, 32)
                 *  .Select(s => s[random.Next(s.Length)]).ToArray());
                 */

                // Textの中からUrlを取得する。
                Regex  regex = new Regex("(.*)(?<url>https://t.co/[a-zA-Z0-9]{10}?)(.*)");
                Match  match = regex.Match(status.Text);
                string url   = "";

                if (match.Success)
                {
                    url = match.Groups["url"].Value;
                }


                log.Info($"Regist: {status.Id}");
                // SampleTableへEntity(レコード)登録
                locationTable.Add(new TweetLocationTable()
                {
                    PartitionKey = "k1",
                    RowKey       = status.Id.ToString(),
                    TweetID      = status.Id,
                    TweetTime    = status.CreatedAt.UtcDateTime,
                    UserID       = status.User.Id,
                    ScreenName   = status.User.ScreenName,
                    Text         = status.Text,
                    Url          = url,
                    Location     = location,
                    PlaceID      = placeID,
                    Latitude     = latitude,
                    Longitude    = longitude
                });
            }
            catch (Exception ex)
            {
                log.Error($"Exception: {ex.Message},{ex.StackTrace}");

                if (ex.InnerException != null)
                {
                    log.Error($"InnerException:  {ex.InnerException.Message}, {ex.InnerException.StackTrace}");
                }
            }
        }
示例#17
0
        public static IActionResult Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
                                        [Table("TweetLocation", Connection = "AzureWebJobsStorage")] ICollector <TweetLocationTable> locationTable,
                                        TraceWriter log,
                                        ExecutionContext context)
        {
            log.Info("C# HTTP trigger function processed a request.");
            int allCount = 0;

            try
            {
                // 環境変数を読み込む
                var config = new ConfigurationBuilder()
                             .SetBasePath(context.FunctionAppDirectory)
                             .AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
                             .AddEnvironmentVariables()
                             .Build();

                // 環境変数からキーを取得する
                string consumerKey       = config["ConsumerKey"];
                string consumerSecret    = config["ConsumerSecret"];
                string accessToken       = config["AccessToken"];
                string accessTokenSecret = config["AccessTokenSecret"];

                if (string.IsNullOrEmpty(consumerKey) || string.IsNullOrEmpty(consumerSecret) || string.IsNullOrEmpty(accessToken) || string.IsNullOrEmpty(accessTokenSecret))
                {
                    log.Error("can't read configuration about token.");
                    return(new BadRequestObjectResult("can't read configuration about token."));
                }

                string query = req.Query["query"];
                if (string.IsNullOrEmpty(query))
                {
                    log.Error("can't read configuration about token.");
                    return(new BadRequestObjectResult("Please pass a keyword on the query string or in the request body"));
                }

                string countParam = req.Query["count"];
                int    count      = 100;
                if (!string.IsNullOrEmpty(countParam))
                {
                    count = Convert.ToInt32(countParam);
                }

                string since    = req.Query["since"];
                string until    = req.Query["until"];
                long   since_id = 0;
                if (!string.IsNullOrEmpty(req.Query["since_id"]))
                {
                    since_id = Convert.ToInt64(req.Query["since_id"]);
                }
                long max_id = Int64.MaxValue;
                if (!string.IsNullOrEmpty(req.Query["max_id"]))
                {
                    max_id = Convert.ToInt64(req.Query["max_id"]);
                }

                /*
                 * string name = req.Query["name"];
                 *
                 * string requestBody = new StreamReader(req.Body).ReadToEnd();
                 * dynamic data = JsonConvert.DeserializeObject(requestBody);
                 * name = name ?? data?.name;
                 *
                 * return name != null
                 *  ? (ActionResult)new OkObjectResult($"Hello, {name}")
                 *  : new BadRequestObjectResult("Please pass a name on the query string or in the request body");
                 */

                /*
                 *               var task = tokens.Statuses.ShowAsync(id => myQueueItem);
                 *              var status = task.Result;
                 */

                int  availableThread, availableCompletionPortThread;
                long minID = long.MaxValue;
                while (true)
                {
                    log.Info($"{query}, {count}, {since}, {until}, {since_id}, {max_id - 1}");
                    // log.Info($"{query}, {count}, {since_id}, {max_id - 1}");
                    // Search Tweets
                    // アクセストークン
                    var    tokens = Tokens.Create(consumerKey, consumerSecret, accessToken, accessTokenSecret);
                    Search search = tokens.Search;
                    Dictionary <string, object> metaDict = new Dictionary <string, object>()
                    {
                        { "q", query },
                        { "count", count },
                        { "exclude_replies", true },
                        { "since_id", since_id },
                        { "max_id", max_id - 1 }
                    };

                    if (!string.IsNullOrEmpty(since))
                    {
                        metaDict.Add("since", since);
                    }

                    if (!string.IsNullOrEmpty(until))
                    {
                        metaDict.Add("until", until);
                    }

                    var task = search.TweetsAsync(metaDict);

                    SearchResult  searchResult = task.Result;
                    TweetRegister register     = new TweetRegister();
                    foreach (Status tweet in searchResult)
                    {
                        System.Threading.ThreadPool.GetAvailableThreads(out availableThread, out availableCompletionPortThread);
                        log.Info($"Process tweet id: {tweet.Id} availableThread: {availableThread}");

                        PlaceResponse place = null;
                        if (tweet.Place != null)
                        {
                            var task2 = tokens.Geo.IdAsync(tweet.Place.Id);
                            place = task2.Result;
                        }

                        // ツイートを記録する
                        var task3 = Task.Run(() =>
                        {
                            register.InsertRecord(locationTable, tweet, place, log);
                        });

                        minID = System.Math.Min(minID, tweet.Id);
                    }

                    allCount += searchResult.Count;

                    // 取得最大値と取得できたカウントが一致した場合、繰り返す
                    if (searchResult.Count == System.Convert.ToInt32(count))
                    {
                        max_id = minID;
                    }
                    else
                    {
                        break;
                    }
                }
            }catch (Exception ex) {
                log.Error($"Exception: {ex.Message}, {ex.StackTrace}");

                if (ex.InnerException != null)
                {
                    log.Error($"InnerException:  {ex.InnerException.Message}, {ex.InnerException.StackTrace}");
                }
            }

            log.Info($"Process tweets count: {allCount}");
            return((ActionResult) new OkObjectResult($"{DateTime.Now.ToString()}, {allCount}"));
        }