/// <summary>
        /// DeSerializes the specified action entity type.
        /// </summary>
        /// <typeparam name="T">The type to be  serialize to</typeparam>
        /// <param name="message">The message.</param>
        /// <returns>
        /// Returns the de serialized object.
        /// </returns>
        public object Deserialize <T>(string message)
        {
            object deserializedObject = null;

            // Initialize serialize for object
            XmlSerializer serializer = new XmlSerializer(typeof(T));

            try
            {
                using (TextReader reader = new StringReader(message))
                {
                    // de serialization of message.
                    deserializedObject = serializer.Deserialize(reader);
                }
            }
            catch (SystemException ex)
            {
                SerializationException serializationException = new SerializationException(ex.Message, ex);
                this.IDSLogger.Log(TraceLevel.Error, serializationException.ToString());

                IdsExceptionManager.HandleException(serializationException);
            }

            return(deserializedObject);
        }
        /// <summary>
        /// Serializes the specified entity in Json Format.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <returns>
        /// Returns the serialize entity in string format.
        /// </returns>
        public string Serialize(object entity)
        {
            string data = string.Empty;
            JsonSerializerSettings settings = new JsonSerializerSettings();

            settings.Converters.Add(new ObjectToEnumConverter());
            settings.Converters.Add(new IntuitConverter());

            settings.NullValueHandling     = NullValueHandling.Ignore;
            settings.MissingMemberHandling = MissingMemberHandling.Error;
            settings.DateFormatHandling    = DateFormatHandling.IsoDateFormat;
            settings.DateTimeZoneHandling  = DateTimeZoneHandling.Utc;
            settings.DateFormatString      = "yyyy-MM-ddTHH:mm:ssK";
            try
            {
                data = JsonConvert.SerializeObject(entity, settings);
            }
            catch (Exception ex)
            {
                SerializationException serializationException = new SerializationException(ex.Message, ex);
                this.IDSLogger.Log(TraceLevel.Error, serializationException.ToString());
                IdsExceptionManager.HandleException(serializationException);
            }
            data = data.Replace("T00:00:00Z", "");
            data = data.Replace("T00:00:00", "");
            return(data);
        }
Beispiel #3
0
        /// <summary>
        /// Logs the Platform Request to Disk.
        /// </summary>
        /// <param name="xml">The xml to log.</param>
        /// <param name="isRequest">Specifies whether the xml is request or response.</param>
        internal void LogPlatformRequests(string xml, bool isRequest)
        {
            if (this.EnableServiceRequestsLogging)
            {
                if (string.IsNullOrWhiteSpace(this.ServiceRequestLoggingLocation))
                {
                    this.ServiceRequestLoggingLocation = Path.GetTempPath();
                }

                string filePath = string.Empty;
                if (isRequest)
                {
                    filePath = string.Format(CultureInfo.InvariantCulture, CoreConstants.REQUESTFILENAME_FORMAT, this.ServiceRequestLoggingLocation, CoreConstants.SLASH_CHAR, DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture));
                }
                else
                {
                    filePath = string.Format(CultureInfo.InvariantCulture, CoreConstants.RESPONSEFILENAME_FORMAT, this.ServiceRequestLoggingLocation, CoreConstants.SLASH_CHAR, DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture));
                }

                try
                {
                    Encoding encoder = Encoding.GetEncoding("utf-8", new EncoderExceptionFallback(), new DecoderExceptionFallback());
                    byte[]   data    = encoder.GetBytes(xml);
                    using (FileStream fs = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write))
                    {
                        fs.Write(data, 0, data.Length);
                    }
                }
                catch (System.Exception exception)
                {
                    IdsException idsException = new IdsException("Exception has been generated. Check inner exception for details.", exception);
                    IdsExceptionManager.HandleException(idsException);
                }
            }
        }
        /// <summary>
        /// Logs the Platform Request to Disk.
        /// </summary>
        /// <param name="xml">The xml to log.</param>
        /// <param name="isRequest">Specifies whether the xml is request or response.</param>
        public void LogPlatformRequests(bool enableLogging, string xml, bool isRequest)
        {
            if (this.EnableServiceRequestsLogging)
            {
                if (string.IsNullOrWhiteSpace(this.ServiceRequestLoggingLocation))
                {
                    this.ServiceRequestLoggingLocation = Path.GetTempPath();
                }

                string filePath = string.Empty;
                if (isRequest)
                {
                    filePath = string.Format(CultureInfo.InvariantCulture, "{0}{1}OAuth2Request-{2}.txt", this.ServiceRequestLoggingLocation, "/", DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture));
                }
                else
                {
                    filePath = string.Format(CultureInfo.InvariantCulture, "{0}{1}OAuth2Response-{2}.txt", this.ServiceRequestLoggingLocation, "/", DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture));
                }

                try
                {
                    Encoding encoder = Encoding.GetEncoding("utf-8", new EncoderExceptionFallback(), new DecoderExceptionFallback());
                    byte[]   data    = encoder.GetBytes(xml);
                    using (FileStream fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
                    {
                        fs.Write(data, 0, data.Length);
                    }
                }
                catch (System.Exception exception)
                {
                    IdsException idsException = new IdsException("Exception has been generated. Check inner exception for details.", exception);
                    IdsExceptionManager.HandleException(idsException);
                }
            }
        }
        /// <summary>
        /// DeSerializes the specified action entity type in Json Format.
        /// </summary>
        /// <typeparam name="T">The type to be  serialize to</typeparam>
        /// <param name="message">The message.</param>
        /// <returns>
        /// Returns the de serialized object.
        /// </returns>
        public object Deserialize <T>(string message)
        {
            object deserializedObject = null;

            // Initialize serialize for object
            JsonSerializerSettings settings = new JsonSerializerSettings();

            settings.Converters.Add(new ObjectToEnumConverter());
            settings.Converters.Add(new IntuitConverter());

            settings.NullValueHandling     = NullValueHandling.Ignore;
            settings.MissingMemberHandling = MissingMemberHandling.Ignore;

            try
            {
                // de serialization of message.

                /*  JObject o = JObject.Parse(message);
                 * string key = o.Properties().Select(p => p.Name).Single();
                 * string entityString = o[key].ToString();*/
                deserializedObject = JsonConvert.DeserializeObject <T>(message, settings);
            }
            catch (SystemException ex)
            {
                SerializationException serializationException = new SerializationException(ex.Message, ex);
                this.IDSLogger.Log(TraceLevel.Error, serializationException.ToString());
                IdsExceptionManager.HandleException(serializationException);
            }

            return(deserializedObject);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ServiceContext"/> class.
        /// </summary>
        /// <param name="appToken">Application Token.</param>
        /// <param name="realmId">The realm id.</param>
        /// <param name="serviceType">Service Type - QBO.</param>
        /// <param name="requestValidator">The request validate.</param>
        /// <returns>Returns ServiceContext object.</returns>
        /// <exception cref="Intuit.Ipp.Exception.IdsException">If arguments are null or empty.</exception>
        /// <exception cref="Intuit.Ipp.Exception.InvalidRealmException">If realm id is invalid.</exception>
        /// <exception cref="Intuit.Ipp.Exception.InvalidTokenException">If the token is invalid.</exception>
        public ServiceContext(string appToken, string realmId, IntuitServicesType serviceType, IRequestValidator requestValidator = null)
            : this()
        {
            // Validate Parameters
            if (string.IsNullOrWhiteSpace(appToken))
            {
                IdsExceptionManager.HandleException(new IdsException(Properties.Resources.ParameterNotNullMessage, new ArgumentNullException(Properties.Resources.AppTokenParameterName, Properties.Resources.ParameterNotNullMessage)));
            }

            if (string.IsNullOrWhiteSpace(realmId))
            {
                IdsExceptionManager.HandleException(new InvalidRealmException(Properties.Resources.ParameterNotNullEmptyMessage, new ArgumentException(Properties.Resources.ParameterNotNullMessage, Properties.Resources.RealmIdParameterName)));
            }

            this.realmId     = realmId;
            this.serviceType = serviceType;
            this.appToken    = appToken;
            if (requestValidator != null)
            {
                this.IppConfiguration.Security = requestValidator;
            }

            if (this.IppConfiguration.Security == null)
            {
                throw new InvalidTokenException("Atleast one security mechanism has to be specified for the SDK to work. Either use config file or use constructor to specify the authenticatio type.");
            }

            this.baseserviceURL = this.GetBaseURL();
            this.isCreateMethod = false;
        }
Beispiel #7
0
        /// <summary>
        /// Adds the specified entity operation.
        /// </summary>
        /// <param name="entity">entitiy for the batch operation.</param>

        public void Add(IEntity entity)
        {
            // Create and Add a new BatchItem
            if (entity == null)
            {
                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);
            }

            if (this.recurringTxnRequests.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);
            }



            RecurringTransaction recurrTxnItem = new RecurringTransaction();

            //tring entityTypeToParseTo = entity.GetType().Name;
            //IEntity mappedEntity = "Intuit.Ipp.Data." + entityTypeToParseTo;
            RecurrTransactionChoiceType result;

            entity.GetType();
            if (Enum.TryParse(entity.GetType().Name, out result))
            {
                recurrTxnItem.AnyIntuitObject = entity as result;
            }

            this.batchRequests.Add(batchItem);
        }
 /// <summary>
 /// Validates the Service context.
 /// </summary>
 /// <param name="serviceContext">Service Context.</param>
 internal static void ServiceContextValidation(ServiceContext serviceContext)
 {
     if (serviceContext == null)
     {
         IdsException exception = new IdsException(Resources.ParameterNotNullMessage, new ArgumentNullException(Resources.ServiceContextParameterName, Resources.ServiceContextNotNullMessage));
         IdsExceptionManager.HandleException(exception);
     }
 }
 /// <summary>
 /// Validate if passed object is null
 /// </summary>
 /// <param name="obj"></param>
 /// <param name="serviceContext"></param>
 internal static void ValidateObject(Object obj, ServiceContext serviceContext)
 {
     if (obj == null)
     {
         IdsException exception = new IdsException(Resources.FieldNullOrEmpty);
         serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Error, string.Format(CultureInfo.InvariantCulture, Resources.ExceptionGeneratedMessage, exception.ToString()));
         IdsExceptionManager.HandleException(exception);
     }
 }
 /// <summary>
 /// Validates if entity is null
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="entity"></param>
 /// <param name="serviceContext"></param>
 internal static void ValidateEntity <T>(T entity, ServiceContext serviceContext) where T : IEntity
 {
     if (!IsTypeNull(entity))
     {
         IdsException exception = new IdsException(Resources.ParameterNotNullMessage, new ArgumentNullException(Resources.EntityString));
         serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Error, string.Format(CultureInfo.InvariantCulture, Resources.ExceptionGeneratedMessage, exception.ToString()));
         IdsExceptionManager.HandleException(exception);
     }
 }
 /// <summary>
 /// Validate Id field null or white space for IntuitEntity object
 /// </summary>
 /// <param name="Id"></param>
 /// <param name="serviceContext"></param>
 internal static void ValidateId(string Id, ServiceContext serviceContext)
 {
     if (string.IsNullOrWhiteSpace(Id))
     {
         IdsException exception = new IdsException(Resources.EntityIdNotNullMessage, new ArgumentNullException(Resources.IdString));
         serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Error, string.Format(CultureInfo.InvariantCulture, Resources.ExceptionGeneratedMessage, exception.ToString()));
         IdsExceptionManager.HandleException(exception);
     }
 }
 /// <summary>
 /// Validate if IntuitEntity was converted successfully
 /// </summary>
 /// <param name="intuitEntity"></param>
 /// <param name="serviceContext"></param>
 internal static void ValidateIntuitEntity(IntuitEntity intuitEntity, ServiceContext serviceContext)
 {
     if (intuitEntity == null)
     {
         IdsException exception = new IdsException(Resources.EntityConversionFailedMessage);
         serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Error, string.Format(CultureInfo.InvariantCulture, Resources.ExceptionGeneratedMessage, exception.ToString()));
         IdsExceptionManager.HandleException(exception);
     }
 }
        /// <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>
        /// Validate if type of entity is same as specified type
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <param name="type"></param>
        internal static void ValidateEntityType <T>(T entity, string type, ServiceContext serviceContext) where T : IEntity
        {
            string entityType = entity.GetType().Name;

            if (entityType != type)
            {
                IdsException exception = new IdsException(entityType + ": " + Resources.OperationNotSupportedOnEntity);
                serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Error, string.Format(CultureInfo.InvariantCulture, Resources.ExceptionGeneratedMessage, exception.ToString()));
                IdsExceptionManager.HandleException(exception);
            }
        }
Beispiel #15
0
        /// <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 HandleExceptionTest4()
        {
            InvalidTokenException exception = new InvalidTokenException();

            try
            {
                IdsExceptionManager.HandleException(exception);
            }
            catch (IdsException target)
            {
                Assert.ReferenceEquals(target, exception);
            }
        }
        public void HandleExceptionTest3()
        {
            string errorMessage = "Unauthorized";

            try
            {
                IdsExceptionManager.HandleException(errorMessage);
            }
            catch (IdsException target)
            {
                Assert.AreEqual(target.Message, errorMessage);
            }
        }
        /// <summary>
        /// Adds the specified entity operation.
        /// </summary>
        /// <param name="entity">entitiy for the batch operation.</param>
        /// <param name="id">Unique batchitem id</param>
        /// <param name="operation">operation to be performed for the entity.</param>
        public void Add(IEntity entity, string id, OperationEnum operation, List <String> optionsData)
        {
            // Create and Add a new BatchItem
            if (entity == null)
            {
                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);
            }

            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    = entity;
            batchItem.bId                = id;
            batchItem.operation          = operation;
            batchItem.operationSpecified = true;
            if (optionsData != null && optionsData.Count > 0)
            {
                batchItem.optionsData = string.Join(",", optionsData.ToArray()).ToLower();
            }
            ItemChoiceType6 result;

            if (Enum.TryParse(entity.GetType().Name, out result))
            {
                batchItem.ItemElementName = result;
            }

            this.batchRequests.Add(batchItem);
        }
Beispiel #19
0
        /// <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);
        }
        public void HandleExceptionTest2()
        {
            string errorMessage = "Unauthorized";
            InvalidServiceRequestException innerException = new InvalidServiceRequestException();

            try
            {
                IdsExceptionManager.HandleException(errorMessage, innerException);
            }
            catch (IdsException target)
            {
                Assert.AreEqual(target.Message, errorMessage);
                Assert.ReferenceEquals(target.InnerException, innerException);
            }
        }
Beispiel #21
0
        /// <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);
            }
        }
        public void HandleExceptionTest()
        {
            string errorMessage = "Unauthorized";
            string errorCode    = "401";
            string source       = "Intuit.Ipp.Test";

            try
            {
                IdsExceptionManager.HandleException(errorMessage, errorCode, source);
            }
            catch (IdsException target)
            {
                Assert.AreEqual(target.Message, errorMessage);
                Assert.AreEqual(target.ErrorCode, errorCode);
                Assert.AreEqual(target.Source, source);
            }
        }
        public void HandleExceptionTest1()
        {
            string errorMessage = "Unauthorized";
            string errorCode    = "401";
            string source       = "Intuit.Ipp.Test";
            InvalidRealmException innerException = new InvalidRealmException();

            try
            {
                IdsExceptionManager.HandleException(errorMessage, errorCode, source, innerException);
            }
            catch (IdsException target)
            {
                Assert.AreEqual(target.Message, errorMessage);
                Assert.AreEqual(target.ErrorCode, errorCode);
                Assert.AreEqual(target.Source, source);
                Assert.ReferenceEquals(target.InnerException, innerException);
            }
        }
Beispiel #24
0
        /// <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;
        }
Beispiel #25
0
        /// <summary>
        /// Gets entitlements against a specified realm. The realm must be set in the context.
        /// </summary>
        /// <param name="entitlementBaseUrl">Base Url of the Entitlements API for OAuth1 vs OAuth2. Default is set to OAuth2 prod environment.</param>
        /// <returns>Returns EntitlementsResponse</returns>
        public EntitlementsResponse GetEntitlements(string entitlementBaseUrl = Utility.CoreConstants.ENTITLEMENT_BASEURL)
        {
            this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Called Method GetEntitlements.");
            string uri = string.Format(CultureInfo.InvariantCulture, "{0}/entitlements/{1}/{2}", entitlementBaseUrl, Utility.CoreConstants.VERSION, serviceContext.RealmId);

            orginialSerializationFormat = this.serviceContext.IppConfiguration.Message.Response.SerializationFormat;

            // Only XML format is supported by Entitlements API
            serviceContext.IppConfiguration.Message.Response.SerializationFormat = Core.Configuration.SerializationFormat.Xml;
            // Creates request parameters
            RequestParameters parameters = new RequestParameters(uri, HttpVerbType.GET, Utility.CoreConstants.CONTENTTYPE_APPLICATIONXML);

            // Prepares request
            HttpWebRequest request = this.restHandler.PrepareRequest(parameters, null, uri);

            string response = string.Empty;

            try
            {
                // gets response
                response = this.restHandler.GetResponse(request);
            }
            catch (IdsException ex)
            {
                IdsExceptionManager.HandleException(ex);
            }

            CoreHelper.CheckNullResponseAndThrowException(response);

            // de serialize object
            EntitlementsResponse restResponse = (EntitlementsResponse)CoreHelper.GetSerializer(this.serviceContext, false).Deserialize <EntitlementsResponse>(response);

            this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Finished Executing Method GetEntitlements.");

            // change Response Serialization Format back to Config value
            serviceContext.IppConfiguration.Message.Response.SerializationFormat = orginialSerializationFormat;

            return(restResponse);
        }
        /// <summary>
        /// Serializes the specified entity.
        /// </summary>
        /// <param name="entity">The entity.</param>
        /// <returns>
        /// Returns the serialize entity in string format.
        /// </returns>
        public string Serialize(object entity)
        {
            string data = string.Empty;

            try
            {
                UTF8Encoding encoder = new UTF8Encoding();
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    XmlSerializer xmlSerializer = new XmlSerializer(entity.GetType());
                    xmlSerializer.Serialize(memoryStream, entity);
                    data = encoder.GetString(memoryStream.ToArray());
                }
            }
            catch (SystemException ex)
            {
                SerializationException serializationException = new SerializationException(ex.Message, ex);
                this.IDSLogger.Log(TraceLevel.Error, serializationException.ToString());
                IdsExceptionManager.HandleException(serializationException);
            }
            data = data.Replace("T00:00:00Z", "");
            data = data.Replace("T00:00:00", "");
            return(data);
        }
        /// <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>
        /// 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);
        }
Beispiel #29
0
        /// <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);
        }
Beispiel #30
0
        /// <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());
        }