Ошибка службы Windows для исключения System.OutOfMemory - PullRequest
0 голосов
/ 28 сентября 2018

Я создал службу Windows, которая работает каждые 1,5 часа 24 часа в сутки.Этот сервис использует API, извлекает записи из API и сохраняет записи в нашей базе данных, в моем случае это MS Dynamics.Проблема в том, что он начинает выдавать сообщение об ошибке «Не удалось выделить буфер управляемой памяти в 8388608 байт. Объем доступной памяти может быть низким».после пробежки 2-3 дня.Затем я должен перезапустить службу, чтобы она снова заработала.

Приведен мой код. Пожалуйста, проверьте.

//This is called when connection with database is succesfully created.
public void getAirpayData()
{

        try
        {
            Airpay airpayVerify = new Airpay();

            QueryExpression getPaymentGatewayTransaction = new QueryExpression("new_paymentgatewaytransaction");
            var filter1 = new FilterExpression(LogicalOperator.Or);
            filter1.AddCondition("new_transactionstatus", ConditionOperator.Null);
            filter1.AddCondition("new_transactionstatus", ConditionOperator.Equal, 211);//Transaction In Process
            filter1.AddCondition("new_transactionstatus", ConditionOperator.Equal, 403);//INCOMPLETE
            filter1.AddCondition("new_transactionstatus", ConditionOperator.Equal, 401);//dropped
            filter1.AddCondition("new_transactionstatus", ConditionOperator.Equal, 405);//bounced
            var filter2 = new FilterExpression(LogicalOperator.And);
            filter2.AddCondition("createdon", ConditionOperator.GreaterEqual, DateTime.Now.AddDays(-15));// Runs for past 15 days transaction
            getPaymentGatewayTransaction.Criteria.AddFilter(filter1);
            getPaymentGatewayTransaction.Criteria.AddFilter(filter2);
            getPaymentGatewayTransaction.ColumnSet = new ColumnSet(true);
            EntityCollection PaymentGatewayTransactionCollection = service.RetrieveMultiple(getPaymentGatewayTransaction);


            if (PaymentGatewayTransactionCollection != null && PaymentGatewayTransactionCollection.Entities.Count > 0)
            {
                foreach (Entity paymentGateway in PaymentGatewayTransactionCollection.Entities)
                {
                    airpayVerify.merchant_txnId = paymentGateway.Contains("new_name") ? paymentGateway.GetAttributeValue<string>("new_name") : "NA";
                    if (airpayVerify.merchant_txnId != "NA")
                    {
                        var client = new RestClient("https://payments.airpay.co.in/order/verify.php");
                        var request = new RestRequest(Method.POST);
                        //request.AddHeader("postman-token", "03b48494-0184-39ed-8e52-a025a2adccfd");
                        request.AddHeader("cache-control", "no-cache");
                        request.AddHeader("content-type", "application/x-www-form-urlencoded");

                        request.AddParameter("application/x-www-form-urlencoded", "mercid=94&merchant_txnId=" + airpayVerify.merchant_txnId + "&privatekey=526c7c9b9a40d564888bdcec3040906d3be3ebc1f3a81ab02e90", ParameterType.RequestBody);

                        IRestResponse response = client.Execute(request);

                        XmlSerializer serializer = new XmlSerializer(typeof(TRANSACTION), new XmlRootAttribute("TRANSACTION"));

                        StringReader stringReader = new StringReader(response.Content.Replace("<![CDATA[", "").Replace("]]>", "").Replace("<?xml version=\"1.0\"?>", "").Replace("<RESPONSE>", "").Replace("</RESPONSE>", ""));

                        TRANSACTION productList = (TRANSACTION)serializer.Deserialize(stringReader);

                        UpdateCRMLog(productList);
                    }
                }
            }
            //  Library.WriteErrorLog("getAirpayDataEnd");
        }
        catch (Exception ex)
        {

            Library.WriteErrorLog(ex.Message);
        }





    }

    public void UpdateCRMLog(TRANSACTION productList)
    {
        try
        {
            //  Library.WriteErrorLog("UpdateCRMStart");
            EntityCollection paymentGatewayTransaction = op.QueryExpression("new_paymentgatewaytransaction", productList.TRANSACTIONID, "new_name", false, service);
            //    EntityCollection paymentGatewayTransaction = Global.GetEntityCollection(service, "new_paymentgatewaytransaction", productList.TRANSACTIONID, string.Empty, false, false, false, "new_name", string.Empty);
            if (paymentGatewayTransaction != null && paymentGatewayTransaction.Entities.Count > 0)
            {
                if (!paymentGatewayTransaction.Entities[0].Contains("new_paymentgatewayresponsestring"))
                {
                    paymentGatewayTransaction.Entities[0]["new_paymentgatewayresponsestring"] = Convert.ToString(productList.APTRANSACTIONID);
                }
                paymentGatewayTransaction.Entities[0]["new_transactiontype"] = Convert.ToString(productList.TRANSACTIONTYPE);
                paymentGatewayTransaction.Entities[0]["new_transactionstatus"] = Convert.ToString(productList.TRANSACTIONSTATUS);
                paymentGatewayTransaction.Entities[0]["new_transactionpaymentstatus"] = Convert.ToString(productList.TRANSACTIONPAYMENTSTATUS);
                paymentGatewayTransaction.Entities[0]["new_responsestatus"] = Convert.ToString(productList.TRANSACTIONPAYMENTSTATUS);
                paymentGatewayTransaction.Entities[0]["new_chmod"] = Convert.ToString(productList.CHMOD);
                if (productList.SURCHARGE == "")
                {
                    productList.SURCHARGE = "0.00";
                }
                decimal paidAmountIncludingSurcharge = Convert.ToDecimal(productList.BILLEDAMOUNT) + Convert.ToDecimal(productList.SURCHARGE);
                paymentGatewayTransaction.Entities[0]["new_paymentgatewayamount"] = Convert.ToString(paidAmountIncludingSurcharge);
                paymentGatewayTransaction.Entities[0]["new_paidamount"] = Convert.ToString(productList.AMOUNT);
                paymentGatewayTransaction.Entities[0]["new_bankname"] = Convert.ToString(productList.BANKNAME);
                paymentGatewayTransaction.Entities[0]["new_customername"] = Convert.ToString(productList.CUSTOMER);
                paymentGatewayTransaction.Entities[0]["new_currencycode"] = Convert.ToString(productList.CURRENCYCODE);
                paymentGatewayTransaction.Entities[0]["new_risk"] = Convert.ToString(productList.RISK);
                paymentGatewayTransaction.Entities[0]["new_transactiontime"] = Convert.ToString(productList.TRANSACTIONTIME);
                string _transactionTime = Convert.ToString(productList.TRANSACTIONTIME);
                string[] formats = { "M/d/yyyy", "d/M/yyyy", "M-d-yyyy", "d-M-yyyy", "d-MMM-yy", "d-MMMM-yyyy", "dd-MM-yyyy", "dd/MM/yyyy", "dd-MM-yyyy HH:mm", "dd-MM-yyyy HH:mm:ss", "dd/MM/yyyy HH:mm", "dd/MM/yyyy HH:mm:ss" };
                DateTime fromdate = DateTime.MinValue;
                DateTime.TryParseExact(_transactionTime, formats, CultureInfo.InvariantCulture, DateTimeStyles.None, out fromdate);
                paymentGatewayTransaction.Entities[0]["new_paymenttransactiondate"] = fromdate;
                service.Update(paymentGatewayTransaction.Entities[0]);
                //   Library.WriteErrorLog("UpdateCRMEnd");
            }
            //      Library.WriteErrorLog("UpdateCRMEnd1");
        }
        catch (Exception ex)
        {
            Library.WriteErrorLog(ex.Message);
        }
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...