/// <summary> /// call back method for asynchronously Executing a Report /// </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 ExecuteReportAsynCompleted(object sender, AsyncCallCompletedEventArgs eventArgs) { ReportCallCompletedEventArgs <Report> reportCallCompletedEventArgs = new ReportCallCompletedEventArgs <Report>(); if (eventArgs.Error == null) { try { IEntitySerializer responseSerializer = CoreHelper.GetSerializer(this.serviceContext, false); string response = eventArgs.Result; if (!response.StartsWith("{\"Report\":")) { response = "{\"Report\":" + response + "}"; } IntuitResponse restResponse = (IntuitResponse)responseSerializer.Deserialize <IntuitResponse>(response); reportCallCompletedEventArgs.Report = restResponse.AnyIntuitObject as Report; this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Finished Executing event Execute ReportAsynCompleted in AsyncService object."); this.OnExecuteReportAsyncCompleted(this, reportCallCompletedEventArgs); } catch (SystemException systemException) { IdsException idsException = CreateIdsException(systemException); this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(TraceLevel.Error, idsException.ToString()); reportCallCompletedEventArgs.Error = idsException; this.OnExecuteReportAsyncCompleted(this, reportCallCompletedEventArgs); } } else { reportCallCompletedEventArgs.Error = eventArgs.Error; this.OnExecuteReportAsyncCompleted(this, reportCallCompletedEventArgs); } }
/// <summary> /// call back method for asynchronously Executing a Report /// </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 AddTaxCodeAsyncCompleted(object sender, AsyncCallCompletedEventArgs eventArgs) { GlobalTaxServiceCallCompletedEventArgs <Intuit.Ipp.Data.TaxService> taxServiceCallCompletedEventArgs = new GlobalTaxServiceCallCompletedEventArgs <Intuit.Ipp.Data.TaxService>(); if (eventArgs.Error == null) { try { IEntitySerializer responseSerializer = CoreHelper.GetSerializer(this.serviceContext, false); IntuitResponse restResponse = (IntuitResponse)responseSerializer.Deserialize <IntuitResponse>(eventArgs.Result); taxServiceCallCompletedEventArgs.TaxService = restResponse.AnyIntuitObject as Intuit.Ipp.Data.TaxService; this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Finished Executing event AddTaxCodeAsyncCompleted in AyncService object."); this.OnAddTaxCodeAsyncCompleted(this, taxServiceCallCompletedEventArgs); } catch (SystemException systemException) { IdsException idsException = CreateIdsException(systemException); this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(TraceLevel.Error, idsException.ToString()); taxServiceCallCompletedEventArgs.Error = idsException; this.OnAddTaxCodeAsyncCompleted(this, taxServiceCallCompletedEventArgs); } } else { taxServiceCallCompletedEventArgs.Error = eventArgs.Error; this.OnAddTaxCodeAsyncCompleted(this, taxServiceCallCompletedEventArgs); } }
public void TimeActivityEntitySerializerTest() { //Term serializableEntity = SerializerTestHelper.CreateTermEntity(); JsonObjectSerializer serializer = new JsonObjectSerializer(); //string serializedJson = serializer.Serialize(serializableEntity); string serializedJson = "{\"QueryResponse\":{\"TimeActivity\":[{\"TxnDate\":\"2013-08-06\",\"NameOf\":\"Employee\",\"EmployeeRef\":{\"value\":\"19\",\"name\":\"DisplayName037e5835\"},\"CustomerRef\":{\"value\":\"57\",\"name\":\"06d3bd51-0f3c-43d6-9\"},\"ItemRef\":{\"value\":\"2\",\"name\":\"Hours\"},\"BillableStatus\":\"NotBillable\",\"Taxable\":false,\"HourlyRate\":0,\"Hours\":10,\"Minutes\":0,\"Description\":\"UpdatedDesca8a\",\"domain\":\"QBO\",\"sparse\":false,\"Id\":\"5\",\"SyncToken\":\"5\",\"MetaData\":{\"CreateTime\":\"2013-08-06T02:07:43-07:00\",\"LastUpdatedTime\":\"2013-08-06T02:23:26-07:00\"}},{\"TxnDate\":\"2013-08-06\",\"NameOf\":\"Employee\",\"EmployeeRef\":{\"value\":\"19\",\"name\":\"DisplayName037e5835\"},\"CustomerRef\":{\"value\":\"57\",\"name\":\"06d3bd51-0f3c-43d6-9\"},\"ItemRef\":{\"value\":\"2\",\"name\":\"Hours\"},\"BillableStatus\":\"NotBillable\",\"Taxable\":false,\"HourlyRate\":0,\"Hours\":10,\"Minutes\":0,\"Description\":\"asdca\",\"domain\":\"QBO\",\"sparse\":false,\"Id\":\"4\",\"SyncToken\":\"0\",\"MetaData\":{\"CreateTime\":\"2013-08-06T02:06:34-07:00\",\"LastUpdatedTime\":\"2013-08-06T02:06:34-07:00\"}},{\"TxnDate\":\"2013-08-06\",\"NameOf\":\"Vendor\",\"VendorRef\":{\"value\":\"34\",\"name\":\"DisplayName_07cc1ef917b54e34accf87300dd2261f\"},\"ItemRef\":{\"value\":\"2\",\"name\":\"Hours\"},\"BillableStatus\":\"NotBillable\",\"Taxable\":false,\"HourlyRate\":0,\"Hours\":13,\"Minutes\":0,\"Description\":\"Updating Employee Time Activity a143d\",\"domain\":\"QBO\",\"sparse\":false,\"Id\":\"3\",\"SyncToken\":\"1\",\"MetaData\":{\"CreateTime\":\"2013-08-05T23:39:15-07:00\",\"LastUpdatedTime\":\"2013-08-05T23:39:43-07:00\"}}],\"startPosition\":1,\"maxResults\":3},\"time\":\"2013-08-06T03:04:31.099-07:00\"}"; IntuitResponse deserializedEntity = (IntuitResponse)serializer.Deserialize <IntuitResponse>(serializedJson); }
public void PreferenceDeSerializerTest() { string serializedJson = "{\"QueryResponse\":{\"Preferences\":[{\"AccountingInfoPrefs\":{\"CustomerTerminology\":\"client\"},\"ProductAndServicesPrefs\":{\"ForSales\":true,\"ForPurchase\":true,\"QuantityWithPriceAndRate\":true,\"QuantityOnHand\":true},\"SalesFormsPrefs\":{\"CustomField\":[{\"CustomField\":[{\"Name\":\"SalesFormsPrefs.UseSalesCustom3\",\"Type\":\"BooleanType\",\"BooleanValue\":false},{\"Name\":\"SalesFormsPrefs.UseSalesCustom2\",\"Type\":\"BooleanType\",\"BooleanValue\":false},{\"Name\":\"SalesFormsPrefs.UseSalesCustom1\",\"Type\":\"BooleanType\",\"BooleanValue\":false}]}],\"CustomTxnNumbers\":false,\"AllowDeposit\":false,\"AllowDiscount\":false,\"AllowEstimates\":false,\"IPNSupportEnabled\":false,\"AllowServiceDate\":false,\"AllowShipping\":false,\"DefaultTerms\":{\"value\":\"3\"}},\"VendorAndPurchasesPrefs\":{\"TrackingByCustomer\":false,\"BillableExpenseTracking\":false,\"POCustomField\":[{\"CustomField\":[{\"Name\":\"PurchasePrefs.UsePurchaseCustom3\",\"Type\":\"BooleanType\",\"BooleanValue\":false},{\"Name\":\"PurchasePrefs.UsePurchaseCustom2\",\"Type\":\"BooleanType\",\"BooleanValue\":false},{\"Name\":\"PurchasePrefs.UsePurchaseCustom1\",\"Type\":\"BooleanType\",\"BooleanValue\":false}]}]},\"TimeTrackingPrefs\":{\"UseServices\":false,\"BillCustomers\":false,\"ShowBillRateToAll\":false,\"MarkTimeEntriesBillable\":false},\"TaxPrefs\":{\"UsingSalesTax\":true},\"CurrencyPrefs\":{\"MultiCurrencyEnabled\":false,\"HomeCurrency\":{\"value\":\"USD\"}},\"OtherPrefs\":{\"NameValue\":[{\"Name\":\"SalesFormsPrefs.DefaultCustomerMessage\"},{\"Name\":\"SalesFormsPrefs.DefaultItem\",\"Value\":\"1\"}]},\"domain\":\"QBO\",\"sparse\":false,\"Id\":\"1\",\"SyncToken\":\"0\",\"MetaData\":{\"CreateTime\":\"2013-07-02T04:37:24-07:00\",\"LastUpdatedTime\":\"2013-07-03T01:24:38-07:00\"}}],\"maxResults\":1},\"time\":\"2013-07-03T01:35:04.566-07:00\"}"; JsonObjectSerializer serializer = new JsonObjectSerializer(); IntuitResponse deserializedEntity = serializer.Deserialize <IntuitResponse>(serializedJson) as IntuitResponse; Assert.IsNotNull(deserializedEntity.AnyIntuitObject); }
/// <summary> /// Adds a TaxCode under the specified realm. The realm must be set in the context. /// </summary> /// <param name="taxCode">TaxCode to Add.</param> /// <returns>Returns an updated version of the entity with updated identifier.</returns> public Intuit.Ipp.Data.TaxService AddTaxCode(Intuit.Ipp.Data.TaxService taxCode) { this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Called Method AddTaxCode for TaxService."); // Validate parameter if (!GlobalTaxServiceHelper.IsTypeNull(taxCode)) { IdsException exception = new IdsException(Resources.ParameterNotNullMessage, new ArgumentNullException(Resources.EntityString)); this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Error, string.Format(CultureInfo.InvariantCulture, Resources.ExceptionGeneratedMessage, exception.ToString())); IdsExceptionManager.HandleException(exception); } string resourceString = taxCode.GetType().Name.ToLower(CultureInfo.InvariantCulture); // Builds resource Uri string uri = string.Format(CultureInfo.InvariantCulture, "{0}/company/{1}/{2}/taxcode", 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.POST, CoreConstants.CONTENTTYPE_APPLICATIONJSON); } else { parameters = new RequestParameters(uri, HttpVerbType.POST, CoreConstants.CONTENTTYPE_APPLICATIONXML); } // Prepares request HttpWebRequest request = this.restHandler.PrepareRequest(parameters, taxCode); 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 Add."); return((Intuit.Ipp.Data.TaxService)(restResponse.AnyIntuitObject as Intuit.Ipp.Data.TaxService)); }
/// <summary> /// This method executes the batch request. /// </summary> public void Execute() { this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Started Executing Method Execute for Batch"); // 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 = this.restHandler.PrepareRequest(parameters, intuitBatchRequest); 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)this.responseSerializer.Deserialize <IntuitResponse>(response); this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Finished Execute method for batch."); foreach (object obj in restResponse.AnyIntuitObjects) { BatchItemResponse batchItemResponse = obj as BatchItemResponse; this.batchResponses.Add(batchItemResponse); // process batch item this.intuitBatchItemResponses.Add(ProcessBatchItemResponse(batchItemResponse)); } }
public void AccountEntitySerializerTest() { Account serializableEntity = SerializerTestHelper.CreateAccountEntity(); JsonObjectSerializer serializer = new JsonObjectSerializer(); string serializedJson = serializer.Serialize(serializableEntity); //serializedJson = "{\"CustomField\":[{\"DefinitionId\":\"1\",\"Name\":\"Field1\",\"Type\":\"StringType\"}]}"; serializedJson = "{\"Account\":{\"Name\":\"Name_updated42b2d\",\"SubAccount\":false,\"Description\":\"description_updated750e4\",\"Active\":true,\"Classification\":\"Expense\",\"AccountType\":\"Expense\",\"AcctNum\":\"96beb5\",\"BankNum\":\"BankNum\",\"OpeningBalance\":100,\"OpeningBalanceDate\":\"2013-06-27\",\"CurrentBalance\":100,\"CurrentBalanceWithSubAccounts\":100,\"OnlineEnabled\":false,\"status\":\"Pending\",\"Id\":\"NG:30031\",\"SyncToken\":\"2\",\"MetaData\":{\"CreateTime\":\"2013-06-27T12:24:58Z\",\"LastUpdatedTime\":\"2013-06-27T12:25:09Z\"},\"CustomField\":[],\"AttachableRef\":[]},\"time\":\"2013-06-27T12:25:09.884Z\"}"; IntuitResponse deserializedEntity = (IntuitResponse)serializer.Deserialize <IntuitResponse>(serializedJson); // SerializerTestHelper.CompareAcconutObjects(deserializedEntity.AnyIntuitObjects.GetValue(0), serializableEntity); Assert.IsNotNull(deserializedEntity.AnyIntuitObject); }
/// <summary> /// Executes the Ids Query and returns the response. /// </summary> /// <param name="idsQuery">The string representation of ids query for getting just the count of records.</param> /// <param name="queryOperationType">Query Operation Type. Default value is query.</param> /// <returns>Count of records.</returns> public long ExecuteIdsQueryForCount(string idsQuery, QueryOperationType queryOperationType = QueryOperationType.query) { // Validate Parameter if (string.IsNullOrWhiteSpace(idsQuery)) { throw new InvalidParameterException(string.Format(CultureInfo.InvariantCulture, "The parameter idsQuery cannot be null or empty.")); } // Buid the service uri string uri = string.Format(CultureInfo.InvariantCulture, "{0}/company/{1}/{2}", CoreConstants.VERSION, this.serviceContext.RealmId, queryOperationType); // Creates request parameters RequestParameters parameters = null; parameters = new RequestParameters(uri, HttpVerbType.POST, CoreConstants.CONTENTTYPE_APPLICATIONTEXT); // Prepares request HttpWebRequest request = this.restHandler.PrepareRequest(parameters, idsQuery); string response = string.Empty; try { // Gets response response = this.restHandler.GetResponse(request); } catch (IdsException ex) { IdsExceptionManager.HandleException(ex); } // Check whether the response is null or empty and throw communication exception. CoreHelper.CheckNullResponseAndThrowException(response); // Deserialize object IntuitResponse restResponse = (IntuitResponse)this.responseSerializer.Deserialize <IntuitResponse>(response); QueryResponse queryResponse = restResponse.AnyIntuitObject as QueryResponse; int totalCount = queryResponse.totalCount; this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Finished Executing Method ExecuteIdsQuery."); return(totalCount); }
/// <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); } }
/// <summary> /// Extracts the Fault from the Error Response. /// </summary> /// <param name="errorString">The error string.</param> /// <returns>Fault object.</returns> private Fault ExtractFaultFromResponse(string errorString) { Fault fault = null; // If the error string is null return null. if (string.IsNullOrWhiteSpace(errorString)) { return(fault); } try { //// TODO: Remove this code after service returns proper response //// This is put in since the service is not returning proper xml header ////if (!errorString.StartsWith("<?xml")) ////{ //// errorString = errorString.Insert(16, " xmlns=\"http://schema.intuit.com/finance/v3\" "); //// errorString = errorString.Insert(0, "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"); ////} if (errorString.Contains("EntitlementsResponse")) { EntitlementsResponse entitlements = (EntitlementsResponse)CoreHelper.GetSerializer(this.context, false).Deserialize <EntitlementsResponse>(errorString); } // Deserialize to IntuitResponse using the Serializer of the context. else { IntuitResponse intuitResponse = (IntuitResponse)CoreHelper.GetSerializer(this.context, false).Deserialize <IntuitResponse>(errorString); // Check whether the object is null or note. Also check for Items property since it has the fault. if (intuitResponse != null && intuitResponse.AnyIntuitObject != null) { // TODO: Check whether only the first item will have fault or not. // Cast the Items to Fault. fault = intuitResponse.AnyIntuitObject as Fault; } } // TODO: Uncomment this if exception has to be added for batch requests. // This is executed if the response is BatchItemResponse for batch requests. // else // { // Deserialize to BatchItemResponse using the Serializer of the context. // BatchItemResponse batchItemResponse = (BatchItemResponse)this.context.Serializer.Deserialize<BatchItemResponse>(errorString); // Check whether the object is null or note. Also check for Item property since it has the fault. // if (batchItemResponse != null && batchItemResponse.Item != null) // { // Cast the Item to Fault. // fault = batchItemResponse.Item as Fault; // } // } } catch (System.Exception ex) { //Download might have Uri in body try { if (new System.Uri(errorString) != null) { return(null); } } catch (UriFormatException) { return(null); } throw ex; } // Return the fault. return(fault); }
/// <summary> /// Entity Service supports multiple queries within a request. Use this method to perform multiple entity query operation. /// </summary> /// <param name="queryOperationValues">The simple query language string collection.</param> /// <typeparam name="TSource">Where TSource is IEntity.</typeparam> /// <returns>Returns a collection of entities for individual simple query.</returns> /// <exception cref="InvalidParameterException">If the parameter is null or empty or exceeds a maximum of five(5) queries.</exception> /// <exception cref="ValidationException">If the query syntax is incorrect.</exception> /// <exception cref="SerializationException">If there were serialization issues with the response from the service.</exception> /// <exception cref="IdsException">When service returned with an error information.</exception> /// <example> /// Usage: /// Use the query service created and invoke the ToIdsQuery method to obtain the simple query as string. /// <code> /// string customerQueryValue = customerContext.Where(c => c.MetaData.CreateTime > this.dateTime).ToIdsQuery(); /// string invoiceQueryValue = invoiceContext.Select(i => new { i.Id, i.status }).ToIdsQuery(); /// </code> /// Invoke the ExecuteMultipleEntityQueries method with the read only collection of the queries. This method can throw exception so surround the method with a try catch block. /// <code> /// <![CDATA[List<string> values = new List<string> { customerQueryValue, invoiceQueryValue };]]> /// try /// { /// <![CDATA[ReadOnlyCollection<ReadOnlyCollection<IEntity>> results = customerContext.ExecuteMultipleEntityQueries<IEntity>(values.AsReadOnly());]]> /// Iterate through the values obtained: /// foreach (var item in results) /// { /// // Read the values /// } /// } /// catch(IdsException) /// { /// // Perform logic here /// } /// </code> /// </example> public System.Collections.ObjectModel.ReadOnlyCollection <System.Collections.ObjectModel.ReadOnlyCollection <TSource> > ExecuteMultipleEntityQueries <TSource>(System.Collections.ObjectModel.ReadOnlyCollection <string> queryOperationValues) where TSource : IEntity { if (queryOperationValues == null || queryOperationValues.Count == 0) { throw new InvalidParameterException(string.Format(CultureInfo.InvariantCulture, "The parameter queryOperationValues cannot be null or empty.")); } if (queryOperationValues.Count > 5) { throw new InvalidParameterException(string.Format(CultureInfo.InvariantCulture, "Query Count exceeded. A maximum of 5 queries can be provided at a time.")); } string idsQuery = string.Empty; foreach (var item in queryOperationValues) { if (!string.IsNullOrWhiteSpace(item)) { idsQuery += item + ";"; } } // Buid the service uri string uri = string.Format(CultureInfo.InvariantCulture, "{0}/company/{1}/query", CoreConstants.VERSION, this.serviceContext.RealmId); // Creates request parameters RequestParameters parameters = null; parameters = new RequestParameters(uri, HttpVerbType.POST, CoreConstants.CONTENTTYPE_APPLICATIONTEXT); // Prepares request HttpWebRequest request = this.restHandler.PrepareRequest(parameters, idsQuery); string response = string.Empty; try { // Gets response response = this.restHandler.GetResponse(request); } catch (IdsException ex) { IdsExceptionManager.HandleException(ex); } // Check whether the response is null or empty and throw communication exception. CoreHelper.CheckNullResponseAndThrowException(response); // Deserialize object IntuitResponse restResponse = (IntuitResponse)this.responseSerializer.Deserialize <IntuitResponse>(response); QueryResponse[] queryResponses = restResponse.AnyIntuitObjects as QueryResponse[]; List <System.Collections.ObjectModel.ReadOnlyCollection <TSource> > returnValues = new List <System.Collections.ObjectModel.ReadOnlyCollection <TSource> >(); foreach (var queryResponse in queryResponses) { Type type = queryResponse.GetType(); List <TSource> entities = new List <TSource>(); 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) { foreach (object item in tempEntityArray) { entities.Add((TSource)item); } } } break; } } returnValues.Add(entities.AsReadOnly()); } this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Finished Executing Method FindAll."); return(returnValues.AsReadOnly()); }
/// <summary> /// Executes the Ids Query and returns the response. /// </summary> /// <param name="idsQuery">The string representation of ids query.</param> /// <param name="queryOperationType">Query Operation Type. Default value is query.</param> /// <returns>ReadOnly Collection fo items of type T.</returns> public System.Collections.ObjectModel.ReadOnlyCollection <T> ExecuteIdsQuery(string idsQuery, QueryOperationType queryOperationType = QueryOperationType.query) { // Validate Parameter if (string.IsNullOrWhiteSpace(idsQuery)) { throw new InvalidParameterException(string.Format(CultureInfo.InvariantCulture, "The parameter idsQuery cannot be null or empty.")); } // Buid the service uri string uri = string.Format(CultureInfo.InvariantCulture, "{0}/company/{1}/{2}", CoreConstants.VERSION, this.serviceContext.RealmId, queryOperationType); // Creates request parameters RequestParameters parameters = null; parameters = new RequestParameters(uri, HttpVerbType.POST, CoreConstants.CONTENTTYPE_APPLICATIONTEXT); // Prepares request HttpWebRequest request = this.restHandler.PrepareRequest(parameters, idsQuery); string response = string.Empty; try { // Gets response response = this.restHandler.GetResponse(request); } catch (IdsException ex) { IdsExceptionManager.HandleException(ex); } // Check whether the response is null or empty and throw communication exception. CoreHelper.CheckNullResponseAndThrowException(response); // Deserialize object IntuitResponse restResponse = (IntuitResponse)this.responseSerializer.Deserialize <IntuitResponse>(response); QueryResponse queryResponse = restResponse.AnyIntuitObject as QueryResponse; if (idsQuery.ToLower().Contains("count(*)")) { int totalCount = queryResponse.totalCount; List <T> dummyCountCollection = new List <T>(); for (int i = 0; i < totalCount; i++) { dummyCountCollection.Add((T)Activator.CreateInstance(typeof(T))); } System.Collections.ObjectModel.ReadOnlyCollection <T> countCollection = new System.Collections.ObjectModel.ReadOnlyCollection <T>(dummyCountCollection); return(countCollection); } List <T> entities = new List <T>(); if (queryResponse.maxResults > 0) { object tempEntities = queryResponse.AnyIntuitObjects; if (tempEntities != null) { object[] tempEntityArray = (object[])tempEntities; if (tempEntityArray.Length > 0) { foreach (object item in tempEntityArray) { entities.Add((T)item); } } } } /* Type type = queryResponse.GetType(); * List<T> entities = new List<T>(); * * PropertyInfo[] propertyInfoArray = type.GetProperties(); * * foreach (PropertyInfo propertyInfo in propertyInfoArray) * { * if (true == propertyInfo.PropertyType.) * { * object tempEntities = propertyInfo.GetValue(queryResponse, null); * if (tempEntities != null) * { * object[] tempEntityArray = (object[])tempEntities; * * if (tempEntityArray.Length > 0) * { * foreach (object item in tempEntityArray) * { * entities.Add((T)item); * } * } * } * * break; * } * }*/ this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Finished Executing Method FindAll."); System.Collections.ObjectModel.ReadOnlyCollection <T> readOnlyCollection = new System.Collections.ObjectModel.ReadOnlyCollection <T>(entities); return(readOnlyCollection); }
/// <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)); }