コード例 #1
0
ファイル: APICall.cs プロジェクト: pneborg/vautointerview
        /// <summary>
        /// Post an Answer to the API to check the results and get a timing in milliseconds
        /// </summary>
        public async static Task <T> PostAnswer(string apiPath, AnswerPost answer)
        {
            try
            {
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri(baseAddress);

                    HttpContent content = new StringContent(answer.ToJson(),
                                                            Encoding.UTF8,
                                                            "application/json");

                    HttpResponseMessage response = await client.PostAsync(apiPath, content);

                    if (response.IsSuccessStatusCode)
                    {
                        var responseString = await response.Content.ReadAsStringAsync();

                        T answerResponse = JsonConvert.DeserializeObject <T>(responseString);
                        return(answerResponse);
                    }
                    else
                    {
                        throw new Exception($"Return Code {response.StatusCode}: Error occured during api call execution {apiPath}");
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception($"Error occured during api call execution {apiPath}", ex);
            }
        }
コード例 #2
0
        private void DoAllAndPostAnswer()
        {
            var timeMeasure = TimeMeasure.BeginTiming("DoAllAndPostAnswer");

            var tokenResponse = GetTokenResponse();

            JsonDisplay.ConsoleDisplayJsonResponse("Token", tokenResponse);
            var categoriesResponse = GetCategoriesResponse(tokenResponse.Token);

            JsonDisplay.ConsoleDisplayJsonResponse("Categories", categoriesResponse);
            var subscribersResponse = GetSubscribers(tokenResponse.Token);

            JsonDisplay.ConsoleDisplayJsonResponse("Subscribers", subscribersResponse);
            var magazineListResponse = GetAllMagazinesResponses(categoriesResponse);

            JsonDisplay.ConsoleDisplayJsonResponse("List of all Magazines", magazineListResponse);

            // fill in the magazines detais for each subscriber
            foreach (var subscriber in subscribersResponse.Data)
            {
                foreach (var magazinesResponse in magazineListResponse)
                {
                    subscriber.Magazines.AddRange(
                        subscriber.MagazineIds
                        .SelectMany(magazineId => magazinesResponse.Data, (magazineId, magazine) => new { magazineId, magazine })
                        .Where(anonim => anonim.magazine.Id == anonim.magazineId)
                        .Select(anon => new Magazine
                    {
                        Id       = anon.magazineId,
                        Category = anon.magazine.Category,
                        Name     = anon.magazine.Name
                    })
                        );
                }
            }
            JsonDisplay.ConsoleDisplayJsonData("Subscribers with filled Magazines", subscribersResponse);

            // prepare the post payload with all subscribers who have at least one subscription in each category
            var answerPost = new AnswerPost
            {
                Subscribers = subscribersResponse.Data
                              .Where(subscriber => subscriber.Magazines
                                     .Select(c => new { c.Category })
                                     .GroupBy(x => x.Category)
                                     .Select(x => x.First()).Count() == categoriesResponse.Data.Count
                                     )
                              .Select(subscriber => subscriber.Id).ToList()
            };

            JsonDisplay.ConsoleDisplayJsonData("answerPost", answerPost);

            var answerResponse = _dataService.PostAnswerAsync(tokenResponse.Token, answerPost).GetAwaiter().GetResult();

            JsonDisplay.ConsoleDisplayJsonResponse("Answer Response after post", answerResponse);

            // display the overal time
            timeMeasure.EndTimingAndConsoleDisplay();
        }
コード例 #3
0
        public static AnswerPost GetDealerVehicles()
        {
            // that could be performed concurrently on the ConcurrentDictionary.  However, global
            // operations like resizing the dictionary take longer as the concurrencyLevel rises.
            // For the purposes of this example, we'll compromise at numCores * 2.
            int concurrencyLevel = Environment.ProcessorCount * 2;
            //Get Dataset id that will be used in subsequent API calls
            var dataSet = GetDataSet().Result;

            if (dataSet != null)
            {
                VerboseWriteMessage($"DataSet Id {dataSet.Id} {DateTime.Now.ToLongTimeString()}");

                var Vehicles = GetVehicles(dataSet.Id, concurrencyLevel);

                if (Vehicles != null && Vehicles.Values != null)
                {
                    var Dealers = GetDealers(
                        dataSet.Id,
                        Vehicles.Values.Select(item => item.DealerId).Distinct().ToList(),             //unique list of Dealer Ids
                        concurrencyLevel);
                    if (Dealers != null)
                    {
                        //Collect the list of vehicles per dealer
                        foreach (var dealer in Dealers.Values)
                        {
                            dealer.Vehicles = new List <Vehicle>();
                            dealer.Vehicles.AddRange(Vehicles.Values.Where(item => item.DealerId == dealer.Id).ToList());
                        }

                        //Create a serializable answer that contains all Dealers
                        //where each Dealer has a nested list of vehicles for that dealer
                        AnswerPost answerPost = new AnswerPost();
                        answerPost.DataSetId = dataSet.Id;
                        answerPost.Dealers   = new List <Dealer>();
                        answerPost.Dealers.AddRange(Dealers.Values);

                        return(answerPost);
                    }
                    else
                    {
                        throw new Exception($"Unable to retreive a list of dealers for dataset {dataSet.Id}");
                    }
                }
                else
                {
                    throw new Exception($"Unable to retreive a list of vehicles for dataset {dataSet.Id}");
                }
            }
            else
            {
                throw new Exception("Unable to retreive initial DataSet from the api");
            }
        }
コード例 #4
0
 public static async Task <AnswerResponse> PostAnswer(AnswerPost answerPost)
 {
     if (answerPost != null)
     {
         var apiPath = $"api/{answerPost.DataSetId}/answer";
         return(await APICall <AnswerResponse> .PostAnswer(apiPath, answerPost));
     }
     else
     {
         throw new Exception($"PostAnswer requires an AnswerPost object");
     }
 }
コード例 #5
0
ファイル: PostHelper.cs プロジェクト: vaginessa/TumblrTools
        /// <summary>
        ///
        /// </summary>
        /// <param name="post"></param>
        /// <param name="jPost"></param>
        public static void GenerateAnswerPost(ref TumblrPost post, dynamic jPost)
        {
            if (post == null)
            {
                throw new ArgumentNullException(nameof(post));
            }
            if (jPost == null)
            {
                throw new ArgumentNullException(nameof(jPost));
            }

            post = new AnswerPost
            {
                Asker    = !string.IsNullOrEmpty((string)jPost.asking_name) ? jPost.asking_name : null,
                AskerUrl = !string.IsNullOrEmpty((string)jPost.asking_url) ? jPost.asking_url : null,
                Question = !string.IsNullOrEmpty((string)jPost.question) ? jPost.question : null,
                Answer   = !string.IsNullOrEmpty((string)jPost.answer) ? jPost.answer : null
            };

            IncludeCommonPostFields(ref post, jPost);
        }
コード例 #6
0
ファイル: AnswerPost.cs プロジェクト: mlaily/TumblrLeecher
        private AnswerPost ParseAnswerPost(JObject jObject, HashSet <string> checkedProperties)
        {
            AnswerPost newPost = new AnswerPost();
            JToken     current;

            if (CheckProperty(jObject, "asking_name", checkedProperties, out current))
            {
                newPost.AskingName = (string)current;
            }
            if (CheckProperty(jObject, "asking_url", checkedProperties, out current))
            {
                newPost.AskingUrl = (string)current;
            }
            if (CheckProperty(jObject, "question", checkedProperties, out current))
            {
                newPost.Question = (string)current;
            }
            if (CheckProperty(jObject, "answer", checkedProperties, out current))
            {
                newPost.Answer = (string)current;
            }
            return(newPost);
        }
コード例 #7
0
        void DoAllAndPostAnswer()
        {
            var datasetId    = GetDataset();
            var vehiclesList = GetVehicles(datasetId);
            var dealersList  = GetDealers(datasetId, vehiclesList);

            var answerPost = new AnswerPost();

            dealersList.ForEach(dealer =>
            {
                var dealerPost = new DealerPost
                {
                    DealerId = dealer.DealerId,
                    Name     = dealer.Name
                };
                var vehiclePostList = vehiclesList
                                      .Where(v => v.DealerId == dealer.DealerId)
                                      .Select(v => new VehiclePost
                {
                    VehicleId = v.VehicleId,
                    make      = v.Make,
                    Model     = v.Model,
                    Year      = v.Year
                }).ToList();
                dealerPost.Vehicles = vehiclePostList;
                answerPost.Dealers.Add(dealerPost);
            });

            //string answerPostJson = JsonConvert.SerializeObject(answerPost, Formatting.Indented);
            //Console.WriteLine($"{answerPostJson}");

            var    answerResponse     = _dataService.PostAnswerAsync(datasetId, answerPost).GetAwaiter().GetResult();
            string answerResponseJson = JsonConvert.SerializeObject(answerResponse, Formatting.Indented);

            Console.WriteLine($"{answerResponseJson}");
        }
コード例 #8
0
        public async Task <AnswerResponse> PostAnswerAsync(string token, AnswerPost answerPost)
        {
            var path = $"answer/{token}";

            return(await GenericPostAsync <AnswerPost, AnswerResponse>(path, answerPost));
        }
コード例 #9
0
        public async Task <AnswerResponse> PostAnswerAsync(string datasetId, AnswerPost answerPost)
        {
            string path = $"api/{datasetId}/answer";

            return(await GenericPostAsync <AnswerPost, AnswerResponse>(path, answerPost));
        }