public async Task <List <TeamDto> > GetTeamsAsync() { var availableLeagues = _mapper.Map <List <AvailableLeague>, List <LeagueDto> >(_configuration .FootballDataOrgAvailableLeagues.ToList()); var availableExternalLeaguesIds = await _leagueManager.GetExternalLeaguesIds(availableLeagues, ExternalSourceEnum.FootballDataOrg); List <TeamDto> teams = new List <TeamDto>(); foreach (var leaguesId in availableExternalLeaguesIds) { try { List <TeamDto> teamsOfCurrentLeague = await GetTeamsByCompetitionAsync(leaguesId); teams.AddRange(teamsOfCurrentLeague); } catch (FlurlHttpException ex) { //TODO: переделать таймаут перед вызовом каждого метода, используя данные ответа с апи в хедере!!! ErrorContract error = await ex.GetResponseJsonAsync <ErrorContract>(); if (error.ErrorCode == 429) { Thread.Sleep(_sourceTimeOutInSeconds * 1000); List <TeamDto> teamsOfCurrentLeague = await GetTeamsByCompetitionAsync(leaguesId); teams.AddRange(teamsOfCurrentLeague); } } } return(teams.Distinct(new TeamDtoComparer()).ToList()); }
public Task <HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { var errorContract = new ErrorContract { Message = Message, Errors = Errors }; var problemHeader = new MediaTypeHeaderValue("application/api-problem+json"); var result = new FormattedContentResult <ErrorContract>( Status, errorContract, _configuration.Formatters.JsonFormatter, problemHeader, _controller); //var contentResult = _controller != null // ? new FormattedContentResult<ErrorContract>( // Status, errorContract, _configuration.Formatters.JsonFormatter, problemHeader, _controller) // : new FormattedContentResult<ErrorContract>( // Status, errorContract, _configuration.Formatters.JsonFormatter, problemHeader, _request); return(result.ExecuteAsync(cancellationToken)); }
protected IActionResult AjaxErrorResponse(string message, HttpStatusCode httpStatusCode = HttpStatusCode.InternalServerError) { var result = new ErrorContract { ErrorMessage = message }; return(new JsonResult(result) { StatusCode = (int)httpStatusCode }); }
public void UpdateDispatchAsReceived(long dispatchId, DateTime receivedDateTime) { try { UpdateMessageDispatchServiceBl.UpdateDispatchAsReceived(dispatchId, receivedDateTime); } catch (Exception exception) { ErrorContract error = new ErrorContract(exception.Message, StatusList.PROCESS_ERROR); WriteErrorLog("Error encountered when executing Update-dispatch-As-Received.", exception); throw new FaultException <ErrorContract>(error); } }
public UserInfoContract GetUserMatchingUsernamePassword(string username, string password) { try { RetrieveUserServiceBl retrieveUserBL = new RetrieveUserServiceBl(); return(retrieveUserBL.GetUserMatchingUsernamePassword(username, password)); } catch (Exception exception) { ErrorContract error = new ErrorContract(exception.Message, StatusList.PROCESS_ERROR); throw new FaultException <ErrorContract>(error); } }
public List <UserInfoContract> GetAllUsers() { try { RetrieveUserServiceBl retrieveUserBL = new RetrieveUserServiceBl(); return(retrieveUserBL.GetAllUsers()); } catch (Exception exception) { ErrorContract error = new ErrorContract(exception.Message, StatusList.PROCESS_ERROR); throw new FaultException <ErrorContract>(error); } }
public async Task Invoke(HttpContext context) { try { await m_next(context); } catch (HttpErrorCodeException exception) { int statusCode; switch (exception.StatusCode) { case HttpStatusCode.Unauthorized: statusCode = StatusCodes.Status401Unauthorized; break; case HttpStatusCode.Forbidden: statusCode = StatusCodes.Status403Forbidden; break; default: statusCode = StatusCodes.Status502BadGateway; break; } await ReExecute(context, statusCode); } catch (MainServiceException exception) { if (IsAjaxRequest(context.Request)) { context.Response.StatusCode = (int)exception.StatusCode; var result = new ErrorContract { ErrorMessage = exception.Description }; await context.Response.WriteAsync(JsonConvert.SerializeObject(result, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() })); } else { await ReExecute(context, (int)exception.StatusCode, exception.Description); } } }
/// <summary> /// Вызывается при переходе обработки запроса данному звену /// </summary> public async Task Invoke(HttpContext httpContext) { try { await _next(httpContext); } catch (Exception exception) { httpContext.Response.StatusCode = StatusCodes.Status400BadRequest; httpContext.Response.ContentType = MediaTypeNames.Application.Json; var error = new ErrorContract() { Error = !String.IsNullOrEmpty(exception.Message) ? exception.Message : exception.ToString() }; await httpContext.Response.WriteAsync(JsonSerializer.Serialize(error)); } }
public List <MessageDispatchInfoContract> GetMessageDipatchesBetweenSenderReceiver(IRetrieveMessageRequest messageRequest) { try { RetrieveMessageServiceBl retrieveMessageBL = new RetrieveMessageServiceBl(); return(retrieveMessageBL.GetMsgDispatchesBetweenSenderReceiver(messageRequest)); } catch (TokenValidationException exception) { WriteErrorLog("Encontered a token validation error getting messages between sender and receiver.", exception); ErrorContract error = new ErrorContract(exception.Message, StatusList.VALIDATION_ERROR); throw new FaultException <ErrorContract>(error); } catch (Exception exception) { WriteErrorLog("Error encountered when Getting-Message-Dispatches-Between-Sender-Receiver.", exception); ErrorContract error = new ErrorContract(exception.Message, StatusList.PROCESS_ERROR); throw new FaultException <ErrorContract>(error); } }
public List <MessageDispatchInfoContract> GetMessagesSentToUser(IRetrieveMessageRequest messageRequest) { try { RetrieveMessageServiceBl retrieveMessageBL = new RetrieveMessageServiceBl(); return(retrieveMessageBL.GetMessagesSentToUser(messageRequest)); } catch (TokenValidationException exception) { WriteErrorLog("Encontered a token validation error getting messages set to user.", exception); ErrorContract error = new ErrorContract(exception.Message, StatusList.VALIDATION_ERROR); throw new FaultException <ErrorContract>(error); } catch (Exception exception) { WriteErrorLog("Error encountered when getting messages-sent-to-user.", exception); ErrorContract error = new ErrorContract(exception.Message, StatusList.PROCESS_ERROR); throw new FaultException <ErrorContract>(error); } }
public MessageRequestTokenContract CreateMessage(MessageContract message) { try { CreateMessageBl createMessageL = new CreateMessageBl(); return(createMessageL.CreateMessage(message)); } catch (TokenValidationException exception) { WriteErrorLog("Encontered a token validation error when trying to create a message.", exception); ErrorContract error = new ErrorContract(exception.Message, StatusList.VALIDATION_ERROR); throw new FaultException <ErrorContract>(error); } catch (Exception exception) { WriteErrorLog("Encontered an error when trying to create a message.", exception); MessageRequestTokenContract tokenContract = CreateMessageStateTokenContract(MessageReceivedState.FailedToProcessRequest, exception.Message); throw new FaultException <MessageRequestTokenContract>(tokenContract); } }
public async Task <AzureOperationResponse <SqlPoolConnectionPolicy> > GetWithHttpMessagesAsync(string resourceGroupName, string workspaceName, string sqlPoolName, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.ApiVersion != null) { if (Client.ApiVersion.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "Client.ApiVersion", 1); } } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.SubscriptionId != null) { if (Client.SubscriptionId.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "Client.SubscriptionId", 1); } } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } if (!System.Text.RegularExpressions.Regex.IsMatch(resourceGroupName, "^[-\\w\\._\\(\\)]+$")) { throw new ValidationException(ValidationRules.Pattern, "resourceGroupName", "^[-\\w\\._\\(\\)]+$"); } } if (workspaceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "workspaceName"); } if (sqlPoolName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "sqlPoolName"); } string connectionPolicyName = "default"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("workspaceName", workspaceName); tracingParameters.Add("sqlPoolName", sqlPoolName); tracingParameters.Add("connectionPolicyName", connectionPolicyName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", 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.Synapse/workspaces/{workspaceName}/sqlPools/{sqlPoolName}/connectionPolicies/{connectionPolicyName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{workspaceName}", System.Uri.EscapeDataString(workspaceName)); _url = _url.Replace("{sqlPoolName}", System.Uri.EscapeDataString(sqlPoolName)); _url = _url.Replace("{connectionPolicyName}", System.Uri.EscapeDataString(connectionPolicyName)); List <string> _queryParameters = new List <string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.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 ErrorContractException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorContract _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ErrorContract>(_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 <SqlPoolConnectionPolicy>(); _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 <SqlPoolConnectionPolicy>(_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); }
/// <summary> /// All operations /// </summary> /// <remarks> /// Get all available operations /// </remarks> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorContractException"> /// 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 <AzureOperationResponse <IList <AvailableRpOperation> > > ListWithHttpMessagesAsync(Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); 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("/") ? "" : "/")), "providers/Microsoft.Synapse/operations").ToString(); 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 ErrorContractException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorContract _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ErrorContract>(_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 <IList <AvailableRpOperation> >(); _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 <IList <AvailableRpOperation> >(_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); }
/// <summary> /// Check name availability /// </summary> /// <remarks> /// Check whether a workspace name is available /// </remarks> /// <param name='request'> /// The check request /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorContractException"> /// 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 <HttpOperationResponse <CheckNameAvailabilityResponse> > CheckNameAvailabilityWithHttpMessagesAsync(CheckNameAvailabilityRequest request, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (Client.ApiVersion != null) { if (Client.ApiVersion.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "Client.ApiVersion", 1); } } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.SubscriptionId != null) { if (Client.SubscriptionId.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "Client.SubscriptionId", 1); } } if (request == null) { throw new ValidationException(ValidationRules.CannotBeNull, "request"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("request", request); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CheckNameAvailability", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Synapse/checkNameAvailability").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List <string> _queryParameters = new List <string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.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 (request != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(request, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // 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 ErrorContractException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorContract _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject <ErrorContract>(_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 <CheckNameAvailabilityResponse>(); _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 <CheckNameAvailabilityResponse>(_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); }
private void ThrowEntityErrorMessage(string message, int status) { ErrorContract error = new ErrorContract(message, status); throw new FaultException <ErrorContract>(error); }
static async Task Main(string[] args) { Console.WriteLine("Starting..."); int port; bool meadow = true; if (!meadow) { port = 7545; } else { // Bootstrap our meadow test node server. var testNode = new Meadow.TestNode.TestNodeServer(); // Print our undefined rpc methods. var undefinedRpcMethods = testNode.GetUndefinedRpcMethods(); Console.WriteLine("Warning: following RPC methods are not defined: \n" + string.Join(", ", undefinedRpcMethods.Select(r => r.Value()))); // Start up the server and obtain the port. await testNode.RpcServer.StartAsync(); port = testNode.RpcServer.ServerPort; } async Task <Exception> GetExecutionTraceException(IJsonRpcClient rpcClient, JsonRpcError error) { if (meadow) { var executionTrace = await rpcClient.GetExecutionTrace(); var traceAnalysis = new ExecutionTraceAnalysis(executionTrace); // Build our aggregate exception var aggregateException = traceAnalysis.GetAggregateException(error.ToException()); return(aggregateException); } else { if (error != null) { throw error.ToException(); } else { throw new Exception("Execution exception"); } } } // Connect our client to the server. var client = JsonRpcClient.Create( new Uri($"http://{IPAddress.Loopback}:{port}"), defaultGasLimit: 6_000_000, defaultGasPrice: 0); client.ErrorFormatter = GetExecutionTraceException; // If we're testing meadow, we enable special coverage/tracing options. if (meadow) { await client.SetCoverageEnabled(true); await client.SetTracingEnabled(true); } //var missingConstructorContract = await MissingConstructorChild.New(client); //var someNum = await missingConstructorContract.someNum().Call(); #region ErrorContract // Try deploying the error generating contract and test some calls. var errorContract = await ErrorContract.New(client, new TransactionParams { Gas = 4712388 }); //await errorContract.doRevert().ExpectRevertTransaction(); //await errorContract.doAssert().ExpectRevertTransaction(); //await errorContract.doThrow().ExpectRevertCall(); #endregion #region Inheritance Tests // Test inheritance with an inherited contract. var inheritedContract = await InheritedContract.New(client, new TransactionParams { Gas = 4712388 }); await inheritedContract.testFunction(); await inheritedContract.testFunctionWithInheritedModifier(); // Test inheritance with a seperate file which we inherited from. var multiInheritedContract = await MultifileInheritedContract.New(client, new TransactionParams { Gas = 4712388 }); await multiInheritedContract.testFunction(); await multiInheritedContract.testFunctionWithInheritedModifier(); #endregion try { await FailDeploymentContract.New(client); } catch { } #region Callstack Tests // Try throwing asserts in further call depth and spanning more than one file. await multiInheritedContract.testInheritedAssertThrow().ExpectRevertTransaction(); if (meadow) { // Test parsing an execution trace of the last call/transaction. var executionTrace = await client.GetExecutionTrace(); ExecutionTraceAnalysis traceAnalysis = new ExecutionTraceAnalysis(executionTrace); // Testing: Build our aggregate exception var aggregateException = traceAnalysis.GetAggregateException(); try { throw aggregateException; } catch { } } #endregion #region ExampleContract Tests // Deploy our main example contract var exContract = await ExampleContract.New($"TestName", true, 34, client, new TransactionParams { Gas = 4712388 }); await exContract.testRevert().ExpectRevertTransaction(); await exContract.testBranchCoverage().ExpectRevertTransaction(); if (meadow) { // Test parsing an execution trace of the last call/transaction. var executionTrace = await client.GetExecutionTrace(); ExecutionTraceAnalysis traceAnalysis = new ExecutionTraceAnalysis(executionTrace); // Testing: Build our aggregate exception var aggregateException = traceAnalysis.GetAggregateException(); try { throw aggregateException; } catch { } } // Test the modexp precompile. var modExpTestBytes = await exContract.testModExp( BigIntegerConverter.GetBytes(BigInteger.Parse("1212121323543453245345678346345737475734753745737774573475377734577", CultureInfo.InvariantCulture)), BigIntegerConverter.GetBytes(BigInteger.Parse("3", CultureInfo.InvariantCulture)), BigIntegerConverter.GetBytes(BigInteger.Parse("4345328123928357434573234217343477", CultureInfo.InvariantCulture))) .Call(); var modExpTest = BigIntegerConverter.GetBigInteger(modExpTestBytes, false, modExpTestBytes.Length); // should be 856753145937825219130387866259147 // Test events var eventTest = await exContract.emitDataEvent(1, 2, 3).TransactionReceipt(); var eventLogFirst = eventTest.FirstEventLog <ExampleContract.DataEvent>(); var eventLogLast = eventTest.LastEventLog <ExampleContract.DataEvent>(); var eventLogAll = eventTest.EventLogs <ExampleContract.DataEvent>(); var eventLogsBase = eventTest.EventLogs(); // Test for chris var result = await exContract.getFirstByteFromByte32(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32 }).Call(); // Try testing branch coverage (which ends in an assert being thrown) await exContract.testBranchCoverage().ExpectRevertTransaction(); //await exContract.noopFunc(); var echoGasEst = await exContract.echoInt24(34).EstimateGas(); await exContract.testInstructions1().TransactionReceipt(); var transactionReceipt = await exContract.echoInt24(22).TransactionReceipt(); #endregion #region Performance Tests // Define start time for an execution loop to test performance of a few basic calls. DateTime start = DateTime.Now; DateTime iteration = start; // Note: Change the loop condition here as needed. for (int i = 0; i < 1; i++) { var addr = await exContract.echoAddress(new Address(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 })); var int24Test = await exContract.echoInt24(7777); var stringTest = await exContract.echoString("This is a string."); var enabledThingTest = await exContract.enabledThing(); var isNineTest = await exContract.myFunc(9); var givenName = await exContract.givenName(); // Precompile hash tests var sha256HashTest = await exContract.sha256str("hello world"); // should be 0xb94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9 var ripemd160HashTest = await exContract.ripemd160str("hello world"); // should be 0x98c615784ccb5fe5936fbc0cbe9dfdb408d92f0f // This ECRecover test should yield 0x75c8aa4b12bc52c1f1860bc4e8af981d6542cccd. This test data is taken from SigningTests.cs var ecRecoverTest = await exContract.testECRecover( new byte[] { 0xc9, 0xf1, 0xc7, 0x66, 0x85, 0x84, 0x5e, 0xa8, 0x1c, 0xac, 0x99, 0x25, 0xa7, 0x56, 0x58, 0x87, 0xb7, 0x77, 0x1b, 0x34, 0xb3, 0x5e, 0x64, 0x1c, 0xca, 0x85, 0xdb, 0x9f, 0xef, 0xd0, 0xe7, 0x1f }, 0x1c, BigIntegerConverter.GetBytes(BigInteger.Parse("68932463183462156574914988273446447389145511361487771160486080715355143414637", CultureInfo.InvariantCulture)), BigIntegerConverter.GetBytes(BigInteger.Parse("47416572686988136438359045243120473513988610648720291068939984598262749281683", CultureInfo.InvariantCulture))); Console.WriteLine($"#{i}: {DateTime.Now - iteration}"); iteration = DateTime.Now; } DateTime end = DateTime.Now; #endregion // If this is meadow, we do special post-execution tasks. if (meadow) { // Test obtaining coverage maps, disabling them, clearing them. var coverageMaps = await client.GetAllCoverageMaps(); await client.SetCoverageEnabled(false); await client.ClearCoverage(); // Obtain our generated solc data, create a report, and open it. var solcData = GeneratedSolcData.Default.GetSolcData(); // Match coverage contract addresses with deployed contracts that the client keeps track of. var contractInstances = GeneratedSolcData.Default.MatchCoverageData(coverageMaps); var reportPath = Path.GetFullPath("Report"); MiscUtil.ResetDirectory(reportPath); ReportGenerator.CreateReport(GeneratedSolcData.Default.SolidityCompilerVersion, contractInstances, solcData.SolcSourceInfo, solcData.SolcBytecodeInfo, null, null, reportPath); MiscUtil.OpenBrowser(Path.Join(reportPath, ReportGenerator.REPORT_INDEX_FILE)); } // Output our execution loop time. Console.WriteLine($"Total Time: {end - start}"); Console.ReadLine(); }