public override void RequestDidFail(ApiError errorResponse) { // Get Profile request failed for profile scope. // If error code = kAIApplicationNotAuthorized, // allow user to log in again. if (errorResponse.Error.Code == AIErrorCode.ApplicationNotAuthorized) InvokeOnMainThread (()=> new UIAlertView ("Error", "App Not Authorized: " + errorResponse.Error.Message, null, "Ok", null).Show ()); else { // Handle other errors InvokeOnMainThread (()=> new UIAlertView ("Error", errorResponse.Error.Message, null, "Ok", null).Show ()); } }
private static void HandleException(ExceptionContext context) { //todo: logging if (!context.IsAjaxRequest()) { return; } var data = new ApiError { Errors = new Dictionary<string, IEnumerable<string>> { {"*", new[] {context.Exception.Message}} } }; var jsonResult = new JsonResult(data) {StatusCode = (int) HttpStatusCode.InternalServerError}; context.Result = jsonResult; }
private static Task HandleNotSuccessRequestAsync(HttpContext httpContext, int code) { httpContext.Response.ContentType = "application/json"; ApiError apiError; if (code == (int)HttpStatusCode.NotFound) { apiError = new ApiError("The specified URI does not exist. Please verify and try again."); } else if (code == (int)HttpStatusCode.NoContent) { apiError = new ApiError("The specified URI does not contain any content."); } else { apiError = new ApiError("Your request cannot be processed. Please contact a support."); } ApiResponse apiResponse = new ApiResponse(code, ResponseMessageEnum.Failure.GetDescription(), null, apiError); httpContext.Response.StatusCode = code; return(httpContext.Response.WriteAsync(JsonConvert.SerializeObject(apiResponse))); }
/// <summary> /// Handles errors returned from the API. It will check the response code, deserialize any relevant JSON error payload /// and throw an appropriate exception. /// </summary> /// <param name="response">The <see cref="HttpResponseMessage" /> returned from the API.</param> /// <returns>A <see cref="Task" />.</returns> /// <exception cref="ApiException"></exception> private async Task HandleErrors(HttpResponseMessage response) { if (!response.IsSuccessStatusCode) { ApiError apiError = null; // Grab the content if (response.Content != null) { var responseContent = await response.Content.ReadAsStringAsync(); if (!string.IsNullOrEmpty(responseContent)) { try { apiError = JsonConvert.DeserializeObject <ApiError>(responseContent); if (apiError.StatusCode == 0) { apiError.StatusCode = (int)response.StatusCode; } } catch (Exception ex) { apiError = new ApiError { Error = responseContent, Message = responseContent, StatusCode = (int)response.StatusCode }; } } } throw new ApiException(response.StatusCode, apiError); } }
public async Task <AllGradesResponse> GetAllGradesAsync() { if (authToken == null) { return new AllGradesResponse() { Success = false, Error = ApiError.NotLoggedInError() } } ; Uri uri = new Uri(String.Format("{0}/{1}/{2}", api_url, "grades", "all")); var request = new HttpRequestMessage { Method = HttpMethod.Get, RequestUri = uri, }; request.Headers.Add("Authorization", String.Format("Bearer {0}", authToken)); Task <HttpResponseMessage> response = Task.Run(() => client.SendAsync(request)); if (response.Wait(TimeSpan.FromSeconds(40))) { var responseBody = await response.Result.Content.ReadAsStringAsync().ConfigureAwait(false); Swimclub.Models.AllGradesResponse res = JsonConvert.DeserializeObject <Swimclub.Models.AllGradesResponse>(responseBody); return(res); } else { return(new AllGradesResponse() { Success = false, Error = ApiError.TimeOutResponse() }); } }
internal string HandleJsonRawResponse(RequestContext context) { ApiError errorResult = null; string json; try { var reader = new StreamReader(context.ResponseStream, Encoding.UTF8); json = reader.ReadToEnd(); } catch (Exception ex) { throw FX.InternalException("ReadStreamAsText", ex, ex.Message); } if (validHttpCodes.Contains(context.HttpStatusCode)) { // the HTTP code matches a success response // do nothing here } else if (errorHttpCodes.Contains(context.HttpStatusCode)) { // the HTTP code matches a error response ThrowJsonErrorResult(context, errorResult, json); } else { // unknown HTTP code var ex1 = FX.ApiException("ApiUnknownHttpCode", context.HttpStatusCode); TryAttachContextDetails(context, null); throw ex1; } return(json); }
/// <summary> /// This method is called from base class handler to add more information to Json Error object. /// Here all special exception types should be handled, so API Json Error returns appropriate data. /// </summary> /// <param name="apiError">ApiError object, which gets returned from API in case of exception/error. Provided by </param> /// <param name="exception">Exception which got bubbled up from somewhere deep in API logic.</param> protected override ApiError HandleSpecialException(ApiError apiError, Exception exception) { if (exception is ConfigurationValidationException configurationException) { apiError.Status = 500; apiError.ErrorType = ApiErrorType.ConfigurationError; foreach (ConfigurationValidationItem configurationValidation in configurationException.ValidationData) { apiError.ValidationErrors.Add(new ApiDataValidationError { PropertyName = $"{configurationValidation.ConfigurationSection}:{configurationValidation.ConfigurationItem}", Message = configurationValidation.ValidationMessage }); } } if (exception is NotImplementedException noImplemented) { apiError.Status = 501; apiError.Title = "Functionality is not yet implemented."; } return(apiError); }
public void OnException(ExceptionContext context) { var error = new ApiError(); if (Environment.IsDevelopment()) { error.Message = context.Exception.Message; error.Detail = context.Exception.ToString(); } else { error.Message = "服务器出错"; error.Detail = context.Exception.Message; } context.Result = new ObjectResult(error) { StatusCode = StatusCodes.Status500InternalServerError }; StringBuilder sb = new StringBuilder(); sb.AppendLine($"服务发生异常: {context.Exception.Message}"); sb.AppendLine(context.Exception.ToString()); Logger.LogCritical(sb.ToString()); }
public ApiException(ErrorCode errorCode, object param = null) { Error = new ApiError(errorCode, param); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure <HotelInfo>(Configuration.GetSection("Info")); services.Configure <HotelOptions>(Configuration); services.Configure <PagingOptions>( Configuration.GetSection("DefaultPagingOptions")); services.AddScoped <IRoomService, DefaultRoomService>(); services.AddScoped <IOpeningService, DefaultOpeningService>(); services.AddScoped <IBookingService, DefaultBookingService>(); services.AddScoped <IDateLogicService, DefaultDateLogicService>(); // Use in-memory database for quick dev and testing // TODO: Swap out for a real database in production services.AddDbContext <HotelApiDbContext>( options => options.UseInMemoryDatabase("landondb")); services .AddMvc(options => { options.CacheProfiles.Add("Static", new CacheProfile { Duration = 86400 }); options.Filters.Add <JsonExceptionFilter>(); options.Filters .Add <RequireHttpsOrCloseAttribute>(); options.Filters.Add <LinkRewritingFilter>(); }) .SetCompatibilityVersion(CompatibilityVersion.Version_2_1) .AddJsonOptions(options => { // These should be the defaults, but we can be explicit: options.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc; options.SerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat; options.SerializerSettings.DateParseHandling = DateParseHandling.DateTimeOffset; }); services .AddRouting(options => options.LowercaseUrls = true); services.AddApiVersioning(options => { options.DefaultApiVersion = new ApiVersion(1, 0); options.ApiVersionReader = new MediaTypeApiVersionReader(); options.AssumeDefaultVersionWhenUnspecified = true; options.ReportApiVersions = true; options.ApiVersionSelector = new CurrentImplementationApiVersionSelector(options); }); services.AddAutoMapper( options => options.AddProfile <MappingProfile>()); services.Configure <ApiBehaviorOptions>(options => { options.InvalidModelStateResponseFactory = context => { var errorResponse = new ApiError(context.ModelState); return(new BadRequestObjectResult(errorResponse)); }; }); }
/// <summary> /// Runs the code example. /// </summary> /// <param name="user">The AdWords user.</param> /// <param name="baseCampaignId">Id of the campaign to use as base of the /// trial.</param> /// <param name="draftId">Id of the draft.</param> public void Run(AdWordsUser user, long draftId, long baseCampaignId) { using (TrialService trialService = (TrialService)user.GetService( AdWordsService.v201806.TrialService)) using (TrialAsyncErrorService trialAsyncErrorService = (TrialAsyncErrorService)user.GetService( AdWordsService.v201806.TrialAsyncErrorService)) { Trial trial = new Trial() { draftId = draftId, baseCampaignId = baseCampaignId, name = "Test Trial #" + ExampleUtilities.GetRandomString(), trafficSplitPercent = 50 }; TrialOperation trialOperation = new TrialOperation() { @operator = Operator.ADD, operand = trial }; try { long trialId = trialService.mutate(new TrialOperation[] { trialOperation }).value[0].id; // Since creating a trial is asynchronous, we have to poll it to wait // for it to finish. Selector trialSelector = new Selector() { fields = new string[] { Trial.Fields.Id, Trial.Fields.Status, Trial.Fields.BaseCampaignId, Trial.Fields.TrialCampaignId }, predicates = new Predicate[] { Predicate.Equals(Trial.Fields.Id, trialId) } }; trial = null; bool isPending = true; int pollAttempts = 0; do { int sleepMillis = (int)Math.Pow(2, pollAttempts) * POLL_INTERVAL_SECONDS_BASE * 1000; Console.WriteLine("Sleeping {0} millis...", sleepMillis); Thread.Sleep(sleepMillis); trial = trialService.get(trialSelector).entries[0]; Console.WriteLine("Trial ID {0} has status '{1}'.", trial.id, trial.status); pollAttempts++; isPending = (trial.status == TrialStatus.CREATING); } while (isPending && pollAttempts <= MAX_RETRIES); if (trial.status == TrialStatus.ACTIVE) { // The trial creation was successful. Console.WriteLine("Trial created with ID {0} and trial campaign ID {1}.", trial.id, trial.trialCampaignId); } else if (trial.status == TrialStatus.CREATION_FAILED) { // The trial creation failed, and errors can be fetched from the // TrialAsyncErrorService. Selector errorsSelector = new Selector() { fields = new string[] { TrialAsyncError.Fields.TrialId, TrialAsyncError.Fields.AsyncError }, predicates = new Predicate[] { Predicate.Equals(TrialAsyncError.Fields.TrialId, trial.id) } }; TrialAsyncErrorPage trialAsyncErrorPage = trialAsyncErrorService.get(errorsSelector); if (trialAsyncErrorPage.entries == null || trialAsyncErrorPage.entries.Length == 0) { Console.WriteLine("Could not retrieve errors for trial {0}.", trial.id); } else { Console.WriteLine("Could not create trial ID {0} for draft ID {1} due to the " + "following errors:", trial.id, draftId); int i = 0; foreach (TrialAsyncError error in trialAsyncErrorPage.entries) { ApiError asyncError = error.asyncError; Console.WriteLine("Error #{0}: errorType='{1}', errorString='{2}', " + "trigger='{3}', fieldPath='{4}'", i++, asyncError.ApiErrorType, asyncError.errorString, asyncError.trigger, asyncError.fieldPath); } } } else { // Most likely, the trial is still being created. You can continue // polling, but we have limited the number of attempts in the // example. Console.WriteLine("Timed out waiting to create trial from draft ID {0} with " + "base campaign ID {1}.", draftId, baseCampaignId); } } catch (Exception e) { throw new System.ApplicationException("Failed to create trial from draft.", e); } } }
public void SetExceptionResult(ApiError error, ExceptionContext context) { context.HttpContext.Response.StatusCode = (int)HttpStatusCode.ExpectationFailed; context.Result = new JsonResult(error); }
public InvalidSaleActionException(IApiResponse response, ApiError apiError) : base(response, apiError) { }
public void Update(long ApiErrorsKey,int ApiType,string Request,string Response,string Url,DateTime? Dateoccured) { ApiError item = new ApiError(); item.MarkOld(); item.IsLoaded = true; item.ApiErrorsKey = ApiErrorsKey; item.ApiType = ApiType; item.Request = Request; item.Response = Response; item.Url = Url; item.Dateoccured = Dateoccured; item.Save(UserName); }
/// <summary> /// 取得用户的所有故障列表 /// </summary> /// <param name="pagecount">第几页</param> /// <param name="pagesize">每页显示数量</param> /// <param name="app_key">第三方应用唯一key</param> /// <param name="call_id">请求序号</param> /// <param name="sig">签名</param> /// <param name="v">api版本</param> /// <param name="format">返回结果格式,暂时值支持json</param> /// <param name="lan">语言环境,暂时只支持中英文</param> /// <returns></returns> public ActionResult PlantTimezoneList(int pagecount, int pagesize, string app_key, string call_id, string sig, string v, string format, string lan) { setlan(lan); string reportData = string.Empty; if (pagecount == 0) pagecount = 1; if (pagesize == 0) pagesize = 10; Pager page = new Pager() { PageIndex = pagecount, PageSize = pagesize }; IList<Plant> plants = PlantService.GetInstance().GetPlantByPage(page); if (plants.Count > 0) { PlantTimezonePageVo plantTimezonePageVo = new PlantTimezonePageVo(); IList<PlantTimezoneVo> timezonevos = new List<PlantTimezoneVo>(); PlantTimezoneVo plantTimezoneVo = null; foreach (Plant plant in plants) { plantTimezoneVo = new PlantTimezoneVo(); plantTimezoneVo.plantId = plant.id.ToString(); plantTimezoneVo.plantName = plant.name; plantTimezoneVo.timezoneCode = plant.timezone.ToString(); plantTimezoneVo.timezoneName = Cn.Loosoft.Zhisou.SunPower.Common.TimeZone.GetText(plant.timezone); timezonevos.Add(plantTimezoneVo); } plantTimezonePageVo.timezones = timezonevos; plantTimezonePageVo.totalpagecount = page.PageCount; reportData = JsonUtil.convertToJson(plantTimezonePageVo, typeof(PlantTimezonePageVo)); } else { ApiError appError = new ApiError(ApiError.plantnoexist, Resources.SunResource.CHART_PLANT_DONT_EXISTED); reportData = JsonUtil.convertToJson(appError, typeof(ApiError)); } return Content(reportData); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // this code writes out the errors of model state. services.Configure <ApiBehaviorOptions>(options => { options.InvalidModelStateResponseFactory = actionContext => { var errors = new ApiError(actionContext.ModelState); return(new BadRequestObjectResult(errors)); }; }); // this add a logger service that can be used on controllers services.AddLogging(loggingBuilder => { loggingBuilder.AddConfiguration(Configuration.GetSection("Logging")); loggingBuilder.AddConsole(); loggingBuilder.AddDebug(); }); var connectionStringsSection = Configuration.GetSection("ConnectionStrings"); var connString = connectionStringsSection.Get <ConnectionsStrings>(); // db in mysql services.AddDbContext <ApiDbContext>(options => { options.UseMySql(connString.Mysql); options.UseLazyLoadingProxies(); }); // ===== Add Identity ======== services.AddIdentity <ApiUser, IdentityRole>() .AddEntityFrameworkStores <ApiDbContext>() .AddDefaultTokenProviders(); services.AddRouting(options => options.LowercaseUrls = true); services.AddHttpContextAccessor(); services.AddMvc(options => { options.FormatterMappings.SetMediaTypeMappingForFormat("json", "application/json"); }).SetCompatibilityVersion(CompatibilityVersion.Version_2_2) .AddJsonOptions(opt => { // These should be the defaults, but we can be explicit: opt.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc; opt.SerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat; opt.SerializerSettings.DateParseHandling = DateParseHandling.DateTimeOffset; }); services.AddHangfire(x => x.UseStorage( new MySqlStorage(connString.Mysql, new MySqlStorageOptions() { TablePrefix = "competition" }))); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Version = "v1", Title = "Midwolf Solutions Competitions API", Description = "Competitions API allowing consumers to track competitions and players entries.", TermsOfService = "None", Contact = new Contact() { Name = "Midwolf Solutions", Email = "*****@*****.**", Url = "www.solutions.midwolf.co.uk" } }); c.ExampleFilters(); c.AddSecurityDefinition("Bearer", new ApiKeyScheme { In = "header", Description = "Please enter JWT with Bearer into field", Name = "Authorization", Type = "apiKey" }); c.AddSecurityRequirement(new Dictionary <string, IEnumerable <string> > { { "Bearer", Enumerable.Empty <string>() }, }); c.DescribeAllEnumsAsStrings(); c.DocumentFilter <SwaggerRemoveModelsDocumentFilter>(); c.DocumentFilter <TagDescriptionsDocumentFilter>(); c.SchemaFilter <ReadOnlySchemaFilter>(); c.EnableAnnotations(); // Set the comments path for the Swagger JSON and UI. var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name.ToLower()}.xml"; var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); c.IncludeXmlComments(xmlPath); var servicesXmlFile = "midwolf.gamesframework.services.xml"; var xmlservicesPath = Path.Combine(AppContext.BaseDirectory, servicesXmlFile); c.IncludeXmlComments(xmlservicesPath); }); // add the automatic examples for responses here... services.AddSwaggerExamplesFromAssemblyOf <CompetitionResponseExample>(); services.AddAutoMapper(opt => { opt.AllowNullCollections = true; // this will leave null collections alone. like dictionaries }); // configure strongly typed settings objects var appSettingsSection = Configuration.GetSection("AppSettings"); services.Configure <AppSettings>(appSettingsSection); // configure jwt authentication var appSettings = appSettingsSection.Get <AppSettings>(); var key = Encoding.ASCII.GetBytes(appSettings.Secret); services.AddAuthentication(x => { x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false, ValidateLifetime = false, // dont care about expiration dates.. RequireExpirationTime = false }; // any exceptions thrown duting authentication are handled by jsonmiddleware.. x.Events = new JwtBearerEvents { OnChallenge = async context => { // Override the response status code. context.Response.StatusCode = 401; // Emit the WWW-Authenticate header. context.Response.Headers.Append( HeaderNames.WWWAuthenticate, context.Options.Challenge); await context.Response.WriteAsync(JsonConvert.SerializeObject(new ApiError("Authentication Failed."))); context.HandleResponse(); } }; }); services.AddAuthorization(options => { options.AddPolicy("User Creation", policy => policy.RequireRole("superuser")); options.AddPolicy("User Only", policy => { policy.Requirements.Add(new ApiMinimumRequirments(new List <IApiRequirement> { new UserMinimumRequirement(UserRolePermission.Administrator) })); }); options.AddPolicy("Minimal Restriction", policy => { policy.Requirements.Add(new ApiMinimumRequirments(new List <IApiRequirement> { new UserMinimumRequirement(UserRolePermission.Public), new PlayerMinimumRequirement(PlayerRolePermission.ApiBasic) })); }); options.AddPolicy("Administrators", policy => { policy.Requirements.Add(new ApiMinimumRequirments(new List <IApiRequirement> { new UserMinimumRequirement(UserRolePermission.Administrator), new PlayerMinimumRequirement(PlayerRolePermission.Administer) })); }); options.AddPolicy("Moderate", policy => { policy.Requirements.Add(new ApiMinimumRequirments(new List <IApiRequirement> { new UserMinimumRequirement(UserRolePermission.Administrator), new PlayerMinimumRequirement(PlayerRolePermission.Moderate) })); }); }); // configure DI for application services services.AddScoped <IUserService, DefaultUserService>(); services.AddScoped <IGameService, DefaultGameService>(); services.AddScoped <IEventService, DefaultEventService>(); services.AddScoped <IChainService, DefaultChainService>(); services.AddScoped <IPlayerService, DefaultPlayerService>(); services.AddScoped <IEntryService, DefaultEntryService>(); services.AddScoped <IModerateService, DefaultModerateService>(); services.AddSingleton <IAuthorizationHandler, ApiPermissionsHandler>(); services.AddScoped <IRandomDrawEventService, RandomDrawEventService>(); services.AddScoped <ICompetitionGameService, GameService>(); services.AddScoped <ICompetitionEntryService, EntryService>(); }
public override void RequestDidFail(ApiError errorResponse) { // Your code when the authorization fails. InvokeOnMainThread (()=> new UIAlertView ("User Authorization Failed", errorResponse.Error.Message, null, "Ok", null).Show ()); }
/// <summary> /// List Streaming Policies /// </summary> /// <remarks> /// Lists the Streaming Policies in the account /// </remarks> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ApiErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse <IPage <StreamingPolicy> > > ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List <string> _queryParameters = new List <string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ApiErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ApiError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ApiError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse <IPage <StreamingPolicy> >(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <Page <StreamingPolicy> >(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public void AddError(ApiError error) { _errors.Add(error); }
public override void RequestDidFail(ApiError errorResponse) { // Your additional logic after the SDK failed to clear // the authorization state. InvokeOnMainThread (()=> new UIAlertView ("User Logout Failed", errorResponse.Error.Message, null, "Ok", null).Show ()); }
public void Insert(int ApiType,string Request,string Response,string Url,DateTime? Dateoccured) { ApiError item = new ApiError(); item.ApiType = ApiType; item.Request = Request; item.Response = Response; item.Url = Url; item.Dateoccured = Dateoccured; item.Save(UserName); }
public ApiException(ApiError apiError) { Error = apiError; }
/// <param name='repository'> /// </param> /// <param name='branch'> /// </param> /// <param name='channelId'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ApiErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse <IList <DefaultChannel> > > ListWithHttpMessagesAsync(string repository = default(string), string branch = default(string), int?channelId = default(int?), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { string apiVersion = "2018-07-16"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("repository", repository); tracingParameters.Add("branch", branch); tracingParameters.Add("channelId", channelId); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/default-channels").ToString(); List <string> _queryParameters = new List <string>(); if (repository != null) { _queryParameters.Add(string.Format("repository={0}", System.Uri.EscapeDataString(repository))); } if (branch != null) { _queryParameters.Add(string.Format("branch={0}", System.Uri.EscapeDataString(branch))); } if (channelId != null) { _queryParameters.Add(string.Format("channelId={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(channelId, Client.SerializationSettings).Trim('"')))); } if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ApiErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ApiError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ApiError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse <IList <DefaultChannel> >(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <IList <DefaultChannel> >(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public async Task <string> MakeCall(string url, Dictionary <string, string> headers, string method, int numberofTrys = 0) { using (var httpClient = new HttpClient()) { //httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); if (_auth != null) { httpClient.DefaultRequestHeaders.Add("Authorization", $"bearer {_auth.AccessToken}"); } foreach (var header in headers) { httpClient.DefaultRequestHeaders.Add(header.Key, header.Value); } var request = new HttpRequestMessage(new HttpMethod(method), url); httpClient.Timeout = new TimeSpan(0, 0, 30, 0); HttpResponseMessage response = new HttpResponseMessage(); bool canRun = false; lock (lck) { canRun = RunningRequests < MAXREQUESTS; if (canRun) { RunningRequests++; } } while (!canRun) { Console.WriteLine($"Waiting to send request there are {RunningRequests} running requests."); await Task.Delay(500); lock (lck) { canRun = RunningRequests < MAXREQUESTS; if (canRun) { RunningRequests++; } } } string res; try { response = await httpClient.SendAsync(request); res = await response.Content.ReadAsStringAsync(); } catch (Exception ex) { if (numberofTrys < AutomaticRetrys) { return(await MakeCall(url, headers, method, numberofTrys + 1)); } throw ex; } lock (lck) { RunningRequests--; } if (!response.IsSuccessStatusCode) { ApiError ae = JsonConvert.DeserializeObject <ApiError>(res, JSONService.Settings); //if (ae.Error.HttpStatusCode == 429 && numberofTrys < AutomaticRetrys) //{ // await Task.Delay(2000); // var newTry = numberofTrys + 1; // return await MakeCall(url, headers, method, newTry); //} throw new ApiException(ae.Error.Message.Value) { ApiError = ae }; } return(res); } }
public IHttpActionResult Put([FromUri] string externalId, [FromBody] CreateCampaign command) { if (command is null || String.IsNullOrWhiteSpace(externalId) || !ModelState.IsValid) { return(BadRequest(ModelState)); } if (externalId != command.ExternalId) { ModelState.AddModelError(nameof(CreateCampaign.ExternalId), "ExternalId does not match"); } try { command.Validate(); } catch (BreakTypeException ex) { ModelState.AddModelError( nameof(CreateCampaign.BreakType), BreakTypeValueErrorMessage(ex) ); } if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var campaign = _campaignRepository.FindByRef(externalId).FirstOrDefault(); if (_featureManager.IsEnabled(nameof(ProductFeature.IncludeChannelGroupFileForOptimiser))) { try { ValidateCampaigns(new List <CreateCampaign> { command }, campaign == null); } catch (ArgumentException exception) when(exception.ParamName == ReflectionUtilities.PropertyName <CreateCampaign>(c => c.IncludeRightSizer)) // Case for 400 Bad Request Code for IncludeRightSizer value validation { return(this.Error().BadRequest(ApiError.BadRequest(exception.Message))); } catch (Exception ex) { return(BadRequest(ex.Message)); } } if (campaign is null) { AddCampaign(new List <CreateCampaign>() { command }); } else { var newCampaign = _mapper.Map <Campaign>(command); campaign.Update(newCampaign); ApplyDeliveryCurrency(newCampaign); ApplyBookingPositionAndSequencing(newCampaign); _campaignRepository.Update(campaign); } _campaignRepository.SaveChanges(); _campaignPassPrioritiesService.AddNewCampaignPassPrioritiesToAllScenariosInLibrary(); return(Ok(_mapper.Map <CampaignModel>(campaign))); }
/// <summary> /// List Streaming Policies /// </summary> /// <remarks> /// Lists the Streaming Policies in the account /// </remarks> /// <param name='resourceGroupName'> /// The name of the resource group within the Azure subscription. /// </param> /// <param name='accountName'> /// The Media Services account name. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ApiErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <AzureOperationResponse <IPage <StreamingPolicy> > > ListWithHttpMessagesAsync(string resourceGroupName, string accountName, ODataQuery <StreamingPolicy> odataQuery = default(ODataQuery <StreamingPolicy>), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } string apiVersion = "2020-05-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Media/mediaServices/{accountName}/streamingPolicies").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", System.Uri.EscapeDataString(accountName)); List <string> _queryParameters = new List <string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ApiErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ApiError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ApiError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse <IPage <StreamingPolicy> >(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject <Page <StreamingPolicy> >(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public void Should_deserialize_all_error_strucutures_correctly(string content, ApiError expected) { var error = JsonConvert.DeserializeObject<ApiError>(content); error.ShouldBeEquivalentTo(expected); }
/// <summary> /// 电站月天数据 /// </summary> /// <param name="pId">电站id</param> /// <param name="startTime">开始时间,格式:yyyyMMdd 20111112</param> /// <param name="endTime">截止时间,格式:yyyyMMdd 20111212</param> /// <param name="app_key">第三方应用唯一key</param> /// <param name="sig">签名</param> /// <param name="v">api版本</param> /// <param name="lan">语言环境,暂时只支持中英文</param> /// <returns>图表封装的数据</returns> public ActionResult PlantMonthDayChart(int pId, string startDate, string endDate, string app_key, string sig, string v, string lan) { setlan(lan); string chartType = ChartType.column; Plant plant = PlantService.GetInstance().GetPlantInfoById(pId); string reportData = string.Empty; if (plant != null) { MonitorType energyMt = MonitorType.getMonitorTypeByCode(MonitorType.PLANT_MONITORITEM_ENERGY_CODE); string unit = energyMt.unit; Cn.Loosoft.Zhisou.SunPower.Common.ChartData chartData = PlantChartService.GetInstance().MMDDChartBypList(new List<Plant> { plant }, startDate, endDate, chartType, unit); reportData = JsonUtil.convertToJson(chartData, typeof(Cn.Loosoft.Zhisou.SunPower.Common.ChartData)); } else { ApiError appError = new ApiError(ApiError.plantnoexist, Resources.SunResource.CHART_PLANT_DONT_EXISTED); reportData = JsonUtil.convertToJson(appError, typeof(ApiError)); } return Content(reportData); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure <HotelInfo>(Configuration.GetSection("Info")); services.Configure <HotelOptions>(Configuration); services.AddScoped <IRoomService, DefaultRoomService>(); services.AddScoped <IOpeningService, DefaultOpeningService>(); services.AddScoped <IBookingService, DefaultBookingService>(); services.AddScoped <IDateLogicService, DefaultDateLogicService>(); services.Configure <PagingOptions>(Configuration.GetSection("DefaultPagingOptions")); //Use in-memory database for quick dev and testing //swap with real databse for production services.AddDbContext <HotelApiDbContext>(options => options.UseInMemoryDatabase("LocalHotel")); services.AddMvc(options => { options.Filters.Add <JsonExceptionFilter>(); options.Filters.Add <RequireHttpsOrCloseAttribute>(); options.Filters.Add <LinkRewritingFilter>(); } ).SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddRouting(options => options.LowercaseUrls = true); services.AddApiVersioning(options => { options.DefaultApiVersion = new ApiVersion(1, 0); options.ApiVersionReader = new MediaTypeApiVersionReader(); options.AssumeDefaultVersionWhenUnspecified = true; options.ReportApiVersions = true; options.ApiVersionSelector = new CurrentImplementationApiVersionSelector(options); }); services.AddAutoMapper( options => options.AddProfile <MappingProfile>()); services.Configure <ApiBehaviorOptions>(options => { options.InvalidModelStateResponseFactory = context => { var errorResponse = new ApiError(context.ModelState); return(new BadRequestObjectResult(errorResponse)); }; }); services.AddCors(options => { options.AddPolicy("AllowApp", //policy=> policy.WithOrigins("https://example.com") //create a white list for prodution environment. policy => policy.AllowAnyOrigin()); // allowing all for dev }); }
/// <summary> /// 按照sn取得对应时区 /// add by qhb in 20120831 /// </summary> /// <param name="sn">sn</param> /// <param name="app_key">第三方应用唯一key</param> /// <param name="call_id">请求序号</param> /// <param name="sig">签名</param> /// <param name="v">api版本</param> /// <param name="format">返回结果格式,暂时值支持json</param> /// <param name="lan">语言环境,暂时只支持中英文</param> /// <returns></returns> public ActionResult SnTimezone(string sn, string app_key, string call_id, string sig, string v, string format, string lan) { setlan(lan); int collectorId = CollectorInfoService.GetInstance().getCollectorIdbyCode(sn); PlantUnit plantUnit = PlantUnitService.GetInstance().GetPlantUnitByCollectorId(collectorId); string reportData = string.Empty; if (plantUnit != null) { Plant plant = PlantService.GetInstance().GetPlantInfoById(plantUnit.plantID); if (plant == null) { ApiError appError = new ApiError(ApiError.plantnoexist, Resources.SunResource.CHART_PLANT_DONT_EXISTED); reportData = JsonUtil.convertToJson(appError, typeof(ApiError)); } else { PlantTimezoneVo plantTimezoneVo = new PlantTimezoneVo(); plantTimezoneVo.plantId = plant.id.ToString(); plantTimezoneVo.plantName = plant.name; plantTimezoneVo.timezoneCode = plant.timezone.ToString(); plantTimezoneVo.timezoneName = Cn.Loosoft.Zhisou.SunPower.Common.TimeZone.GetText(plant.timezone); reportData = JsonUtil.convertToJson(plantTimezoneVo, typeof(PlantTimezoneVo)); } } else { ApiError appError = new ApiError(ApiError.plantnoexist, Resources.SunResource.CHART_PLANT_DONT_EXISTED); reportData = JsonUtil.convertToJson(appError, typeof(ApiError)); } return Content(reportData); }
public OrderCloudIntegrationException(ApiError error) { ApiError = error; }
/// <param name='data'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ApiErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse> CreateWithHttpMessagesAsync(PostData data = default(PostData), Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (data != null) { data.Validate(); } string apiVersion = "2018-07-16"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("data", data); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Create", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "api/default-channels").ToString(); List <string> _queryParameters = new List <string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if (data != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(data, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json-patch+json; charset=utf-8"); } // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 201) { var ex = new ApiErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ApiError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ApiError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public void Should_deserialize_all_error_strucutures_correctly(string content, ApiError expected) { var error = JsonConvert.DeserializeObject <ApiError>(content); error.ShouldBeEquivalentTo(expected); }
private Task HandleExceptionAsync(HttpContext context, System.Exception exception) { ApiError apiError = null; int code = 0; if (exception is ApiException) { var ex = exception as ApiException; if (ex.IsModelValidatonError) { apiError = new ApiError(ResponseMessageEnum.ValidationError.GetDescription(), ex.Errors) { ReferenceErrorCode = ex.ReferenceErrorCode, ReferenceDocumentLink = ex.ReferenceDocumentLink, }; _logger.Log(LogLevel.Warning, exception, $"[{ex.StatusCode}]: {ResponseMessageEnum.ValidationError.GetDescription()}"); } else { apiError = new ApiError(ex.Message) { ReferenceErrorCode = ex.ReferenceErrorCode, ReferenceDocumentLink = ex.ReferenceDocumentLink, }; _logger.Log(LogLevel.Warning, exception, $"[{ex.StatusCode}]: {ResponseMessageEnum.Exception.GetDescription()}"); } code = ex.StatusCode; context.Response.StatusCode = code; } else if (exception is UnauthorizedAccessException) { apiError = new ApiError(ResponseMessageEnum.UnAuthorized.GetDescription()); code = (int)HttpStatusCode.Unauthorized; context.Response.StatusCode = code; _logger.Log(LogLevel.Warning, exception, $"[{code}]: {ResponseMessageEnum.UnAuthorized.GetDescription()}"); } else { var exceptionMessage = ResponseMessageEnum.Unhandled.GetDescription(); #if !DEBUG var message = exceptionMessage; string stackTrace = null; #else var message = $"{ exceptionMessage } { exception.GetBaseException().Message }"; string stackTrace = exception.StackTrace; #endif apiError = new ApiError(message) { Details = stackTrace }; code = (int)HttpStatusCode.InternalServerError; context.Response.StatusCode = code; _logger.Log(LogLevel.Error, exception, $"[{code}]: {exceptionMessage}"); } var jsonString = ConvertToJSONString(GetErrorResponse(code, apiError)); context.Response.ContentType = "application/json"; return(context.Response.WriteAsync(jsonString)); }
public void LoginFailure(ApiError error) { UnityEngine.Debug.Log("code=" + error.code + " msg=" + error.message); }
public override void OnException(ExceptionContext context) { Debugger.Break(); int statusCode; ApiError apiError = null; switch (context.Exception) { case ApiException apiException: // handle explicit 'known' API errors context.Exception = null; apiError = new ApiError(apiException.Message) { Errors = apiException.Errors, Detail = apiException.Detail }; statusCode = apiException.StatusCode; break; case InvalidModelStateException invalidModelStateException: apiError = new ApiError(invalidModelStateException.Errors, invalidModelStateException.Message); statusCode = invalidModelStateException.StatusCode; break; case DbSaveFailedException dbSaveFailedException: apiError = new ApiError(dbSaveFailedException.Message); statusCode = dbSaveFailedException.StatusCode; break; case EntityNotFoundException entityNotFoundException: apiError = new ApiError(entityNotFoundException.Message); statusCode = entityNotFoundException.StatusCode; break; case EntityConflictException entityConflictException: apiError = new ApiError(entityConflictException.Message); statusCode = entityConflictException.StatusCode; break; case UnauthorizedAccessException _: apiError = new ApiError("Unauthorized Access"); statusCode = 401; break; default: { // Unhandled errors #if !DEBUG var msg = "An unhandled error occurred."; string stack = null; #else var msg = context.Exception.GetBaseException().Message; string stack = context.Exception.StackTrace; #endif apiError = new ApiError(msg) { Detail = stack }; statusCode = 500; _logger.LogError("Unhandled exception: {Exception})", context.Exception); break; } } context.HttpContext.Response.ContentType = "application/problem+json"; context.HttpContext.Response.StatusCode = statusCode; // always return a JSON result context.Result = new JsonResult(apiError); base.OnException(context); }
private async Task UpdateContextResponse(HttpContext context, object currentBodyObject, ApiError error = null) { var result = new ApiResponse <object>( (HttpStatusCode)context.Response.StatusCode, apiRequestContext.Id, currentBodyObject, error); context.Response.ContentType = "application/json"; await context.Response.WriteAsync(JsonConvert.SerializeObject(result, settings)); }
protected ApiException(HttpStatusCode statusCode, ApiError apiError, Exception innerException) : base(null, innerException) { StatusCode = statusCode; ApiError = apiError ?? throw new ArgumentNullException(nameof(apiError), "ApiError can't be null"); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure <ApiInfo>(Configuration.GetSection("Info")); services.Configure <PagingOptions>(Configuration.GetSection("DefaultPagingOptions")); services.AddScoped <IBSWordService, DefaultBSWordService>(); services.AddScoped <IUsersService, DefaultUserService>(); services.AddDbContextPool <BSBingoApiDbContext>(options => { options.UseInMemoryDatabase("bsworddb"); }); services.AddDbContextPool <UserDabaseContext>(options => { options.UseInMemoryDatabase("identity"); options.UseOpenIddict <Guid>(); }); services.AddOpenIddict() .AddCore(options => { options.UseEntityFrameworkCore() .UseDbContext <UserDabaseContext>() .ReplaceDefaultEntities <Guid>(); }) .AddServer(options => { options.UseMvc(); options.EnableTokenEndpoint("/token"); options.AllowPasswordFlow(); options.AcceptAnonymousClients(); }) .AddValidation(); services.Configure <IdentityOptions>(options => { options.ClaimsIdentity.UserNameClaimType = OpenIdConnectConstants.Claims.Name; options.ClaimsIdentity.UserIdClaimType = OpenIdConnectConstants.Claims.Subject; options.ClaimsIdentity.RoleClaimType = OpenIdConnectConstants.Claims.Role; }); services.AddAuthentication(options => { options.DefaultScheme = OpenIddictValidationDefaults.AuthenticationScheme; }); services.AddAuthorization(options => { options.AddPolicy("ViewAllUsersPolicy", p => p.RequireAuthenticatedUser().RequireRole("Admin")); }); services.AddMvc(options => { options.Filters.Add <JsonExceptionFilter>(); options.Filters.Add <RequireHttpsOrCloseAttribute>(); options.Filters.Add <LinkRewritingFilter>(); }) .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddRouting(options => options.LowercaseUrls = true); services.AddApiVersioning(options => { options.DefaultApiVersion = new ApiVersion(1, 0); options.ApiVersionReader = new MediaTypeApiVersionReader(); options.AssumeDefaultVersionWhenUnspecified = true; options.ReportApiVersions = true; options.ApiVersionSelector = new CurrentImplementationApiVersionSelector(options); }); services.AddCors(options => { options.AddPolicy("AllowMyApp", policy => policy.AllowAnyOrigin()); }); // Add ASP.NET Core identity AddIdentityCoreServices(services); services.AddAutoMapper(options => options.AddProfile <MappingProfile>()); services.Configure <ApiBehaviorOptions>(options => { options.InvalidModelStateResponseFactory = context => { var errorResponse = new ApiError(context.ModelState); return(new BadRequestObjectResult(errorResponse)); }; }); }
internal static VirtualMachineScaleSetRollingUpgradeData DeserializeVirtualMachineScaleSetRollingUpgradeData(JsonElement element) { IDictionary <string, string> tags = default; AzureLocation location = default; ResourceIdentifier id = default; string name = default; ResourceType type = default; SystemData systemData = default; Optional <RollingUpgradePolicy> policy = default; Optional <RollingUpgradeRunningStatus> runningStatus = default; Optional <RollingUpgradeProgressInfo> progress = default; Optional <ApiError> error = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("tags")) { Dictionary <string, string> dictionary = new Dictionary <string, string>(); foreach (var property0 in property.Value.EnumerateObject()) { dictionary.Add(property0.Name, property0.Value.GetString()); } tags = dictionary; continue; } if (property.NameEquals("location")) { location = property.Value.GetString(); continue; } if (property.NameEquals("id")) { id = new ResourceIdentifier(property.Value.GetString()); continue; } if (property.NameEquals("name")) { name = property.Value.GetString(); continue; } if (property.NameEquals("type")) { type = property.Value.GetString(); continue; } if (property.NameEquals("systemData")) { systemData = JsonSerializer.Deserialize <SystemData>(property.Value.ToString()); continue; } if (property.NameEquals("properties")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } foreach (var property0 in property.Value.EnumerateObject()) { if (property0.NameEquals("policy")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } policy = RollingUpgradePolicy.DeserializeRollingUpgradePolicy(property0.Value); continue; } if (property0.NameEquals("runningStatus")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } runningStatus = RollingUpgradeRunningStatus.DeserializeRollingUpgradeRunningStatus(property0.Value); continue; } if (property0.NameEquals("progress")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } progress = RollingUpgradeProgressInfo.DeserializeRollingUpgradeProgressInfo(property0.Value); continue; } if (property0.NameEquals("error")) { if (property0.Value.ValueKind == JsonValueKind.Null) { property0.ThrowNonNullablePropertyIsNull(); continue; } error = ApiError.DeserializeApiError(property0.Value); continue; } } continue; } } return(new VirtualMachineScaleSetRollingUpgradeData(id, name, type, systemData, tags, location, policy.Value, runningStatus.Value, progress.Value, error.Value)); }
internal T HandleXmlResponse <T>(RequestContext context) where T : class, new() { T result = null; ApiError errorResult = null; // create serializers // it may fail if attributes are wrong XmlSerializer serializer, errorSerializer; try { serializer = new XmlSerializer(typeof(T)); errorSerializer = new XmlSerializer(typeof(ApiError)); } catch (Exception ex) { throw FX.InternalException("SerializerCtor", ex, ex.Message); } if (validHttpCodes.Contains(context.HttpStatusCode)) { // the HTTP code matches a success response try { result = (T)serializer.Deserialize(context.ResponseStream); } catch (Exception ex) { var ex1 = FX.InternalException("SerializerDeserialize", ex, ex.Message); TryAttachContextDetails(context, ex1); throw ex1; } } else if (errorHttpCodes.Contains(context.HttpStatusCode)) { // the HTTP code matches a error response try { errorResult = (ApiError)serializer.Deserialize(context.ResponseStream); } catch (Exception ex) { var ex1 = FX.InternalException("SerializerDeserializeError", ex, ex.Message); TryAttachContextDetails(context, ex1); throw ex1; } { var ex1 = FX.ApiException("ApiErrorResult", errorResult.Status, errorResult.Message, context.UrlPath); TryAttachContextDetails(context, null); ex1.Data.Add("ErrorResult", errorResult); if (errorResult != null) { if (errorResult.Status == 401) { ex1.Data["ShouldRenewToken"] = true; } } throw ex1; } } else { // unknown HTTP code var ex1 = FX.ApiException("ApiUnknownHttpCode", context.HttpStatusCode); TryAttachContextDetails(context, null); throw ex1; } if (result == null) { var ex1 = FX.ApiException("ApiEmptyResult"); TryAttachContextDetails(context, null); throw ex1; } return(result); }