Base solution for your next web application
Open Closed

Aysnc function not working. #11603


User avatar
0
kansoftware created

Hi,

I called a function 'LikePost' from JS on some case, it will call a procedure which will insert a new entry in one table and update a field in another. After the above work is completed i want to send notification which I want to call asynchronously. When i am doing that it gives me the below error in audit log:

Microsoft.Data.SqlClient.SqlException (0x80131904): The transaction operation cannot be performed because there are pending requests working on this transaction. at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady) at Microsoft.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) at Microsoft.Data.SqlClient.TdsParser.TdsExecuteTransactionManagerRequest(Byte[] buffer, TransactionManagerRequestType request, String transactionName, TransactionManagerIsolationLevel isoLevel, Int32 timeout, SqlInternalTransaction transaction, TdsParserStateObject stateObj, Boolean isDelegateControlRequest) at Microsoft.Data.SqlClient.SqlInternalConnectionTds.ExecuteTransactionYukon(TransactionRequest transactionRequest, String transactionName, IsolationLevel iso, SqlInternalTransaction internalTransaction, Boolean isDelegateControlRequest) at Microsoft.Data.SqlClient.SqlInternalTransaction.Commit() at Microsoft.Data.SqlClient.SqlTransaction.Commit() at Microsoft.EntityFrameworkCore.Storage.RelationalTransaction.Commit() at Abp.EntityFrameworkCore.Uow.DbContextEfCoreTransactionStrategy.Commit() at Abp.EntityFrameworkCore.Uow.EfCoreUnitOfWork.CommitTransaction() at Abp.EntityFrameworkCore.Uow.EfCoreUnitOfWork.CompleteUowAsync() at Abp.Domain.Uow.UnitOfWork...

Can you please help me out in resolving this.

I am pasting the code below: public async Task<int> LikePost(GetLikePostInput input) { var LikeCount = 0; Int64 FeedCreatorUserId = 0;

        try
        {
            _storedProcedureCalling.EnsureConnectionOpen();

            SqlParameter[] parameters = new SqlParameter[]
                {
             new SqlParameter(){ Direction=ParameterDirection.Input, SqlDbType =SqlDbType.UniqueIdentifier,ParameterName="@FeedId",Value= input.PostId}
            ,new SqlParameter(){ Direction=ParameterDirection.Input, SqlDbType =SqlDbType.BigInt,ParameterName="@UserId",Value= AbpSession.UserId}
            ,new SqlParameter(){ Direction=ParameterDirection.Input, SqlDbType =SqlDbType.Int,ParameterName="@TenantId",Value= AbpSession.TenantId}
            ,new SqlParameter(){ Direction=ParameterDirection.Input, SqlDbType =SqlDbType.Int,ParameterName="@PostReferenceType",Value= PostReferenceType.Like}
            ,new SqlParameter(){ Direction=ParameterDirection.Input, SqlDbType =SqlDbType.Bit,ParameterName="@IsLike",Value= input.IsLikeClick}
                };

            List&lt;IDataRecord&gt; outputUserOrderdsDataReader = new List&lt;IDataRecord&gt;();
            var outputPOEmailDataReader = new List&lt;IDataRecord&gt;();
            using (var command = _storedProcedureCalling.CreateCommand("LikePostOrComment", CommandType.StoredProcedure, parameters))
            {
                using (var dataReader = await command.ExecuteReaderAsync())
                {
                    if (dataReader.HasRows)
                    {
                        DataTable dt = new DataTable();
                        dt.Load(dataReader);
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            LikeCount = Convert.ToInt32(dt.Rows[0]["LikeCount"]);
                            FeedCreatorUserId = Convert.ToInt64(dt.Rows[0]["CreatorUserId"]);
                        }
                    }
                }
            }
           
            if (input.IsLikeClick)
            {
                if ((long)AbpSession.UserId != FeedCreatorUserId)
                {                   
                    await _customNotificationAppService.GenerateLikeNotification((Guid)input.PostId, (long)AbpSession.UserId, "postlike");                     

                }
            }              

        }
        catch (Exception ex)
        {
            Logger.Info("LikePost error: " + ex.StackTrace);
            return 0;
            throw new UserFriendlyException(ex.Message + " " + ex.StackTrace);
        }
        

        return LikeCount;

}

public async Task GenerateLikeNotification(Guid FeedId, long UserId, string LikeType) { _storedProcedureCalling.EnsureConnectionOpen(); List<IDataRecord> outputDataReader = new List<IDataRecord>();

        SqlParameter[] parameters = new SqlParameter[]
        {
                 new SqlParameter(){ Direction=ParameterDirection.Input, SqlDbType =SqlDbType.UniqueIdentifier,ParameterName="@FeedId",Value= FeedId}
                ,new SqlParameter(){ Direction=ParameterDirection.Input, SqlDbType =SqlDbType.BigInt,ParameterName="@SenderUserId",Value= UserId}                    
                ,new SqlParameter(){ Direction=ParameterDirection.Input, SqlDbType =SqlDbType.NVarChar,ParameterName="@LikeType",Value= LikeType}
        };
        
        try
        {
            DataTable dt = new DataTable();
            using (var command = _storedProcedureCalling.CreateCommand("GenerateLikeNotification", CommandType.StoredProcedure, parameters))
            {
                using (var dataReader = await command.ExecuteReaderAsync()) 
                {
                    if (dataReader.HasRows)
                    {
                        dt.Load(dataReader);                            
                    }
                    
                }
            }

            /*real time notification in web*/
            if (dt != null && dt.Rows.Count > 0)
            {
                var notificationData = new LocalizableMessageNotificationData(new LocalizableString(dt.Rows[0]["SendMsgType"].ToString(), CDPConsts.LocalizationSourceName));
                notificationData["0"] = dt.Rows[0]["SenderName"].ToString();

                var userNotifications = new List&lt;UserNotification&gt;();
                userNotifications = dt.AsEnumerable().Select(dataRow => new UserNotification
                {
                    Id = Guid.Parse(dataRow["UserNotificationsId"].ToString()),
                    TenantId = Convert.ToInt32(dataRow["TenantId"]),
                    UserId = Convert.ToInt64(dataRow["ReceiverID"]),
                    State = (UserNotificationState)Convert.ToInt32(dataRow["State"]),
                    Notification = new TenantNotification()
                    {
                        Id = Guid.Parse(dataRow["TenantNotificationId"].ToString()),
                        NotificationName = dataRow["NotificationName"].ToString(),
                        TenantId = Convert.ToInt32(dataRow["TenantId"]),
                        Severity = NotificationSeverity.Info,
                        Data = notificationData,
                        CreationTime = DateTime.UtcNow
                    }
                }).ToList();

                await _realTimeNotifier.SendNotificationsAsync(userNotifications.ToArray());
            }
            
        }
        catch (Exception e)
        {
            Logger.Info("GenerateLikeNotification error: " + e.StackTrace);                
        }

}


1 Answer(s)
  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi,

    Could you call dataReader.Close(); as the last line of the using statements ?