/// <summary> /// Removes batchitem with the specified batchitem id. /// </summary> /// <param name="id"> unique batchitem id</param> public void Remove(string id) { BatchItemRequest removeItem = this.batchRequests.FirstOrDefault(bid => bid.bId == id); if (removeItem == null) { IdsException exception = new IdsException(string.Format(CultureInfo.InvariantCulture, Resources.BatchItemIdNotFound, id)); this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Error, string.Format(CultureInfo.InvariantCulture, Resources.ExceptionGeneratedMessage, exception.ToString())); IdsExceptionManager.HandleException(exception); } else { this.batchRequests.Remove(removeItem); } }
internal static T SendEmail <T>(ServiceContext context, T entity, String sendToEmail = null) where T : IEntity { try { //Initializing the Dataservice object with ServiceContext DataService.DataService service = new DataService.DataService(context); IdsException exp = null; // Used to signal the waiting test thread that a async operation have completed. ManualResetEvent manualEvent = new ManualResetEvent(false); T returnedEntity = default(T); // Async callback events are anonomous and are in the same scope as the test code, // and therefore have access to the manualEvent variable. service.OnSendEmailAsyncCompleted += (sender, e) => { if (e.Entity == null) { throw new IdsException(e.Error.Message); } Assert.IsNotNull(e); Assert.IsNotNull(e.Entity); manualEvent.Set(); returnedEntity = (T)e.Entity; }; // Call the service method service.SendEmailAsync <T>(entity, sendToEmail); manualEvent.WaitOne(20000, false); Thread.Sleep(10000); if (exp != null) { throw exp; } // Set the event to non-signaled before making next async call. manualEvent.Reset(); return(returnedEntity); } catch (IdsException idsEx) { throw idsEx; } }
/// <summary> /// Returns the response stream by calling REST service. /// </summary> /// <param name="request">The request.</param> /// <returns>Response from REST service.</returns> public override byte[] GetResponseStream(HttpWebRequest request) { FaultHandler handler = new FaultHandler(this.context); byte[] receivedBytes = new byte[0]; try { // Check whether the retryPolicy is null. if (this.context.IppConfiguration.RetryPolicy == null) { // If yes then call the rest service without retry framework enabled. receivedBytes = GetRestServiceCallResponseStream(request); } else { // If no then call the rest service using the execute action of retry framework. this.context.IppConfiguration.RetryPolicy.ExecuteAction(() => { receivedBytes = GetRestServiceCallResponseStream(request); }); } } catch (WebException webException) { // System.Net.HttpWebRequest.Abort() was previously called.-or- The time-out // period for the request expired.-or- An error occurred while processing the request. bool isIps = false; if (this.context.ServiceType == IntuitServicesType.IPS) { isIps = true; } IdsException idsException = handler.ParseResponseAndThrowException(webException, isIps); if (idsException != null) { this.context.IppConfiguration.Logger.CustomLogger.Log(TraceLevel.Error, idsException.ToString()); CoreHelper.AdvancedLogging.Log(idsException.ToString()); throw idsException; } } finally { this.context.RequestId = null; } return(receivedBytes); }
/// <summary> /// Executes a Report (asynchronously) under the specified realm in an asynchronous manner. The realm must be set in the context. /// </summary> /// <param name="reportName">Name of the Report to Run</param> /// <param name="reportsQueryParameters">Report Parameters for query string</param> public void ExecuteReportAsync(string reportName, string reportsQueryParameters) { this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Called Method ExecuteReport Asynchronously."); AsyncRestHandler asyncRestHandler = new AsyncRestHandler(this.serviceContext); asyncRestHandler.OnCallCompleted += new EventHandler <AsyncCallCompletedEventArgs>(this.ExecuteReportAsynCompleted); ReportCallCompletedEventArgs <Report> reportCallCompletedEventArgs = new ReportCallCompletedEventArgs <Report>(); string resourceString = reportName; try { // Builds resource Uri string uri = ""; if (!string.IsNullOrEmpty(reportsQueryParameters)) { uri = string.Format(CultureInfo.InvariantCulture, "{0}/company/{1}/reports/{2}?{3}", Utility.CoreConstants.VERSION, this.serviceContext.RealmId, resourceString, reportsQueryParameters); } else { uri = string.Format(CultureInfo.InvariantCulture, "{0}/company/{1}/reports/{2}", Utility.CoreConstants.VERSION, this.serviceContext.RealmId, resourceString); } // Create request parameters RequestParameters parameters; if (this.serviceContext.IppConfiguration.Message.Request.SerializationFormat == Intuit.Ipp.Core.Configuration.SerializationFormat.Json) { parameters = new RequestParameters(uri, HttpVerbType.GET, Utility.CoreConstants.CONTENTTYPE_APPLICATIONJSON); } else { parameters = new RequestParameters(uri, HttpVerbType.GET, Utility.CoreConstants.CONTENTTYPE_APPLICATIONXML); } // Prepare request HttpWebRequest request = asyncRestHandler.PrepareRequest(parameters, new Report()); //// get response asyncRestHandler.GetResponse(request); } catch (SystemException systemException) { this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(TraceLevel.Error, systemException.Message); IdsException idsException = new IdsException(systemException.Message); reportCallCompletedEventArgs.Error = idsException; this.OnExecuteReportAsyncCompleted(this, reportCallCompletedEventArgs); } }
/// <summary> /// call back method for asynchronous batch execution. /// </summary> /// <param name="sender">The sender.</param> /// <param name="eventArgs">The <see cref="Intuit.Ipp.Core.AsyncCallCompletedEventArgs"/> instance containing the event data.</param> private void BatchAsyncompleted(object sender, AsyncCallCompletedEventArgs eventArgs) { BatchExecutionCompletedEventArgs batchCompletedEventArgs = new BatchExecutionCompletedEventArgs(); try { if (eventArgs.Error == null) { try { IEntitySerializer responseSerializer = CoreHelper.GetSerializer(this.serviceContext, false); IntuitResponse restResponse = (IntuitResponse)responseSerializer.Deserialize <IntuitResponse>(eventArgs.Result); foreach (object obj in restResponse.AnyIntuitObjects) { BatchItemResponse batchItemResponse = obj as BatchItemResponse; this.batchResponses.Add(batchItemResponse); // process batch item this.intuitBatchItemResponses.Add(ProcessBatchItemResponse(batchItemResponse)); } batchCompletedEventArgs.Batch = this; this.OnBatchExecuteAsyncCompleted(this, batchCompletedEventArgs); } catch (SystemException systemException) { IdsException idsException = new IdsException("Batch execution failed", systemException); this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(TraceLevel.Error, idsException.ToString()); batchCompletedEventArgs.Error = idsException; this.OnBatchExecuteAsyncCompleted(this, batchCompletedEventArgs); } } else { batchCompletedEventArgs.Error = eventArgs.Error; this.OnBatchExecuteAsyncCompleted(this, batchCompletedEventArgs); } } catch (Exception e) { IdsException idsException = new IdsException("Batch execution failed", e); this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(TraceLevel.Error, idsException.ToString()); batchCompletedEventArgs.Error = idsException; this.OnBatchExecuteAsyncCompleted(this, batchCompletedEventArgs); } }
internal static T FindByIdAsync <T>(ServiceContext context, T entity) where T : IEntity { //Initializing the Dataservice object with ServiceContext DataService.DataService service = new DataService.DataService(context); bool isFindById = false; IdsException exp = null; // Used to signal the waiting test thread that a async operation have completed. ManualResetEvent manualEvent = new ManualResetEvent(false); T returnedEntity = default(T); // Async callback events are anonomous and are in the same scope as the test code, // and therefore have access to the manualEvent variable. service.OnFindByIdAsyncCompleted += (sender, e) => { Assert.IsNotNull(e); Assert.IsNotNull(e.Entity); manualEvent.Set(); isFindById = true; returnedEntity = (T)e.Entity; }; // Call the service method service.FindByIdAsync <T>(entity); manualEvent.WaitOne(60000, false); Thread.Sleep(10000); // Check if we completed the async call, or fail the test if we timed out. if (!isFindById) { Assert.Fail("FindByID Failed"); } if (exp != null) { throw exp; } // Set the event to non-signaled before making next async call. manualEvent.Reset(); return(returnedEntity); }
/// <summary> /// Adds the specified query. /// </summary> /// <param name="query"> IDS query. </param> /// <param name="id"> unique batchitem id.</param> /// <example> /// query parameter : This parameter takes IDS query string. /// Developers can write LINQ query and convert it the IDS query using QueryService class. /// Please see the example below. In this example LINQ query is converted to it's equivalent IDS query. /// Please refer online documentation more details. /// </example> /// <code> /// QueryService<Customer> customerContext=new QueryService<Customer>(serviceContext); /// string query = this.customerContext.Where(c => c.MiddleName.StartsWith("a") && c.FamilyName.EndsWith("z")).ToIdsQuery(); /// </code> public void Add(string query, string id, List <String> optionsData) { // Create and Add a new BatchItem if (string.IsNullOrEmpty(query)) { IdsException exception = new IdsException(Resources.StringParameterNullOrEmpty, new ArgumentException(Resources.IdString)); this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Error, string.Format(CultureInfo.InvariantCulture, Resources.ExceptionGeneratedMessage, exception.ToString())); IdsExceptionManager.HandleException(exception); } if (string.IsNullOrEmpty(id)) { IdsException exception = new IdsException(Resources.StringParameterNullOrEmpty, new ArgumentException(Resources.IdString)); this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Error, string.Format(CultureInfo.InvariantCulture, Resources.ExceptionGeneratedMessage, exception.ToString())); IdsExceptionManager.HandleException(exception); } if (this.batchRequests.Count > 25) { IdsException exception = new IdsException(Resources.batchItemsExceededMessage, new BatchItemsExceededException(Resources.batchItemsExceededMessage)); this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Error, string.Format(CultureInfo.InvariantCulture, Resources.ExceptionGeneratedMessage, exception.ToString())); IdsExceptionManager.HandleException(exception); } if (this.batchRequests.Count > 0 && this.batchRequests.Find(item => item.bId == id) != null) { IdsException exception = new IdsException(Resources.BatchIdAlreadyUsed, new ArgumentException(Resources.IdString)); this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Error, string.Format(CultureInfo.InvariantCulture, Resources.ExceptionGeneratedMessage, exception.ToString())); IdsExceptionManager.HandleException(exception); } BatchItemRequest batchItem = new BatchItemRequest(); batchItem.AnyIntuitObject = query; batchItem.bId = id; //batchItem.operation = OperationEnum.query; batchItem.operationSpecified = false; if (optionsData != null && optionsData.Count > 0) { batchItem.optionsData = string.Join(",", optionsData.ToArray()).ToLower(); } batchItem.ItemElementName = ItemChoiceType6.Query; this.batchRequests.Add(batchItem); }
internal static void VoidAsync <T>(ServiceContext context, T entity) where T : IEntity { //Initializing the Dataservice object with ServiceContext DataService service = new DataService(context); bool isVoided = false; // Used to signal the waiting test thread that a async operation have completed. ManualResetEvent manualEvent = new ManualResetEvent(false); IdsException exp = null; // Async callback events are anonomous and are in the same scope as the test code, // and therefore have access to the manualEvent variable. service.OnVoidAsyncCompleted += (sender, e) => { isVoided = true; manualEvent.Set(); if (e.Error != null) { exp = e.Error; } }; // Call the service method service.VoidAsync(entity); manualEvent.WaitOne(30000, false); Thread.Sleep(10000); if (exp != null) { throw exp; } //// Check if we completed the async call, or fail the test if we timed out. //if (!isVoided) //{ // return null; //} // Set the event to non-signaled before making next async call. manualEvent.Reset(); }
/// <summary> /// This method executes the batch request Asynchronously. /// </summary> public void ExecuteAsync() { this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Started Executing Method ExecuteAsync for Batch"); AsyncRestHandler asyncRestHandler = new AsyncRestHandler(this.serviceContext); asyncRestHandler.OnCallCompleted += new EventHandler <AsyncCallCompletedEventArgs>(this.BatchAsyncompleted); BatchExecutionCompletedEventArgs batchCompletedEventArgs = new BatchExecutionCompletedEventArgs(); // Create Intuit Batch Request IntuitBatchRequest intuitBatchRequest = new IntuitBatchRequest(); intuitBatchRequest.BatchItemRequest = this.batchRequests.ToArray <BatchItemRequest>(); string uri = string.Format(CultureInfo.InvariantCulture, "{0}/company/{1}/batch", Utility.CoreConstants.VERSION, this.serviceContext.RealmId); // Creates request parameters RequestParameters parameters; if (this.serviceContext.IppConfiguration.Message.Request.SerializationFormat == Intuit.Ipp.Core.Configuration.SerializationFormat.Json) { parameters = new RequestParameters(uri, HttpVerbType.POST, Utility.CoreConstants.CONTENTTYPE_APPLICATIONJSON); } else { parameters = new RequestParameters(uri, HttpVerbType.POST, Utility.CoreConstants.CONTENTTYPE_APPLICATIONXML); } // Prepares request HttpWebRequest request = asyncRestHandler.PrepareRequest(parameters, intuitBatchRequest); try { // gets response asyncRestHandler.GetResponse(request); } catch (SystemException systemException) { IdsException idsException = new IdsException(systemException.Message); this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(TraceLevel.Error, idsException.ToString()); batchCompletedEventArgs.Error = idsException; this.OnBatchExecuteAsyncCompleted(this, batchCompletedEventArgs); } }
/// <summary> /// Parses the error response and prepares the response. /// </summary> /// <param name="errorString">The error string.</param> /// <returns>Ids Exception.</returns> public IdsException ParseErrorResponseAndPrepareException(string errorString) { IdsException idsException = null; // If the error string is null return null. if (string.IsNullOrWhiteSpace(errorString)) { return(idsException); } // Parse the xml to get the error. // Extract the Fault from the response. Fault fault = this.ExtractFaultFromResponse(errorString); // Iterate the Fault and Prepare the exception. idsException = this.IterateFaultAndPrepareException(fault); // return the exception. return(idsException); }
/// <summary> /// Creates the Event Args for Exception/Fault responses from server. /// </summary> /// <param name="exception">The exception class.</param> /// <returns>Async CallCompletedEvent Arguments.</returns> private AsyncCallCompletedEventArgs CreateEventArgsForException(Exception exception) { AsyncCallCompletedEventArgs resultArguments = null; WebException webException = exception as WebException; if (webException != null) { bool isIps = false; if (this.context.ServiceType == IntuitServicesType.IPS) { isIps = true; } FaultHandler handler = new FaultHandler(this.context); IdsException idsException = handler.ParseResponseAndThrowException(webException, isIps); if (idsException != null) { this.context.IppConfiguration.Logger.CustomLogger.Log(TraceLevel.Error, idsException.ToString()); CoreHelper.AdvancedLogging.Log(idsException.ToString()); resultArguments = new AsyncCallCompletedEventArgs(null, idsException); } } else { IdsException idsException = exception as IdsException; if (idsException != null) { this.context.IppConfiguration.Logger.CustomLogger.Log(TraceLevel.Error, idsException.ToString()); CoreHelper.AdvancedLogging.Log(idsException.ToString()); resultArguments = new AsyncCallCompletedEventArgs(null, idsException); } else { this.context.IppConfiguration.Logger.CustomLogger.Log(TraceLevel.Error, idsException.ToString()); CoreHelper.AdvancedLogging.Log(idsException.ToString()); resultArguments = new AsyncCallCompletedEventArgs(null, new IdsException("Exception has been generated.", exception)); } } return(resultArguments); }
/// <summary> /// Adds an entity (asynchronously) under the specified realm in an asynchronous manner. The realm must be set in the context. /// </summary> /// <param name="entity">Entity to Add</param> public void AddTaxCodeAsync(Intuit.Ipp.Data.TaxService taxCode) { this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Called Method Add Asynchronously."); AsyncRestHandler asyncRestHandler = new AsyncRestHandler(this.serviceContext); asyncRestHandler.OnCallCompleted += new EventHandler <AsyncCallCompletedEventArgs>(this.AddTaxCodeAsyncCompleted); GlobalTaxServiceCallCompletedEventArgs <Intuit.Ipp.Data.TaxService> taxServiceCallCompletedEventArgs = new GlobalTaxServiceCallCompletedEventArgs <Intuit.Ipp.Data.TaxService>(); string resourceString = taxCode.GetType().Name.ToLower(CultureInfo.InvariantCulture); try { // Builds resource Uri string uri = string.Format(CultureInfo.InvariantCulture, "{0}/company/{1}/{2}/taxcode", CoreConstants.VERSION, this.serviceContext.RealmId, resourceString); // Create request parameters RequestParameters parameters; if (this.serviceContext.IppConfiguration.Message.Request.SerializationFormat == Intuit.Ipp.Core.Configuration.SerializationFormat.Json) { parameters = new RequestParameters(uri, HttpVerbType.POST, CoreConstants.CONTENTTYPE_APPLICATIONJSON); } else { parameters = new RequestParameters(uri, HttpVerbType.POST, CoreConstants.CONTENTTYPE_APPLICATIONXML); } // Prepare request HttpWebRequest request = asyncRestHandler.PrepareRequest(parameters, taxCode); //// get response asyncRestHandler.GetResponse(request); } catch (SystemException systemException) { this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(TraceLevel.Error, systemException.Message); IdsException idsException = new IdsException(systemException.Message); taxServiceCallCompletedEventArgs.Error = idsException; this.OnAddTaxCodeAsyncCompleted(this, taxServiceCallCompletedEventArgs); } }
/// <summary> /// Initializes a new instance of the <see cref="AsyncService"/> class. /// </summary> /// <param name="serviceContext">IPP Service Context</param> public AsyncService(ServiceContext serviceContext) { if (serviceContext == null) { IdsException exception = new IdsException(Resources.ParameterNotNullMessage, new ArgumentNullException("serviceContext", "The Service Context cannot be null.")); IdsExceptionManager.HandleException(exception); } if (serviceContext.IppConfiguration.Logger == null) { IdsException exception = new IdsException("The Logger cannot be null."); IdsExceptionManager.HandleException(exception); } if (string.IsNullOrWhiteSpace(serviceContext.RealmId)) { InvalidRealmException exception = new InvalidRealmException(); IdsExceptionManager.HandleException(exception); } this.serviceContext = serviceContext; }
public void IdsExceptionConstructorTest2() { string errorMessage = "Unauthorized"; string errorCode = "401"; string source = "Intuit.Ipp.Test"; System.Exception innerException = new ArgumentNullException(); IdsException target = new IdsException(errorMessage, errorCode, source, innerException); IdsException newTarget = null; using (Stream s = new MemoryStream()) { BinaryFormatter formatter = new BinaryFormatter(); formatter.Serialize(s, target); s.Position = 0; // Reset stream position newTarget = (IdsException)formatter.Deserialize(s); } Assert.IsNotNull(newTarget); Assert.AreEqual(newTarget.Message, errorMessage); Assert.AreEqual(newTarget.ErrorCode, errorCode); Assert.AreEqual(newTarget.Source, source); Assert.ReferenceEquals(newTarget.InnerException, innerException); }
/// <summary> /// Parses the Response and throws appropriate exceptions. /// </summary> /// <param name="webException">Web Exception.</param> /// <param name="isIps">Specifies whether the exception is generated by an IPS call.</param> /// <returns>Ids Exception.</returns> internal IdsException ParseResponseAndThrowException(WebException webException, bool isIps = false) { IdsException idsException = null; // Checks whether the webException is null or not. if (webException != null) { // If not null then check the response property of the webException object. if (webException.Response != null) { // There is a response from the Ids server. Cast it to HttpWebResponse. HttpWebResponse errorResponse = (HttpWebResponse)webException.Response; // Get the status code description of the error response. string statusCodeDescription = errorResponse.StatusCode.ToString(); // Get the status code of the error response. int statusCode = (int)errorResponse.StatusCode; string errorString = string.Empty; ICompressor responseCompressor = CoreHelper.GetCompressor(this.context, false); if (!string.IsNullOrWhiteSpace(errorResponse.ContentEncoding) && responseCompressor != null) { using (var responseStream = errorResponse.GetResponseStream()) { using (var decompressedStream = responseCompressor.Decompress(responseStream)) { // Get the response stream. StreamReader reader = new StreamReader(decompressedStream); // Read the Stream errorString = reader.ReadToEnd(); // Close reader reader.Close(); } } } else { using (Stream responseStream = errorResponse.GetResponseStream()) { // Get the response stream. StreamReader reader = new StreamReader(responseStream); // Read the Stream errorString = reader.ReadToEnd(); // Close reader reader.Close(); } } string response_intuit_tid_header = ""; //get intuit_tid header for (int i = 0; i < errorResponse.Headers.Count; ++i) { if (errorResponse.Headers.Keys[i] == "intuit_tid") { response_intuit_tid_header = errorResponse.Headers[i]; } } //Log errorstring to disk CoreHelper.GetRequestLogging(this.context).LogPlatformRequests(" Response Intuit_Tid header: " + response_intuit_tid_header + ", Response Payload: " + errorString, false); if (isIps) { IdsException exception = new IdsException(errorString, statusCode.ToString(CultureInfo.InvariantCulture), webException.Source); this.context.IppConfiguration.Logger.CustomLogger.Log(TraceLevel.Error, exception.ToString()); return(exception); } // Use the above idsException to set to innerException of the specific exception which will be created below. // Ids will set the following error codes. Depending on that we will be throwing specific exceptions. switch (errorResponse.StatusCode) { // Bad Request: 400 case HttpStatusCode.BadRequest: // Parse the error response and create the aggregate exception. idsException = this.ParseErrorResponseAndPrepareException(errorString); idsException = new IdsException(statusCodeDescription, statusCode.ToString(CultureInfo.InvariantCulture), webException.Source, idsException); break; // Unauthorized: 401 case HttpStatusCode.Unauthorized: // Create Invalid Token Exception. idsException = this.ParseErrorResponseAndPrepareException(errorString); InvalidTokenException invalidTokenException = new InvalidTokenException(string.Format(CultureInfo.InvariantCulture, "{0}-{1}", statusCodeDescription, statusCode), idsException); idsException = invalidTokenException; break; // ServiceUnavailable: 503 case HttpStatusCode.ServiceUnavailable: // InternalServerError: 500 case HttpStatusCode.InternalServerError: // Forbidden: 403 case HttpStatusCode.Forbidden: // NotFound: 404 case HttpStatusCode.NotFound: idsException = new IdsException(statusCodeDescription, statusCode.ToString(CultureInfo.InvariantCulture), webException.Source, new EndpointNotFoundException()); break; // Throttle Exceeded: 429 case (HttpStatusCode)429: idsException = new IdsException(statusCodeDescription, statusCode.ToString(CultureInfo.InvariantCulture), webException.Source, new ThrottleExceededException()); break; // Default. Throw generic exception i.e. IdsException. default: // Parse the error response and create the aggregate exception. // TODO: Do we need to give error string in exception also. If so then uncomemnt the below line. // idsException = new IdsException(errorString, statusCode.ToString(CultureInfo.InvariantCulture), webException.Source); idsException = new IdsException(statusCodeDescription, statusCode.ToString(CultureInfo.InvariantCulture), webException.Source); break; } } } // Return the Ids Exception. return(idsException); }
private IdsException IterateFaultAndPrepareException(Fault fault) { if (fault == null) { return(null); } IdsException idsException = null; // Create a list of exceptions. List <IdsError> aggregateExceptions = new List <IdsError>(); // Check whether the fault is null or not. if (fault != null) { // Fault types can be of Validation, Service, Authentication and Authorization. Run them through the switch case. switch (fault.type) { // If Validation errors iterate the Errors and add them to the list of exceptions. case "Validation": case "ValidationFault": if (fault.Error != null && fault.Error.Count() > 0) { foreach (var item in fault.Error) { // Add commonException to aggregateExceptions // CommonException defines four properties: Message, Code, Element, Detail. aggregateExceptions.Add(new IdsError(item.Message, item.code, item.element, item.Detail)); } // Throw specific exception like ValidationException. idsException = new ValidationException(aggregateExceptions); } break; // If Validation errors iterate the Errors and add them to the list of exceptions. case "Service": case "ServiceFault": if (fault.Error != null && fault.Error.Count() > 0) { foreach (var item in fault.Error) { // Add commonException to aggregateExceptions // CommonException defines four properties: Message, Code, Element, Detail. aggregateExceptions.Add(new IdsError(item.Message, item.code, item.element, item.Detail)); } // Throw specific exception like ServiceException. idsException = new ServiceException(aggregateExceptions); } break; // If Validation errors iterate the Errors and add them to the list of exceptions. case "Authentication": case "AuthenticationFault": case "Authorization": case "AuthorizationFault": if (fault.Error != null && fault.Error.Count() > 0) { foreach (var item in fault.Error) { // Add commonException to aggregateExceptions // CommonException defines four properties: Message, Code, Element, Detail. aggregateExceptions.Add(new IdsError(item.Message, item.code, item.element, item.Detail)); } // Throw specific exception like AuthenticationException which is wrapped in SecurityException. idsException = new SecurityException(aggregateExceptions); } break; // Use this as default if there was some other type of Fault default: if (fault.Error != null && fault.Error.Count() > 0) { foreach (var item in fault.Error) { // Add commonException to aggregateExceptions // CommonException defines four properties: Message, Code, Element, Detail. aggregateExceptions.Add(new IdsError(item.Message, item.code, item.element, item.Detail)); } // Throw generic exception like IdsException. idsException = new IdsException(string.Format(CultureInfo.InvariantCulture, "Fault Exception of type: {0} has been generated.", fault.type), aggregateExceptions); } break; } } // Return idsException which will be of type Validation, Service or Security. return(idsException); }
/// <summary> /// Reads the configuration from the config file and converts it to custom /// config objects which the end developer will use to get or set the properties. /// </summary> /// <returns>The custom config object.</returns> public IppConfiguration ReadConfiguration() { IppConfiguration ippConfig = new IppConfiguration(); #if !NETSTANDARD2_0 IppConfigurationSection ippConfigurationSection = IppConfigurationSection.Instance; if (ippConfigurationSection == null) { ippConfig.Logger = new Logger { CustomLogger = new TraceLogger(), RequestLog = new RequestLog { EnableRequestResponseLogging = false, ServiceRequestLoggingLocation = System.IO.Path.GetTempPath() } }; ippConfig.Message = new Message { Request = new Request { CompressionFormat = CompressionFormat.GZip, SerializationFormat = SerializationFormat.Xml//do not change this as it will break code for devs }, Response = new Response { CompressionFormat = CompressionFormat.GZip, SerializationFormat = SerializationFormat.Json } }; ippConfig.BaseUrl = new BaseUrl { Qbo = null, Ips = null, OAuthAccessTokenUrl = null, UserNameAuthentication = null }; ippConfig.MinorVersion = new MinorVersion { Qbo = null }; ippConfig.VerifierToken = new VerifierToken { Value = null }; return(ippConfig); } ippConfig.Logger = new Logger(); ippConfig.Logger.RequestLog = new RequestLog(); ippConfig.Logger.RequestLog.EnableRequestResponseLogging = ippConfigurationSection.Logger.RequestLog.EnableRequestResponseLogging; if (string.IsNullOrEmpty(ippConfigurationSection.Logger.RequestLog.RequestResponseLoggingDirectory)) { ippConfig.Logger.RequestLog.ServiceRequestLoggingLocation = Path.GetTempPath(); } else { string location = ippConfigurationSection.Logger.RequestLog.RequestResponseLoggingDirectory; if (!Directory.Exists(location)) { IdsException exception = new IdsException(Properties.Resources.ValidDirectoryPathMessage, new DirectoryNotFoundException()); IdsExceptionManager.HandleException(exception); } ippConfig.Logger.RequestLog.ServiceRequestLoggingLocation = ippConfigurationSection.Logger.RequestLog.RequestResponseLoggingDirectory; } if (!string.IsNullOrEmpty(ippConfigurationSection.Logger.CustomLogger.Name) && !string.IsNullOrEmpty(ippConfigurationSection.Logger.CustomLogger.Type) && ippConfigurationSection.Logger.CustomLogger.Enable) { Type customerLoggerType = Type.GetType(ippConfigurationSection.Logger.CustomLogger.Type); ippConfig.Logger.CustomLogger = Activator.CreateInstance(customerLoggerType) as ILogger; } else { ippConfig.Logger.CustomLogger = new TraceLogger(); } switch (ippConfigurationSection.Security.Mode) { case SecurityMode.OAuth: OAuth2RequestValidator validator = new OAuth2RequestValidator( ippConfigurationSection.Security.OAuth.AccessToken); ippConfig.Security = validator; break; case SecurityMode.Custom: if (!string.IsNullOrEmpty(ippConfigurationSection.Security.CustomSecurity.Name) && !string.IsNullOrEmpty(ippConfigurationSection.Security.CustomSecurity.Type) && ippConfigurationSection.Security.CustomSecurity.Enable) { Type customSecurityType = Type.GetType(ippConfigurationSection.Security.CustomSecurity.Type); string[] paramateres = ippConfigurationSection.Security.CustomSecurity.Params.Split(','); ippConfig.Security = Activator.CreateInstance(customSecurityType, paramateres) as IRequestValidator; } break; } //// TODO : This will not be used now. ////if (!string.IsNullOrEmpty(ippConfigurationSection.Message.CustomSerializer.Name) && !string.IsNullOrEmpty(ippConfigurationSection.Message.CustomSerializer.Type) && ippConfigurationSection.Message.CustomSerializer.Enable) ////{ //// Type customSerializerType = Type.GetType(ippConfigurationSection.Message.CustomSerializer.Type); //// IEntitySerializer entitySerializer = Activator.CreateInstance(customSerializerType) as IEntitySerializer; //// if (ippConfigurationSection.Message.Request.SerializationFormat == SerializationFormat.Custom) //// { //// ippConfig.Message.Request.Serializer = entitySerializer; //// } //// if (ippConfigurationSection.Message.Response.SerializationFormat == SerializationFormat.Custom) //// { //// ippConfig.Message.Response.Serializer = entitySerializer; //// } ////} ippConfig.Message = new Message(); ippConfig.Message.Request = new Request(); ippConfig.Message.Response = new Response(); switch (ippConfigurationSection.Message.Request.CompressionFormat) { case Intuit.Ipp.Utility.CompressionFormat.None: ippConfig.Message.Request.CompressionFormat = CompressionFormat.None; break; case Intuit.Ipp.Utility.CompressionFormat.DEFAULT: case Intuit.Ipp.Utility.CompressionFormat.GZip: ippConfig.Message.Request.CompressionFormat = CompressionFormat.GZip; break; case Intuit.Ipp.Utility.CompressionFormat.Deflate: ippConfig.Message.Request.CompressionFormat = CompressionFormat.Deflate; break; default: break; } switch (ippConfigurationSection.Message.Response.CompressionFormat) { case Intuit.Ipp.Utility.CompressionFormat.None: ippConfig.Message.Response.CompressionFormat = CompressionFormat.None; break; case Intuit.Ipp.Utility.CompressionFormat.DEFAULT: case Intuit.Ipp.Utility.CompressionFormat.GZip: ippConfig.Message.Response.CompressionFormat = CompressionFormat.GZip; break; case Intuit.Ipp.Utility.CompressionFormat.Deflate: ippConfig.Message.Response.CompressionFormat = CompressionFormat.Deflate; break; } switch (ippConfigurationSection.Message.Request.SerializationFormat) { case Intuit.Ipp.Utility.SerializationFormat.DEFAULT: case Intuit.Ipp.Utility.SerializationFormat.Xml: ippConfig.Message.Request.SerializationFormat = SerializationFormat.Xml; //do not change this as it will break code for devs break; case Intuit.Ipp.Utility.SerializationFormat.Json: ippConfig.Message.Request.SerializationFormat = SerializationFormat.Json; break; case Intuit.Ipp.Utility.SerializationFormat.Custom: ippConfig.Message.Request.SerializationFormat = SerializationFormat.Custom; break; } switch (ippConfigurationSection.Message.Response.SerializationFormat) { case Intuit.Ipp.Utility.SerializationFormat.Xml: ippConfig.Message.Response.SerializationFormat = SerializationFormat.Xml; break; case Intuit.Ipp.Utility.SerializationFormat.DEFAULT: case Intuit.Ipp.Utility.SerializationFormat.Json: ippConfig.Message.Response.SerializationFormat = SerializationFormat.Json; break; case Intuit.Ipp.Utility.SerializationFormat.Custom: ippConfig.Message.Response.SerializationFormat = SerializationFormat.Custom; break; } switch (ippConfigurationSection.Retry.Mode) { case RetryMode.Linear: if (!CoreHelper.IsInvalidaLinearRetryMode( ippConfigurationSection.Retry.LinearRetry.RetryCount, ippConfigurationSection.Retry.LinearRetry.RetryInterval)) { ippConfig.RetryPolicy = new IntuitRetryPolicy( ippConfigurationSection.Retry.LinearRetry.RetryCount, ippConfigurationSection.Retry.LinearRetry.RetryInterval); } break; case RetryMode.Incremental: if (!CoreHelper.IsInvalidaIncrementalRetryMode( ippConfigurationSection.Retry.IncrementatlRetry.RetryCount, ippConfigurationSection.Retry.IncrementatlRetry.InitialInterval, ippConfigurationSection.Retry.IncrementatlRetry.Increment)) { ippConfig.RetryPolicy = new IntuitRetryPolicy( ippConfigurationSection.Retry.IncrementatlRetry.RetryCount, ippConfigurationSection.Retry.IncrementatlRetry.InitialInterval, ippConfigurationSection.Retry.IncrementatlRetry.Increment); } break; case RetryMode.Exponential: if (!CoreHelper.IsInvalidaExponentialRetryMode( ippConfigurationSection.Retry.ExponentialRetry.RetryCount, ippConfigurationSection.Retry.ExponentialRetry.MinBackoff, ippConfigurationSection.Retry.ExponentialRetry.MaxBackoff, ippConfigurationSection.Retry.ExponentialRetry.DeltaBackoff)) { ippConfig.RetryPolicy = new IntuitRetryPolicy( ippConfigurationSection.Retry.ExponentialRetry.RetryCount, ippConfigurationSection.Retry.ExponentialRetry.MinBackoff, ippConfigurationSection.Retry.ExponentialRetry.MaxBackoff, ippConfigurationSection.Retry.ExponentialRetry.DeltaBackoff); } break; } ippConfig.BaseUrl = new BaseUrl(); ippConfig.BaseUrl.Qbo = ippConfigurationSection.Service.BaseUrl.Qbo; ippConfig.BaseUrl.Ips = ippConfigurationSection.Service.BaseUrl.Ips; ippConfig.BaseUrl.OAuthAccessTokenUrl = ippConfigurationSection.Service.BaseUrl.OAuthAccessTokenUrl; ippConfig.BaseUrl.UserNameAuthentication = ippConfigurationSection.Service.BaseUrl.UserNameAuthentication; ippConfig.MinorVersion = new MinorVersion(); ippConfig.MinorVersion.Qbo = ippConfigurationSection.Service.MinorVersion.Qbo; ippConfig.VerifierToken = new VerifierToken(); ippConfig.VerifierToken.Value = ippConfigurationSection.WebhooksService.WebhooksVerifier.Value; #endif #if NETSTANDARD2_0 //Setting defaults for configurations #region defaults ippConfig.Logger = new Logger { CustomLogger = new TraceLogger(), RequestLog = new RequestLog { EnableRequestResponseLogging = false, ServiceRequestLoggingLocation = System.IO.Path.GetTempPath() } }; ippConfig.Message = new Message { Request = new Request { CompressionFormat = CompressionFormat.GZip, SerializationFormat = SerializationFormat.Json }, Response = new Response { CompressionFormat = CompressionFormat.GZip, SerializationFormat = SerializationFormat.Json } }; ippConfig.BaseUrl = new BaseUrl { Qbo = null, Ips = null, OAuthAccessTokenUrl = null, UserNameAuthentication = null }; ippConfig.MinorVersion = new MinorVersion { Qbo = null }; ippConfig.VerifierToken = new VerifierToken { Value = null }; #endregion //ippConfig.Logger = new Logger(); //ippConfig.Logger.RequestLog = new RequestLog(); //Read all appsettings.json sections var loggerSettings = builder.GetSection("Logger").GetSection("RequestLog"); var customLoggerSettings = builder.GetSection("CustomLogger").GetSection("RequestLog"); var securitySettings = builder.GetSection("Security").GetSection("Mode"); var securityOauthSettings = builder.GetSection("Security").GetSection("Mode").GetSection("OAuth"); var securityCustomSettings = builder.GetSection("Security").GetSection("Mode").GetSection("Custom"); var messageRequestSettings = builder.GetSection("Message").GetSection("Request"); var messageResponseSettings = builder.GetSection("Message").GetSection("Response"); var retrySettings = builder.GetSection("Retry").GetSection("Mode"); var retrySettingsLinear = builder.GetSection("Retry").GetSection("Mode").GetSection("LinearRetry"); var retrySettingsIncremental = builder.GetSection("Retry").GetSection("Mode").GetSection("IncrementalRetry"); var retrySettingsExponential = builder.GetSection("Retry").GetSection("Mode").GetSection("ExponentialRetry"); var serviceSettings = builder.GetSection("Service"); var serviceBaseUrlSettings = builder.GetSection("Service").GetSection("BaseUrl"); var serviceMinorversionSettings = builder.GetSection("Service").GetSection("Minorversion"); var webhooksVerifierTokenSettings = builder.GetSection("WebhooksService").GetSection("VerifierToken"); if (!string.IsNullOrEmpty(loggerSettings["LogDirectory"]) && Convert.ToBoolean(loggerSettings["Enablelogs"]) == true) { ippConfig.Logger.RequestLog.EnableRequestResponseLogging = Convert.ToBoolean(loggerSettings["Enablelogs"]); string location = loggerSettings["LogDirectory"]; if (!Directory.Exists(location)) { IdsException exception = new IdsException(Properties.Resources.ValidDirectoryPathMessage, new DirectoryNotFoundException()); IdsExceptionManager.HandleException(exception); } ippConfig.Logger.RequestLog.ServiceRequestLoggingLocation = loggerSettings["LogDirectory"]; } if (!string.IsNullOrEmpty(customLoggerSettings["Name"]) && !string.IsNullOrEmpty(customLoggerSettings["Type"]) && Convert.ToBoolean(customLoggerSettings["Enable"]) == true) { Type customerLoggerType = Type.GetType(customLoggerSettings["Type"]); ippConfig.Logger.CustomLogger = Activator.CreateInstance(customerLoggerType) as ILogger; } else { ippConfig.Logger.CustomLogger = new TraceLogger(); } if (!string.IsNullOrEmpty(securityOauthSettings["AccessToken"]) && Convert.ToBoolean(securityOauthSettings["Enable"]) == true) { OAuth2RequestValidator validator = new OAuth2RequestValidator( securityOauthSettings["AccessToken"]); ippConfig.Security = validator; } else if (securityCustomSettings["Enable"] == "true") { if (!string.IsNullOrEmpty(securityCustomSettings["Name"]) && !string.IsNullOrEmpty(securityCustomSettings["Type"]) && Convert.ToBoolean(securityCustomSettings["Enable"]) == true) { Type customSecurityType = Type.GetType(securityCustomSettings["Type"]); if (!string.IsNullOrEmpty(securityCustomSettings["Params"])) { string[] paramateres = securityCustomSettings["Params"].Split(','); ippConfig.Security = Activator.CreateInstance(customSecurityType, paramateres) as IRequestValidator; } } } ippConfig.Message = new Message(); ippConfig.Message.Request = new Request(); ippConfig.Message.Response = new Response(); if (!string.IsNullOrEmpty(messageRequestSettings["CompressionFormat"])) { switch (Enum.Parse(typeof(Utility.CompressionFormat), messageRequestSettings["CompressionFormat"])) { case Intuit.Ipp.Utility.CompressionFormat.None: ippConfig.Message.Request.CompressionFormat = CompressionFormat.None; break; case Intuit.Ipp.Utility.CompressionFormat.DEFAULT: case Intuit.Ipp.Utility.CompressionFormat.GZip: ippConfig.Message.Request.CompressionFormat = CompressionFormat.GZip; break; case Intuit.Ipp.Utility.CompressionFormat.Deflate: ippConfig.Message.Request.CompressionFormat = CompressionFormat.Deflate; break; default: break; } } if (!string.IsNullOrEmpty(messageResponseSettings["CompressionFormat"])) { switch (Enum.Parse(typeof(Utility.CompressionFormat), messageResponseSettings["CompressionFormat"])) { case Intuit.Ipp.Utility.CompressionFormat.None: ippConfig.Message.Response.CompressionFormat = CompressionFormat.None; break; case Intuit.Ipp.Utility.CompressionFormat.DEFAULT: case Intuit.Ipp.Utility.CompressionFormat.GZip: ippConfig.Message.Response.CompressionFormat = CompressionFormat.GZip; break; case Intuit.Ipp.Utility.CompressionFormat.Deflate: ippConfig.Message.Response.CompressionFormat = CompressionFormat.Deflate; break; } } if (!string.IsNullOrEmpty(messageRequestSettings["SerializationFormat"])) { switch (Enum.Parse(typeof(Utility.SerializationFormat), messageRequestSettings["SerializationFormat"])) { case Intuit.Ipp.Utility.SerializationFormat.DEFAULT: case Intuit.Ipp.Utility.SerializationFormat.Xml: ippConfig.Message.Request.SerializationFormat = SerializationFormat.Xml; break; case Intuit.Ipp.Utility.SerializationFormat.Json: ippConfig.Message.Request.SerializationFormat = SerializationFormat.Json; break; case Intuit.Ipp.Utility.SerializationFormat.Custom: ippConfig.Message.Request.SerializationFormat = SerializationFormat.Custom; break; } } if (!string.IsNullOrEmpty(messageResponseSettings["SerializationFormat"])) { switch (Enum.Parse(typeof(Utility.SerializationFormat), messageResponseSettings["SerializationFormat"])) { case Intuit.Ipp.Utility.SerializationFormat.Xml: ippConfig.Message.Response.SerializationFormat = SerializationFormat.Xml; break; case Intuit.Ipp.Utility.SerializationFormat.DEFAULT: case Intuit.Ipp.Utility.SerializationFormat.Json: ippConfig.Message.Response.SerializationFormat = SerializationFormat.Json; break; case Intuit.Ipp.Utility.SerializationFormat.Custom: ippConfig.Message.Response.SerializationFormat = SerializationFormat.Custom; break; } } if ((!string.IsNullOrEmpty(retrySettingsLinear["Enable"])) && Convert.ToBoolean(retrySettingsLinear["Enable"]) == true) { if (!string.IsNullOrEmpty(retrySettingsLinear["RetryCount"]) && !string.IsNullOrEmpty(retrySettingsLinear["RetryInterval"])) { if (!CoreHelper.IsInvalidaLinearRetryMode( Convert.ToInt32(retrySettingsLinear["RetryCount"]), TimeSpan.Parse(retrySettingsLinear["RetryInterval"]))) { ippConfig.RetryPolicy = new IntuitRetryPolicy( Convert.ToInt32(retrySettingsLinear["RetryCount"]), TimeSpan.Parse(retrySettingsLinear["RetryInterval"])); } } } else if ((!string.IsNullOrEmpty(retrySettingsIncremental["Enable"])) && Convert.ToBoolean(retrySettingsIncremental["Enable"]) == true) { if (!string.IsNullOrEmpty(retrySettingsLinear["RetryCount"]) && !string.IsNullOrEmpty(retrySettingsLinear["InitialInterval"]) && !string.IsNullOrEmpty(retrySettingsLinear["Increment"])) { if (!CoreHelper.IsInvalidaIncrementalRetryMode( Convert.ToInt32(retrySettingsIncremental["RetryCount"]), TimeSpan.Parse(retrySettingsIncremental["InitialInterval"]), TimeSpan.Parse(retrySettingsIncremental["Increment"]))) { ippConfig.RetryPolicy = new IntuitRetryPolicy( Convert.ToInt32(retrySettingsIncremental["RetryCount"]), TimeSpan.Parse(retrySettingsIncremental["InitialInterval"]), TimeSpan.Parse(retrySettingsIncremental["Increment"])); } } } else if ((!string.IsNullOrEmpty(retrySettingsExponential["Enable"])) && Convert.ToBoolean(retrySettingsExponential["Enable"]) == true) { if (!string.IsNullOrEmpty(retrySettingsLinear["RetryCount"]) && !string.IsNullOrEmpty(retrySettingsLinear["MinBackoff"]) && !string.IsNullOrEmpty(retrySettingsLinear["MaxBackoff"]) && !string.IsNullOrEmpty(retrySettingsLinear["DeltaBackoff"])) { if (!CoreHelper.IsInvalidaExponentialRetryMode( Convert.ToInt32(retrySettingsExponential["RetryCount"]), TimeSpan.Parse(retrySettingsExponential["MinBackoff"]), TimeSpan.Parse(retrySettingsExponential["MaxBackoff"]), TimeSpan.Parse(retrySettingsExponential["DeltaBackoff"]))) { ippConfig.RetryPolicy = new IntuitRetryPolicy( Convert.ToInt32(retrySettingsExponential["RetryCount"]), TimeSpan.Parse(retrySettingsExponential["MinBackoff"]), TimeSpan.Parse(retrySettingsExponential["MaxBackoff"]), TimeSpan.Parse(retrySettingsExponential["DeltaBackoff"])); } } } //ippConfig.BaseUrl = new BaseUrl(); ippConfig.BaseUrl.Qbo = serviceBaseUrlSettings["Qbo"]; ippConfig.BaseUrl.Ips = serviceBaseUrlSettings["Ips"]; ippConfig.BaseUrl.OAuthAccessTokenUrl = serviceBaseUrlSettings["OAuthAccessTokenUrl"]; ippConfig.BaseUrl.UserNameAuthentication = serviceBaseUrlSettings["UserNameAuthentication"]; //ippConfig.MinorVersion = new MinorVersion(); ippConfig.MinorVersion.Qbo = serviceMinorversionSettings["Qbo"]; //ippConfig.VerifierToken = new VerifierToken(); ippConfig.VerifierToken.Value = webhooksVerifierTokenSettings["Value"]; #endif //#if NETSTANDARD2_0 // //IppConfiguration ippConfig = new IppConfiguration(); // string temppath = Path.Combine(this.logPath, "Request-" + DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture) + ".txt"); // ippConfig.Logger = new Logger // { // RequestLog = new RequestLog // { // EnableRequestResponseLogging = true,//test // ServiceRequestLoggingLocation = temppath // } // }; //#endif return(ippConfig); }
/// <summary> /// Creates the ids exception. /// </summary> /// <param name="applicationException">The application exception.</param> /// <returns>Returns the IdsException.</returns> private static IdsException CreateIdsException(Exception applicationException) { IdsException idsException = new IdsException(applicationException.Message); return(idsException); }
internal static List <T> FindAllAsync <T>(ServiceContext context, T entity, int startPosition = 1, int maxResults = 500) where T : IEntity { //Initializing the Dataservice object with ServiceContext DataService service = new DataService(context); bool isFindAll = false; IdsException exp = null; // Used to signal the waiting test thread that a async operation have completed. ManualResetEvent manualEvent = new ManualResetEvent(false); List <T> entities = new List <T>(); // Async callback events are anonomous and are in the same scope as the test code, // and therefore have access to the manualEvent variable. service.OnFindAllAsyncCompleted += (sender, e) => { isFindAll = true; manualEvent.Set(); if (e.Error != null) { exp = e.Error; } if (exp == null) { if (e.Entities != null) { foreach (IEntity en in e.Entities) { entities.Add((T)en); } } } }; // Call the service method service.FindAllAsync <T>(entity, 1, 10); manualEvent.WaitOne(60000, false); Thread.Sleep(10000); //// Check if we completed the async call, or fail the test if we timed out. //if (!isFindAll) //{ // return null; //} if (exp != null) { throw exp; } //if (entities != null) //{ // Assert.IsTrue(entities.Count >= 0); //} // Set the event to non-signaled before making next async call. manualEvent.Reset(); return(entities); }
/// <summary> /// Handles Exception thrown to the user. /// </summary> /// <param name="idsException">Ids Exception</param> public static void HandleException(IdsException idsException) { throw idsException; }
private AsyncCallCompletedEventArgs CreateEventArgsForRequest(IAsyncResult asyncResult) { IdsException exception = null; AsyncCallCompletedEventArgs resultArguments = null; byte[] receiveBytes = new byte[0]; bool isResponsePdf = false; // Get the async state of the web request. HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState; // Invoke the end method of the asynchronous call. HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult); string resultString = string.Empty; if (!string.IsNullOrWhiteSpace(response.ContentEncoding) && this.ResponseCompressor != null) { using (var responseStream = response.GetResponseStream()) { using (var decompressedStream = this.ResponseCompressor.Decompress(responseStream)) { if (response.ContentType.ToLower().Contains(CoreConstants.CONTENTTYPE_APPLICATIONPDF.ToLower())) { receiveBytes = ConvertResponseStreamToBytes(decompressedStream); isResponsePdf = true; } else { // Get the response stream. StreamReader reader = new StreamReader(decompressedStream); // Read the Stream resultString = reader.ReadToEnd(); // Close reader reader.Close(); } } } } else { using (Stream responseStream = response.GetResponseStream()) { //get the response in bytes if the conten-type is application/pdf if (response.ContentType.ToLower().Contains(CoreConstants.CONTENTTYPE_APPLICATIONPDF.ToLower())) { receiveBytes = ConvertResponseStreamToBytes(responseStream); isResponsePdf = true; } else { // Get the response stream. StreamReader reader = new StreamReader(responseStream); // Read the Stream resultString = reader.ReadToEnd(); // Close reader reader.Close(); } } } string response_intuit_tid_header = ""; //get intuit_tid header for (int i = 0; i < response.Headers.Count; ++i) { if (response.Headers.Keys[i] == "intuit_tid") { response_intuit_tid_header = response.Headers[i]; } } // Log the response to Disk. this.RequestLogging.LogPlatformRequests(" Response Intuit_Tid header: " + response_intuit_tid_header + ", Response Payload: " + resultString, false); // Log response to Serilog CoreHelper.AdvancedLogging.Log(" Response Intuit_Tid header: " + response_intuit_tid_header + ", Response Payload: " + resultString); //log response to logs TraceSwitch traceSwitch = new TraceSwitch("IPPTraceSwitch", "IPP Trace Switch"); this.context.IppConfiguration.Logger.CustomLogger.Log(TraceLevel.Info, (int)traceSwitch.Level > (int)TraceLevel.Info ? "Got the response from service.\n Start Dump: \n" + resultString : "Got the response from service."); CoreHelper.AdvancedLogging.Log("Got the response from service.\n Start Dump: \n" + resultString); //if response is of not type pdf do as usual if (!isResponsePdf) { // If the response string is null then there was a communication mismatch with the server. So throw exception. if (string.IsNullOrWhiteSpace(resultString)) { exception = new IdsException(Resources.CommunicationErrorMessage, new CommunicationException(Resources.ResponseStreamNullOrEmptyMessage)); resultArguments = new AsyncCallCompletedEventArgs(null, exception); } else { if (this.context.ServiceType == IntuitServicesType.IPS) { // Handle errors here resultArguments = this.HandleErrors(resultString); } else { FaultHandler handler = new FaultHandler(this.context); IdsException idsException = handler.ParseErrorResponseAndPrepareException(resultString); if (idsException != null) { this.context.IppConfiguration.Logger.CustomLogger.Log(TraceLevel.Error, idsException.ToString()); CoreHelper.AdvancedLogging.Log(idsException.ToString()); resultArguments = new AsyncCallCompletedEventArgs(null, idsException); } else { resultArguments = new AsyncCallCompletedEventArgs(resultString, null); } } } } else //if response is of type pdf act accordingly { if (receiveBytes.Length <= 0) { //response equivalent to nullorwhitespace above so act in similar way exception = new IdsException(Resources.CommunicationErrorMessage, new CommunicationException(Resources.ResponseStreamNullOrEmptyMessage)); resultArguments = new AsyncCallCompletedEventArgs(null, exception); } //faults not applicable here since we are expecting only pdf in binary resultArguments = new AsyncCallCompletedEventArgs(null, null, receiveBytes); } return(resultArguments); }
internal static T GetPdfAsync <T>(ServiceContext context, T entity) where T : IEntity { //Initializing the Dataservice object with ServiceContext DataService.DataService service = new DataService.DataService(context); IdsException exp = null; // Used to signal the waiting test thread that a async operation have completed. ManualResetEvent manualEvent = new ManualResetEvent(false); T returnedEntity = default(T); string fileName = String.Empty; byte[] originalBytes = new byte[0]; // Async callback events are anonomous and are in the same scope as the test code, // and therefore have access to the manualEvent variable. service.OnGetPdfAsyncCompleted += (sender, e) => { //bool isFindById = false; Assert.IsNotNull(e); manualEvent.Set(); //isFindById = true; fileName = String.Format(@"C:\{0}_{1}.pdf", entity.GetType().FullName, Guid.NewGuid()); File.WriteAllBytes(fileName, e.PdfBytes); originalBytes = e.PdfBytes; }; // Call the service method service.GetPdfAsync <T>(entity); manualEvent.WaitOne(200000, false); Thread.Sleep(10000); //check if file exists Assert.IsTrue(File.Exists(fileName)); //read the file from bytes and compare bytes byte[] readFromFile = File.ReadAllBytes(fileName); //bytes read from file should be greater than 0 Assert.IsTrue(readFromFile.Length > 0); for (int i = 0; i < readFromFile.Length; i++) { Assert.AreEqual(originalBytes[i], readFromFile[i]); } //cleanup if (File.Exists(fileName)) { File.Delete(fileName); } if (exp != null) { throw exp; } // Set the event to non-signaled before making next async call. manualEvent.Reset(); return(returnedEntity); }
/// <summary> /// Executes a report against a specified realm. The realm must be set in the context. /// </summary> /// <param name="reportName">Name of Report to Run.</param> /// <returns>Returns an updated version of the entity with updated identifier and sync token.</returns> public Report ExecuteReport(string reportName) { this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Called Method ExecuteReport."); // Validate parameter if (string.IsNullOrEmpty(reportName)) { IdsException exception = new IdsException(Resources.ParameterNotNullMessage, new ArgumentNullException(Resources.StringParameterNullOrEmpty)); this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Error, string.Format(CultureInfo.InvariantCulture, Resources.ExceptionGeneratedMessage, exception.ToString())); IdsExceptionManager.HandleException(exception); } string resourceString = reportName; //Build Query Parameters // Builds resource Uri string uri = ""; string reportsQueryParameters = GetReportQueryParameters(); if (reportsQueryParameters.Length > 0) { uri = string.Format(CultureInfo.InvariantCulture, "{0}/company/{1}/reports/{2}?{3}", Utility.CoreConstants.VERSION, this.serviceContext.RealmId, resourceString, reportsQueryParameters); } else { uri = string.Format(CultureInfo.InvariantCulture, "{0}/company/{1}/reports/{2}", Utility.CoreConstants.VERSION, this.serviceContext.RealmId, resourceString); } // Creates request parameters RequestParameters parameters; if (this.serviceContext.IppConfiguration.Message.Request.SerializationFormat == Intuit.Ipp.Core.Configuration.SerializationFormat.Json) { parameters = new RequestParameters(uri, HttpVerbType.GET, Utility.CoreConstants.CONTENTTYPE_APPLICATIONJSON); } else { parameters = new RequestParameters(uri, HttpVerbType.GET, Utility.CoreConstants.CONTENTTYPE_APPLICATIONXML); } // Prepares request HttpWebRequest request = this.restHandler.PrepareRequest(parameters, null); string response = string.Empty; try { // gets response response = this.restHandler.GetResponse(request); } catch (IdsException ex) { IdsExceptionManager.HandleException(ex); } CoreHelper.CheckNullResponseAndThrowException(response); // de serialize object IntuitResponse restResponse = (IntuitResponse)CoreHelper.GetSerializer(this.serviceContext, false).Deserialize <IntuitResponse>(response); this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Finished Executing Method ExecuteReport."); return((Report)(restResponse.AnyIntuitObject as Report)); }
public void ExecuteAction <TResult>(Action <AsyncCallback> beginAction, Func <IAsyncResult, TResult> endAction, Action <TResult> successHandler, Action <Exception> faultHandler) { IntuitRetryHelper.IsArgumentNull(beginAction, "beginAction"); IntuitRetryHelper.IsArgumentNull(endAction, "endAction"); IntuitRetryHelper.IsArgumentNull(successHandler, "successHandler"); IntuitRetryHelper.IsArgumentNull(faultHandler, "faultHandler"); int retryCount = 0; AsyncCallback endInvoke = null; Func <Action, bool> executeWithRetry = null; // Configure a custom callback delegate that invokes the end operation and the success handler if the operation succeedes endInvoke = ar => { var result = default(TResult); if (executeWithRetry(() => result = endAction(ar))) { successHandler(result); } }; // Utility delegate to invoke an action and implement the core retry logic // If the action succeeds (i.e. does not throw an exception) it returns true. // If the action throws, it analizes it for retries. If a retry is required, it restarts the async operation; otherwise, it invokes the fault handler. executeWithRetry = a => { try { // Invoke the callback delegate which can throw an exception if the main async operation has completed with a fault. a(); return(true); } catch (Exception ex) { // Capture the original exception for analysis. var lastError = ex; // Handling of RetryLimitExceededException needs to be done separately. This exception type indicates the application's intent to exit from the retry loop. if (lastError is RetryExceededException) { if (lastError.InnerException != null) { faultHandler(lastError.InnerException); return(false); } else { faultHandler(lastError); return(false); } } else { var delay = TimeSpan.Zero; // Check if we should continue retrying on this exception. If not, invoke the fault handler so that user code can take control. if (!IsTransient(lastError) || ((this.ExtendedRetryException != null) && this.ExtendedRetryException.IsRetryException(ex))) { faultHandler(lastError); return(false); } else { if (delay.TotalMilliseconds < 0) { delay = TimeSpan.Zero; } retryCount = retryCount + 1; if (!this.shouldRetry(retryCount, lastError, out delay)) { WebException webException = ex as WebException; string errorString = string.Empty; if (webException != null) { // If not null then check the response property of the webException object. if (webException.Response != null) { // There is a response from the Ids server. Cast it to HttpWebResponse. HttpWebResponse errorResponse = (HttpWebResponse)webException.Response; // Get the status code description of the error response. string statusCodeDescription = errorResponse.StatusCode.ToString(); // Get the status code of the error response. int statusCode = (int)errorResponse.StatusCode; ICompressor responseCompressor = CoreHelper.GetCompressor(this.context, false); if (!string.IsNullOrWhiteSpace(errorResponse.ContentEncoding) && responseCompressor != null) { using (var responseStream = errorResponse.GetResponseStream()) //Check for decompressing { using (var decompressedStream = responseCompressor.Decompress(responseStream)) { // Get the response stream. StreamReader reader = new StreamReader(decompressedStream); //StreamReader reader = new StreamReader(responseStream); // Read the Stream errorString = reader.ReadToEnd(); // Close reader reader.Close(); } } } else { using (Stream responseStream = errorResponse.GetResponseStream()) { // Get the response stream. StreamReader reader = new StreamReader(responseStream); // Read the Stream errorString = reader.ReadToEnd(); // Close reader reader.Close(); } } // Log the error string to disk. CoreHelper.GetRequestLogging(this.context).LogPlatformRequests(errorString, false); } } Core.Rest.FaultHandler fault = new Core.Rest.FaultHandler(this.context); IdsException idsException = fault.ParseErrorResponseAndPrepareException(errorString); if (idsException != null) { faultHandler(new RetryExceededException(webException.Message, webException.Status.ToString(), webException.Source, idsException)); return(false); } else if (webException != null) { faultHandler(new RetryExceededException(webException.Message, webException.Status.ToString(), webException.Source, webException)); return(false); } faultHandler(new RetryExceededException(ex.Message, ex)); return(false); } // Notify the respective subscribers about this exception. this.OnRetrying(retryCount, lastError, delay); // Sleep for the defined interval before repetitively executing the main async operation. if (retryCount > 2 && delay > TimeSpan.Zero) { Thread.Sleep(delay); } executeWithRetry(() => beginAction(endInvoke)); } } return(false); } }; // Invoke the the main async operation for the first time which should return control to the caller immediately. executeWithRetry(() => beginAction(endInvoke)); }
/// <summary> /// Repetitively executes the specified action while it satisfies the current retry policy. /// </summary> /// <typeparam name="TResult">The type of result expected from the executable action.</typeparam> /// <param name="func">A delegate representing the executable action which returns the result of type R.</param> /// <returns>The result from the action.</returns> private TResult ExecuteAction <TResult>(Func <TResult> func) { IntuitRetryHelper.IsArgumentNull(func, "func"); int retryCount = 1; TimeSpan delay = TimeSpan.Zero; Exception lastError; while (true) { lastError = null; try { return(func()); } catch (RetryExceededException retryExceededException) { // The user code can throw a RetryLimitExceededException to force the exit from the retry loop. // The RetryLimitExceeded exception can have an inner exception attached to it. This is the exception // which we will have to throw up the stack so that callers can handle it. if (retryExceededException.InnerException != null) { throw retryExceededException.InnerException; } else { return(default(TResult)); } } catch (Exception ex) { lastError = ex; if (!IsTransient(lastError) || ((this.ExtendedRetryException != null) && this.ExtendedRetryException.IsRetryException(ex))) { throw; } if (!this.shouldRetry(retryCount++, lastError, out delay)) { WebException webException = ex as WebException; string errorString = string.Empty; if (webException != null) { // If not null then check the response property of the webException object. if (webException.Response != null) { // There is a response from the Ids server. Cast it to HttpWebResponse. HttpWebResponse errorResponse = (HttpWebResponse)webException.Response; // Get the status code description of the error response. string statusCodeDescription = errorResponse.StatusCode.ToString(); // Get the status code of the error response. int statusCode = (int)errorResponse.StatusCode; ICompressor responseCompressor = CoreHelper.GetCompressor(this.context, false); if (!string.IsNullOrWhiteSpace(errorResponse.ContentEncoding) && responseCompressor != null) { using (var responseStream = errorResponse.GetResponseStream()) //Check for decompressing { using (var decompressedStream = responseCompressor.Decompress(responseStream)) { // Get the response stream. StreamReader reader = new StreamReader(decompressedStream); //StreamReader reader = new StreamReader(responseStream); // Read the Stream errorString = reader.ReadToEnd(); // Close reader reader.Close(); } } } else { using (Stream responseStream = errorResponse.GetResponseStream()) { // Get the response stream. StreamReader reader = new StreamReader(responseStream); // Read the Stream errorString = reader.ReadToEnd(); // Close reader reader.Close(); } } // Log the error string to disk. CoreHelper.GetRequestLogging(this.context).LogPlatformRequests(errorString, false); } } Core.Rest.FaultHandler fault = new Core.Rest.FaultHandler(this.context); IdsException idsException = fault.ParseErrorResponseAndPrepareException(errorString); if (idsException != null) { throw new RetryExceededException(webException.Message, webException.Status.ToString(), webException.Source, idsException); } else if (webException != null) { throw new RetryExceededException(webException.Message, webException.Status.ToString(), webException.Source, webException); } throw new RetryExceededException(ex.Message, ex); } } // Perform an extra check in the delay interval. Should prevent from accidentally ending up with the value of -1 that will block a thread indefinitely. // In addition, any other negative numbers will cause an ArgumentOutOfRangeException fault that will be thrown by Thread.Sleep. if (delay.TotalMilliseconds < 0) { delay = TimeSpan.Zero; } this.OnRetrying(retryCount - 1, lastError, delay); if (retryCount > 2 && delay > TimeSpan.Zero) { Thread.Sleep(delay); } } }
/// <summary> /// Reads the configuration from the config file and converts it to custom /// config objects which the end developer will use to get or set the properties. /// </summary> /// <returns>The custom config object.</returns> public IppConfiguration ReadConfiguration() { IppConfigurationSection ippConfigurationSection = IppConfigurationSection.Instance; IppConfiguration ippConfig = new IppConfiguration(); if (ippConfigurationSection == null) { ippConfig.Logger = new Logger { CustomLogger = new TraceLogger(), RequestLog = new RequestLog { EnableRequestResponseLogging = false, ServiceRequestLoggingLocation = System.IO.Path.GetTempPath() } }; ippConfig.Message = new Message { Request = new Request { CompressionFormat = CompressionFormat.GZip, SerializationFormat = SerializationFormat.Xml }, Response = new Response { CompressionFormat = CompressionFormat.GZip, SerializationFormat = SerializationFormat.Json } }; ippConfig.BaseUrl = new BaseUrl { Qbo = null, Ips = null, OAuthAccessTokenUrl = null, UserNameAuthentication = null }; ippConfig.MinorVersion = new MinorVersion { Qbo = null }; ippConfig.VerifierToken = new VerifierToken { Value = null }; return(ippConfig); } ippConfig.Logger = new Logger(); ippConfig.Logger.RequestLog = new RequestLog(); ippConfig.Logger.RequestLog.EnableRequestResponseLogging = ippConfigurationSection.Logger.RequestLog.EnableRequestResponseLogging; if (string.IsNullOrEmpty(ippConfigurationSection.Logger.RequestLog.RequestResponseLoggingDirectory)) { ippConfig.Logger.RequestLog.ServiceRequestLoggingLocation = Path.GetTempPath(); } else { string location = ippConfigurationSection.Logger.RequestLog.RequestResponseLoggingDirectory; if (!Directory.Exists(location)) { IdsException exception = new IdsException(Properties.Resources.ValidDirectoryPathMessage, new DirectoryNotFoundException()); IdsExceptionManager.HandleException(exception); } ippConfig.Logger.RequestLog.ServiceRequestLoggingLocation = ippConfigurationSection.Logger.RequestLog.RequestResponseLoggingDirectory; } if (!string.IsNullOrEmpty(ippConfigurationSection.Logger.CustomLogger.Name) && !string.IsNullOrEmpty(ippConfigurationSection.Logger.CustomLogger.Type) && ippConfigurationSection.Logger.CustomLogger.Enable) { Type customerLoggerType = Type.GetType(ippConfigurationSection.Logger.CustomLogger.Type); ippConfig.Logger.CustomLogger = Activator.CreateInstance(customerLoggerType) as ILogger; } else { ippConfig.Logger.CustomLogger = new TraceLogger(); } switch (ippConfigurationSection.Security.Mode) { case SecurityMode.OAuth: OAuthRequestValidator validator = new OAuthRequestValidator( ippConfigurationSection.Security.OAuth.AccessToken, ippConfigurationSection.Security.OAuth.AccessTokenSecret, ippConfigurationSection.Security.OAuth.ConsumerKey, ippConfigurationSection.Security.OAuth.ConsumerSecret); ippConfig.Security = validator; break; case SecurityMode.Custom: if (!string.IsNullOrEmpty(ippConfigurationSection.Security.CustomSecurity.Name) && !string.IsNullOrEmpty(ippConfigurationSection.Security.CustomSecurity.Type) && ippConfigurationSection.Security.CustomSecurity.Enable) { Type customSecurityType = Type.GetType(ippConfigurationSection.Security.CustomSecurity.Type); string[] paramateres = ippConfigurationSection.Security.CustomSecurity.Params.Split(','); ippConfig.Security = Activator.CreateInstance(customSecurityType, paramateres) as IRequestValidator; } break; } //// TODO : This will not be used now. ////if (!string.IsNullOrEmpty(ippConfigurationSection.Message.CustomSerializer.Name) && !string.IsNullOrEmpty(ippConfigurationSection.Message.CustomSerializer.Type) && ippConfigurationSection.Message.CustomSerializer.Enable) ////{ //// Type customSerializerType = Type.GetType(ippConfigurationSection.Message.CustomSerializer.Type); //// IEntitySerializer entitySerializer = Activator.CreateInstance(customSerializerType) as IEntitySerializer; //// if (ippConfigurationSection.Message.Request.SerializationFormat == SerializationFormat.Custom) //// { //// ippConfig.Message.Request.Serializer = entitySerializer; //// } //// if (ippConfigurationSection.Message.Response.SerializationFormat == SerializationFormat.Custom) //// { //// ippConfig.Message.Response.Serializer = entitySerializer; //// } ////} ippConfig.Message = new Message(); ippConfig.Message.Request = new Request(); ippConfig.Message.Response = new Response(); switch (ippConfigurationSection.Message.Request.CompressionFormat) { case Intuit.Ipp.Utility.CompressionFormat.None: ippConfig.Message.Request.CompressionFormat = CompressionFormat.None; break; case Intuit.Ipp.Utility.CompressionFormat.DEFAULT: case Intuit.Ipp.Utility.CompressionFormat.GZip: ippConfig.Message.Request.CompressionFormat = CompressionFormat.GZip; break; case Intuit.Ipp.Utility.CompressionFormat.Deflate: ippConfig.Message.Request.CompressionFormat = CompressionFormat.Deflate; break; default: break; } switch (ippConfigurationSection.Message.Response.CompressionFormat) { case Intuit.Ipp.Utility.CompressionFormat.None: ippConfig.Message.Response.CompressionFormat = CompressionFormat.None; break; case Intuit.Ipp.Utility.CompressionFormat.DEFAULT: case Intuit.Ipp.Utility.CompressionFormat.GZip: ippConfig.Message.Response.CompressionFormat = CompressionFormat.GZip; break; case Intuit.Ipp.Utility.CompressionFormat.Deflate: ippConfig.Message.Response.CompressionFormat = CompressionFormat.Deflate; break; } switch (ippConfigurationSection.Message.Request.SerializationFormat) { case Intuit.Ipp.Utility.SerializationFormat.DEFAULT: case Intuit.Ipp.Utility.SerializationFormat.Xml: ippConfig.Message.Request.SerializationFormat = SerializationFormat.Xml; break; case Intuit.Ipp.Utility.SerializationFormat.Json: ippConfig.Message.Request.SerializationFormat = SerializationFormat.Json; break; case Intuit.Ipp.Utility.SerializationFormat.Custom: ippConfig.Message.Request.SerializationFormat = SerializationFormat.Custom; break; } switch (ippConfigurationSection.Message.Response.SerializationFormat) { case Intuit.Ipp.Utility.SerializationFormat.Xml: ippConfig.Message.Response.SerializationFormat = SerializationFormat.Xml; break; case Intuit.Ipp.Utility.SerializationFormat.DEFAULT: case Intuit.Ipp.Utility.SerializationFormat.Json: ippConfig.Message.Response.SerializationFormat = SerializationFormat.Json; break; case Intuit.Ipp.Utility.SerializationFormat.Custom: ippConfig.Message.Response.SerializationFormat = SerializationFormat.Custom; break; } switch (ippConfigurationSection.Retry.Mode) { case RetryMode.Linear: if (!CoreHelper.IsInvalidaLinearRetryMode( ippConfigurationSection.Retry.LinearRetry.RetryCount, ippConfigurationSection.Retry.LinearRetry.RetryInterval)) { ippConfig.RetryPolicy = new IntuitRetryPolicy( ippConfigurationSection.Retry.LinearRetry.RetryCount, ippConfigurationSection.Retry.LinearRetry.RetryInterval); } break; case RetryMode.Incremental: if (!CoreHelper.IsInvalidaIncrementalRetryMode( ippConfigurationSection.Retry.IncrementatlRetry.RetryCount, ippConfigurationSection.Retry.IncrementatlRetry.InitialInterval, ippConfigurationSection.Retry.IncrementatlRetry.Increment)) { ippConfig.RetryPolicy = new IntuitRetryPolicy( ippConfigurationSection.Retry.IncrementatlRetry.RetryCount, ippConfigurationSection.Retry.IncrementatlRetry.InitialInterval, ippConfigurationSection.Retry.IncrementatlRetry.Increment); } break; case RetryMode.Exponential: if (!CoreHelper.IsInvalidaExponentialRetryMode( ippConfigurationSection.Retry.ExponentialRetry.RetryCount, ippConfigurationSection.Retry.ExponentialRetry.MinBackoff, ippConfigurationSection.Retry.ExponentialRetry.MaxBackoff, ippConfigurationSection.Retry.ExponentialRetry.DeltaBackoff)) { ippConfig.RetryPolicy = new IntuitRetryPolicy( ippConfigurationSection.Retry.ExponentialRetry.RetryCount, ippConfigurationSection.Retry.ExponentialRetry.MinBackoff, ippConfigurationSection.Retry.ExponentialRetry.MaxBackoff, ippConfigurationSection.Retry.ExponentialRetry.DeltaBackoff); } break; } ippConfig.BaseUrl = new BaseUrl(); ippConfig.BaseUrl.Qbo = ippConfigurationSection.Service.BaseUrl.Qbo; ippConfig.BaseUrl.Ips = ippConfigurationSection.Service.BaseUrl.Ips; ippConfig.BaseUrl.OAuthAccessTokenUrl = ippConfigurationSection.Service.BaseUrl.OAuthAccessTokenUrl; ippConfig.BaseUrl.UserNameAuthentication = ippConfigurationSection.Service.BaseUrl.UserNameAuthentication; ippConfig.MinorVersion = new MinorVersion(); ippConfig.MinorVersion.Qbo = ippConfigurationSection.Service.MinorVersion.Qbo; ippConfig.VerifierToken = new VerifierToken(); ippConfig.VerifierToken.Value = ippConfigurationSection.WebhooksService.WebhooksVerifier.Value; return(ippConfig); }
/// <summary> /// Handles Exception thrown to the user. /// </summary> /// <param name="errorMessage">Error Message</param> /// <param name="errorCode">Error Code.</param> /// <param name="source">Source of the exception.</param> /// <param name="innerException">Ids Exception</param> public static void HandleException(string errorMessage, string errorCode, string source, IdsException innerException) { throw new IdsException(errorMessage, errorCode, source, innerException); }
/// <summary> /// Returns the response by calling REST service. /// </summary> /// <param name="request">The request.</param> /// <returns>Response from REST service.</returns> public override string GetResponse(HttpWebRequest request) { FaultHandler handler = new FaultHandler(this.context); // Create a variable for storing the response. string response = string.Empty; try { // Check whether the retryPolicy is null. if (this.context.IppConfiguration.RetryPolicy == null) { // If yes then call the rest service without retry framework enabled. response = this.CallRestService(request); } else { // If no then call the rest service using the execute action of retry framework. this.context.IppConfiguration.RetryPolicy.ExecuteAction(() => { response = this.CallRestService(request); }); } if (request != null && request.RequestUri != null && request.RequestUri.Segments != null) { if (System.Array.IndexOf(request.RequestUri.Segments, "reports/") >= 0) { if (!response.StartsWith("{\"Report\":")) { response = "{\"Report\":" + response + "}"; } } } if (request != null && request.RequestUri != null && request.RequestUri.Segments != null) { if (System.Array.IndexOf(request.RequestUri.Segments, "taxservice/") >= 0) { //This if condition was added as Json serialization was failing for the FaultResponse bcoz of missing TaxService seriliazation tag on AnyIntuitObject in Fms.cs class if (!response.Contains("Fault")) { if (!response.StartsWith("{\"TaxService\":")) { response = "{\"TaxService\":" + response + "}"; } } } } } catch (RetryExceededException retryExceededException) { // System.Net.HttpWebRequest.Abort() was previously called.-or- The time-out // period for the request expired.-or- An error occurred while processing the request. bool isIps = false; if (this.context.ServiceType == IntuitServicesType.IPS) { isIps = true; } this.context.IppConfiguration.Logger.CustomLogger.Log(TraceLevel.Error, retryExceededException.ToString()); CoreHelper.AdvancedLogging.Log(retryExceededException.ToString()); throw; } catch (WebException webException) { // System.Net.HttpWebRequest.Abort() was previously called.-or- The time-out // period for the request expired.-or- An error occurred while processing the request. bool isIps = false; if (this.context.ServiceType == IntuitServicesType.IPS) { isIps = true; } IdsException idsException = handler.ParseResponseAndThrowException(webException, isIps); if (idsException != null) { this.context.IppConfiguration.Logger.CustomLogger.Log(TraceLevel.Error, idsException.ToString()); CoreHelper.AdvancedLogging.Log(idsException.ToString()); throw idsException; } } finally { this.context.RequestId = null; } if (this.context.ServiceType == IntuitServicesType.IPS) { // Handle errors here Utility.IntuitErrorHandler.HandleErrors(response); } else { // Check the response if there are any fault tags and throw appropriate exceptions. IdsException exception = handler.ParseErrorResponseAndPrepareException(response); if (exception != null) { throw exception; } } // Return the response. return(response); }
/// <summary> /// process batch item response /// </summary> /// <param name="batchitemResponse">The batchitem response.</param> /// <returns> returns IntuitBatchResponse object.</returns> private static IntuitBatchResponse ProcessBatchItemResponse(BatchItemResponse batchitemResponse) { IntuitBatchResponse result = new IntuitBatchResponse(); result.Id = batchitemResponse.bId; Fault fault = batchitemResponse.AnyIntuitObject as Fault; if (fault == null) { CDCResponse cdcResponses = batchitemResponse.AnyIntuitObject as CDCResponse; if (cdcResponses != null) { result.ResponseType = ResponseType.CdcQuery; int count = 1; IntuitCDCResponse returnValue = new IntuitCDCResponse(); object[] queryResponses = cdcResponses.AnyIntuitObjects; if (queryResponses != null) { foreach (QueryResponse queryResponse in queryResponses) { Type type = queryResponse.GetType(); List <IEntity> entities = new List <IEntity>(); PropertyInfo[] propertyInfoArray = type.GetProperties(); foreach (PropertyInfo propertyInfo in propertyInfoArray) { if (true == propertyInfo.PropertyType.IsArray) { object tempEntities = propertyInfo.GetValue(queryResponse, null); if (tempEntities != null) { object[] tempEntityArray = (object[])tempEntities; if (tempEntityArray.Length > 0) { List <IEntity> arr = new List <IEntity>(); string entityName = string.Empty; foreach (object item in tempEntityArray) { entities.Add((IEntity)item); entityName = item.GetType().Name; count++; } returnValue.entities.Add(entityName, entities); } break; } } } result.CDCResponse = returnValue; } } } else { IEntity entity = batchitemResponse.AnyIntuitObject as IEntity; if (entity == null) { QueryResponse queryResponse = batchitemResponse.AnyIntuitObject as QueryResponse; if (queryResponse != null) { result.ResponseType = ResponseType.Query; QueryResponse returnValue = new QueryResponse(); returnValue.totalCount = queryResponse.totalCount; returnValue.totalCountSpecified = queryResponse.totalCountSpecified; result.QueryResponse = returnValue; if (queryResponse.AnyIntuitObjects != null && queryResponse.AnyIntuitObjects.Count() > 0) { foreach (object obj in queryResponse.AnyIntuitObjects) { result.AddEntities(obj as IEntity); } } } else { //Not sure how we end up here } } else { result.ResponseType = ResponseType.Entity; result.Entity = entity; } } } else { result.ResponseType = ResponseType.Exception; IdsException idsException = IterateFaultAndPrepareException(fault); result.Exception = idsException; } return(result); }
/// <summary> /// Executes the Asynchronous Request. /// </summary> /// <param name="asyncRequest">Asynchronous web request.</param> private void ExecAsyncRequestWithRetryPolicy(HttpWebRequest asyncRequest) { AsyncCallCompletedEventArgs resultArguments = null; // Check whether the Method is post. if (asyncRequest.Method == "POST") { // If true then ExecuteAction which calls the service using retry framework. this.context.IppConfiguration.RetryPolicy.ExecuteAction( ac => { // Invoke the begin method of the asynchronous call. asyncRequest.BeginGetRequestStream(ac, asyncRequest); }, ar => { // Invoke the end method of the asynchronous call. HttpWebRequest request = (HttpWebRequest)ar.AsyncState; //enabling header logging in Serilogger WebHeaderCollection allHeaders = request.Headers; CoreHelper.AdvancedLogging.Log(" RequestUrl: " + request.RequestUri); CoreHelper.AdvancedLogging.Log("Logging all headers in the request:"); for (int i = 0; i < allHeaders.Count; i++) { CoreHelper.AdvancedLogging.Log(allHeaders.GetKey(i) + "-" + allHeaders[i]); } // Log Request Body to a file this.RequestLogging.LogPlatformRequests(" RequestUrl: " + request.RequestUri + ", Request Payload: " + this.requestBody, true); // Log Request Body to Serilog CoreHelper.AdvancedLogging.Log(" Request Payload: " + this.requestBody); // Using encoding get the byte value of the requestBody. UTF8Encoding encoding = new UTF8Encoding(); byte[] content = encoding.GetBytes(this.requestBody); TraceSwitch traceSwitch = new TraceSwitch("IPPTraceSwitch", "IPP Trace Switch"); this.context.IppConfiguration.Logger.CustomLogger.Log(TraceLevel.Info, (int)traceSwitch.Level > (int)TraceLevel.Info ? "Adding the payload to request. \n Start dump: " + this.requestBody : "Adding the payload to request."); // Check whether compression is enabled and compress the stream accordingly. if (this.RequestCompressor != null) { // get the request stream. using (var requeststream = request.EndGetRequestStream(ar)) { this.RequestCompressor.Compress(content, requeststream); } } else { // Get the Request stream. using (System.IO.Stream postStream = request.EndGetRequestStream(ar)) { // Write the byte content to the stream. postStream.Write(content, 0, content.Length); } } }, () => { // Action to perform if the asynchronous operation // succeeded. this.ExecuteServiceCallAsync(asyncRequest); }, e => { // Action to perform if the asynchronous operation // failed after all the retries. IdsException idsException = e as IdsException; if (idsException != null) { resultArguments = new AsyncCallCompletedEventArgs(null, idsException); } else { resultArguments = new AsyncCallCompletedEventArgs(null, new IdsException("Exception has been generated.", e)); } this.OnCallCompleted(this, resultArguments); }); } else { // Call the service without writing the request body to request stream. this.ExecuteServiceCallAsync(asyncRequest); } }