private static void SetHttpError <T>(RestResult <T> r, HttpRequestException hex, HttpResponseMessage response) { r.Error.HasError = true; r.Error.Message = $"http error: {hex.Message}"; r.Error.ErrorCode = response.StatusCode.ToString(); r.Error.Type = ErrorType.Http; }
public void UpdatePartial() { using (MSSQLDbClient sqlClient = new MSSQLDbClient(ConnectionString)) { ProductRowApiO existing = sqlClient.Fill <ProductRowApiO>(GetRecordSql); if (existing == null) { this.Create(); existing = sqlClient.Fill <ProductRowApiO>(GetRecordSql); } Assert.NotNull(existing); using (RESTClient restClient = new RESTClient(BaseUrl)) { string partialJson = "{ \"ProductId\": " + existing.ProductId + ", \"CategoryId\": 2, \"SupplierId\": 1, \"UnitPrice\": 32.1 }"; RestResult <ProductRowApiO> apiResult = restClient.Execute <ProductRowApiO>("Product", RestSharp.Method.PATCH, jsonBodyPartial: partialJson, headerParameters: Headers); Assert.True(apiResult.StatusCode == 200, apiResult.Content); ProductRowApiO dbValue = sqlClient.Fill <ProductRowApiO>(GetRecordSql); Assert.True(dbValue.UnitPrice == (decimal)32.1, "Incorrect text was saved."); } } }
public async Task <IActionResult> GetEventApplicationByUserQuery(GetEventApplicationByUserQuery.Contract request) { request.UserId = this.GetUserId(); var result = await this.Send(request); return(RestResult.CreateHttpResponse(result)); }
public void Create() { using (MSSQLDbClient sqlClient = new MSSQLDbClient(ConnectionString)) { ProductRowApiO existing = sqlClient.Fill <ProductRowApiO>(GetRecordSql); if (existing != null) { this.Delete(); } using (RESTClient restClient = new RESTClient(BaseUrl)) { ProductRowApiO newItem = new ProductRowApiO() { ProductName = TestProductName, CategoryId = 2, QuantityPerUnit = "4 in a box", UnitPrice = (decimal)12.37, SupplierId = 1 }; RestResult <ProductRowApiO> apiResult = restClient.Execute <ProductRowApiO>("Product", RestSharp.Method.PUT, jsonBody: newItem, headerParameters: Headers); Assert.True(apiResult.StatusCode == 201, apiResult.Content); ProductRowApiO sqlResult = sqlClient.Fill <ProductRowApiO>(GetRecordSql); Assert.True(sqlResult.ProductName == apiResult.Result.ProductName && sqlResult.CategoryId == apiResult.Result.CategoryId && sqlResult.QuantityPerUnit == apiResult.Result.QuantityPerUnit && sqlResult.ProductId == apiResult.Result.ProductId); } } }
public async Task <IActionResult> ChangeUserEventApplicationSchedule([FromBody] ChangeUserEventApplicationSchedule.Contract request) { request.CurrentUserRole = this.GetUserRole(); var result = await this.Send(request); return(RestResult.CreateHttpResponse(result)); }
public async Task <IActionResult> MigrateStructure(MigrateStructure.Contract request) { request.UserRole = this.GetUserRole(); var result = await this.Send(request); return(RestResult.CreateHttpResponse(result)); }
public async Task <IActionResult> ExportTrackNps(GetAllNpsQuery.Contract request) { request.UserRole = this.GetUserRole(); var result = await _mediator.Send(request); return(RestResult.CreateHttpResponse(result)); }
public async Task <IActionResult> ManageEventReaction([FromBody] ManageEventReactionSuggestionCommand.Contract request) { request.UserRole = this.GetUserRole(); var result = await this.Send(request); return(RestResult.CreateHttpResponse(result)); }
public async Task <IActionResult> ManageDraftModuleWeight([FromBody] ManageModuleWeightDraft.Contract request) { request.UserRole = this.GetUserRole(); var result = await this.Send(request); return(RestResult.CreateHttpResponse(result)); }
public async Task <IActionResult> GetEffectivenessIndicators(GetEffectivenessIndicatorsQuery.Contract request) { request.UserRole = this.GetUserRole(); var result = await _mediator.Send(request); return(RestResult.CreateHttpResponse(result)); }
public async Task <IActionResult> RejectCandidate([FromBody] RejectCandidate.Contract request) { request.CurrentUserRole = this.GetUserRole(); var result = await this.Send(request); return(RestResult.CreateHttpResponse(result)); }
public async Task <IActionResult> FinishExamValuation([FromBody] AnswerQuestionCommand.Contract request) { request.UserId = this.GetUserId(); var result = await this.Send(request); return(RestResult.CreateHttpResponse(result)); }
public async Task <IActionResult> UpdateJobPositionStatus([FromBody] UpdateJobPositionStatus.Contract request) { request.UserRole = this.GetUserRole(); var result = await this.Send(request); return(RestResult.CreateHttpResponse(result)); }
public async Task <IActionResult> RemoveCandidateFromJobPosition(RemoveCandidateFromJobPosition.Contract request) { request.CurrentUserRole = this.GetUserRole(); var result = await this.Send(request); return(RestResult.CreateHttpResponse(result)); }
public async Task <IActionResult> ManageFormulaTypeVariables([FromBody] ManageFormulaTypeVariables.Contract request) { request.UserRole = this.GetUserRole(); var result = await this.Send(request); return(RestResult.CreateHttpResponse(result)); }
public async Task <IActionResult> AddFormula([FromBody] AddFormula.Contract request) { request.UserRole = this.GetUserRole(); var result = await this.Send(request); return(RestResult.CreateHttpResponse(result)); }
public async Task <IActionResult> GetFormulaById(GetFormulaById.Contract request) { request.UserRole = this.GetUserRole(); var result = await this.Send(request); return(RestResult.CreateHttpResponse(result)); }
public override void OnException(ExceptionContext context) { var exception = context.Exception; logger.LogWarning("发生异常:" + exception.Message); logger.LogWarning("异常位置:" + exception.StackTrace); logger.LogWarning("内部异常:" + exception.InnerException.Message); logger.LogWarning("内部异常位置:" + exception.InnerException.StackTrace); RestResult result; if (exception is BadRequestException) { result = new RestResult(WebLite.StatusCode.请求错误, reasonPhrase: "Bad request!"); } else if (exception is NotFoundException) { result = new RestResult(WebLite.StatusCode.路由错误, reasonPhrase: "Check the url please!"); } else if (exception is UnAuthenticationException) { result = new RestResult(WebLite.StatusCode.身份异常, reasonPhrase: "UnAuthentication request!"); } else if (exception is UnAuthorizationException) { result = new RestResult(WebLite.StatusCode.鉴权异常, reasonPhrase: "UnAuthorized request!"); } else { result = new RestResult(WebLite.StatusCode.务器异常, reasonPhrase: "The server comes across an error!"); } context.Result = result; }
public void QueryTest() { var id = "id"; var point = new Point(new GeographicPosition(30.0, 110.0)); var feature = new Feature(point); var features = new List <Feature>(); features.Add(feature); var collection = new FeatureCollection(features); var expected = new FeatureCollection[] { collection }; var url = String.Join("/", new string[] { urlPrefix, db1, "layers", id, "data" }); var handler = new MockHttpHandler(url, "POST", (req, res, param) => { var result = new RestResult(); result.Success = true; result.Count = 1; result.Data = JsonConvert.SerializeObject(expected); return(JsonConvert.SerializeObject(result)); }); mockServer.AddRequestHandler(handler); try { var db = new MapDB(db1); var filter = new QueryFilter(); var actual = db.Query(filter, 0, 10, new string[] { id }); Assert.AreEqual(expected[0], actual[0]); } catch (Exception ex) { Assert.Fail(ex.Message); } }
public IHttpActionResult GetActiveRaceDayPools() { IList <Service.RaceDay.Contracts.PoolService.ActivePoolsForRaceDay> activeRaceDayPools = _raceDayServiceGateway.GetActivePoolsForRaceDay(); //--- FEATURE TOGGLING START--- Remove Qplus from RaceDay foreach (var activePoolsForRaceDay in activeRaceDayPools) { activePoolsForRaceDay.Products = activePoolsForRaceDay.Products.Where(x => x.Product != BetTypeCode.QPlus).ToList(); } // removes all products for Gallop foreach (var gallopRaceDay in activeRaceDayPools.Where(pool => pool.SportType == SportType.G)) { gallopRaceDay.Products = new List <ProductForRaceDay>(); } //--- FEATURE TOGGLING END--- IList <ActivePoolsForRaceDay> activeRaceDays = _mapper.Map <IList <ActivePoolsForRaceDay> >(activeRaceDayPools); List <ActivePoolsForRaceDayGroupedByDate> groupedByDate = activeRaceDays .GroupBy(g => g.StartTime.Date) .Select(s => new ActivePoolsForRaceDayGroupedByDate { Date = s.Key.Date, PoolsForRaceDay = s.OrderBy(x => x.StartTime).ToList() }) .OrderBy(x => x.Date) .ToList(); return(Ok(RestResult <List <ActivePoolsForRaceDayGroupedByDate> > .CreateSuccess(groupedByDate))); }
public void GetDbInfoTest() { var expected = new DbInfo(); expected.Name = db1; expected.Version = "1.0.0"; expected.CRS = CRS.WGS84; var url = String.Join("/", new string[] { urlPrefix, db1 }); var handler = new MockHttpHandler(url, "GET", (req, res, param) => { var result = new RestResult(); result.Success = true; result.Data = JsonConvert.SerializeObject(expected); return(JsonConvert.SerializeObject(result)); }); mockServer.AddRequestHandler(handler); try { var db = new MapDB(db1); var actual = db.GetDbInfo(); Assert.AreEqual <DbInfo>(expected, actual); } catch { Assert.Fail(); } }
public async Task <IActionResult> SendFileToS3() { try { if (Request.Form == null) { throw new Exception("Arquivo não encontrado"); } var file = Request.Form.Files[0]; if (file.Length > 0) { var result = await AWS.UploadFileToS3(file, _configuration); return(RestResult.CreateHttpResponse(result)); } return(RestResult.CreateFailHttpResponse("Ocorreu um erro ao realizar a operação.")); } catch (Exception ex) { var execption = ex.Message; return(RestResult.CreateFailHttpResponse("Ocorreu um erro ao realizar a operação.")); } }
public void Update() { using (MSSQLDbClient sqlClient = new MSSQLDbClient(ConnectionString)) { ProductRowApiO existing = sqlClient.Fill <ProductRowApiO>(GetRecordSql); if (existing == null) { this.Create(); existing = sqlClient.Fill <ProductRowApiO>(GetRecordSql); } Assert.NotNull(existing); using (RESTClient restClient = new RESTClient(BaseUrl)) { ProductRowApiO updated = existing; updated.UnitPrice = 123; RestResult <ProductRowApiO> apiResult = restClient.Execute <ProductRowApiO>("Product", RestSharp.Method.PATCH, jsonBody: updated, headerParameters: Headers); Assert.True(apiResult.StatusCode == 200, apiResult.Content); Assert.True(apiResult.Result.UnitPrice == 123, "The updated value was not returned"); } ProductRowApiO dbValue = sqlClient.Fill <ProductRowApiO>(GetRecordSql); Assert.True(dbValue.UnitPrice == 123, "The updated value was not returned"); } }
public async Task <IActionResult> GetuserProgress(GetUsersPerfomanceTimeReportQuery.Contract request) { request.UserRole = this.GetUserRole(); var result = await _mediator.Send(request); return(RestResult.CreateHttpResponse(result)); }
private async Task <RestResult <T> > DoHttpGet <T>(string url) { var r = new RestResult <T>(); var response = new HttpResponseMessage(); try { var request = new HttpRequestMessage(HttpMethod.Get, new Uri(BaseUrl + url, UriKind.RelativeOrAbsolute)); response = await _client.SendAsync(request); switch (response.StatusCode) { case HttpStatusCode.OK: { var content = await response.Content.ReadAsStringAsync(); r.Error = new Error { HasError = false }; ExtractResponse(r, content); } break; case HttpStatusCode.BadRequest: { var content = await response.Content.ReadAsStringAsync(); r.Error = new Error { HasError = true, ErrorCode = response.StatusCode.ToString() }; r.Data = content.FromJson <T>(); } break; default: r.Error.HasError = true; r.Error.Message = $"http error: {response.StatusCode}"; r.Error.ErrorCode = response.StatusCode.ToString(); r.Raw = await response.Content.ReadAsStringAsync(); break; } } catch (HttpRequestException hex) { SetHttpError(r, hex, response); } catch (Exception ex) { SetUnhandledError(r, ex); } return(r); }
public async Task <IActionResult> AddEventReaction([FromBody] AddEventReactionCommand.Contract request) { request.UserId = this.GetUserId(); var result = await this.Send(request); return(RestResult.CreateHttpResponse(result)); }
public void UpdatePartialBadly() { using (MSSQLDbClient sqlClient = new MSSQLDbClient(ConnectionString)) { ProductRowApiO existingCategory = sqlClient.Fill <ProductRowApiO>(GetRecordSql); if (existingCategory == null) { this.Create(); existingCategory = sqlClient.Fill <ProductRowApiO>(GetRecordSql); } Assert.NotNull(existingCategory); using (RESTClient restClient = new RESTClient(BaseUrl)) { string partialJson = "{ \"ProductId\": " + existingCategory.ProductId + " }"; RestResult <ProductRowApiO> apiResult = restClient.Execute <ProductRowApiO>("Product", RestSharp.Method.PATCH, jsonBodyPartial: partialJson, headerParameters: Headers); Assert.False(apiResult.StatusCode == 200, apiResult.Content); } ProductRowApiO dbValue = sqlClient.Fill <ProductRowApiO>(GetRecordSql); Assert.False(dbValue.ProductName == string.Empty, "Incorrect text was saved."); } }
public async Task <IActionResult> GetPastEvents(GetPastEventsQuery.Contract request) { request.UserRole = this.GetUserRole(); var result = await this.Send(request); return(RestResult.CreateHttpResponse(result)); }
public void Delete() { using (MSSQLDbClient sqlClient = new MSSQLDbClient(ConnectionString)) { ProductRowApiO existingCategory = sqlClient.Fill <ProductRowApiO>(GetRecordSql); if (existingCategory == null) { this.Create(); existingCategory = sqlClient.Fill <ProductRowApiO>(GetRecordSql); } Assert.NotNull(existingCategory); using (RESTClient restClient = new RESTClient(BaseUrl)) { List <KeyValuePair <string, string> > routeParams = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("key", existingCategory.ProductId.ToString()) }; RestResult <ProductRowApiO> apiResult = restClient.Execute <ProductRowApiO>("Product/{key}", RestSharp.Method.DELETE, routeParameters: routeParams, headerParameters: Headers); Assert.True(apiResult.StatusCode == 301, apiResult.Content); } ProductRowApiO dbValue = sqlClient.Fill <ProductRowApiO>(GetRecordSql); Assert.Null(dbValue); } }
public async Task <IActionResult> AdminChangePassword([FromBody] AdminChangePassword.Contract request) { request.UserRole = this.GetUserRole(); var result = await _mediator.Send(request); return(RestResult.CreateHttpResponse(result)); }
statuses_upload_async(string filepath, string status, string access_token) { string path = string.Format("statuses/upload.json?access_token={0}", access_token); var rtn = new RestResult<Status>(); using (var client = new HttpClient(new HttpClientHandler() { AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip })) { client.DefaultRequestHeaders.AcceptEncoding.Add(StringWithQualityHeaderValue.Parse("gzip")); client.DefaultRequestHeaders.AcceptEncoding.Add(StringWithQualityHeaderValue.Parse("deflate")); var filec = new StreamContent(File.OpenRead(filepath)); var form = new MultipartFormDataContent { {new StringContent(access_token), "access_token"}, {new StringContent(status), "status"}, {filec, "pic", "weizhi.jpg"} }; var resp = await client.PostAsync(WeiboSources.SinaUpload(path), form); rtn.StatusCode = resp.StatusCode; rtn.Reason = resp.ReasonPhrase; if (resp.IsSuccessStatusCode) rtn.Value = JsonConvert.DeserializeObject<Status>(await resp.Content.ReadAsStringAsync()); else if ((int)resp.StatusCode >= 400) { var er = JsonConvert.DeserializeObject<WeiboError>(await resp.Content.ReadAsStringAsync()); rtn.Reason = er.Translate(); } } return rtn; }