Exemplo n.º 1
0
            public void SetsSpecifiedExceptionMessageAndStatusCode()
            {
                var exception = new ApiException("Shit still broke", HttpStatusCode.Gone);

                Assert.Equal("Shit still broke", exception.Message);
                Assert.Equal(HttpStatusCode.Gone, exception.StatusCode);
            }
Exemplo n.º 2
0
        protected void HandleBadRequest(ApiException apiException)
        {
            if (apiException.StatusCode == HttpStatusCode.BadRequest)
            {
                //There are, at the moment, two types of bad requests: when signing in, JsonData might contain an error and error_description field.
                //When returning a BadRequest from the Web API, we'll get a message and ModelState error dictionary back.

                var badRequestData = JsonConvert.DeserializeObject<JsonBadRequest>(apiException.JsonData);

                if (badRequestData.ModelState != null)
                {
                    foreach (var modelStateItem in badRequestData.ModelState)
                    {
                        foreach (var message in modelStateItem.Value)
                        {
                            ModelState.AddModelError(modelStateItem.Key, message);
                        }
                    }
                }

                //When an error occurs while signing in, Error equals "invalid_grant" and ErrorDescription will contain more detail.
                //This error is being set in the Web API project in the YetAnotherTodo.WebApi.Providers.ApplicationOAuthProvider class
                if (string.Equals(badRequestData.Error, "invalid_grant"))
                {
                    ModelState.AddModelError("", badRequestData.ErrorDescription);
                }
            }
        }
 public static Exception GetCustomTestException(ApiException apiException, string currentClassName, string currentMethodName, HttpStatusCode expectedCode)
 {
     var correlationId = apiException.CorrelationId;
     var printableError = string.Format("{0} || {1}.{2} {3} | Error: {4} | CorrelationId: {5}",
         apiException.HttpStatusCode.ToString(),
         currentClassName, currentMethodName,
         apiException.ApplicationName ?? "", apiException.Message ?? "",
         correlationId
         );
     Debug.WriteLine(printableError);
     switch (apiException.HttpStatusCode)
     {
         case HttpStatusCode.NotFound:
             return null; // or use new Exception("No Item Found with API transaction.") ;
         case HttpStatusCode.NoContent:
             return null; // or use new Exception("No Content was returned by the API") ;
         case HttpStatusCode.Unauthorized:
             return new Exception("Unauthorized Access To this API, Please check your behaviors and possibly re-install the application to this store to pick up changes.");
         case HttpStatusCode.Forbidden:
             return new Exception("Forbidden Access To this API, Please check your SiteId settings and possibly re-install the application to this store.");
         default:
             return new Exception(String.Format("Test Fails - [{0}:expected {1}] but the actual return code is {2}. {3}",
                 currentMethodName,
                 expectedCode.ToString(),
                 apiException.HttpStatusCode,
                 printableError));
     }
 }
Exemplo n.º 4
0
            public void SetsSpecifiedExceptionMessageAndInnerException()
            {
                var inner = new InvalidOperationException();

                var exception = new ApiException("Shit broke", inner);

                Assert.Equal("Shit broke", exception.Message);
                Assert.Same(inner, exception.InnerException);
            }
		protected virtual ErrorMessage CreateErrorMessage(ApiException ae, Exception e)
		{
			HttpContext context = HttpContext.Current;
			return new ErrorMessage
			{
				Message = ae.Message,
				ErrorCode = (int)ae.StatusCode,
				Exception = (context != null && context.IsDebuggingEnabled) ? CreateErrorException(e) : null
			};
		}
Exemplo n.º 6
0
            public void CreatesGitHubErrorIfResponseMessageIsNotValidJson(string responseContent)
            {
                var response = new Response(
                    HttpStatusCode.GatewayTimeout,
                    responseContent,
                    new Dictionary<string, string>(),
                    "application/json");

                var exception = new ApiException(response);

                Assert.Equal(responseContent, exception.ApiError.Message);
                Assert.Equal(HttpStatusCode.GatewayTimeout, exception.StatusCode);
            }
            public void CreatesGitHubErrorIfResponseMessageIsNotValidJson(string responseContent)
            {
                var response = new ApiResponse<object>
                {
                    Body = responseContent,
                    StatusCode = HttpStatusCode.GatewayTimeout
                };

                var exception = new ApiException(response);

                Assert.Equal(responseContent, exception.ApiError.Message);
                Assert.Equal(HttpStatusCode.GatewayTimeout, exception.StatusCode);
            }
        private static bool ContainsNameEmptyValidationError(ApiException ex)
        {
            ex.StatusCode.Should().Be(HttpStatusCode.BadRequest);

            var validationErrors = ex.GetContentAs<IDictionary<string, IDictionary<string, string[]>>>();
            validationErrors.Should().HaveCount(1);
            validationErrors.First().Key.Should().Be("errors");
            validationErrors.First().Value.Should().HaveCount(1);
            validationErrors.First().Value.Should().ContainKey("name");
            validationErrors.First().Value.First().Value.Should().Contain("'Name' should not be empty.");
            
            return true;
        }
            public void CreatesEmptyGitHubErrorWhenResponseBodyIsNull()
            {
                var response = Substitute.For<IResponse>();
                response.Body.Returns("test");

                var exception = new ApiException();
                var anotherException = new ApiException(new ApiResponse<object> { Body = "message1" });
                var thirdException = new ApiException(new ApiResponse<object> { Body = "message2" });

                // It's fine if the message is null when there's no response body as long as this doesn't throw.
                Assert.Null(exception.ApiError.Message);
                Assert.Equal("message1", anotherException.ApiError.Message);
                Assert.Equal("message2", thirdException.ApiError.Message);
            }
Exemplo n.º 10
0
 public ValidationException(ApiException apiException)
     : base(apiException)
 {
     if (apiException.Elements != null && apiException.Elements.Any())
     {
         ValidationErrors = new List<ValidationError>();
         foreach (var ve in apiException
             .Elements
             .SelectMany(e => e.ValidationErrors))
         {
             ValidationErrors.Add(ve);
         }
     }
 }
Exemplo n.º 11
0
            public void CreatesGitHubErrorFromJsonResponse()
            {
                var response = new ApiResponse<object>
                {
                    Body = @"{""errors"":[{""code"":""custom"",""field"":""key"",""message"":""key is " +
                           @"already in use"",""resource"":""PublicKey""}],""message"":""Validation Failed""}",
                    StatusCode = HttpStatusCode.GatewayTimeout
                };

                var exception = new ApiException(response);

                Assert.Equal("Validation Failed", exception.ApiError.Message);
                Assert.Equal("key is already in use", exception.ApiError.Errors.First().Message);
                Assert.Equal(HttpStatusCode.GatewayTimeout, exception.StatusCode);
            }
Exemplo n.º 12
0
            public void CreatesGitHubErrorFromJsonResponse()
            {
                var response = new Response(
                    HttpStatusCode.GatewayTimeout,
                    @"{""errors"":[{""code"":""custom"",""field"":""key"",""message"":""key is " +
                           @"already in use"",""resource"":""PublicKey""}],""message"":""Validation Failed""}",
                    new Dictionary<string, string>(),
                    "application/json"
                );

                var exception = new ApiException(response);

                Assert.Equal("Validation Failed", exception.ApiError.Message);
                Assert.Equal("key is already in use", exception.ApiError.Errors.First().Message);
                Assert.Equal(HttpStatusCode.GatewayTimeout, exception.StatusCode);
            }
Exemplo n.º 13
0
		public static async Task EnsureSuccessAsync(HttpResponseMessage response, IApiContext apiContext)
		{
			if (!response.IsSuccessStatusCode)
			{
				var content = await response.Content.ReadAsStringAsync();
				ApiException exception;
				var htmlMediaType = new MediaTypeHeaderValue("text/html");
				if (response.Content.Headers.ContentType != null &&
					response.Content.Headers.ContentType.MediaType == htmlMediaType.MediaType)
				{
					var message = String.Format("Status Code {0}, Uri - {1}", response.StatusCode,
						response.RequestMessage.RequestUri.AbsoluteUri);
					exception = new ApiException(message, new Exception(content));
				}
				else
					exception = JsonConvert.DeserializeObject<ApiException>(content);
				exception.HttpStatusCode = response.StatusCode;
				exception.CorrelationId = HttpHelper.GetHeaderValue(Headers.X_VOL_CORRELATION, response.Headers);
				exception.ApiContext = apiContext;
				throw exception;
			}
		}
        public ValidationException(ApiException apiException)
            : base(apiException)
        {
            if (apiException.Elements != null && apiException.Elements.Any())
            {
                ValidationErrors = new List<ValidationError>();
                AccountNumbers = new List<string>();

                foreach (var ve in apiException
                    .Elements
                    .SelectMany(e => e.ValidationErrors))
                {
                    ValidationErrors.Add(ve);
                }

                foreach(var an in apiException
                    .Elements
                    .Select(e => e.AccountNumber))
                {
                    AccountNumbers.Add(an);
                }
            }
        }
Exemplo n.º 15
0
        /// <summary>
        /// Creates and send an HTTP request to the specified URL
        /// </summary>
        /// <param name="httpMethod">A valid HTTP method</param>
        /// <param name="url">Target URL</param>
        /// <param name="parameters">Optional request data</param>
        /// <returns>Response string</returns>
        /// <exception cref="ApiException">Thrown when an exception occurs at server</exception>
        /// <exception cref="NetworkException">Thrown when server is unreachable</exception>
        public static string SendRequest(string httpMethod, string url, Dictionary <string, object> parameters)
        {
            httpMethod = httpMethod.ToUpper();

            if (httpMethod == "GET")
            {
                url = AppendUrlParameters(url, parameters);
            }

            ConfigureTls();
            var webRequest = HttpWebRequestFactory(url);

            webRequest.Method      = httpMethod;
            webRequest.Credentials = new NetworkCredential(ApiKey, "");

            if (httpMethod != "GET" && parameters != null)
            {
                webRequest.ContentType = "application/json";
                using (var sw = new StreamWriter(webRequest.GetRequestStream()))
                {
                    sw.Write(Serializer.Serialize(parameters));
                    sw.Flush();
                }
            }

            try
            {
                string          result   = null;
                HttpWebResponse response = webRequest.GetResponse() as HttpWebResponse;
                using (var sr = new StreamReader(response.GetResponseStream()))
                {
                    result = sr.ReadToEnd();
                }

                return(result);
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError)
                {
                    string result   = null;
                    var    response = ex.Response as HttpWebResponse;
                    using (var sr = new StreamReader(response.GetResponseStream()))
                    {
                        result = sr.ReadToEnd();
                    }

                    if ((int)response.StatusCode == 429)
                    {
                        throw new TooManyRequestsException("Too Many Requests")
                              {
                                  HttpStatusCode  = (int)response.StatusCode,
                                  ResponsePayload = result
                              };
                    }

                    if ((int)response.StatusCode >= 400 && (int)response.StatusCode < 600)
                    {
                        dynamic resObj = Serializer.Deserialize <object>(result);

                        var msg = "";
                        try { msg = resObj.message; } catch {}
                        var exception = new ApiException(msg)
                        {
                            HttpStatusCode  = (int)response.StatusCode,
                            ResponsePayload = result,
                        };

                        try { exception.Type = resObj.type.ToString(); } catch {}
                        try { exception.Errors = resObj.errors.ToString(); } catch {}

                        try
                        {
                            exception.ErrorsDictionary =
                                Serializer.Deserialize <Dictionary <string, List <string> > >(resObj.errors.ToString());
                        } catch {}

                        throw exception;
                    }
                }

                throw new NetworkException("Could not connect to Moyasar service", ex);
            }
        }
Exemplo n.º 16
0
        /// <summary>
        /// Add a CustomerFeed that associates the feed with this customer for
        /// the LOCATION placeholder type.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="feed">The GMB feed.</param>
        void AddCustomerFeed(AdWordsUser user, Feed feed)
        {
            using (CustomerFeedService customerFeedService = (CustomerFeedService)user.GetService(
                       AdWordsService.v201802.CustomerFeedService)) {
                // Add a CustomerFeed that associates the feed with this customer for
                // the LOCATION placeholder type.
                CustomerFeed customerFeed = new CustomerFeed();
                customerFeed.feedId           = feed.id;
                customerFeed.placeholderTypes = new int[] { PLACEHOLDER_LOCATION };

                // Create a matching function that will always evaluate to true.
                Function        customerMatchingFunction = new Function();
                ConstantOperand constOperand             = new ConstantOperand();
                constOperand.type                   = ConstantOperandConstantType.BOOLEAN;
                constOperand.booleanValue           = true;
                customerMatchingFunction.lhsOperand = new FunctionArgumentOperand[] { constOperand };
                customerMatchingFunction.@operator  = FunctionOperator.IDENTITY;
                customerFeed.matchingFunction       = customerMatchingFunction;

                // Create an operation to add the customer feed.
                CustomerFeedOperation customerFeedOperation = new CustomerFeedOperation();
                customerFeedOperation.operand   = customerFeed;
                customerFeedOperation.@operator = Operator.ADD;

                // After the completion of the Feed ADD operation above the added feed
                // will not be available for usage in a CustomerFeed until the sync
                // between the AdWords and GMB accounts completes.  The loop below
                // will retry adding the CustomerFeed up to ten times with an
                // exponential back-off policy.
                CustomerFeed addedCustomerFeed = null;

                AdWordsAppConfig config = new AdWordsAppConfig();
                config.RetryCount = 10;

                ErrorHandler errorHandler = new ErrorHandler(config);
                try {
                    do
                    {
                        try {
                            CustomerFeedReturnValue customerFeedResult =
                                customerFeedService.mutate(
                                    new CustomerFeedOperation[] { customerFeedOperation });
                            addedCustomerFeed = customerFeedResult.value[0];

                            Console.WriteLine("Added CustomerFeed for feed ID {0} and placeholder type {1}",
                                              addedCustomerFeed.feedId, addedCustomerFeed.placeholderTypes[0]);
                            break;
                        } catch (AdWordsApiException e) {
                            ApiException apiException = (ApiException)e.ApiException;
                            foreach (ApiError error in apiException.errors)
                            {
                                if (error is CustomerFeedError)
                                {
                                    if ((error as CustomerFeedError).reason ==
                                        CustomerFeedErrorReason.MISSING_FEEDMAPPING_FOR_PLACEHOLDER_TYPE)
                                    {
                                        errorHandler.DoExponentialBackoff();
                                        errorHandler.IncrementRetriedAttempts();
                                    }
                                    else
                                    {
                                        throw;
                                    }
                                }
                            }
                        }
                    } while (errorHandler.HaveMoreRetryAttemptsLeft());
                    // OPTIONAL: Create a CampaignFeed to specify which FeedItems to use at
                    // the Campaign level.  This will be similar to the CampaignFeed in the
                    // AddSiteLinks example, except you can also filter based on the
                    // business name and category of each FeedItem by using a
                    // FeedAttributeOperand in your matching function.

                    // OPTIONAL: Create an AdGroupFeed for even more fine grained control
                    // over which feed items are used at the AdGroup level.
                } catch (Exception e) {
                    throw new System.ApplicationException("Failed to create customer feed.", e);
                }
            }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">Id of the ad group to which ads are added.
        /// </param>
        public void Run(AdWordsUser user, long adGroupId)
        {
            // Get the AdGroupAdService.
            AdGroupAdService service =
                (AdGroupAdService)user.GetService(AdWordsService.v201502.AdGroupAdService);

            // Create the third party redirect ad that violates a policy.
            ThirdPartyRedirectAd redirectAd = new ThirdPartyRedirectAd();

            redirectAd.name              = "Policy violation demo ad " + ExampleUtilities.GetRandomString();
            redirectAd.url               = "gopher://gopher.google.com";
            redirectAd.dimensions        = new Dimensions();
            redirectAd.dimensions.width  = 300;
            redirectAd.dimensions.height = 250;

            redirectAd.snippet                 = "<img src=\"https://sandbox.google.com/sandboximages/image.jpg\"/>";
            redirectAd.impressionBeaconUrl     = "http://www.examples.com/beacon1";
            redirectAd.certifiedVendorFormatId = 119;
            redirectAd.isCookieTargeted        = false;
            redirectAd.isUserInterestTargeted  = false;
            redirectAd.isTagged                = false;

            AdGroupAd redirectAdGroupAd = new AdGroupAd();

            redirectAdGroupAd.adGroupId = adGroupId;
            redirectAdGroupAd.ad        = redirectAd;

            // Create the operations.
            AdGroupAdOperation redirectAdOperation = new AdGroupAdOperation();

            redirectAdOperation.@operator = Operator.ADD;
            redirectAdOperation.operand   = redirectAdGroupAd;

            try {
                AdGroupAdReturnValue retVal = null;

                // Setup two arrays, one to hold the list of all operations to be
                // validated, and another to hold the list of operations that cannot be
                // fixed after validation.
                List <AdGroupAdOperation> allOperations         = new List <AdGroupAdOperation>();
                List <AdGroupAdOperation> operationsToBeRemoved = new List <AdGroupAdOperation>();

                allOperations.Add(redirectAdOperation);

                try {
                    // Validate the operations.
                    service.RequestHeader.validateOnly = true;
                    retVal = service.mutate(allOperations.ToArray());
                } catch (AdWordsApiException ex) {
                    ApiException innerException = ex.ApiException as ApiException;
                    if (innerException == null)
                    {
                        throw new Exception("Failed to retrieve ApiError. See inner exception for more " +
                                            "details.", ex);
                    }

                    // Examine each ApiError received from the server.
                    foreach (ApiError apiError in innerException.errors)
                    {
                        int index = ErrorUtilities.GetOperationIndex(apiError.fieldPath);
                        if (index == -1)
                        {
                            // This API error is not associated with an operand, so we cannot
                            // recover from this error by removing one or more operations.
                            // Rethrow the exception for manual inspection.
                            throw;
                        }

                        // Handle policy violation errors.
                        if (apiError is PolicyViolationError)
                        {
                            PolicyViolationError policyError = (PolicyViolationError)apiError;

                            if (policyError.isExemptable)
                            {
                                // If the policy violation error is exemptable, add an exemption
                                // request.
                                List <ExemptionRequest> exemptionRequests = new List <ExemptionRequest>();
                                if (allOperations[index].exemptionRequests != null)
                                {
                                    exemptionRequests.AddRange(allOperations[index].exemptionRequests);
                                }

                                ExemptionRequest exemptionRequest = new ExemptionRequest();
                                exemptionRequest.key = policyError.key;
                                exemptionRequests.Add(exemptionRequest);
                                allOperations[index].exemptionRequests = exemptionRequests.ToArray();
                            }
                            else
                            {
                                // Policy violation error is not exemptable, remove this
                                // operation from the list of operations.
                                operationsToBeRemoved.Add(allOperations[index]);
                            }
                        }
                        else
                        {
                            // This is not a policy violation error, remove this operation
                            // from the list of operations.
                            operationsToBeRemoved.Add(allOperations[index]);
                        }
                    }
                    // Remove all operations that aren't exemptable.
                    foreach (AdGroupAdOperation operation in operationsToBeRemoved)
                    {
                        allOperations.Remove(operation);
                    }
                }

                if (allOperations.Count > 0)
                {
                    // Perform the operations exemptible of a policy violation.
                    service.RequestHeader.validateOnly = false;
                    retVal = service.mutate(allOperations.ToArray());

                    // Display the results.
                    if (retVal != null && retVal.value != null && retVal.value.Length > 0)
                    {
                        foreach (AdGroupAd newAdGroupAd in retVal.value)
                        {
                            Console.WriteLine("New ad with id = \"{0}\" and displayUrl = \"{1}\" was created.",
                                              newAdGroupAd.ad.id, newAdGroupAd.ad.displayUrl);
                        }
                    }
                    else
                    {
                        Console.WriteLine("No ads were created.");
                    }
                }
                else
                {
                    Console.WriteLine("There are no ads to create after policy violation checks.");
                }
            } catch (Exception ex) {
                throw new System.ApplicationException("Failed to create ads.", ex);
            }
        }
Exemplo n.º 18
0
		public Dictionary<string, string> OnApiFailed(ApiException apiException)
		{
			CanCancel = false;
			return HandleApiError(new Dictionary<string, string>(), apiException);
		}
Exemplo n.º 19
0
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="gmbEmailAddress">The email address for Google My Business
        /// account.</param>
        /// <param name="gmbAccessToken">The OAuth2 access token for Google
        /// My Business account.</param>
        /// <param name="businessAccountIdentifier">The account identifier for
        /// Google My Business account.</param>
        public void Run(AdWordsUser user, string gmbEmailAddress, string gmbAccessToken,
                        string businessAccountIdentifier)
        {
            FeedService feedService = (FeedService)user.GetService(AdWordsService.v201605.FeedService);

            CustomerFeedService customerFeedService = (CustomerFeedService)user.GetService(
                AdWordsService.v201605.CustomerFeedService);

            // Create a feed that will sync to the Google My Business account
            // specified by gmbEmailAddress. Do not add FeedAttributes to this object,
            // as AdWords will add them automatically because this will be a
            // system generated feed.
            Feed gmbFeed = new Feed();

            gmbFeed.name = String.Format("Google My Business feed #{0}",
                                         ExampleUtilities.GetRandomString());

            PlacesLocationFeedData feedData = new PlacesLocationFeedData();

            feedData.emailAddress = gmbEmailAddress;
            feedData.businessAccountIdentifier = businessAccountIdentifier;

            // Optional: specify labels to filter Google My Business listings. If
            // specified, only listings that have any of the labels set are
            // synchronized into FeedItems.
            feedData.labelFilters = new string[] { "Stores in New York City" };

            OAuthInfo oAuthInfo = new OAuthInfo();

            oAuthInfo.httpMethod = "GET";

            // Permissions for the AdWords API scope will also cover GMB.
            oAuthInfo.httpRequestUrl          = user.Config.GetDefaultOAuth2Scope();
            oAuthInfo.httpAuthorizationHeader = string.Format("Bearer {0}", gmbAccessToken);
            feedData.oAuthInfo = oAuthInfo;

            gmbFeed.systemFeedGenerationData = feedData;

            // Since this feed's feed items will be managed by AdWords,
            // you must set its origin to ADWORDS.
            gmbFeed.origin = FeedOrigin.ADWORDS;

            // Create an operation to add the feed.
            FeedOperation feedOperation = new FeedOperation();

            feedOperation.operand   = gmbFeed;
            feedOperation.@operator = Operator.ADD;

            try {
                // Add the feed. Since it is a system generated feed, AdWords will
                // automatically:
                // 1. Set up the FeedAttributes on the feed.
                // 2. Set up a FeedMapping that associates the FeedAttributes of the
                //    feed with the placeholder fields of the LOCATION placeholder
                //    type.
                FeedReturnValue addFeedResult = feedService.mutate(new FeedOperation[] { feedOperation });
                Feed            addedFeed     = addFeedResult.value[0];
                Console.WriteLine("Added GMB feed with ID {0}", addedFeed.id);

                // Add a CustomerFeed that associates the feed with this customer for
                // the LOCATION placeholder type.
                CustomerFeed customerFeed = new CustomerFeed();
                customerFeed.feedId           = addedFeed.id;
                customerFeed.placeholderTypes = new int[] { PLACEHOLDER_LOCATION };

                // Create a matching function that will always evaluate to true.
                Function        customerMatchingFunction = new Function();
                ConstantOperand constOperand             = new ConstantOperand();
                constOperand.type                   = ConstantOperandConstantType.BOOLEAN;
                constOperand.booleanValue           = true;
                customerMatchingFunction.lhsOperand = new FunctionArgumentOperand[] { constOperand };
                customerMatchingFunction.@operator  = FunctionOperator.IDENTITY;
                customerFeed.matchingFunction       = customerMatchingFunction;

                // Create an operation to add the customer feed.
                CustomerFeedOperation customerFeedOperation = new CustomerFeedOperation();
                customerFeedOperation.operand   = customerFeed;
                customerFeedOperation.@operator = Operator.ADD;

                // After the completion of the Feed ADD operation above the added feed
                // will not be available for usage in a CustomerFeed until the sync
                // between the AdWords and GMB accounts completes.  The loop below
                // will retry adding the CustomerFeed up to ten times with an
                // exponential back-off policy.
                CustomerFeed addedCustomerFeed = null;

                AdWordsAppConfig config = new AdWordsAppConfig();
                config.RetryCount = 10;

                ErrorHandler errorHandler = new ErrorHandler(config);
                do
                {
                    try {
                        CustomerFeedReturnValue customerFeedResult =
                            customerFeedService.mutate(new CustomerFeedOperation[] { customerFeedOperation });
                        addedCustomerFeed = customerFeedResult.value[0];

                        Console.WriteLine("Added CustomerFeed for feed ID {0} and placeholder type {1}",
                                          addedCustomerFeed.feedId, addedCustomerFeed.placeholderTypes[0]);
                        break;
                    } catch (AdWordsApiException e) {
                        ApiException apiException = (ApiException)e.ApiException;
                        foreach (ApiError error in apiException.errors)
                        {
                            if (error is CustomerFeedError)
                            {
                                if ((error as CustomerFeedError).reason ==
                                    CustomerFeedErrorReason.MISSING_FEEDMAPPING_FOR_PLACEHOLDER_TYPE)
                                {
                                    errorHandler.DoExponentialBackoff();
                                    errorHandler.IncrementRetriedAttempts();
                                }
                                else
                                {
                                    throw;
                                }
                            }
                        }
                    }
                } while (errorHandler.HaveMoreRetryAttemptsLeft());

                // OPTIONAL: Create a CampaignFeed to specify which FeedItems to use at
                // the Campaign level.  This will be similar to the CampaignFeed in the
                // AddSiteLinks example, except you can also filter based on the
                // business name and category of each FeedItem by using a
                // FeedAttributeOperand in your matching function.

                // OPTIONAL: Create an AdGroupFeed for even more fine grained control
                // over which feed items are used at the AdGroup level.
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to create customer feed.", e);
            }
        }
Exemplo n.º 20
0
        /// <summary>
        /// The result of a job execution. The result of a job execution.
        /// </summary>
        /// <exception cref="IO.Swagger.Client.ApiException">Thrown when fails to make API call</exception>
        /// <param name="id">The id of a process</param>
        /// <param name="jobID">The id of a job</param>
        /// <returns>Task of ApiResponse (Result)</returns>
        public async System.Threading.Tasks.Task <ApiResponse <Result> > ProcessesIdJobsJobIDResultGetAsyncWithHttpInfo(string id, string jobID)
        {
            // verify the required parameter 'id' is set
            if (id == null)
            {
                throw new Client.ApiException(400, "Missing required parameter 'id' when calling GetResultApi->ProcessesIdJobsJobIDResultGet");
            }
            // verify the required parameter 'jobID' is set
            if (jobID == null)
            {
                throw new Client.ApiException(400, "Missing required parameter 'jobID' when calling GetResultApi->ProcessesIdJobsJobIDResultGet");
            }

            var    localVarPath         = "./processes/{id}/jobs/{jobID}/result";
            var    localVarPathParams   = new Dictionary <String, String>();
            var    localVarQueryParams  = new List <KeyValuePair <String, String> >();
            var    localVarHeaderParams = new Dictionary <String, String>(this.Configuration.DefaultHeader);
            var    localVarFormParams   = new Dictionary <String, String>();
            var    localVarFileParams   = new Dictionary <String, FileParameter>();
            Object localVarPostBody     = null;

            // to determine the Content-Type header
            String[] localVarHttpContentTypes = new String[] {
            };
            String localVarHttpContentType    = this.Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);

            // to determine the Accept header
            String[] localVarHttpHeaderAccepts = new String[] {
                "application/json"
            };
            String localVarHttpHeaderAccept = this.Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);

            if (localVarHttpHeaderAccept != null)
            {
                localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
            }

            if (id != null)
            {
                localVarPathParams.Add("id", this.Configuration.ApiClient.ParameterToString(id));             // path parameter
            }
            if (jobID != null)
            {
                localVarPathParams.Add("jobID", this.Configuration.ApiClient.ParameterToString(jobID));                // path parameter
            }
            // make the HTTP request
            IRestResponse localVarResponse = (IRestResponse)await this.Configuration.ApiClient.CallApiAsync(localVarPath,
                                                                                                            Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
                                                                                                            localVarPathParams, localVarHttpContentType);

            int localVarStatusCode = (int)localVarResponse.StatusCode;

            if (ExceptionFactory != null)
            {
                ApiException exception = ExceptionFactory("ProcessesIdJobsJobIDResultGet", localVarResponse);
                if (exception != null)
                {
                    throw exception;
                }
            }

            return(new ApiResponse <Result>(localVarStatusCode,
                                            localVarResponse.Headers.ToDictionary(x => x.Key, x => string.Join(",", x.Value)),
                                            (Result)this.Configuration.ApiClient.Deserialize(localVarResponse, typeof(Result))));
        }
Exemplo n.º 21
0
 public static void FireOnError(ApiException exception)
 {
     OnError(exception);
 }
Exemplo n.º 22
0
 public void SetsDefaultExceptionMessage()
 {
     var exception = new ApiException();
     Assert.Equal("An error occurred with this API request", exception.Message);
 }
Exemplo n.º 23
0
 private void AssertApiException(ApiException exception, HttpStatusCode code)
 {
     Assert.AreEqual(code, exception.ResponseCode);
 }
 protected virtual Response <TResult> GetResponse <TResult>(ApiException fromApiException)
 {
     throw new InvalidOperationException($"If you are returning true in CanPrepareResponse method " +
                                         "you have to override GetResponse methods.");
 }
Exemplo n.º 25
0
 public ErrorModel(ApiException exception)
 {
     Message = exception.Message;
     Content = exception.Content;
 }
 protected virtual bool CanPrepareResponse(ApiException fromApiException) => false;
Exemplo n.º 27
0
 public static bool IsENException(this ApiException apiException)
 => ApiExceptionStatusCodes.FAILED_ALL.Contains(apiException.StatusCode);
Exemplo n.º 28
0
 public void Put(int id, [FromBody] ApiException value)
 {
 }
Exemplo n.º 29
0
 public void Post([FromBody] ApiException value)
 {
 }
        /// <summary>
        /// 创建一个对象信息
        /// </summary>
        /// <param name="info">新增对象</param>
        /// <param name="logonInfo">登录人信息</param>
        /// <returns></returns>
        public virtual ResultView Create(T info, TokenLogonInfo logonInfo)
        {
            if (info == null)
            {
                ApiException.ThrowBadRequest("新增对象不能为空");
            }
            _logger.LogTrace($"新增一个对象信息 ==> 类型为:[{typeof(T).FullName}]\r\n新增对象:[{info.ToJson()}]");

            try
            {
                // 新增数据前的预制数据
                info.CreateDate   = DateTime.Now;
                info.UpdateDate   = DateTime.Now;
                info.UpdaterId    = logonInfo.Id;
                info.UpdaterName  = logonInfo.Name;
                info.CreaterId    = logonInfo.Id;
                info.CreaterName  = logonInfo.Name;
                info.IsDelete     = false;
                info.ProcessState = ProcessState.Edit;

                #region 保存验证
                // 保存的数据校验
                SavingCheck(info, logonInfo);
                // 判断是否可以执行新增操作
                if (!IsExecuteCreate(info, logonInfo))
                {
                    return(ResultView.Success());
                }
                // 保存数据验证的事件处理
                OnCreateCheck?.Invoke(info, logonInfo);
                OnSaveCheck?.Invoke(info, logonInfo);
                #endregion

                #region 保存的前置处理
                // 新增的前置操作,可以被重写
                Creating(info, logonInfo);
                // 新增/保存的通用前置操作,可以被重写
                Saving(info, logonInfo);
                // 新增时的前置事件处理
                OnCreating?.Invoke(info, logonInfo);
                OnSaving?.Invoke(info, logonInfo);
                #endregion

                // 持久化数据
                _Dal.InsertObject(info);

                #region 保存后置处理
                // 新增的通用后置操作,可以被重写
                Created(info, logonInfo);
                // 新增/保存的通用后置操作,可以被重写
                Saved(info, logonInfo);
                // 新增后的后置事件处理
                OnCreated?.Invoke(info, logonInfo);
                OnSaved?.Invoke(info, logonInfo);
                #endregion

                // 返回保存结果
                return(ResultView.Success(info.IdString));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"新增一个对象信息异常 ==> 类型为:[{typeof(T).FullName}]\r\n操作人信息:[{logonInfo.ToJson()}]\r\n新增对象:[{info.ToJson()}]");
                throw;
            }
        }
            /// <summary>
            /// Main method for the thread.
            /// </summary>
            /// <param name="obj">The thread parameter.</param>
            public void Run(Object obj)
            {
                // Create the operations.
                List <AdGroupCriterionOperation> operations = new List <AdGroupCriterionOperation>();

                for (int j = 0; j < NUM_KEYWORDS; j++)
                {
                    // Create the keyword.
                    Keyword keyword = new Keyword();
                    keyword.text      = "mars cruise thread " + threadIndex.ToString() + " seed " + j.ToString();
                    keyword.matchType = KeywordMatchType.BROAD;

                    // Create the biddable ad group criterion.
                    AdGroupCriterion keywordCriterion = new BiddableAdGroupCriterion();
                    keywordCriterion.adGroupId = adGroupId;
                    keywordCriterion.criterion = keyword;

                    // Create the operations.
                    AdGroupCriterionOperation keywordOperation = new AdGroupCriterionOperation();
                    keywordOperation.@operator = Operator.ADD;
                    keywordOperation.operand   = keywordCriterion;

                    operations.Add(keywordOperation);
                }

                // Get the AdGroupCriterionService. This should be done within the
                // thread, since a service can only handle one outgoing HTTP request
                // at a time.
                using (AdGroupCriterionService adGroupCriterionService =
                           (AdGroupCriterionService)user.GetService(
                               AdWordsService.v201705.AdGroupCriterionService)) {
                    adGroupCriterionService.RequestHeader.validateOnly = true;
                    int       retryCount  = 0;
                    const int NUM_RETRIES = 3;
                    try {
                        while (retryCount < NUM_RETRIES)
                        {
                            try {
                                // Validate the keywords.
                                adGroupCriterionService.mutate(operations.ToArray());
                                break;
                            } catch (AdWordsApiException e) {
                                // Handle API errors.
                                ApiException innerException = e.ApiException as ApiException;
                                if (innerException == null)
                                {
                                    throw new Exception("Failed to retrieve ApiError. See inner exception " +
                                                        "for more details.", e);
                                }
                                foreach (ApiError apiError in innerException.errors)
                                {
                                    if (!(apiError is RateExceededError))
                                    {
                                        // Rethrow any errors other than RateExceededError.
                                        throw;
                                    }
                                    // Handle rate exceeded errors.
                                    RateExceededError rateExceededError = (RateExceededError)apiError;
                                    Console.WriteLine("Got Rate exceeded error - rate name = '{0}', " +
                                                      "scope = '{1}', retry After {2} seconds.", rateExceededError.rateScope,
                                                      rateExceededError.rateName, rateExceededError.retryAfterSeconds);
                                    Thread.Sleep(rateExceededError.retryAfterSeconds * 1000);
                                    retryCount = retryCount + 1;
                                }
                            } finally {
                                if (retryCount == NUM_RETRIES)
                                {
                                    throw new Exception(String.Format("Could not recover after making {0} attempts.",
                                                                      retryCount));
                                }
                            }
                        }
                    } catch (Exception e) {
                        throw new System.ApplicationException("Failed to validate keywords.", e);
                    }
                }
            }
 /// <summary>
 /// Initializes a new instance of <see cref="ErrorResponseException"/> with response error details and API excepiton.
 /// </summary>
 /// <param name="error">The response error details</param>
 /// <param name="inner">The exception occurred during calling service API.</param>
 public ErrorResponseException(ErrorResponse error, ApiException inner) :
     base(error.GetSummaryMessage() ?? string.Empty, inner)
 {
     Error      = error;
     StatusCode = inner.StatusCode;
 }
Exemplo n.º 33
0
 public ServerResponseException(ApiException apiException) : base(apiException.Message, apiException)
 {
     _message = FormatExceptionMessage(apiException);
 }
Exemplo n.º 34
0
        public async Task <UserResponse> Login(string brandToken, UserLoginRequest model)
        {
            try
            {
                var result = new UserResponse();
                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("http://authorizecore.unicode.edu.vn");
                    var oBject = new
                    {
                        Email      = model.Email,
                        Password   = model.Password,
                        brandToken = brandToken
                    };

                    var response = await client.PostAsJsonAsync("/api/authorize/login", oBject);

                    if (response.IsSuccessStatusCode)
                    {
                        var responseObj = await response.Content.ReadAsAsync <JObject>();

                        var token = responseObj.SelectToken("token").ToString();
                        var role  = responseObj.SelectToken("roles").ToArray();
                        var emp   = employeeService.Get(model.Email).FirstOrDefault();
                        result.Token    = token;
                        result.Employee = emp;
                        result.Role     = role;
                        var loyaltyResponse = RootConfig.LoyaltyClient.MembershipsApi.Get(new ResoLoyalty.Client.Models.Request.MembershipRequest()
                        {
                            of_emp_code = emp.EmpEnrollNumber,
                            includes    = new List <string>()
                            {
                                MembershipRequest.Basic,
                                MembershipRequest.CreditAcc
                            }
                        }).Result;
                        var membership = loyaltyResponse.Content.ReadAsAsync <BaseResponse <IEnumerable <Membership> > >().Result.Data.FirstOrDefault();
                        result.Membership = membership;
                        //var tokenJWT = Utils.DecodeJwtToken(token);
                        //tokenJWT.Claims.Where(p => p.Type )
                        //var email = data.SelectToken("email").ToString();
                        //employeeService.Add(model);
                    }
                    else
                    {
                        if (response.StatusCode == HttpStatusCode.Unauthorized)
                        {
                            throw ApiException.Get(false, ConstantManager.UNAUTHORIZED, ResultEnum.Unauthorization, HttpStatusCode.Unauthorized);
                        }
                        else
                        {
                            throw ApiException.Get(false, ConstantManager.FAIL, ResultEnum.InternalError, HttpStatusCode.InternalServerError);
                        }
                    }
                }
                return(result);
            }
            catch (Exception ex)
            {
                if (ex is ApiException)
                {
                    throw ex;
                }
                else
                {
                    throw  ApiException.Get(false, ConstantManager.FAIL, ResultEnum.InternalError, HttpStatusCode.InternalServerError);
                }
            }
        }
        /// <summary>
        /// Checks a list of keywords for policy violations, and add the errors to
        /// a list of traffic estimates.
        /// </summary>
        /// <param name="user">The user.</param>
        /// <param name="trafficEstimates">The list of keywords and their traffic
        /// estimates.</param>
        /// <param name="adGroupId">The ad group ID.</param>
        /// <remarks>Users can use the policy violation details to decide whether
        /// to pick a keyword and submit an exemption request, or skip the
        /// violating keyword and scout for other keywords that are policy
        /// compliant.</remarks>
        private void CheckPolicyViolations(AdWordsUser user, List <TrafficEstimate> trafficEstimates,
                                           long adGroupId)
        {
            // Get the AdGroupCriterionService.
            AdGroupCriterionService adGroupCriterionService =
                (AdGroupCriterionService)user.GetService(
                    AdWordsService.v201509.AdGroupCriterionService);

            adGroupCriterionService.RequestHeader.validateOnly = true;

            for (int i = 0; i < trafficEstimates.Count; i += Settings.AGCS_KEYWORDS_LIST_SIZE)
            {
                List <AdGroupCriterionOperation> operations = new List <AdGroupCriterionOperation>();

                for (int j = i; j < i + Settings.AGCS_KEYWORDS_LIST_SIZE &&
                     j < trafficEstimates.Count; j++)
                {
                    AdGroupCriterionOperation operation = new AdGroupCriterionOperation()
                    {
                        @operator = Operator.ADD,
                        operand   = new BiddableAdGroupCriterion()
                        {
                            adGroupId = adGroupId,
                            criterion = new Keyword()
                            {
                                text      = trafficEstimates[i].Keyword.KeywordText,
                                matchType = trafficEstimates[i].MatchType,
                            },
                            userStatus = UserStatus.ENABLED
                        }
                    };

                    operations.Add(operation);
                }

                try {
                    AdGroupCriterionReturnValue retVal = adGroupCriterionService.mutate(
                        operations.ToArray());
                } catch (AdWordsApiException e) {
                    ApiException innerException = e.ApiException as ApiException;
                    if (innerException == null)
                    {
                        throw new Exception("Failed to retrieve ApiError. See inner exception for more " +
                                            "details.", e);
                    }

                    // Examine each ApiError received from the server.
                    foreach (ApiError apiError in innerException.errors)
                    {
                        int index = ErrorUtilities.GetOperationIndex(apiError.fieldPath);
                        if (index == -1)
                        {
                            // This API error is not associated with an operand, so we cannot
                            // recover from this error by removing one or more operations.
                            // Rethrow the exception for manual inspection.
                            throw;
                        }

                        // Handle policy violation errors.
                        if (apiError is PolicyViolationError)
                        {
                            PolicyViolationError policyError = (PolicyViolationError)apiError;
                            trafficEstimates[i + index].Errors.Add(policyError);
                        }
                    }
                }
            }
            return;
        }
Exemplo n.º 36
0
 internal void Print(ApiException level, string Method)
 {
     Print("Warning", Method, level.Message);
 }
Exemplo n.º 37
0
		private static Dictionary<string, string> HandleApiError(Dictionary<string, string> errors, ApiException e)
		{
			if (e.StatusCode == HttpStatusCode.Unauthorized) {
				if (e.HasContent && e.Content.StartsWith("<html")) {
					errors.Add("Auth", "Access denied to VPDB. Seems like the site is protected and you need to put additional credentials in here.");
				} else {
					errors.Add("ApiKey", "Authentication failed. Are you sure you've correctly pasted your API key?");
				}
			} else {
				errors.Add("ApiKey", e.Message);
			}
			return errors;
		}
Exemplo n.º 38
0
            public void DoesNotPrintNonStringContent()
            {
                var responceBody = new byte[0];
                var response = new Response(
                    HttpStatusCode.GatewayTimeout,
                    responceBody,
                    new Dictionary<string, string>(),
                    "application/json"
                );

                var exception = new ApiException(response);
                var stringRepresentation = exception.ToString();
                Assert.NotNull(stringRepresentation);
            }
Exemplo n.º 39
0
        private void OnTransactionReply(uint transactionId, Codes replyCode, Codes extendedCode, OrderStatus status, long orderId, string message)
        {
            this.AddDebugLog("Order: transId {0} replyCode {1} extendedCode {2} status {3} orderId {4} message {5}", transactionId, replyCode, extendedCode, status, orderId, message);

            if (!IsAsyncMode)
            {
                return;
            }

            try
            {
                var builder = _transactions.TryGetValue(transactionId);

                if (builder == null)
                {
                    throw new InvalidOperationException(LocalizedStrings.Str1839Params.Put(transactionId));
                }

                if (builder.TransactionType == TransactionTypes.CancelGroup)
                {
                    if (replyCode != Codes.Success || status != OrderStatus.Accepted)
                    {
                        SendOutError(new ApiException(replyCode, message));
                    }

                    return;
                }

                if (builder.TransactionType == TransactionTypes.Register && extendedCode == Codes.Success && orderId == 0)
                {
                    extendedCode = Codes.Failed;
                }

                var isCancelFailed = builder.TransactionType == TransactionTypes.Cancel && status != OrderStatus.Accepted;

                if (isCancelFailed)
                {
                    extendedCode = Codes.Failed;
                }

                ApiException exception = null;

                if (extendedCode != Codes.Success)
                {
                    exception = new ApiException(extendedCode, message);
                }

                var orderMessage = builder.Message.CreateReply();

                orderMessage.SystemComment = message;

                if (!isCancelFailed)
                {
                    orderMessage.OrderStatus = (long)status;
                }

                ProcessTransactionReply(orderMessage, builder, orderId, message, replyCode, exception);
            }
            catch (Exception ex)
            {
                SendOutError(ex);
            }
        }
Exemplo n.º 40
0
            public void CanPopulateObjectFromSerializedData()
            {
                IResponse response = new Response(
                    (HttpStatusCode)422,
                    @"{""errors"":[{""code"":""custom"",""field"":""key"",""message"":""key is " +
                    @"already in use"",""resource"":""PublicKey""}],""message"":""Validation Failed""}",
                    new Dictionary<string, string>(),
                    "application/json");

                var exception = new ApiException(response);

                using (var stream = new MemoryStream())
                {
                    var formatter = new BinaryFormatter();
                    formatter.Serialize(stream, exception);
                    stream.Position = 0;
                    var deserialized = (ApiException)formatter.Deserialize(stream);
                    Assert.Equal("Validation Failed", deserialized.ApiError.Message);
                    Assert.Equal("key is already in use", exception.ApiError.Errors.First().Message);
                }
            }
Exemplo n.º 41
0
        public static IHttpActionResult CreateErrorResult(HttpRequestMessage request, ApiException ex)
        {
            HttpResponseMessage response = request.CreateResponse(ex.HttpStatusCode,
                                                                  new ApiResponse
            {
                ApiStatusCode    = ex.ErrorCode,
                ApiStatusMessage = ex.Message,
                ExceptionDetails = new ApiExceptionDetails(ex)
            });

            return(new ResponseMessageResult(response));
        }
Exemplo n.º 42
0
            public void DoesNotThrowIfBodyIsNotDefined()
            {
                var response = new Response(
                    HttpStatusCode.GatewayTimeout,
                    null,
                    new Dictionary<string, string>(),
                    "application/json"
                );

                var exception = new ApiException(response);
                var stringRepresentation = exception.ToString();
                Assert.NotNull(stringRepresentation);
            }
Exemplo n.º 43
0
 /// <summary>
 /// Initializes a new instance of <see cref="DefaultErrorResponseException"/> with response error details and API excepiton.
 /// </summary>
 /// <param name="error"></param>
 /// <param name="inner"></param>
 public DefaultErrorResponseException(ErrorResponse error, ApiException inner) : base(error, inner)
 {
 }
Exemplo n.º 44
0
        /// <summary>
        /// Handles IoT Hub exception and transform it as an <see cref="ApiException"/> with a well-known application error code.
        /// </summary>
        /// <param name="deviceId"></param>
        /// <param name="iotHubException"></param>
        /// <param name="apiException"></param>
        /// <returns></returns>
        private bool TryHandleIotHubException(string deviceId, IotHubException iotHubException, out ApiException apiException)
        {
            switch (iotHubException)
            {
            // thrown when there's no IoT Hub device registration OR there's an enabled IoT Hub device registration but device did not establish connection yet
            case DeviceNotFoundException ex:
                apiException = new IdNotFoundException(ErrorCodes.DeviceNotFound, deviceId, ex);
                break;

            // thrown when an attempt to communicate with the IoT Hub fails
            case IotHubCommunicationException ex:
                m_Logger.LogWarning($"An IotHubCommunicationException occurred: {ex}");
                apiException = new CommunicationException(ErrorCodes.CommunicationError, ex.Message, ex);
                break;

            // thrown when the IoT Hub returns an error code (i.e. device registration is disable which prevent the actual device from establishing a connection)
            case ServerErrorException ex:
                m_Logger.LogWarning($"A ServerErrorException occurred: {ex}");
                apiException = new CommunicationException(ErrorCodes.GatewayError, ErrorMessages.GetGatewayErrorMessage(), ex);
                break;

            // thrown when the maximum number of IoT Hub messages has been reached
            case QuotaExceededException ex:
                apiException = new CommunicationException(ErrorCodes.QuotaExceeded, ErrorMessages.GetQuotaExceededErrorMessage(), ex);
                break;

            // thrown when the message size is greater than the max size allowed (131072 bytes)
            case MessageTooLargeException ex:
                apiException = new InvalidResultException(ErrorCodes.MessageTooLarge, ErrorMessages.GetMessageTooLargeErrorMessage(), ex);
                break;

            // thrown when an error occurs during device client operation (i.e. device doesn't repond within the configured time out)
            // shall always be kept last
            case IotHubException ex:
                m_Logger.LogWarning($"An IotHubException occurred: {ex}");
                apiException = new OperationException(ErrorCodes.DeviceOperationError, ErrorMessages.GetOperationErrorMessage(), ex);
                break;

            // exception won't be transformed and therefore will be logged accordingly
            default:
                apiException = null;
                break;
            }

            return(apiException != null);
        }
Exemplo n.º 45
0
        /// <summary>
        /// Header传递关键参数处理方法
        /// </summary>
        /// <param name="controller">控制器</param>
        /// <param name="baseApi">传入参数</param>
        /// <returns></returns>
        private object HeaderBussResults(Controller controller, BaseApi baseApi, IPAddress iPAddress)
        {
            var route           = "";
            var action          = "";
            var routeController = controller.RouteData.Values["controller"].ToString();
            var routeAction     = controller.RouteData.Values["action"].ToString();

            route  = Global.ROUTE_PX + "/" + routeController + "/" + routeAction;
            action = routeAction.Replace("/", "");

            if (controller.Request.Headers.ContainsKey("userid"))
            {
                baseApi.code = controller.Request.Headers["userid"].ToString();
            }
            if (controller.Request.Headers.ContainsKey("token"))
            {
                baseApi.token = controller.Request.Headers["token"].ToString();
            }
            if (controller.Request.Headers.ContainsKey("sign") && controller.Request.Headers.ContainsKey("nonceStr"))
            {
                baseApi.sign     = controller.Request.Headers["sign"].ToString();
                baseApi.nonceStr = controller.Request.Headers["nonceStr"].ToString();
            }

            Message msg = null;

            switch (baseApi.GetCheckType())
            {
            case CheckType.Open:
                break;

            case CheckType.Token:
                msg = CheckToken(baseApi, true, route);
                break;

            case CheckType.OpenToken:
                msg = CheckToken(baseApi, false, route);
                break;

            case CheckType.Sign:
                msg = CheckSign(baseApi, route);
                break;

            case CheckType.WhiteList:
                msg = CheckWhiteList(baseApi, iPAddress);
                break;

            default:
                break;
            }

            if (msg != null)
            {
                controller.Response.Headers.Add("code", ((int)msg.code).ToString());
                controller.Response.Headers.Add("msg", msg.msg);
                return("");
            }
            var        obj        = bussList[baseApi.GetApiType()];
            MethodInfo methodInfo = obj.GetType().GetMethod("Do_" + action);

            if (methodInfo == null)
            {
                controller.Response.Headers.Add("code", ((int)CodeMessage.InvalidMethod).ToString());
                controller.Response.Headers.Add("msg", "InvalidMethod");
                return("");
            }
            else
            {
                Message message = null;
                object  data    = null;
                try
                {
                    data = methodInfo.Invoke(obj, new object[] { baseApi });
                }
                catch (Exception ex)
                {
                    if (ex.InnerException.GetType() == typeof(ApiException))
                    {
                        ApiException apiException = (ApiException)ex.InnerException;
                        message = new Message(apiException.code, apiException.msg);
                    }
                    else
                    {
                        message = new Message(CodeMessage.InnerError, "InnerError");
                    }
                }
                if (message != null)
                {
                    controller.Response.Headers.Add("code", ((int)message.code).ToString());
                    controller.Response.Headers.Add("msg", message.msg);
                }
                else
                {
                    controller.Response.Headers.Add("code", ((int)CodeMessage.OK).ToString());
                    controller.Response.Headers.Add("msg", "");
                }

                return(data);
            }
        }
        /// <summary>
        /// Runs the code example.
        /// </summary>
        /// <param name="user">The AdWords user.</param>
        /// <param name="adGroupId">Id of the ad group to which ads are added.
        /// </param>
        public void Run(AdWordsUser user, long adGroupId)
        {
            // Get the AdGroupAdService.
            AdGroupAdService service =
                (AdGroupAdService)user.GetService(AdWordsService.v201603.AdGroupAdService);

            // Create the text ad.
            TextAd textAd = new TextAd();

            textAd.headline     = "Luxury Cruise to Mars";
            textAd.description1 = "Visit the Red Planet in style.";
            textAd.description2 = "Low-gravity fun for everyone!!";
            textAd.displayUrl   = "www.example.com";
            textAd.finalUrls    = new string[] { "http://www.example.com" };

            AdGroupAd textadGroupAd = new AdGroupAd();

            textadGroupAd.adGroupId = adGroupId;
            textadGroupAd.ad        = textAd;

            // Create the operations.
            AdGroupAdOperation textAdOperation = new AdGroupAdOperation();

            textAdOperation.@operator = Operator.ADD;
            textAdOperation.operand   = textadGroupAd;

            try {
                AdGroupAdReturnValue retVal = null;

                // Setup two arrays, one to hold the list of all operations to be
                // validated, and another to hold the list of operations that cannot be
                // fixed after validation.
                List <AdGroupAdOperation> allOperations         = new List <AdGroupAdOperation>();
                List <AdGroupAdOperation> operationsToBeRemoved = new List <AdGroupAdOperation>();

                allOperations.Add(textAdOperation);

                try {
                    // Validate the operations.
                    service.RequestHeader.validateOnly = true;
                    retVal = service.mutate(allOperations.ToArray());
                } catch (AdWordsApiException e) {
                    ApiException innerException = e.ApiException as ApiException;
                    if (innerException == null)
                    {
                        throw new Exception("Failed to retrieve ApiError. See inner exception for more " +
                                            "details.", e);
                    }

                    // Examine each ApiError received from the server.
                    foreach (ApiError apiError in innerException.errors)
                    {
                        int index = ErrorUtilities.GetOperationIndex(apiError.fieldPath);
                        if (index == -1)
                        {
                            // This API error is not associated with an operand, so we cannot
                            // recover from this error by removing one or more operations.
                            // Rethrow the exception for manual inspection.
                            throw;
                        }

                        // Handle policy violation errors.
                        if (apiError is PolicyViolationError)
                        {
                            PolicyViolationError policyError = (PolicyViolationError)apiError;

                            if (policyError.isExemptable)
                            {
                                // If the policy violation error is exemptable, add an exemption
                                // request.
                                List <ExemptionRequest> exemptionRequests = new List <ExemptionRequest>();
                                if (allOperations[index].exemptionRequests != null)
                                {
                                    exemptionRequests.AddRange(allOperations[index].exemptionRequests);
                                }

                                ExemptionRequest exemptionRequest = new ExemptionRequest();
                                exemptionRequest.key = policyError.key;
                                exemptionRequests.Add(exemptionRequest);
                                allOperations[index].exemptionRequests = exemptionRequests.ToArray();
                            }
                            else
                            {
                                // Policy violation error is not exemptable, remove this
                                // operation from the list of operations.
                                operationsToBeRemoved.Add(allOperations[index]);
                            }
                        }
                        else
                        {
                            // This is not a policy violation error, remove this operation
                            // from the list of operations.
                            operationsToBeRemoved.Add(allOperations[index]);
                        }
                    }
                    // Remove all operations that aren't exemptable.
                    foreach (AdGroupAdOperation operation in operationsToBeRemoved)
                    {
                        allOperations.Remove(operation);
                    }
                }

                if (allOperations.Count > 0)
                {
                    // Perform the operations exemptible of a policy violation.
                    service.RequestHeader.validateOnly = false;
                    retVal = service.mutate(allOperations.ToArray());

                    // Display the results.
                    if (retVal != null && retVal.value != null && retVal.value.Length > 0)
                    {
                        foreach (AdGroupAd newAdGroupAd in retVal.value)
                        {
                            Console.WriteLine("New ad with id = \"{0}\" and displayUrl = \"{1}\" was created.",
                                              newAdGroupAd.ad.id, newAdGroupAd.ad.displayUrl);
                        }
                    }
                    else
                    {
                        Console.WriteLine("No ads were created.");
                    }
                }
                else
                {
                    Console.WriteLine("There are no ads to create after policy violation checks.");
                }
            } catch (Exception e) {
                throw new System.ApplicationException("Failed to create ads.", e);
            }
        }
Exemplo n.º 47
0
 public BadRequestException(ApiException apiException)
     : base(HttpStatusCode.BadRequest, apiException.Message)
 {
     ErrorNumber = apiException.ErrorNumber;
     Type = apiException.Type;            
 }
Exemplo n.º 48
0
            public void ContainsResponseBody()
            {
                const string responseBody = @"{""errors"":[{""code"":""custom"",""field"":""key"",""message"":""key is " +
                                            @"already in use"",""resource"":""PublicKey""}],""message"":""Validation Failed""}";
                var response = new Response(
                    HttpStatusCode.GatewayTimeout,
                    responseBody,
                    new Dictionary<string, string>(),
                    "application/json"
                    );

                var exception = new ApiException(response);
                var stringRepresentation = exception.ToString();
                Assert.Contains(responseBody, stringRepresentation);
            }
Exemplo n.º 49
0
 public Message LogApiError(ApiException exception, string message)
 {
     var msg = CreateError(exception, message, MessageType.ApiError);
     msg.Data.Add(DataStatusCode, exception.StatusCode.ToString());
     msg.Data.Add(DataContent, exception.Content);
     _crashManager.Report(exception, "api");
     return Log(msg);
 }
Exemplo n.º 50
0
 public ErrorModel(ApiException exception)
 {
     Message = exception.Message;
     Content = exception.Content;
 }
 /// <summary>
 /// Identify whether the API exception was caused by a request validation problem
 /// </summary>
 public static bool IsValidationProblem(this ApiException ex)
 {
     return(ex.ErrorCode == (int)HttpStatusCode.BadRequest);
 }
        /// <summary>
        /// 更新一个对象信息
        /// </summary>
        /// <param name="info">更新对象</param>
        /// <param name="logonInfo">登录人信息</param>
        /// <returns></returns>
        public virtual ResultView Update(T info, TokenLogonInfo logonInfo)
        {
            if (info == null)
            {
                ApiException.ThrowBadRequest("更新对象不能为空");
            }
            _logger.LogTrace($"更新一个对象信息 ==> 类型为:[{typeof(T).FullName}]\r\n操作人信息:[{logonInfo.ToJson()}]\r\n更新对象:[{info.ToJson()}]");

            try
            {
                // 根据ID获取原数据信息
                var old = _SearchById(info.Id);
                // 更新数据前的预制数据
                info.CreateDate  = old.CreateDate;
                info.CreaterId   = old.CreaterId;
                info.CreaterName = old.CreaterName;
                info.UpdateDate  = DateTime.Now;
                info.UpdaterId   = logonInfo.Id;
                info.UpdaterName = logonInfo.Name;
                info.IsDelete    = false;
                if (info.ProcessState == ProcessState.None)
                {
                    info.ProcessState = ProcessState.Edit;
                }

                #region 保存验证
                // 保存的数据校验,可以被重写
                SavingCheck(info, logonInfo);
                // 判断是否可以执行新增操作,可以被重写
                if (!IsExecuteUpdate(info, old, logonInfo))
                {
                    return(ResultView.Success());
                }
                OnUpdateCheck?.Invoke(info, old, logonInfo);
                OnSaveCheck?.Invoke(info, logonInfo);
                #endregion

                #region 保存的前置处理
                // 更新的前置操作,可以被重写
                Updating(info, old, logonInfo);
                // 新增/保存的通用前置操作,可以被重写
                Saving(info, logonInfo);
                // 事件处理
                OnUpdating?.Invoke(info, old, logonInfo);
                OnSaving?.Invoke(info, logonInfo);
                #endregion

                // 持久化数据
                _Dal.UpdateObject(info);

                #region 保存后置处理
                // 更新的后置操作,可以被重写
                Updated(info, old, logonInfo);
                // 新增/保存的通用后置操作,可以被重写
                Saved(info, logonInfo);
                // 新增后的后置事件处理
                OnUpdated?.Invoke(info, old, logonInfo);
                OnSaved?.Invoke(info, logonInfo);
                #endregion

                // 返回保存结果
                return(ResultView.Success(info.IdString));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, $"更新一个对象信息异常 ==> 类型为:[{typeof(T).FullName}]\r\n操作人信息:[{logonInfo.ToJson()}]\r\n更新对象:[{info.ToJson()}]");
                throw;
            }
        }
Exemplo n.º 53
0
            public void CreatesEmptyGitHubErrorWhenResponseBodyIsNull()
            {
                var response = Substitute.For<IResponse>();
                response.Body.Returns("test");

                var exception = new ApiException();
                var anotherException = new ApiException(new Response(HttpStatusCode.ServiceUnavailable, "message1", new Dictionary<string, string>(), "application/json"));
                var thirdException = new ApiException(new Response(HttpStatusCode.ServiceUnavailable, "message2", new Dictionary<string, string>(), "application/json"));

                // It's fine if the message is null when there's no response body as long as this doesn't throw.
                Assert.Null(exception.ApiError.Message);
                Assert.Equal("message1", anotherException.ApiError.Message);
                Assert.Equal("message2", thirdException.ApiError.Message);
            }
Exemplo n.º 54
0
        /// <summary>
        /// Execute the specified action, resourcePath and baseObject.
        /// </summary>
        /// <param name="action">Action.</param>
        /// <param name="resourcePath">Resource path.</param>
        /// <param name="requestMap">Request Map.</param>
        /// <param name="headerList">Header List.</param>
        public virtual IDictionary <String, Object> Execute(OperationConfig config, OperationMetadata metadata, BaseObject requestMap)
        {
            IRestResponse           response;
            RestyRequest            request;
            IRestClient             client;
            CryptographyInterceptor interceptor;

            try
            {
                request     = this.GetRequest(config, metadata, requestMap);
                interceptor = request.interceptor;

                //arizzini: create client
                if (this.restClient != null)
                {
                    client = restClient;
                }
                else
                {
                    client = new RestClient();
                }

                client.BaseUrl = request.BaseUrl;
                client.Proxy   = ApiConfig.GetProxy();

                log.Debug(">>Execute(action='" + config.Action + "', resourcePaht='" + config.ResourcePath + "', requestMap='" + requestMap + "'");
                log.Debug("excute(), request.Method='" + request.Method + "'");
                log.Debug("excute(), request.URL=" + request.AbsoluteUrl.ToString());
                log.Debug("excute(), request.Header=");
                log.Debug(request.Parameters.Where(x => x.Type == ParameterType.HttpHeader));
                log.Debug("excute(), request.Body=");
                log.Debug(request.Parameters.Where(x => x.Type == ParameterType.RequestBody));
                response = client.Execute(request);
                log.Debug("Execute(), response.Header=");
                log.Debug(response.Headers);
                log.Debug("Execute(), response.Body=");
                log.Debug(response.Content.ToString());


                if (response.ErrorException == null && response.Content != null)
                {
                    IDictionary <String, Object> responseObj = new Dictionary <String, Object>();

                    if (response.Content.Length > 0)
                    {
                        if (response.StatusCode < HttpStatusCode.Ambiguous)
                        {
                            responseObj = SmartMap.AsDictionary(response.Content);
                            if (interceptor != null)
                            {
                                try
                                {
                                    responseObj = interceptor.Decrypt(responseObj);
                                }
                                catch (Exception e)
                                {
                                    throw new ApiException("Error: decrypting payload", e);
                                }
                            }

                            log.Debug("<<Execute()");
                            return(responseObj);
                        }
                        else
                        {
                            int status = (int)response.StatusCode;
                            throw new ApiException(status, SmartMap.AsObject(response.Content));
                        }
                    }
                    else
                    {
                        return(responseObj);
                    }
                }
                else
                {
                    throw new ApiException(response.ErrorMessage, response.ErrorException);
                }
            } catch (ApiException apiE) {
                log.Error(apiE.Message, apiE);
                throw;
            } catch (Exception genE) {
                ApiException wrapper = new ApiException(genE.Message, genE);
                log.Error(wrapper.Message, wrapper);
                throw wrapper;
            }
        }
Exemplo n.º 55
0
        private ApiException CreateErrorResponseException(ErrorResponse response)
        {
            Exception innerException = null;

            if (!String.IsNullOrEmpty(response.sub_code))
            {
                innerException = new ApiException(response.sub_msg, response.sub_code);
            }

            if (innerException == null)
            {
                return new ApiException(response.msg, response.code);
            }

            return new ApiException(response.msg, response.code, innerException);
        }
Exemplo n.º 56
0
        /// <summary>
        /// Body传递关键参数处理方法
        /// </summary>
        /// <param name="controller">控制器</param>
        /// <param name="baseApi">传入参数</param>
        /// <returns></returns>
        private object BodyBussResults(Controller controller, BaseApi baseApi)
        {
            var route           = "";
            var action          = "";
            var routeController = controller.RouteData.Values["controller"].ToString();
            var routeAction     = controller.RouteData.Values["action"].ToString();

            route  = Global.ROUTE_PX + "/" + routeController + "/" + routeAction + "/" + baseApi.method;
            action = routeAction.Replace("/", "");
            Message msg = null;

            switch (baseApi.GetCheckType())
            {
            case CheckType.Open:
                break;

            case CheckType.Token:
                msg = CheckToken(baseApi, true, route);
                break;

            case CheckType.OpenToken:
                msg = CheckToken(baseApi, false, route);
                break;

            case CheckType.Sign:
                msg = CheckSign(baseApi, route);
                break;

            default:
                break;
            }

            if (msg != null)
            {
                return(new ResultsJson(new Message(CodeMessage.InvalidToken, "InvalidToken"), null));
            }
            var        obj        = bussList[baseApi.GetApiType()];
            MethodInfo methodInfo = obj.GetType().GetMethod("Do_" + baseApi.method);

            if (methodInfo == null)
            {
                return(new ResultsJson(new Message(CodeMessage.InvalidMethod, "InvalidMethod"), null));
            }
            else
            {
                Message message = null;
                object  data    = null;
                try
                {
                    data = methodInfo.Invoke(obj, new object[] { baseApi });
                }
                catch (Exception ex)
                {
                    if (ex.InnerException.GetType() == typeof(ApiException))
                    {
                        ApiException apiException = (ApiException)ex.InnerException;
                        message = new Message(apiException.code, apiException.msg);
                    }
                    else
                    {
                        message = new Message(CodeMessage.InnerError, "InnerError");
                    }
                }
                ResultsJson resultsJson = new ResultsJson(message, data);
                return(resultsJson);
            }
        }
Exemplo n.º 57
-1
        /// <summary>
        /// Validate HttpResponse message, throws an Api Exception with context
        /// </summary>
        /// <param name="response"></param>
        /// <param name="request"></param>
        /// <param name="apiContext"></param>
        /// <exception cref="ApiException"></exception>
        public static void EnsureSuccess(HttpResponseMessage response, HttpRequestMessage request=null, IApiContext apiContext=null)
        {
		    if (response.IsSuccessStatusCode) return;
		    if (response.StatusCode == HttpStatusCode.NotModified) return;
		    var content = response.Content.ReadAsStringAsync().Result;
		    ApiException exception ;
		    var htmlMediaType = new MediaTypeHeaderValue("text/html");
		    if (response.Content.Headers.ContentType != null && 
		        response.Content.Headers.ContentType.MediaType == htmlMediaType.MediaType)
		    {
		        var message = String.Format("Status Code {0}, Uri - {1}", response.StatusCode,
		            response.RequestMessage.RequestUri.AbsoluteUri);
		        exception = new ApiException(message, new Exception(content));
		    }
		    else if (!String.IsNullOrEmpty(content))
		        exception = JsonConvert.DeserializeObject<ApiException>(content);
		    else if (HttpStatusCode.NotFound == response.StatusCode && string.IsNullOrEmpty(content) && request != null)
                exception = new ApiException("Uri "+request.RequestUri.AbsoluteUri + " does not exist");
            else
		        exception = new ApiException("Unknow Exception");
		    exception.HttpStatusCode = response.StatusCode;
		    exception.CorrelationId = HttpHelper.GetHeaderValue(Headers.X_VOL_CORRELATION, response.Headers);
		    exception.ApiContext = apiContext;
		    if (!MozuConfig.ThrowExceptionOn404 &&
		        string.Equals(exception.ErrorCode, "ITEM_NOT_FOUND", StringComparison.OrdinalIgnoreCase)
		        && response.RequestMessage.Method.Method == "GET")
		        return;
		    throw exception;
        }