//// GET api/authors //public IEnumerable<Author> Get() //{ // var repo = new AuthorRepository(); // return repo.GetAuthors(); //} // GET api/authors public Task <FullResponse> Get() { var authorRepo = new AuthorRepository(); var titleRepo = new TitleRepository(); var tcs = new TaskCompletionSource <FullResponse>(); var response = new FullResponse(); int outstandingOperations = 2; Task.Factory.FromAsync(authorRepo.BeginGetAuthors(null, null), iar => { response.Authors = authorRepo.EndGetAuthors(iar); int currentCount = Interlocked.Decrement(ref outstandingOperations); if (currentCount == 0) { tcs.SetResult(response); } }); Task.Factory.FromAsync(titleRepo.BeginGetTitles(null, null), iar => { response.Titles = titleRepo.EndGetTitles(iar); int currentCount = Interlocked.Decrement(ref outstandingOperations); if (currentCount == 0) { tcs.SetResult(response); } }); return(tcs.Task); }
public async Task <FullResponse> getIPdetails(ProviderQuality p1) { FullResponse response = new FullResponse(); try { HttpResponseMessage httpResult = await _httpClient.GetAsync(url.AbsoluteUri); Stopwatch stopwatch = new Stopwatch(); p1.requestCount++; if (httpResult.IsSuccessStatusCode) { stopwatch.Reset(); stopwatch.Start(); string data = await httpResult.Content.ReadAsStringAsync(); response = JsonConvert.DeserializeObject <FullResponse>(data); stopwatch.Stop(); p1.avgResponseTime += stopwatch.ElapsedMilliseconds / 2; } else { p1.errorCount++; } } catch (Exception e) { //log exception } return(response); }
/// <summary> /// EWF use only. /// </summary> public EwfResponse( FullResponse fullResponse ) { ContentType = fullResponse.ContentType; FileNameCreator = () => fullResponse.FileName; BodyCreator = fullResponse.TextBody != null ? new EwfResponseBodyCreator( () => fullResponse.TextBody ) : new EwfResponseBodyCreator( () => fullResponse.BinaryBody ); }
//called from core.reset internal void EndSession() { StopAllCoroutines(); //write all active webrequests to cache if (LocalCache.LocalStorageActive) { if (lastDataResponse != 200) { //unclear if cached request will actually reach backend, based on previous response codes //session is ending, so can't wait for response from this request //abort request and write to local cache foreach (var v in activeRequests) { if (v.isDone) { continue; } string content = System.Text.Encoding.UTF8.GetString(v.uploadHandler.data); if (isuploadingfromcache && CacheRequest != null) { isuploadingfromcache = false; CacheResponseAction = null; CacheRequest.Abort(); CacheRequest.Dispose(); CacheRequest = null; } if (lc == null) { break; } if (lc.CanAppend(v.url, content)) { v.Abort(); if (v.uploadHandler.data.Length > 0) { lc.Append(v.url, content); } } } } } activeRequests.Clear(); }
public FullResponse GetNowPlaying() { List <NowPlayingResults> resultSet = new List <NowPlayingResults>(); foreach (string region in regions) { int i = 1; int total_pages = 0; do { NowPlayingResults npr = GetRegionPageResults(region, i); npr.region = region; total_pages = npr.total_pages; resultSet.Add(npr); i++; } while (i <= total_pages); } var movieIDs = (from result in resultSet from movie in result.results select movie.id).Distinct().ToList(); Dictionary <int, MovieDetails> movieDetails = new Dictionary <int, MovieDetails>(); Dictionary <int, MovieCredits> movieCredits = new Dictionary <int, MovieCredits>(); Dictionary <int, MovieReviews[]> movieReviews = new Dictionary <int, MovieReviews[]>(); foreach (int movieID in movieIDs) { movieDetails[movieID] = getDetailsForMovieID(movieID); movieCredits[movieID] = getCreditsForMovieID(movieID); movieReviews[movieID] = getReviewsForMovieID(movieID); } FullResponse fr = new FullResponse { nowPlaying = resultSet, details = movieDetails, credits = movieCredits, reviews = movieReviews }; return(fr); }
// GET api/Full/ public async Task <FullResponse> Get() { var authorRepo = new AuthorRepository(); var titleRepo = new TitleRepository(); var authorTask = authorRepo.GetAuthorsAsync(); var titleTask = titleRepo.GetTitlesAsync(); await Task.WhenAll(authorTask, titleTask); var response = new FullResponse { Authors = authorTask.Result, Titles = titleTask.Result }; return(response); }
private async Task <string> ValidatePostResponse(HttpResponseMessage response) { var fullResponse = new FullResponse { Body = await response.Content.ReadAsStringAsync(), Headers = response.Headers.ToDictionary(key => key.Key, value => value.Value.FirstOrDefault()), StatusCode = response.StatusCode }; fullResponse.LogResponseDetails(); if (!response.IsSuccessStatusCode) { throw new SafeguardDotNetException($"Error returned from sps api.", fullResponse.StatusCode, fullResponse.Body); } return(fullResponse.Body); }
System.Collections.IEnumerator WaitForFullResponse(WWW www, string contents, FullResponse callback, bool allowLocalUpload) { yield return(www); if (callback != null) { var headers = www.responseHeaders; int responsecode = Util.GetResponseCode(headers); if (responsecode == 200) { //check cvr header to make sure not blocked by capture portal if (!headers.ContainsKey("cvr-request-time")) { responsecode = 404; } } callback.Invoke(www.url, contents, responsecode, www.error, www.text, allowLocalUpload); } }
public async Task <IActionResult> OnGetAsync(int?id) { if (id == null) { return(NotFound()); } Visit visit = await _context.Visits.FirstOrDefaultAsync(m => m.Id == id); if (visit == null) { return(NotFound()); } var uaParser = Parser.GetDefault(); ClientInfo client = uaParser.Parse(visit.UserAgent); FullResponse response = null; try { var api = new IpInfoApi(configuration.GetValue <string>("IpinfoToken"), clientFactory.CreateClient()); response = await api.GetInformationByIpAsync(visit.IP); } catch (Exception) { } Visit = new() { Id = visit.Id, Share = visit.Share, User = visit.User, Date = visit.Date, IP = visit.IP, UserAgent = visit.UserAgent, ClientInfo = client, IpInfo = response, Access = visit.Access }; return(Page()); }
//either started manually from LocalCache.UploadAllLocalData or from successful 200 response from current session data void LoopUploadFromLocalCache() { if (isuploadingfromcache) { return; } if (lc.CanReadFromCache()) { isuploadingfromcache = true; string url = ""; string content = ""; lc.GetCachedDataPoint(out url, out content); //wait for post response var bytes = System.Text.UTF8Encoding.UTF8.GetBytes(content); CacheRequest = UnityWebRequest.Put(url, bytes); CacheRequest.method = "POST"; CacheRequest.SetRequestHeader("Content-Type", "application/json"); CacheRequest.SetRequestHeader("X-HTTP-Method-Override", "POST"); CacheRequest.SetRequestHeader("Authorization", CognitiveStatics.ApplicationKey); CacheRequest.Send(); if (CognitiveVR_Preferences.Instance.EnableDevLogging) { Util.logDevelopment("NETWORK LoopUploadFromLocalCache " + url + " " + content); } CacheResponseAction = Sender.CACHEDResponseCallback; Sender.StartCoroutine(Sender.WaitForFullResponse(CacheRequest, content, CacheResponseAction, false)); } else if (lc.CacheEmpty()) { if (cacheCompletedAction != null) { cacheCompletedAction.Invoke(); } cacheCompletedAction = null; } }
public async Task <FullResponse> getIPdetails(ProviderQuality p1) { FullResponse response = new FullResponse(); Stopwatch stopwatch = new Stopwatch(); try { var client = new HttpClient(); var api = new IpInfoApi(client); p1.requestCount++; stopwatch.Reset(); stopwatch.Start(); response = await api.GetCurrentInformationAsync(); stopwatch.Stop(); p1.avgResponseTime += stopwatch.ElapsedMilliseconds / 2; } catch (Exception e) { //log exception } return(response); }
System.Collections.IEnumerator WaitForFullResponse(UnityWebRequest www, string contents, FullResponse callback, bool autoDispose) { float time = 0; float timeout = 10; //yield return new WaitUntil(() => www.isDone); while (time < timeout) { yield return(null); if (www == null) { break; } if (www.isDone) { break; } time += Time.deltaTime; } if (www == null) { Debug.LogError("WaitForFullResponse request is null!"); yield break; } if (CognitiveVR_Preferences.Instance.EnableDevLogging) { Util.logDevelopment("response code to " + www.url + " " + www.responseCode); } lastDataResponse = (int)www.responseCode; if (callback != null) { var headers = www.GetResponseHeaders(); int responsecode = (int)www.responseCode; if (responsecode == 200) { //check cvr header to make sure not blocked by capture portal if (!headers.ContainsKey("cvr-request-time")) { if (CognitiveVR_Preferences.Instance.EnableDevLogging) { Util.logDevelopment("capture portal error! " + www.url); } responsecode = 404; lastDataResponse = responsecode; } } callback.Invoke(www.url, contents, responsecode, www.error, www.downloadHandler.text); } if (autoDispose) { www.Dispose(); } activeRequests.Remove(www); }
System.Collections.IEnumerator WaitForFullResponse(UnityWebRequest www, string contents, FullResponse callback, bool allowLocalUpload) { yield return(new WaitUntil(() => www.isDone)); if (CognitiveVR_Preferences.Instance.EnableDevLogging) { Util.logDevelopment("response code to " + www.url + " " + www.responseCode); } if (callback != null) { var headers = www.GetResponseHeaders(); int responsecode = (int)www.responseCode; if (responsecode == 200) { //check cvr header to make sure not blocked by capture portal if (!headers.ContainsKey("cvr-request-time")) { if (CognitiveVR_Preferences.Instance.EnableDevLogging) { Util.logDevelopment("capture portal error! " + www.url); } responsecode = 404; } } callback.Invoke(www.url, contents, responsecode, www.error, www.downloadHandler.text, allowLocalUpload); } www.Dispose(); }
private void navigate( ResourceInfo destination, FullResponse secondaryResponse ) { var requestState = AppRequestState.Instance.EwfPageRequestState; string destinationUrl; try { // Determine the final redirect destination. If a destination is already specified and it is the current page or a page with the same entity setup, // replace any default optional parameter values it may have with new values from this post back. If a destination isn't specified, make it the current // page with new parameter values from this post back. At the end of this block, redirectInfo is always newly created with fresh data that reflects any // changes that may have occurred in EH methods. It's important that every case below *actually creates* a new page info object to guard against this // scenario: // 1. A page modifies data such that a previously created redirect destination page info object that is then used here is no longer valid because it // would throw an exception from init if it were re-created. // 2. The page redirects, or transfers, to this destination, leading the user to an error page without developers being notified. This is bad behavior. if( requestState.ModificationErrorsExist || ( requestState.DmIdAndSecondaryOp != null && requestState.DmIdAndSecondaryOp.Item2 == SecondaryPostBackOperation.NoOperation ) ) destination = InfoAsBaseType.CloneAndReplaceDefaultsIfPossible( true ); else if( destination != null ) destination = destination.CloneAndReplaceDefaultsIfPossible( false ); else destination = createInfoFromNewParameterValues(); // This GetUrl call is important even for the transfer case below for the same reason that we *actually create* a new page info object in every case // above. We want to force developers to get an error email if a page modifies data to make itself unauthorized/disabled without specifying a different // page as the redirect destination. The resulting transfer would lead the user to an error page. destinationUrl = destination.GetUrl(); } catch( Exception e ) { throw getPossibleDeveloperMistakeException( "The post-modification destination page became invalid.", innerException: e ); } // Put the secondary response into session state right before navigation so that it doesn't get sent if there is an error before this point. if( secondaryResponse != null ) { // It's important that we put the response in session state first since it's used by the Info.init method of the pre-built-response page. StandardLibrarySessionState.Instance.ResponseToSend = secondaryResponse; StandardLibrarySessionState.Instance.SetClientSideNavigation( EwfApp.MetaLogicFactory.CreatePreBuiltResponsePageInfo().GetUrl(), !secondaryResponse.FileName.Any(), null ); } // If the redirect destination is identical to the current page, do a transfer instead of a redirect. if( destination.IsIdenticalToCurrent() ) { AppRequestState.Instance.ClearUserAndImpersonator(); resetPage(); } // If the redirect destination is the current page, but with different query parameters, save request state in session state until the next request. if( destination.GetType() == InfoAsBaseType.GetType() ) StandardLibrarySessionState.Instance.EwfPageRequestState = requestState; NetTools.Redirect( destinationUrl ); }