Calling an asynchronous method in nopCommerce 3.9 Schedule Task

497 views Asked by At

I was writing a schedule task for refreshing access token from tradeGecko. Here's the code for the task :

using Newtonsoft.Json.Linq;
using Nop.Core;
using Nop.Core.Domain.Orders;
using Nop.Services.Configuration;
using Nop.Services.Tasks;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using static Nop.Core.TradeGeckoHelperMethods;

namespace Nop.Services.Catalog
{
    public partial class TradeGeckoRefreshToken : ITask
    {
        private readonly IStoreContext _storeContext;
        private readonly ISettingService _settingService;

        public TradeGeckoRefreshToken(IStoreContext storeContext, ISettingService settingService)
        {
            _storeContext = storeContext;
            _settingService = settingService;
        }

        public async System.Threading.Tasks.Task UpdateRefreshToken()
        {
            var orderSettings = _settingService.LoadSetting<OrderSettings>();
            Task<JObject> returnObject = TradeGeckoHelperMethods.RefreshAccessToken(orderSettings.TradeGeckoApplicationId, orderSettings.TradeGeckoSecretId, orderSettings.TradeGeckoCallBackUrl, orderSettings.TradeGeckoRefreshToken);
            JObject refresheObject = await returnObject;

            if (refresheObject[JsonKeys.AccessToken] != null)
            {
                Console.WriteLine(refresheObject[JsonKeys.AccessToken].ToString());
                orderSettings.TradeGeckoAccessToken = refresheObject[JsonKeys.AccessToken].ToString();
                orderSettings.TradeGeckoRefreshToken = refresheObject[JsonKeys.RefreshToken].ToString();
                _settingService.SaveSetting(orderSettings);
                _settingService.ClearCache();
            }
        }

        public void Execute()
        {
            System.Threading.Tasks.Task t = UpdateRefreshToken();
            Thread.Sleep(2000);
        }
    }
}

While running the task manually from the admin panel sometimes it produces the following error:

Message=There is already an open DataReader associated with this Command which must be closed first.

Am I doing it right? OR there's a better a to do this.

1

There are 1 answers

0
Kalpesh Boghara On

Please add this MultipleActiveResultSets=True in the connection string.

Please refer this link for more information.

https://www.nopcommerce.com/boards/t/16243/there-is-already-an-open-datareader-error-on-25.aspx