string CheckErrors(AbstractResponseType abstractResponse) { bool errorsExist = false; string errorList = ""; // First, check the Obvious. Make sure Ack is not Success if (!abstractResponse.Ack.Equals(AckCodeType.Success)) { errorsExist = true; } // Check to make sure there is nothing in the Errors Collection if (abstractResponse.Errors != null) { if (abstractResponse.Errors.Length > 0) { errorsExist = true; // Do something with the errors errorList = "ERROR: "; for (int i = 0; i < abstractResponse.Errors.Length; i++) { // Access each error abstractResponse.Errors[i] and do something errorList += abstractResponse.Errors[i].LongMessage + " (" + abstractResponse.Errors[i].ErrorCode + ")" + Environment.NewLine; } } } return(errorList); }
/// <summary> /// Parses paypal response and returns true if operation succeeds. False otherwise. /// </summary> /// <param name="response"></param> /// <param name="error"></param> /// <returns></returns> public static bool ParseResponseSuccess(AbstractResponseType response, out string error) { var success = false; if (response.Ack.HasValue) { switch (response.Ack) { case AckCodeType.SUCCESS: case AckCodeType.SUCCESSWITHWARNING: success = true; break; } } var builder = new StringBuilder(); var errorFormat = "LongMessage: {0}" + Environment.NewLine + "ShortMessage: {1}" + Environment.NewLine + "ErrorCode: {2}" + Environment.NewLine; if (response.Errors != null) { foreach (var errorType in response.Errors) { if (builder.Length <= 0) { builder.Append(Environment.NewLine); } builder.Append(string.Format(errorFormat, errorType.LongMessage, errorType.ShortMessage, errorType.ErrorCode)); } } error = builder.ToString(); return(success); }
/// <summary> /// Checks response /// </summary> /// <param name="abstractResponse">response</param> /// <param name="errorMsg">Error message if exists</param> /// <returns>True - response OK; otherwise, false</returns> public static bool CheckSuccess(AbstractResponseType abstractResponse, out string errorMsg) { bool success = false; StringBuilder sb = new StringBuilder(); switch (abstractResponse.Ack) { case AckCodeType.Success: case AckCodeType.SuccessWithWarning: success = true; break; default: break; } if (null != abstractResponse.Errors) { foreach (ErrorType errorType in abstractResponse.Errors) { if (sb.Length <= 0) { sb.Append(Environment.NewLine); } sb.Append("LongMessage: ").Append(errorType.LongMessage).Append(Environment.NewLine); sb.Append("ShortMessage: ").Append(errorType.ShortMessage).Append(Environment.NewLine); sb.Append("ErrorCode: ").Append(errorType.ErrorCode).Append(Environment.NewLine); } } errorMsg = sb.ToString(); return(success); }
/// <summary> /// Checks the PayPal API response for errors. /// </summary> /// <param name="abstractResponse">the PayPal API response.</param> /// <returns>The error message list(s) when abstractResponse.Ack is not Success or SuccessWithWarning. When everything OK, return string.Empty.</returns> public string CheckErrors(AbstractResponseType abstractResponse) { var errorList = string.Empty; // First, check the Obvious. Make sure Ack is not Success if (abstractResponse.Ack != AckCodeType.SUCCESS && abstractResponse.Ack != AckCodeType.SUCCESSWITHWARNING) { // The value returned in CorrelationID is important for PayPal to determine the precise cause of any error you might encounter. // If you have to troubleshoot a problem with your requests, capture the value of CorrelationID so you can report it to PayPal. errorList = $"PayPal API {abstractResponse.Version}.{abstractResponse.Build}: [{abstractResponse.Ack.ToString()}] CorrelationID={abstractResponse.CorrelationID}.\n"; if (abstractResponse.Errors.Count > 0) { foreach (var error in abstractResponse.Errors) { errorList += $"\n[{error.SeverityCode.ToString()}-{error.ErrorCode}]: {error.LongMessage}."; } } else { errorList += _localizationService.GetString("/Commerce/Checkout/PayPal/PayPalAPICallError"); } } return(errorList); }
private bool CheckResponse(AbstractResponseType response, out string error) { var retVal = false; if (response != null) { if ((response.Errors != null && response.Errors.Any()) || !(response.Ack.Equals(AckCodeType.SUCCESS) || response.Ack.Equals(AckCodeType.SUCCESSWITHWARNING))) { StringBuilder sb = new StringBuilder(); foreach (var err in response.Errors) { sb.AppendLine(err.LongMessage); } error = sb.ToString(); } else { error = string.Empty; retVal = true; } } else { error = "response in null"; } return(retVal); }
/// <summary> /// Checks response /// </summary> /// <param name="abstractResponse">response</param> /// <param name="errorMsg">Error message if exists</param> /// <returns>True - response OK; otherwise, false</returns> public static bool CheckSuccess(PluginHelper helper, AbstractResponseType abstractResponse, out string errorMsg) { bool success = false; StringBuilder sb = new StringBuilder(); switch (abstractResponse.Ack) { case AckCodeType.Success: case AckCodeType.SuccessWithWarning: success = true; break; default: break; } if (null != abstractResponse.Errors) { foreach (ErrorType errorType in abstractResponse.Errors) { if (sb.Length <= 0) { sb.Append(Environment.NewLine); } sb.AppendLine("{0}: {1}".FormatWith(helper.GetResource("Admin.System.Log.Fields.FullMessage"), errorType.LongMessage)); sb.AppendLine("{0}: {1}".FormatWith(helper.GetResource("Admin.System.Log.Fields.ShortMessage"), errorType.ShortMessage)); sb.Append("Code: ").Append(errorType.ErrorCode).Append(Environment.NewLine); } } errorMsg = sb.ToString(); return(success); }
private static string CheckErrors(AbstractResponseType resp) { string text = ""; if (resp.Ack != AckCodeType.Success) { } string result; if (resp.Errors != null) { if (resp.Errors.Length <= 0) { result = text; return(result); } text = "ERROR: "; for (int i = 0; i < resp.Errors.Length; i++) { string text2 = text; text = string.Concat(new string[] { text2, resp.Errors[i].LongMessage, " (", resp.Errors[i].ErrorCode, ")", Environment.NewLine }); } } result = text; return(result); }
private bool CheckResponse(AbstractResponseType response) { if (response != null) { if (response.Errors != null && response.Errors.Count > 0) { StringBuilder sb = new StringBuilder(); foreach (var error in response.Errors) { sb.Append("LongMessage: ").Append(error.LongMessage).Append(Environment.NewLine); sb.Append("ShortMessage: ").Append(error.ShortMessage).Append(Environment.NewLine); sb.Append("ErrorCode: ").Append(error.ErrorCode).Append(Environment.NewLine); } throw new NullReferenceException(sb.ToString()); } else if (!(response.Ack == AckCodeType.SUCCESS) && !(response.Ack == AckCodeType.SUCCESSWITHWARNING)) { throw new NullReferenceException("Paypal error without detail info"); } } else { throw new NullReferenceException("response in null"); } return(true); }
private string CheckForErrors(AbstractResponseType abstractResponse) { bool errorsExist = false; string errorList = ""; // First, check if Ack is not Success if (!abstractResponse.Ack.Equals(AckCodeType.Success)) { errorsExist = true; } // Check for nothing in the Errors Collection if (abstractResponse.Errors != null) { if (abstractResponse.Errors.Length > 0) { errorsExist = true; errorList = "ERROR: "; for (int i = 0; i < abstractResponse.Errors.Length; i++) { errorList += abstractResponse.Errors[i].LongMessage + " (" + abstractResponse.Errors[i].ErrorCode + ")" + Environment.NewLine; } } } return(errorList); }
/// <summary> /// Check the PayPal API response for errors. /// </summary> /// <param name="abstractResponse">the PayPal API response</param> /// <returns>if abstractResponse.Ack is not Success or SuccessWithWarning, return the error message list(s). If everything OK, return string.empty</returns> public static string CheckErrors(this AbstractResponseType abstractResponse) { string errorList = string.Empty; // First, check the Obvious. Make sure Ack is not Success if (abstractResponse.Ack != AckCodeType.SUCCESS && abstractResponse.Ack != AckCodeType.SUCCESSWITHWARNING) { errorList = string.Format("PayPal API {0}.{1}: [{2}] CorrelationID={3}.\n", abstractResponse.Version, abstractResponse.Build, abstractResponse.Ack.ToString(), abstractResponse.CorrelationID // The value returned in CorrelationID is important for PayPal to determine the precise cause of any error you might encounter. // If you have to troubleshoot a problem with your requests, capture the value of CorrelationID so you can report it to PayPal. ); if (abstractResponse.Errors.Count > 0) { foreach (ErrorType error in abstractResponse.Errors) { errorList += string.Format("\n[{0}-{1}]: {2}.", error.SeverityCode.ToString(), error.ErrorCode, error.LongMessage); } } else { errorList += "Unknown error while calling PayPal API."; // TODO: localize } } return(errorList); }
protected ResultInfoByServerResponseBase(AbstractResponseType response) : base(response.Timestamp) { if (response != null && response.Errors != null) { AddErrors(response.Errors.Select(e => new ErrorInfo(e))); } }
public void CheckErrors_WhenAckCodeIsSuccess_ShouldReturnEmpty(AckCodeType ackCode) { var abstractResponseType = new AbstractResponseType { Ack = ackCode }; var result = _subject.CheckErrors(abstractResponseType); Assert.Equal(string.Empty, result); }
internal static void HandleError(AbstractResponseType resp) { if (resp.Errors != null && resp.Errors.Length > 0) { // errors occured throw new Exception("Exception(s) occured when calling PayPal. First exception: " + resp.Errors[0].LongMessage); } }
public void CheckErrors_WhenAckCodeIsNotSuccessAndResponseHasNoErrors_ShouldReturnCorrectly(AckCodeType ackCode) { var abstractResponseType = new AbstractResponseType { Ack = ackCode }; var result = _subject.CheckErrors(abstractResponseType); Assert.True(!string.IsNullOrEmpty(result)); }
/// <summary> /// Gets the <see cref="ExpressCheckoutResponse"/> from PayPal's <see cref="AbstractResponseType"/>. /// </summary> /// <param name="response"> /// The response. /// </param> /// <param name="token"> /// The token. /// </param> /// <returns> /// The <see cref="ExpressCheckoutResponse"/>. /// </returns> public ExpressCheckoutResponse Build(AbstractResponseType response, string token = "") { return new ExpressCheckoutResponse { Ack = response.Ack, Build = response.Build, ErrorTypes = response.Errors, Token = token, Version = response.Version }; }
/// <summary> /// Gets the <see cref="ExpressCheckoutResponse"/> from PayPal's <see cref="AbstractResponseType"/>. /// </summary> /// <param name="response"> /// The response. /// </param> /// <param name="token"> /// The token. /// </param> /// <returns> /// The <see cref="ExpressCheckoutResponse"/>. /// </returns> public ExpressCheckoutResponse Build(AbstractResponseType response, string token = "") { return(new ExpressCheckoutResponse { Ack = response.Ack, Build = response.Build, ErrorTypes = response.Errors, Token = token, Version = response.Version }); }
public PayPalServiceResponceExceptionWrapper(AbstractResponseType response) { BaseException = new ServiceResponceException(response); if (response.Errors != null && response.Errors.Length != 0) { Errors = response.Errors.Select(err => new ServiceErrorType { ErrorCode = err.ErrorCode, LongMessage = err.LongMessage, SeverityCode = err.SeverityCode.ToString() }).ToArray(); } }
public void CheckErrors_WhenAckCodeIsNotSuccessAndResponseHasErrors_ShouldReturnCorrectly(AckCodeType ackCode) { var errorCode = "E0001"; var message = "ThisIsVeryLongMessage"; var abstractResponseType = new AbstractResponseType { Ack = ackCode }; abstractResponseType.Errors.Add(new ErrorType { SeverityCode = SeverityCodeType.ERROR, ErrorCode = errorCode, LongMessage = message }); var result = _subject.CheckErrors(abstractResponseType); Assert.Contains(SeverityCodeType.ERROR.ToString(), result); Assert.Contains(errorCode, result); Assert.Contains(message, result); }
protected bool IsSuccess(AbstractResponseType abstractResponse, out string errorMsg) { var success = false; var sb = new StringBuilder(); switch (abstractResponse.Ack) { case AckCodeType.Success: case AckCodeType.SuccessWithWarning: success = true; break; default: break; } if (null != abstractResponse.Errors) { foreach (ErrorType errorType in abstractResponse.Errors) { if (errorType.ShortMessage.IsEmpty()) { continue; } if (sb.Length > 0) { sb.Append(Environment.NewLine); } sb.Append("{0}: {1}".FormatInvariant(Services.Localization.GetResource("Admin.System.Log.Fields.ShortMessage"), errorType.ShortMessage)); sb.AppendLine(" ({0}).".FormatInvariant(errorType.ErrorCode)); if (errorType.LongMessage.HasValue() && errorType.LongMessage != errorType.ShortMessage) { sb.AppendLine("{0}: {1}".FormatInvariant(Services.Localization.GetResource("Admin.System.Log.Fields.FullMessage"), errorType.LongMessage)); } } } errorMsg = sb.ToString(); return(success); }
private bool CheckResponse(AbstractResponseType response) { if (response != null) { if (response.Ack.Equals(AckCodeType.FAILURE) || (response.Errors != null && response.Errors.Count > 0)) { StringBuilder sb = new StringBuilder(); foreach (var error in response.Errors) { sb.AppendLine(error.LongMessage); } throw new NullReferenceException(sb.ToString()); } } else { throw new NullReferenceException("response in null"); } return(true); }
public ResultInfoError(AbstractResponseType response) : base(response) { }
public ServiceResponceException(AbstractResponseType response) { _Response = response; }
public FailServiceRequestException(AbstractResponseType response) { ResultInfoError = new ResultInfoError(response); }
/// <summary> /// /// </summary> internal void SendRequest() { try { if (AbstractRequest == null) throw new ApiException("RequestType reference not set to an instance of an object.", new System.ArgumentNullException()); if (ApiContext == null) throw new ApiException("ApiContext reference not set to an instance of an object.", new System.ArgumentNullException()); if (ApiContext.ApiCredential == null) throw new ApiException("Credentials reference in ApiContext object not set to an instance of an object.", new System.ArgumentNullException()); string apiName = AbstractRequest.GetType().Name.Replace("RequestType",""); if (this.ApiContext.EnableMetrics) { mCallMetrics = this.ApiContext.CallMetricsTable.GetNewEntry(apiName); mCallMetrics.ApiCallStarted = System.DateTime.Now; } CustomSecurityHeaderType secHdr = this.GetSecurityHeader(); // Get default constructor. /* ConstructorInfo svcCCTor = this.mServiceType.GetConstructor( BindingFlags.Instance | BindingFlags.Public, null, CallingConventions.HasThis, null, null); */ ConstructorInfo svcCCTor = this.mServiceType.GetConstructor(new Type[] {}); object svcInst = svcCCTor.Invoke(null); PropertyInfo pi; pi = this.mServiceType.GetProperty("ApiLogManager"); if( pi == null ) throw new SdkException("ApiLogManager was not found in InterfaceServiceType"); pi.SetValue(svcInst, this.mApiContext.ApiLogManager, null); pi = this.mServiceType.GetProperty("EnableComression"); if( pi == null ) throw new SdkException("EnableComression was not found in InterfaceServiceType"); pi.SetValue(svcInst, this.mEnableCompression, null); pi = this.mServiceType.GetProperty("RequesterCredentials"); if( pi == null ) throw new SdkException("RequesterCredentials was not found in InterfaceServiceType"); pi.SetValue(svcInst, secHdr, null); pi = this.mServiceType.GetProperty("WebProxy"); if (pi == null) throw new SdkException("WebProxy was not found in InterfaceServiceType"); pi.SetValue(svcInst, this.mApiContext.WebProxy, null); if (this.mApiContext.WebProxy != null) { LogMessage("Proxy Server is Set", MessageType.Information, MessageSeverity.Informational); } pi = this.mServiceType.GetProperty("CallMetricsEntry"); if( pi == null ) throw new SdkException("CallMetricsEntry was not found in InterfaceServiceType"); if (this.ApiContext.EnableMetrics) pi.SetValue(svcInst, this.mCallMetrics, null); else pi.SetValue(svcInst, null, null); string url = ""; try { if (ApiContext.SoapApiServerUrl != null && ApiContext.SoapApiServerUrl.Length > 0) url = String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}?callname={1}&siteid={2}&client=netsoap", ApiContext.SoapApiServerUrl, apiName, SiteUtility.GetSiteID(Site).ToString(System.Globalization.CultureInfo.InvariantCulture)); else { url = (string)this.mServiceType.GetProperty("Url").GetValue(svcInst, null); url = String.Format(System.Globalization.CultureInfo.InvariantCulture, "{0}?callname={1}&siteid={2}&client=netsoap", url, apiName, SiteUtility.GetSiteID(Site).ToString(System.Globalization.CultureInfo.InvariantCulture)); } //svcCCTor.Url = url; this.mServiceType.GetProperty("Url").SetValue(svcInst, url, null); } catch(Exception ex) { throw new ApiException(ex.Message, ex); } LogMessage(url, MessageType.Information, MessageSeverity.Informational); //svcCCTor.Timeout = Timeout; this.mServiceType.GetProperty("Timeout").SetValue(svcInst, Timeout, null); AbstractRequest.Version = Version; if (!mDetailLevelOverride && AbstractRequest.DetailLevel == null) { AbstractRequest.DetailLevel = new DetailLevelCodeTypeCollection(); AbstractRequest.DetailLevel.AddRange(mDetailLevelList); } if (ApiContext.ErrorLanguage != ErrorLanguageCodeType.CustomCode) AbstractRequest.ErrorLanguage = ApiContext.ErrorLanguage.ToString(); //Populate the message AbstractRequest.MessageID = System.Guid.NewGuid().ToString(); Type methodtype = svcInst.GetType(); object[] reqparm = new object[] {AbstractRequest}; int retries = 0; int maxRetries = 0; bool doretry = false; CallRetry retry = null; if (mCallRetry != null) { retry = mCallRetry; maxRetries = retry.MaximumRetries; } else if (ApiContext.CallRetry != null) { retry = ApiContext.CallRetry; maxRetries = retry.MaximumRetries; } do { Exception callException = null; try { mResponse = null; mApiException = null; if (retries > 0) { LogMessage("Invoking Call Retry", MessageType.Information, MessageSeverity.Informational); System.Threading.Thread.Sleep(retry.DelayTime); } if( BeforeRequest != null ) BeforeRequest(this, new BeforeRequestEventArgs(AbstractRequest)); //Invoke the Service DateTime start = DateTime.Now; mResponse = (AbstractResponseType) methodtype.GetMethod(apiName).Invoke(svcInst, reqparm); mResponseTime = DateTime.Now - start; if( AfterRequest != null ) AfterRequest(this, new AfterRequestEventArgs(mResponse)); // Catch Token Expiration warning if (mResponse != null && secHdr.HardExpirationWarning != null) { ApiContext.ApiCredential.TokenHardExpirationWarning( System.Convert.ToDateTime(secHdr.HardExpirationWarning, System.Globalization.CultureInfo.CurrentUICulture)); } if (mResponse != null && mResponse.Errors != null && mResponse.Errors.Count > 0) { throw new ApiException(new ErrorTypeCollection(mResponse.Errors)); } } catch (Exception ex) { // this catches soap faults if (ex.GetType() == typeof(TargetInvocationException)) { // we never care about the outer exception Exception iex = ex.InnerException; // Parse Soap Faults if (iex.GetType() == typeof(SoapException)) { ex = ApiException.FromSoapException((SoapException) iex); } else if (iex.GetType() == typeof(InvalidOperationException)) { // Go to innermost exception while (iex.InnerException != null) iex = iex.InnerException; ex = new ApiException(iex.Message, iex); } else if (iex.GetType() == typeof(HttpException)) { HttpException httpEx = (HttpException) iex; String str = "HTTP Error Code: " + httpEx.StatusCode; ex = new ApiException(str, iex); } else { ex = new ApiException(iex.Message, iex); } } callException = ex; // log the message - override current switches - *if* (a) we wouldn't normally log it, and (b) // the exception matches the exception filter. if (retry != null) doretry = retry.ShouldRetry(ex); if (!doretry || retries == maxRetries) { throw ex; } else { string soapReq = (string)this.mServiceType.GetProperty("SoapRequest").GetValue(svcInst, null); string soapResp = (string)this.mServiceType.GetProperty("SoapResponse").GetValue(svcInst, null); LogMessagePayload(soapReq + "\r\n\r\n" + soapResp, MessageSeverity.Informational, ex); MessageSeverity svr = ((ApiException) ex).SeverityErrorCount > 0 ? MessageSeverity.Error : MessageSeverity.Warning; LogMessage(ex.Message, MessageType.Exception, svr); } } finally { string soapReq = (string)this.mServiceType.GetProperty("SoapRequest").GetValue(svcInst, null); string soapResp = (string)this.mServiceType.GetProperty("SoapResponse").GetValue(svcInst, null); if (!doretry || retries == maxRetries) LogMessagePayload(soapReq + "\r\n\r\n" + soapResp, MessageSeverity.Informational, callException); if (mResponse != null && mResponse.TimestampSpecified) ApiContext.CallUpdate(mResponse.Timestamp); else ApiContext.CallUpdate(new DateTime(0)); mSoapRequest = soapReq; mSoapResponse = soapResp; retries++; } } while (doretry && retries <= maxRetries); } catch (Exception ex) { ApiException aex = ex as ApiException; if (aex != null) { mApiException = aex; } else { mApiException = new ApiException(ex.Message, ex); } MessageSeverity svr = mApiException.SeverityErrorCount > 0 ? MessageSeverity.Error : MessageSeverity.Warning; LogMessage(mApiException.Message, MessageType.Exception, svr); if (mApiException.SeverityErrorCount > 0) throw mApiException; } finally { if (this.ApiContext.EnableMetrics) mCallMetrics.ApiCallEnded = DateTime.Now; } }
/// <summary> /// /// </summary> /// <param name="AbstractResponse">The <see cref="AbstractResponse"/> for this API Call.</param> public AfterRequestEventArgs(AbstractResponseType AbstractResponse) { mResponse = AbstractResponse; }