public override Task <GetResponse> Get(GetRequest request, ServerCallContext context) { string token = request.Token; var user = this.service.FindUserByUserToken(token); var res = new GetResponse(); res.User = user; return(Task.FromResult(res)); }
public static GetResponse <T> CreateGetResponse <T>( ISpecimenContext context, bool successful) { return(GetResponse <T> .Create( successful : successful, successful?context.Create <T>() : default(T), context.Create <string>())); }
public void Get(string url, OSDMap request, GetResponse response) { if (m_doRemote) { Util.FireAndForget((o) => { response(GetInternal(true, url, request)); }); } else response(m_registry.RequestModuleInterface<ISyncMessageRecievedService>().FireMessageReceived(request)); }
public void HandleResponse(GetResponse response) { if (response.ForceRetry) { Result = null; RequiresRetry = true; return; } if (response.Result != null) { if (_clusterSession._session.NoTracking) { var result = new Dictionary <string, CompareExchangeValue <T> >(StringComparer.OrdinalIgnoreCase); foreach (var kvp in CompareExchangeValueResultParser <BlittableJsonReaderObject> .GetValues((BlittableJsonReaderObject)response.Result, materializeMetadata: false, _conventions)) { if (kvp.Value == null) { result[kvp.Key] = _clusterSession.RegisterMissingCompareExchangeValue(kvp.Key).GetValue <T>(_conventions); continue; } result[kvp.Key] = _clusterSession.RegisterCompareExchangeValue(kvp.Value).GetValue <T>(_conventions); } Result = result; return; } foreach (var kvp in CompareExchangeValueResultParser <BlittableJsonReaderObject> .GetValues((BlittableJsonReaderObject)response.Result, materializeMetadata: false, _conventions)) { if (kvp.Value == null) { continue; } _clusterSession.RegisterCompareExchangeValue(kvp.Value); } } if (_keys != null) { foreach (var key in _keys) { if (_clusterSession.IsTracked(key)) { continue; } _clusterSession.RegisterMissingCompareExchangeValue(key); } } Result = _clusterSession.GetCompareExchangeValuesFromSessionInternal <T>(_keys, out var notTrackedKeys); Debug.Assert(_clusterSession._session.NoTracking || notTrackedKeys == null, "notTrackedKeys == null"); }
public void HeadersAreApplied() { var responseConverter = new RestToHttpResponseConverter(); var restResponse = new GetResponse(GetResponse.ResponseStatus.OK, new Dictionary <string, string> { { "X-CustomHeader", "CustomValue" } }, null); var httpResponse = responseConverter.ConvertToHttpResponse(restResponse, default(RestServerRequest)); Assert.AreEqual(httpResponse.Headers.First(x => x.Name == "X-CustomHeader").Value, "CustomValue"); }
/// <summary> </summary> JsonResult IDriver.Get(string target) { FullPath fullPath = ParsePath(target); GetResponse answer = new GetResponse(); using (StreamReader reader = new StreamReader(fullPath.File.OpenRead())) { answer.content = reader.ReadToEnd(); } return(Json(answer)); }
public static IEnumerable <KeyValuePair> GetKeyValuePair(this GetResponse response) { if (response.Results.Count > 0) { foreach (var pair in response.Results) { yield return(pair); } } }
JsonResult IDriver.Get(string target) { var fullPath = ParsePath(target); var answer = new GetResponse(); using (var blob = BlobFactory.GetBlobStorage(fullPath.File.ResourceId, BlobFactory.Container.Resources)) { answer.Content = Encoding.ASCII.GetString(blob.Content); } return(Json(answer)); }
public override async Task <GetResponse <IReadOnlyList <ILocation> > > GetAllAsync(int entityId) { var response = new GetResponse <IReadOnlyList <ILocation> >(); try { using (var connection = ConnectionFactory.GetConnection()) { var sql = $@"{GetSelectByParentIdStatement()}; {GetLocationClassCodesSelectStatement(AuditTypeEnum.WC)} WHERE EntityId = @parentId"; var results = await connection.QueryMultipleAsync(sql, new { ParentId = entityId }); // Get locations var locations = results .Read <LocationsDto>() .Select(dto => dto.ToModel()) .AsList(); var classCodeDtos = results .Read <ClassCodeDto>() .AsList(); foreach (var location in locations) { // Get class codes for the location location.ClassCodes = classCodeDtos .Where(dto => dto.LocationID == location.Id) .Select(dto => dto.ToModel()) .AsList(); // get the payroll for this location var payrollResponse = await _payrollRepository.GetAllPayrollAsync(location.Id); if (payrollResponse.IsSuccessful && payrollResponse.Content.Any()) { location.Payroll = payrollResponse .Content .AsList(); } } response.Content = locations; } } catch (Exception e) { var messaage = $@"Unable to retrieve location records."; response.AddError(e); LogManager.LogError(e, messaage); Console.WriteLine(e); } return(response); }
/// <summary> /// Método para la busqueda de entidades por medio de parametros. /// </summary> /// <param name="finderTemplateViewModel">Parámetro que contiene los valores de filtro y los parámtros de paginación.</param> /// <returns>Objeto que contiene los registros consultados y la información de paginación</returns> public GetResponse <TemplateViewModel> GetByParam(FinderTemplateViewModel finderTemplateViewModel) { _finderTemplateService.finderTemplateDTO = _mapper.Map <FinderTemplateDTO>(finderTemplateViewModel); this._finderTemplateService.SetExpression(); var getResponseTemplate = _finderTemplateService.GetByParam <FinderTemplateDTO>(_finderTemplateService.finderTemplateDTO); IEnumerable <TemplateViewModel> templateViewModels = _mapper.Map <List <TemplateViewModel> >(getResponseTemplate.Result); GetResponse <TemplateViewModel> Result = new GetResponse <TemplateViewModel>(templateViewModels, getResponseTemplate.Pagination, getResponseTemplate.PaginationCatalog); return(Result); }
public void HandleResponse(GetResponse response) { if (response.ForceRetry) { Result = null; RequiresRetry = true; return; } Result = JsonDeserializationClient.FacetedQueryResult((BlittableJsonReaderObject)response.Result); }
public void HandleResponse(GetResponse response) { if (response.RequestHasErrors()) { throw new InvalidOperationException("Got an unexpected response code for the request: " + response.Status + "\r\n" + response.Result); } var result = (RavenJObject)response.Result; Result = result.JsonDeserialization <FacetResults>(); }
protected virtual GetResponse <ObjTransl> SetTranslator_Internal(ObjTransl transl, Type t) { var resp = typeDict.GetOrAdd( t, () => { return(GetResponse <ObjTransl> .Succeed(transl)); }); return(resp); }
public override Task <GetResponse> Get(GetRequest request, ServerCallContext context) { string cityName = request.CityName; var weathers = this.service.FindOpenWeatherByCityName(cityName); GrpcEnvironment.Logger.Debug(weathers.ToString()); var response = new GetResponse(); response.WeatherList.Add(weathers); return(Task.FromResult(response)); }
public IActionResult GetPINCls() { var list = _commonDataService.GetPINCLs(); var response = new GetResponse <IEnumerable <PInclude> > { Result = list, Error = new Error() }; return(Ok(response)); }
public static IObservable <IChangeSet <LoadOrderListing> > GetLiveLoadOrder( FilePath cccFilePath, DirectoryPath dataFolderPath, out IObservable <ErrorResponse> state, bool orderListings = true) { var raw = ObservableExt.WatchFile(cccFilePath.Path) .StartWith(Unit.Default) .Select(_ => { try { return(GetResponse <IObservable <IChangeSet <ModKey> > > .Succeed( File.ReadAllLines(cccFilePath.Path) .Select(x => ModKey.FromNameAndExtension(x)) .AsObservableChangeSet())); } catch (Exception ex) { return(GetResponse <IObservable <IChangeSet <ModKey> > > .Fail(ex)); } }) .Replay(1) .RefCount(); state = raw .Select(r => (ErrorResponse)r); var ret = ObservableListEx.And( raw .Select(r => { return(r.Value ?? Observable.Empty <IChangeSet <ModKey> >()); }) .Switch(), ObservableExt.WatchFolderContents(dataFolderPath.Path) .Transform(x => { if (ModKey.TryFromNameAndExtension(Path.GetFileName(x), out var modKey)) { return(TryGet <ModKey> .Succeed(modKey)); } return(TryGet <ModKey> .Failure); }) .Filter(x => x.Succeeded) .Transform(x => x.Value) .RemoveKey()) .Transform(x => new LoadOrderListing(x, true)); if (orderListings) { ret = ret.OrderListings(); } return(ret); }
public IActionResult GetAwardingBodies() { var list = _commonDataService.GetAwardingBodies(); var response = new GetResponse <IEnumerable <AwardingBody> > { Result = list, Error = new Error() }; return(Ok(response)); }
public IActionResult GetSenStatuses() { var list = _commonDataService.GetSENStatus(); var response = new GetResponse <IEnumerable <SpecialEducationNeed> > { Result = list, Error = new Error() }; return(Ok(response)); }
public static async Task <IOrderedEnumerable <History> > GetBestPriceFromAllWorlds(string dataCenter, ulong itemId) { GetResponse response = await Get(dataCenter, itemId); List <History> results = new List <History>(); foreach (IGrouping <string?, History> worldGroup in response.RecentHistory.GroupBy(x => x.WorldName)) { string worldName = worldGroup.Key ?? string.Empty; ulong? bestHqPrice = ulong.MaxValue; History?bestHq = null; ulong? bestNmPrice = ulong.MaxValue; History?bestNm = null; foreach (History entry in worldGroup) { if (entry.PricePerUnit == null) { continue; } if (entry.Hq == true) { if (entry.PricePerUnit < bestHqPrice) { bestHq = entry; bestHqPrice = entry.PricePerUnit; } } else { if (entry.PricePerUnit < bestNmPrice) { bestNm = entry; bestNmPrice = entry.PricePerUnit; } } } if (bestHq != null) { results.Add(bestHq); } if (bestNm != null) { results.Add(bestNm); } } return(results.OrderBy(x => x.PricePerUnit)); }
public ConfirmQuote CreateConfirmQuoteObject(GetQuote quote, GetResponse allData, UserDetailsFullVM userData) { ConfirmQuote confirmQuoteDetails = new ConfirmQuote(); confirmQuoteDetails.User = userData; confirmQuoteDetails.Car = allData.Cars.AsQueryable().Where(x => x.CarId == quote.CarId).First(); confirmQuoteDetails.Mileage = allData.Mileages.AsQueryable().Where(x => x.MileageId == quote.MileageId).First(); confirmQuoteDetails.PaybackTime = allData.PaybackTimes.AsQueryable().Where(x => x.MonthId == quote.MonthId).First(); confirmQuoteDetails.Price = quote.Price; return(confirmQuoteDetails); }
public void HandleResponse(GetResponse response) { var result = response.Result; var multiLoadResult = new MultiLoadResult { Includes = result.Value<RavenJArray>("Includes").Cast<RavenJObject>().ToList(), Results = result.Value<RavenJArray>("Results").Cast<RavenJObject>().ToList() }; HandleResponse(multiLoadResult); }
public IActionResult GetYearGroups() { var list = _commonDataService.GetYearGroups(); var response = new GetResponse <IEnumerable <YearGroup> > { Result = list, Error = new Error() }; return(Ok(response)); }
public IActionResult GetLanguages() { var list = _commonDataService.GetLanguages(); var response = new GetResponse <IEnumerable <FirstLanguage> > { Result = list, Error = new Error() }; return(Ok(response)); }
public IActionResult GetEthnicities() { var list = _commonDataService.GetEthnicities(); var response = new GetResponse <IEnumerable <Ethnicity> > { Result = list, Error = new Error() }; return(Ok(response)); }
public void Get(string url, OSDMap request, GetResponse response) { if (m_doRemote) { Util.FireAndForget((o) => { response(GetInternal(true, url, request)); }); } else { response(m_registry.RequestModuleInterface <ISyncMessageRecievedService>().FireMessageReceived(request)); } }
public IActionResult GetAmendReference() { var list = _commonDataService.GetAmendCodes(); var response = new GetResponse <IEnumerable <AmendCode> > { Result = list, Error = new Error() }; return(Ok(response)); }
public void HandleResponse(GetResponse response) { if (response.Status == 404) { throw new InvalidOperationException("There is no index named: " + queryOperation.IndexName + Environment.NewLine + response.Result); } var json = (RavenJObject)response.Result; var queryResult = SerializationHelper.ToQueryResult(json, response.GetEtagHeader()); HandleResponse(queryResult); }
private GetResponse MapperToGetResponse(CustomerEntity customer) { var _response = new GetResponse() { Id = customer.Id, Name = customer.Name, Age = customer.Age }; return(_response); }
public MultiGetHttpContext(InMemoryRavenConfiguration configuration, IHttpContext realContext, GetRequest req, string tenantId) { this.configuration = configuration; this.realContext = realContext; this.tenantId = tenantId; getResponse = new GetResponse(); if (req == null) return; Request = new MultiGetHttpRequest(req, realContext.Request); Response = new MultiGetHttpResponse(getResponse, realContext.Response); }
public void UninterestingNameQueriesContext( GetResponse <int> ret, ISpecimenContext context, GetResponseParameterBuilder sut) { context.MockToReturn(ret); var param = typeof(NonInterestingClass).Methods().First().GetParameters().First(); GetResponse <int> resp = (GetResponse <int>)sut.Create(param, context); context.ShouldHaveCreated <GetResponse <int> >(); resp.Should().Be(ret); }
public void HandleResponse(GetResponse response) { if (response.Status != 200) { throw new InvalidOperationException("Got an unexpected response code for the request: " + response.Status + "\r\n" + response.Result); } var result = RavenJObject.Parse(response.Result); Result = result.JsonDeserialization <IDictionary <string, IEnumerable <FacetValue> > >(); }
public void Get(OSDMap request, UUID userID, ulong RegionHandle, GetResponse response) { Util.FireAndForget((o) => { OSDMap retval = null; List<string> serverURIs = m_registry.RequestModuleInterface<IConfigurationService>().FindValueOf(userID.ToString(), RegionHandle.ToString(), "MessagingServerURI"); foreach (string host in serverURIs) { string backURL = "/" + UUID.Random(); request["ResponseURL"] = MainServer.Instance.ServerURI + backURL; OSDMap message = CreateWebRequest(request); MainServer.Instance.AddStreamHandler(new GenericStreamHandler("POST", backURL, (path, req, httpRequest, httpResponse) => { string resultStr = req.ReadUntilEnd(); if (resultStr != "") { retval = OSDParser.DeserializeJson(resultStr) as OSDMap; if (retval != null) response(retval); } MainServer.Instance.RemoveStreamHandler("POST", backURL); return MainServer.NoResponse; })); string result = WebUtils.PostToService(host, message); if (result != "") { OSDMap r = OSDParser.DeserializeJson(result) as OSDMap; if (r == null || !r.ContainsKey("WillHaveResponse")) response(null); } else response(null); } }); }
/// <summary> /// Completes the request. /// </summary> /// <param name="request">The request.</param> /// <param name="respond">The respond action.</param> private void CompleteRequest(HttpWebRequest request, GetResponse respond) { HttpWebResponse response = null; try { // get the request response response = request.GetResponse() as HttpWebResponse; if (response.StatusCode == HttpStatusCode.OK) { // request response returned status code OK, procede if a delagate was specified if (respond != null) { respond(response); } } else { // status code was anything but OK throw new ServiceException(ServiceError.BadRequest, "There was a problem with your request."); } } catch (WebException exc) { this.HandleException(exc); } finally { // close the connection (if we had a respose to read) if (response != null) { response.Close(); } response = null; } }
public void Get(OSDMap request, UUID userID, ulong RegionHandle, GetResponse response) { response(m_registry.RequestModuleInterface<IAsyncMessageRecievedService>().FireMessageReceived( RegionHandle.ToString(), request)); }
/// <summary> /// Wait for a response on the serial port. /// </summary> /// <param name="getResponse"></param> /// <returns></returns> private IEnumerator<ITask> CommGetResponseHandler(GetResponse getResponse) { string errorMessage = null; SendCommandRequest cmdRequest = _commState.PendingRequests.Peek(); if (cmdRequest == null) yield break; #region If the data isn't ready yet, wait a little and try again. if (_commState.SerialPort.BytesToRead == 0) { TimeSpan elapsed = (cmdRequest.Stopwatch == null) ? TimeSpan.MinValue : cmdRequest.Stopwatch.Elapsed; TimeSpan remaining; if (elapsed != TimeSpan.MinValue && elapsed < cmdRequest.MinExpectedTimeSpan) { // Wait until the minimum expected time for this command. remaining = cmdRequest.MinExpectedTimeSpan.Subtract(elapsed); } else if (elapsed.TotalSeconds < 1.0) { // No data yet, wait 3 milliseconds remaining = new TimeSpan(0, 0, 0, 0, 3); } else { // Timeout has occurred // Remove from the pending list _commState.PendingRequests.Pop(); _commState.ConsecutiveReadTimeouts++; if (_commState.ConsecutiveReadTimeouts > 5) { // Several read timeouts in a row means the serial port is no longer connected. _state.Connected = false; SendNotification<ConnectionUpdate>(_subMgrPort, new ConnectionUpdate(_state.Connected)); } errorMessage = "Timeout receiving data from the LEGO NXT."; if (cmdRequest.InternalResponsePort != null) { Fault faultResponse = Fault.FromException(new IOException(errorMessage)); cmdRequest.InternalResponsePort.Post(faultResponse); } else { LogError(errorMessage); } yield break; } // Leave the exclusive handler, // but wake up in a little bit and try again. Activate(Arbiter.Receive(false, TimeoutPort(remaining), delegate(DateTime timeout) { _commGetResponsePort.Post(GetResponse.Instance); })); yield break; } // When data starts to come in, clear the read timeout counter. if (_commState.ConsecutiveReadTimeouts > 0) _commState.ConsecutiveReadTimeouts = 0; #endregion // See if there is data on the serial port. // if not, post back to _commGetResponsePort // otherwise read it and send it back LegoCommand cmd = cmdRequest.LegoCommand; bool resetComm = false; try { int packetSize = cmd.ExpectedResponseSize; if (_state.ConnectOverBluetooth) { packetSize = _commState.SerialPort.ReadByte() + (_commState.SerialPort.ReadByte() * 256); if (packetSize != cmd.ExpectedResponseSize) { errorMessage = "Bluetooth header does not match the expected LEGO Command response size."; resetComm = true; } } // Read the data and get a response packet. byte[] receiveData = new byte[packetSize]; _commState.SerialPort.Read(receiveData, 0, packetSize); LogInfo("Received Data -------------------------------------"); for (int i = 0; i < receiveData.Length; i++) LogInfo(receiveData[i].ToString(CultureInfo.InvariantCulture)); #region Timing Stats if (cmdRequest.Stopwatch != null) { cmdRequest.Stopwatch.Stop(); _CodeTimerStats.Add(new CodeTimer(cmd.LegoCommandCode, cmdRequest.Stopwatch.Elapsed.TotalMilliseconds * 1000.0)); if (_CodeTimerStats.Count > 20) ProcessCommunicationStats(); } #endregion LegoResponse legoReceive = cmd.GetResponse(receiveData); byte commandType = (byte)(receiveData[0] & 0x7F); // Is this a valid starting type? if (commandType != 0x00 && commandType != 0x01 && commandType != 0x02) { errorMessage = string.Format("Invalid LEGO response command: {0}", commandType); resetComm = true; } else { // Data is received successfully // Remove from the pending list _commState.PendingRequests.Pop(); if (!_state.Connected) { _state.Connected = true; SendNotification<ConnectionUpdate>(_subMgrPort, new ConnectionUpdate(_state.Connected)); } if (cmdRequest.InternalResponsePort != null) cmdRequest.InternalResponsePort.Post(legoReceive); yield break; } } catch (ArgumentException ex) { resetComm = true; if (ex.Message == "Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.") errorMessage = "A connection error occured which may be caused by an invalid Baud Rate"; else errorMessage = "A connection error occured while accessing the LEGO NXT serial port"; } catch (TimeoutException) { // Ignore timeouts for now. errorMessage = "Timeout reading from LEGO NXT brick"; resetComm = true; } catch (IOException ex) { errorMessage = string.Format("Error reading from the serial port in NxtComm(): {0}", ex); resetComm = true; } catch (Exception ex) { errorMessage = string.Format("Error reading from the serial port in NxtComm(): {0}", ex); resetComm = true; } // Some error has occurred // Remove from the pending list _commState.PendingRequests.Pop(); if (resetComm) { // A serious error occurred LogInfo(LogGroups.Console, "Resetting LEGO Serial Port"); // Wait for remaining bytes yield return Arbiter.Receive(false, TimeoutPort(300), delegate(DateTime timeout) { }); // Clear the serial port buffer _commState.SerialPort.DiscardInBuffer(); } if (string.IsNullOrEmpty(errorMessage)) errorMessage = "Invalid or missing response data from LEGO NXT."; if (cmdRequest.InternalResponsePort != null) { Fault faultResponse = Fault.FromException(new IOException(errorMessage)); cmdRequest.InternalResponsePort.Post(faultResponse); } else { LogError(errorMessage); } yield break; }
/// <summary> /// Completes the request. /// </summary> /// <param name="request">The request.</param> /// <param name="respond">The respond action.</param> private void CompleteRequest(HttpWebRequest request, GetResponse respond) { HttpWebResponse response = null; try { response = request.GetResponse() as HttpWebResponse; if (response.StatusCode == HttpStatusCode.OK) { if (respond != null) { respond(response); } } else { throw new ServiceException(ServiceError.BadRequest, "There was a problem with your request."); } } catch (WebException exc) { this.HandleException(exc); } finally { if (response != null) { response.Close(); } response = null; } }