SqlClient: 5.2 localized `Operation cancelled by user` and does not have a specific error code

Is your feature request related to a problem? Please describe.

In MDS 5.2 when Operation canceled by user occurs there is no way to tell from the exception that the operation was canceled. We can’t just look at the token, the application is huge, and we are using ApplicationInsights to track exceptions using ITelemetryProcessor to add custom dimentions on which exceptions to ignore.

Now because the exception message is Localized we can’t reliably tell if the operation was from a canceled token. For example when the Current culture to ja.

image

image

image

Describe the solution you’d like

  • add an option not to automatically translate the error message
  • add a specific error number for this case

Describe alternatives you’ve considered

A clear and concise description of any alternative solutions or features you’ve considered.

How to repro

See te attached zip file for repro project. Or inline here:

Expand code example

EfExample.csproj

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net6.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="EntityFramework" Version="6.4.4" />
    <PackageReference Include="ErikEJ.EntityFramework.SqlServer" Version="6.6.9" />
  <PackageReference Include="Microsoft.Data.SqlClient" Version="5.2.0" />
    <!--<PackageReference Include="Microsoft.Data.SqlClient" Version="5.1.5" />-->
  </ItemGroup>

</Project>

Program.cs

using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Globalization;

namespace EfExample
{
    internal class Program
    {
        private const string MyConnectionString = "Server=.\\sqlexpress;Database=SchoolDb;User ID=sa;Password=mypassword;TrustServerCertificate=True";

        static async Task Main(string[] args)
        {
            var context = new SchoolContext(MyConnectionString);
            var allCourses = await context.Courses.ToListAsync();

            var simulateUseRequestLocalisation = true;

            if (simulateUseRequestLocalisation)
            {
                var culture = new CultureInfo("ja");
                CultureInfo.CurrentCulture = culture;
                CultureInfo.CurrentUICulture = culture;
            }

            try
            {
                var cts = new CancellationTokenSource(200);
                await context.Database.ExecuteSqlCommandAsync("WAITFOR DELAY '00:00:10';", cts.Token);
                //var resuult = await context.Courses.Where(x => x.Students.Any()).ToListAsync(cancel);
            }
            catch(Exception e)
            {
                Console.WriteLine(e);
            }
        }
    }

    [DbConfigurationType(typeof(System.Data.Entity.SqlServer.MicrosoftSqlDbConfiguration))]
    public class SchoolContext : DbContext
    {

        public SchoolContext(string connectionString) : base(connectionString)
        {
            Database.SetInitializer(new SchoolDBInitializer());
        }

        public DbSet<Student> Students { get; set; }
        public DbSet<Course> Courses { get; set; }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
        }
    }

    public class SchoolDBInitializer : DropCreateDatabaseAlways<SchoolContext>
    {
        protected override void Seed(SchoolContext context)
        {
            var students = new List<Student>
            {
                new Student { LastName = "S", FirstMidName = "Alex", },
                new Student { LastName = "M", FirstMidName = "Bob", }
            };

            var courses = new List<Course>
            {
                new Course { Title = "Math", Credits = 100 },
                new Course { Title = "Astro", Credits = 200 },
            };

            context.Students.AddRange(students);
            context.Courses.AddRange(courses);

            context.SaveChanges();
            

            base.Seed(context);
        }
    }

    public class Student
    {
        [Key]
        public int ID { get; set; }
        public string LastName { get; set; }
        public string FirstMidName { get; set; }
    }

    public class Course
    {
        [Key]
        public int CourseID { get; set; }
        public string Title { get; set; }
        public int Credits { get; set; }

        public virtual ICollection<Student> Students { get; set; }
    }
}

Additional context

  • we are using Ef6 with ErikEJ Adapter to MDS ErikEJ.EntityFramework.SqlServer Stacktrace.
Microsoft.Data.SqlClient.SqlException: 'A severe error occurred on the current command.  The results, if any, should be discarded.
Operation cancelled by user.'

   at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, SqlCommand command, 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.SqlCommand.InternalEndExecuteNonQuery(IAsyncResult asyncResult, Boolean isInternal, String endMethod)
   at Microsoft.Data.SqlClient.SqlCommand.EndExecuteNonQueryInternal(IAsyncResult asyncResult)
   at Microsoft.Data.SqlClient.SqlCommand.EndExecuteNonQueryAsync(IAsyncResult asyncResult)
   at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
--- End of stack trace from previous location ---
   at System.Data.Entity.Core.Objects.ObjectContext.<ExecuteStoreCommandInternalAsync>d__181.MoveNext()
   at System.Data.Entity.Core.Objects.ObjectContext.<ExecuteInTransactionAsync>d__156`1.MoveNext()
   at System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.<ExecuteAsyncImplementation>d__6`1.MoveNext()
   at System.Data.Entity.Core.Objects.ObjectContext.<ExecuteStoreCommandInternalAsync>d__180.MoveNext()

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 15 (11 by maintainers)

Most upvoted comments

Note the relationship with #26 - at least for async operations, SqlClient should be throwing TaskCanceledException which is the standard way to indicate cancellation.