text:
Better LINQ support for Microsoft.SqlServer.Types

Methods like STDistance are not easy to translate right now because they are t-sql "instance" methods called like this:
SELECT [Id], [Geography1].STDistance([Geography2]) as [Distance] From [Foos]

Function registration and method call translation does not support this out-of-the-box, but it shouldn't be too hard to add support. Once this is done, we should consider whether to write the common translations and ship them somewhere or maybe publish them as a sample.

@smitpatel Will do the initial work to support method call translation to this kind of function, and then pass of to @ajcvickers for testing.

Notes for triage: I was able to map t-sql functions and use them.
Functions look like:
public static class SqlGeographyExtensions
{
    public static bool Contains(this SqlGeography geography, SqlGeography otherGeography)
        => throw new NotImplementedException();

    public static double Distance(this SqlGeography geography, SqlGeography otherGeography)
        => throw new NotImplementedException();
}

Function mapping looks like:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.HasDbFunction(
        typeof(SqlGeographyExtensions).GetMethod(nameof(SqlGeographyExtensions.Contains)),
        b => b.HasTranslation(e =>
            new SqlFunctionExpression(e.First(), "STContains", typeof(bool), e.Skip(1))));

    modelBuilder.HasDbFunction(
        typeof(SqlGeographyExtensions).GetMethod(nameof(SqlGeographyExtensions.Distance)),
        b => b.HasTranslation(e =>
            new SqlFunctionExpression(e.First(), "STDistance", typeof(double), e.Skip(1))));
}

Usages:
var redmond = context.Cities.Single(c => c.Name == "Redmond");
var housesInRedmond = context.Houses.Where(h => redmond.Shape.Contains(h.Location)).ToList();

foreach (var house in context.Houses)
{
    foreach (var distanceInfo in context.Houses.Select(h => new
    {
        Name = h.Name,
        Distance = h.Location.Distance(house.Location)
    }))
    {
    }
}

Full sample:
using System;
using System.Data.SqlTypes;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Query.Expressions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Console;
using Microsoft.SqlServer.Types;

namespace SqlTypesTest
{
    public static class SqlGeographyExtensions
    {
        public static bool Contains(this SqlGeography geography, SqlGeography otherGeography)
            => throw new NotImplementedException();

        public static double Distance(this SqlGeography geography, SqlGeography otherGeography)
            => throw new NotImplementedException();
    }

    public class House
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public SqlGeography Location { get; set; }
    }

    public class City
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public SqlGeography Shape { get; set; }
    }

    public class TestContext : DbContext
    {
        public static readonly LoggerFactory MyLoggerFactory
            = new LoggerFactory(new[] { new ConsoleLoggerProvider((_, __) => true, true) });

        public DbSet<City> Cities { get; set; }
        public DbSet<House> Houses { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.HasDbFunction(
                typeof(SqlGeographyExtensions).GetMethod(nameof(SqlGeographyExtensions.Contains)),
                b => b.HasTranslation(e =>
                    new SqlFunctionExpression(e.First(), "STContains", typeof(bool), e.Skip(1))));

            modelBuilder.HasDbFunction(
                typeof(SqlGeographyExtensions).GetMethod(nameof(SqlGeographyExtensions.Distance)),
                b => b.HasTranslation(e =>
                    new SqlFunctionExpression(e.First(), "STDistance", typeof(double), e.Skip(1))));
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
            => optionsBuilder
                //.UseLoggerFactory(MyLoggerFactory)
                .UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=GeoTest;ConnectRetryCount=0");
    }

    public class Program
    {
        public static void Main(string[] args)
        {
            using (var context = new TestContext())
            {
                context.Database.EnsureDeleted();
                context.Database.EnsureCreated();

                context.AddRange(
                    new House
                    {
                        Name = "The Schoolhouse",
                        Location = SqlGeography.Point(47.6828774, -122.1105578, 4326)
                    },
                    new House
                    {
                        Name = "Mountain Estate",
                        Location = SqlGeography.Point(47.548186, -122.100786, 4326)
                    },
                    new House
                    {
                        Name = "City House",
                        Location = SqlGeography.Point(47.632915, -122.107813, 4326)
                    },
                    new House
                    {
                        Name = "Issquah4222",
                        Location = SqlGeography.Point(47.568359, -122.091143, 4326)
                    });

                context.AddRange(
                    new City
                    {
                        Name = "Bellevue",
                        Shape = SqlGeography.STPolyFromText(new SqlChars(new SqlString("POLYGON ((" + Bellevue + "))")),
                            4326)
                    },
                    new City
                    {
                        Name = "Redmond",
                        Shape = SqlGeography.STPolyFromText(new SqlChars(new SqlString("POLYGON ((" + Redmond + "))")),
                            4326)
                    },
                    new City
                    {
                        Name = "Issaquah",
                        Shape = SqlGeography.STPolyFromText(new SqlChars(new SqlString("POLYGON ((" + Issaquah + "))")),
                            4326)
                    });

                context.SaveChanges();
            }

            using (var context = new TestContext())
            {
                var redmond = context.Cities.Single(c => c.Name == "Redmond");
                var housesInRedmond = context.Houses.FromSql("SELECT Id, Name, Location FROM Houses WHERE {0}.STContains(Location) = 1", redmond.Shape).ToList();

                Console.WriteLine("Houses in Redmond:");
                foreach (var house in housesInRedmond)
                {
                    Console.WriteLine($"  {house.Name} at {house.Location.Lat}, {house.Location.Long}");
                }
            }

            using (var context = new TestContext())
            {
                var redmond = context.Cities.Single(c => c.Name == "Redmond");
                var housesInRedmond = context.Houses.Where(h => redmond.Shape.Contains(h.Location)).ToList();

                Console.WriteLine("Houses in Redmond:");
                foreach (var house in housesInRedmond)
                {
                    Console.WriteLine($"  {house.Name} at {house.Location.Lat}, {house.Location.Long}");
                }
            }

            using (var context = new TestContext())
            {
                foreach (var house in context.Houses)
                {
                    Console.WriteLine($"{house.Name} is ");
                    foreach (var distanceInfo in context.Houses.Select(h => new
                    {
                        Name = h.Name,
                        Distance = h.Location.Distance(house.Location)
                    }))
                    {
                        Console.WriteLine($"  {distanceInfo.Distance / 1609.344} miles from {distanceInfo.Name}");
                    }
                }
            }
        }

        // Note: this is not real data
        public const string Bellevue = @"
-122.209860 47.643414, -122.165056 47.646652, -122.164198 47.660528, -122.164198 47.660528, -122.142740 47.627335, -122.111841 47.646421,
-122.111841 47.646421, -122.087465 47.628030, -122.111326 47.605812, -122.097765 47.571427, -122.111326 47.536231, -122.196127 47.546081,
-122.191835 47.578283, -122.222656 47.621237, -122.209781 47.643564, -122.209860 47.643414";

        public const string Redmond = @"
 -122.163192 47.711288, -122.099677 47.710595, -122.091952 47.654082, -122.111522 47.667378, -122.126628 47.666800, -122.086974 47.627595,
 -122.111178 47.628174, -122.111865 47.646450, -122.143107 47.627364, -122.143622 47.660673, -122.164565 47.661944, -122.163192 47.711288";

        public const string Issaquah = @"
-122.097974 47.571744, -122.082524 47.567691, -122.067933 47.552052, -122.051969 47.552747, -122.051969 47.552747, -122.051969 47.552747,
-122.051969 47.552747, -121.988454 47.555064, -121.994977 47.522964, -122.079949 47.520182, -122.077031 47.547765, -122.101235 47.549156,
-122.097974 47.571744";
    }
}

Filed https://github.com/aspnet/EntityFramework.Docs/issues/611 to document.

repo: aspnet/EntityFrameworkCore


text:
SqlException: Invalid column name 'Id'

This is strange for me. It was working quite in the past months until today.
A simple query like the one below is throwing the error SqlException: Invalid column name 'Id'.
         var book = await _context.Books
                        .Include(x => x.BookAuthors).ThenInclude(x => x.Author)
                        .Include(x => x.Category)
                        .Include(x => x.Publisher)
                        .Include(x => x.Variants).ThenInclude(x => x.Year)
                        .Include(x => x.Variants).ThenInclude(x => x.Month)
                        .Include(x => x.Variants).ThenInclude(x => x.VariantCopies)
                        .Select(x => new BookDetailsViewModel
                        {
                            Id = x.Id,
                            Title = x.Title,
                            SubTitle = x.SubTitle,
                            Category = x.Category.Name,
                            Publisher = x.Publisher.Name,
                            Cover = x.Cover != null ? x.Cover.Path : string.Empty,
                            YearOfPublication = x.Variants.OrderBy(y => y.Id).Take(1).Select(y => y.Year.Name).FirstOrDefault(),
                            MonthOfPublication = x.Variants.OrderBy(y => y.Id).Take(1).Select(y => y.Month.Name).FirstOrDefault(),
                            Authors = string.Join(", ", x.BookAuthors.Select(ba => ba.Author.FullName).ToList()),
                        })
                        .Where(x => x.Id == id)
                        .SingleOrDefaultAsync();

Stacktrace

SqlException: Invalid column name 'Id'. Invalid column name 'Id'.

    System.Data.SqlClient.SqlCommand+<>c.<ExecuteDbDataReaderAsync>b__108_0(Task<SqlDataReader> result)
    System.Threading.Tasks.ContinuationResultTaskFromResultTask.InnerInvoke()
    System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, object state)
    System.Threading.Tasks.Task.ExecuteWithThreadLocal(ref Task currentTaskSlot)
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    System.Runtime.CompilerServices.TaskAwaiter.GetResult()
    Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand+<ExecuteAsync>d__17.MoveNext()
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable+AsyncEnumerator+<BufferlessMoveNext>d__10.MoveNext()
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    Microsoft.EntityFrameworkCore.Storage.Internal.SqlServerExecutionStrategy+<ExecuteAsync>d__7.MoveNext()
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    Microsoft.EntityFrameworkCore.Query.Internal.AsyncQueryingEnumerable+AsyncEnumerator+<MoveNext>d__9.MoveNext()
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    Microsoft.EntityFrameworkCore.Query.EntityQueryModelVisitor+AsyncSelectEnumerable+AsyncSelectEnumerator+<MoveNext>d__3.MoveNext()
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    System.Runtime.CompilerServices.ConfiguredTaskAwaitable+ConfiguredTaskAwaiter.GetResult()
    System.Linq.AsyncEnumerable+<SingleOrDefault_>d__381.MoveNext()
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    System.Runtime.CompilerServices.TaskAwaiter.GetResult()
    Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider+TaskResultAsyncEnumerable+Enumerator+<MoveNext>d__3.MoveNext()
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    System.Runtime.CompilerServices.TaskAwaiter.GetResult()
    Microsoft.EntityFrameworkCore.Query.Internal.AsyncLinqOperatorProvider+ExceptionInterceptor+EnumeratorExceptionInterceptor+<MoveNext>d__5.MoveNext()
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    System.Runtime.CompilerServices.TaskAwaiter.GetResult()
    Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler+<ExecuteSingletonAsyncQuery>d__23.MoveNext()
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
    System.Runtime.CompilerServices.TaskAwaiter.GetResult()
    Library.Web.Areas.Admin.Controllers.BooksController+<Details>d__14.MoveNext() in BooksController.cs

                var book = await _context.Books

System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
System.Runtime.CompilerServices.TaskAwaiter.GetResult()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeActionMethodAsync>d__12.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeNextActionFilterAsync>d__10.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker+<InvokeInnerFilterAsync>d__14.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeNextResourceFilter>d__22.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeFilterPipelineAsync>d__17.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker+<InvokeAsync>d__15.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Builder.RouterMiddleware+<Invoke>d__4.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware+<Invoke>d__6.MoveNext()
System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware+<Invoke>d__7.MoveNext()

Please I need to rectify this issue as quickly as possible.
Thanks so much

@smithaitufe  Can you provide code listings for all the entities used in the query, as well as contents of your OnModelCreating? This will help us get to the bottom of this much faster.

Also, something that might help is putting the Where before the Select:
         var book = await _context.Books
                        .Include(x => x.BookAuthors).ThenInclude(x => x.Author)
                        .Include(x => x.Category)
                        .Include(x => x.Publisher)
                        .Include(x => x.Variants).ThenInclude(x => x.Year)
                        .Include(x => x.Variants).ThenInclude(x => x.Month)
                        .Include(x => x.Variants).ThenInclude(x => x.VariantCopies)
                        .Where(x => x.Id == id)
                        .Select(x => new BookDetailsViewModel
                        {
                            Id = x.Id,
                            Title = x.Title,
                            SubTitle = x.SubTitle,
                            Category = x.Category.Name,
                            Publisher = x.Publisher.Name,
                            Cover = x.Cover != null ? x.Cover.Path : string.Empty,
                            YearOfPublication = x.Variants.OrderBy(y => y.Id).Take(1).Select(y => y.Year.Name).FirstOrDefault(),
                            MonthOfPublication = x.Variants.OrderBy(y => y.Id).Take(1).Select(y => y.Month.Name).FirstOrDefault(),
                            Authors = string.Join(", ", x.BookAuthors.Select(ba => ba.Author.FullName).ToList()),
                        })
                        .SingleOrDefaultAsync();

it's effectively the same query, but from EFCore perspective its much easier to translate

@maumar
book.js
public class Book: BaseEntity
    {
        public Book () {
            BookAuthors = new HashSet<BookAuthor>();
            Variants = new HashSet<Variant>();
        }
        [Required]
        [MaxLength(255)]
        public string Title { get; set; }
        [MaxLength(255)]
        public string SubTitle { get; set; }
        [DataType(DataType.MultilineText)]
        public string Description { get; set; }
        [Required]
        [ForeignKey("Genre")]
        public int GenreId { get; set; }
        [Required]
        [ForeignKey("Category")]
        public int CategoryId { get; set; }
        [Required]
        [ForeignKey("Publisher")]
        public int PublisherId { get; set; }
        public bool Series { get; set; } = false;
        public int? NoInSeries { get; set; }
        public Image Cover { get; set; }
        // Navigation Properties
        public Term Genre { get; set; }
        public Term Category { get; set; }
        public Publisher Publisher { get; set; }
        public ICollection<Variant> Variants { get; set; }
        public ICollection<BookAuthor> BookAuthors { get; set; }
    }

public class BaseEntity {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int Id { get; set; }
        public DateTimeOffset InsertedAt { get; set; } = DateTimeOffset.Now;
        public DateTimeOffset UpdatedAt { get; set; } = DateTimeOffset.Now;
    }

With respect to the second suggestion, the code was initially in that way. I moved the where clause to after the select because I wanted to see if it would help. But it was the same.

also need listing for related entities. What version of EFCore are you using, and which one were you using before it started failing?

Term.cs
public class Term:BaseEntity
    {
        [Required]
        public int TermSetId { get;set; }
        [Required]
        public string Name { get; set; }
        [ForeignKey("TermSetId")]
        public TermSet TermSet { get; set; }
        public ICollection<Book> CategoryBooks { get; set; }
        public ICollection<Book> GenreBooks { get; set; }
        public ICollection<Variant> DaysAllowedVariants { get; set; }
        public ICollection<Variant> GrantVariants { get; set; }
        public ICollection<Variant> YearVariants { get; set; }
        public ICollection<Variant> FormatVariants { get; set; }
        public ICollection<Variant> LanguageVariants { get; set; }
        public ICollection<VariantCopy> AvailabilityVariantCopies { get; set; }
        public ICollection<VariantCopy> SourceVariantCopies { get; set; }

    }

Variant.cs
    public class Variant: BaseEntity
    {
        public Variant()
        {
            VariantCopies = new HashSet<VariantCopy>();
            VariantPrices = new HashSet<VariantPrice>();
        }
        [Required]
        [ForeignKey("Book")]
        public int BookId { get; set; }
        [Required]
        [MaxLength(30)]
        public string ISBN { get; set; }
        [StringLength(50)]
        public string Edition { get; set; }
        [StringLength(50)]
        public string Volume { get; set; }
        [ForeignKey("Language")]
        public int LanguageId { get; set; }
        [Required]
        public int Pages { get; set; }
        [Required]
        [ForeignKey("Format")]
        public int FormatId { get; set; }
        [Required]
        [ForeignKey("Grant")]
        public int GrantId { get; set; }
        [Required]
        [ForeignKey("Year")]
        public int YearId { get; set; }
        [ForeignKey("Month")]
        public int? MonthId { get; set; }
        public Term Month { get; set; }
        [Required]
        [ForeignKey("DaysAllowed")]
        public int DaysAllowedId { get; set; }
        [ForeignKey("CollectionMode")]
        public int CollectionModeId { get; set; }
        [ForeignKey("Fine")]
        public int FineId { get; set; }
        public string CallNumber { get; set; }
        // Navigation Properties
        public Term Language { get; set; }
        public Term DaysAllowed { get; set; }
        public Term CollectionMode { get; set; }
        public Item Fine { get; set; }
        public Term Grant { get; set; }
        public Term Year { get; set; }
        public Term Format { get; set; }
        public Book Book { get; set; }
        public ICollection<CheckOut> CheckOuts { get; set; }
        public ICollection<VariantPrice> VariantPrices { get; set; }
        public ICollection<VariantCopy> VariantCopies { get; set; }
        public ICollection<Inventory> Inventories { get; set; }
    }

Publisher.cs
public class Publisher: BaseEntity
    {
        [Required]
        [MaxLength(255)]
        public string Name { get; set; }
        public string PhoneNumber { get; set; }
        public int? CountryId { get; set; }
        public ICollection<Book> Books { get; set; }
        public Country Country { get; set; }
    }

Image.cs
    public class Image: BaseEntity {
        public string Path { get; set; }
        public string ContentType { get; set; }
        public string Extension { get; set; }
        public string Base64 { get; set; }
    }

BookAuthor.cs
public class BookAuthor: BaseEntity
    {
        public int BookId { get; set; }
        public int AuthorId { get; set; }

        [ForeignKey("BookId")]
        public Book Book { get; set; }
        [ForeignKey("AuthorId")]
        public Author Author { get; set; }
    }

EF Core Version
.NET Command Line Tools (2.0.3)

Product Information:
 Version:            2.0.3
 Commit SHA-1 hash:  eb1d5ee318

Runtime Environment:
 OS Name:     ubuntu
 OS Version:  16.10
 OS Platform: Linux
 RID:         ubuntu.16.10-x64
 Base Path:   /home/smith/dotnet/sdk/2.0.3/

Microsoft .NET Core Shared Framework Host

  Version  : 2.0.3
  Build    : a9190d4a75f4a982ae4b4fa8d1a24526566c69df

I was able to reproduce the problem. Try the following:
         var book = await _context.Books
                        .Include(x => x.BookAuthors).ThenInclude(x => x.Author)
                        .Include(x => x.Category)
                        .Include(x => x.Publisher)
                        .Include(x => x.Variants).ThenInclude(x => x.Year)
                        .Include(x => x.Variants).ThenInclude(x => x.Month)
                        .Include(x => x.Variants).ThenInclude(x => x.VariantCopies)
                        .Where(x => x.Id == id)
                        .Select(x => new BookDetailsViewModel
                        {
                            Id = x.Id,
                            Title = x.Title,
                            SubTitle = x.SubTitle,
                            Category = x.Category.Name,
                            Publisher = x.Publisher.Name,
                            Cover = x.Cover != null ? x.Cover.Path : string.Empty,
                            YearOfPublication = x.Variants.OrderBy(y => y.Id).Select(y => y.Year.Name).FirstOrDefault(),
                            MonthOfPublication = x.Variants.OrderBy(y => y.Id).Select(y => y.Month.Name).FirstOrDefault(),
                            Authors = string.Join(", ", x.BookAuthors.Select(ba => ba.Author.FullName).ToList()),
                        })
                        .SingleOrDefaultAsync();

Basicaly removing Take(1) calls from YearsOfPublication and MonthsOfPublication, it is not needed anyways because FirstOrDefault does the same thing under the covers.

If I take that away, will it solve the problem? I will try that tomorrow. About to sleep. Thanks for your help

It solves it on my machine, so it should work for you also.

Problem is in HandleFirst() after the subquery already has a limit, e.g.
SELECT TOP(1) [o].[CustomerID]
FROM [Orders] AS [o]
WHERE [c].[CustomerID] = [o].[CustomerID]
ORDER BY [o].[OrderID]

we try to pushdown subuqery:
SELECT [t].*
FROM (
    SELECT TOP(1) [o].[CustomerID]
    FROM [Orders] AS [o]
    WHERE [c].[CustomerID] = [o].[CustomerID]
    ORDER BY [o].[OrderID]
) AS [t]

and then we try to lift order by. Currently as a result we generate the following, incorrect sql:
SELECT [t].*
FROM (
    SELECT TOP(1) [o].[CustomerID]
    FROM [Orders] AS [o]
    WHERE [c].[CustomerID] = [o].[CustomerID]
    ORDER BY [o].[OrderID]
) AS [t]
ORDER BY [t].[OrderID]

problem is that the outer query doesn't have OrderID available. We would have to modify the inner projection to include the order column(s), and then manually re-project only the column(s) that were originally there:
SELECT TOP(1) [t].CustomerID
FROM (
    SELECT TOP(1) [o].[CustomerID], o.OrderID
    FROM [Orders] AS [o]
    WHERE [c].[CustomerID] = [o].[CustomerID]
    ORDER BY [o].[OrderID]
) AS [t]
ORDER BY [t].[OrderID]

Alternatively, we could optimize QM and prune all Take calls when FirstOrDefault is present. We can't do that for case like this though:
var i = 0;
ctx.Customers.Select(c => c.Orders.OrderBy(o => o.Id).Take(i).FirstOrDefault())

Bug in SelectExpression.LiftOrderBy function. It should ensure that ordering which is being pulled outside is referenced by the projection.

@maumar
Removing the .Take(1) did solve the problem.
I know I arrived at using Take(1) due to an issue I had then. I guess it has been resolved.
Can this issue be closed?

@smithaitufe this is a legitimate EFCore bug, while Take + FirstOrDefault is redundant and workaround is easy, it still should produce a working query.

Noted.
I recall that it was an issue that led me into using .Take in the first place. Guess that was resolved.

added tests for this issue in SimpleQueryTestBase.Select

source: gharchive/issue

authors: maumar smithaitufe smitpatel

license: MIT

license_type: permissive

license_source: github-api


text:
Update-Database generates correct migration but applies wrong one (even when forced to do so)

Error presented:
Generated script seems to be using Initial migraiton instead of last one, even if forced to do so (see below)
Table 'Activities' already exists
Update-Database generates script not compatible with last migration. And Script-Migration --From LastMigrationName is empty
Migration expected to be run:
public partial class _20180815 : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "GymSubscriptionPlan",
                columns: table => new
                {
                    GymSubscriptionPlanId = table.Column<int>(nullable: false)
                        .Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
                    Active = table.Column<bool>(nullable: false),
                    BillingPeriodization = table.Column<int>(nullable: false),
                    PagarMePlanCode = table.Column<string>(nullable: true),
                    PlanDetail = table.Column<string>(nullable: true),
                    PlanName = table.Column<string>(nullable: true),
                    Price = table.Column<double>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_GymSubscriptionPlan", x => x.GymSubscriptionPlanId);
                });

            migrationBuilder.CreateTable(
                name: "GymSubscription",
                columns: table => new
                {
                    GymSubscriptionId = table.Column<Guid>(nullable: false),
                    Active = table.Column<bool>(nullable: false),
                    CreateDate = table.Column<DateTime>(nullable: false),
                    GymId = table.Column<Guid>(nullable: false),
                    GymSubscriptionPlanId = table.Column<int>(nullable: false),
                    PagarMeSubscriptionId = table.Column<string>(nullable: true),
                    UpdateDate = table.Column<DateTime>(nullable: false)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_GymSubscription", x => x.GymSubscriptionId);
                    table.ForeignKey(
                        name: "FK_GymSubscription_Gyms_GymId",
                        column: x => x.GymId,
                        principalTable: "Gyms",
                        principalColumn: "GymId",
                        onDelete: ReferentialAction.Cascade);
                    table.ForeignKey(
                        name: "FK_GymSubscription_GymSubscriptionPlan_GymSubscriptionPlanId",
                        column: x => x.GymSubscriptionPlanId,
                        principalTable: "GymSubscriptionPlan",
                        principalColumn: "GymSubscriptionPlanId",
                        onDelete: ReferentialAction.Cascade);
                });

            migrationBuilder.CreateIndex(
                name: "IX_GymSubscription_GymId",
                table: "GymSubscription",
                column: "GymId");

            migrationBuilder.CreateIndex(
                name: "IX_GymSubscription_GymSubscriptionPlanId",
                table: "GymSubscription",
                column: "GymSubscriptionPlanId");
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "GymSubscription");

            migrationBuilder.DropTable(
                name: "GymSubscriptionPlan");
        }
    }

Steps to reproduce
Add the above migration to the Migrations folder of your project and run the following commands:
Update-Database -Migration "20180815"
Script-Migration -From 20180815
Neither should word
Further technical details
EF Core version: 2.0.1
Database Provider: Pomelo.EntityFrameworkCore.Mysql (2.0.1)
Operating system: Win10 x64
IDE: (e.g. Visual Studio 2017 15.4)

@vfilenga The first case should execute all migrations that have not been applied from the initial upto and including the one specified. The second case should do nothing, since migrating from the last migration to the last migration is a no-op. If you are seeing behaviors different from these, then can you please post a runnable project/solution that demonstrates the behavior you are seeing?

@ajcvickers What is weird about the first case is that the last applied migration (see below)
Select from database:

Migrations folder:

@vfilenga We have not been able to reproduce this. Can you post a runnable project/solution that demonstrates the behavior you are seeing?

EF Team Triage: Closing this issue as the requested additional details have not been provided and we have been unable to reproduce it.
BTW this is a canned response and may have info or details that do not directly apply to this particular issue. While we'd like to spend the time to uniquely address every incoming issue, we get a lot traffic on the EF projects and that is not practical. To ensure we maximize the time we have to work on fixing bugs, implementing new features, etc. we use canned responses for common triage decisions.

authors: ajcvickers vfilenga


text:
Reverse enginnering scaffolding command fails for EF Core 3 Preview 4

I am using EF Core 3 Preview 4 inside an ASP.NET Core 3 Preview 4 application.

I installed dotnet-ef tool using this command

dotnet tool install --global dotnet-ef --version 3.0.0-preview4.19216.3

I added NuGet packages for Microsoft.EntityFrameworkCore, Microsoft.EntityFrameworkCore.Relational and Microsoft.EntityFrameworkCore.SqlServer

All are version 3.0.0-preview4.19216.3

Then added NuGet package for Microsoft.EntityFrameworkCore.Design

Version = 3.0.0-preview4.19216.3

Then I issue this command at command prompt

dotnet ef dbcontext scaffold  "Server=.;Database=MyDb;Integrated Security=true;"   Microsoft.EntityFrameworkCore.SqlServer -o Data -c MyDbContext -t MyTable1 -t MyTable2
I get this error :
System.InvalidCastException: Unable to cast object of type 'Microsoft.EntityFram
eworkCore.Diagnostics.RelationalLoggingDefinitions' to type 'Microsoft.EntityFra
meworkCore.SqlServer.Diagnostics.Internal.SqlServerLoggingDefinitions'.
at Microsoft.EntityFrameworkCore.SqlServer.Internal.SqlServerResources.LogFou
ndDefaultSchema(IDiagnosticsLogger logger)
at Microsoft.EntityFrameworkCore.SqlServer.Internal.SqlServerLoggerExtensions
.DefaultSchemaFound(IDiagnosticsLogger1 diagnostics, String schemaName)    at Microsoft.EntityFrameworkCore.SqlServer.Scaffolding.Internal.SqlServerData baseModelFactory.GetDefaultSchema(DbConnection connection)    at Microsoft.EntityFrameworkCore.SqlServer.Scaffolding.Internal.SqlServerData baseModelFactory.Create(DbConnection connection, DatabaseModelFactoryOptions opt ions)    at Microsoft.EntityFrameworkCore.SqlServer.Scaffolding.Internal.SqlServerData baseModelFactory.Create(String connectionString, DatabaseModelFactoryOptions opt ions)    at Microsoft.EntityFrameworkCore.Scaffolding.Internal.ReverseEngineerScaffold er.ScaffoldModel(String connectionString, DatabaseModelFactoryOptions options, S tring rootNamespace, String modelNamespace, String contextNamespace, String lang uage, String contextDir, String contextName, ModelReverseEngineerOptions modelOp tions, ModelCodeGenerationOptions codeOptions)    at Microsoft.EntityFrameworkCore.Design.Internal.DatabaseOperations.ScaffoldC ontext(String provider, String connectionString, String outputDir, String output ContextDir, String dbContextClassName, IEnumerable1 schemas, IEnumerable1 tabl es, Boolean useDataAnnotations, Boolean overwriteFiles, Boolean useDatabaseNames )    at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScaffoldContextImpl (String provider, String connectionString, String outputDir, String outputDbCont extDir, String dbContextClassName, IEnumerable1 schemaFilters, IEnumerable1 ta bleFilters, Boolean useDataAnnotations, Boolean overwriteFiles, Boolean useDatab aseNames)    at Microsoft.EntityFrameworkCore.Design.OperationExecutor.ScaffoldContext.<>c __DisplayClass0_1.<.ctor>b__0()    at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__ DisplayClass3_01.b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execu
te(Action action)
Unable to cast object of type 'Microsoft.EntityFrameworkCore.Diagnostics.Relatio
nalLoggingDefinitions' to type 'Microsoft.EntityFrameworkCore.SqlServer.Diagnost
ics.Internal.SqlServerLoggingDefinitions'.
What might be the problem ??
Thank you.

Duplicate of #15414

@roji Thanks for taking care of closing this. Can you also add a closed-duplicate tag next time?

Sorry, am still learning the ropes it seems...

@roji No need to apologize. :-)

authors: AspNetWebDev ajcvickers roji


text:
Can not create the database table by the Fluent API way

I create the model, but Table cannot be generated automatically in SQLServer. I try create the table by myselft, the Database operation success.
Further technical details
EF Core version: 2.0.0
Database Provider: Microsoft.EntityFrameworkCore.SqlServer
Operating system: win 10
IDE: Visual Studio 2017 15.3.1

i use Database.EnsureCreated, the table is created.
Can the ef core generated  itself, not by useEnsureCreated?

@tomwangliming EF Core does not have any mechanism to automatically create the database in the way that EF6 and earlier did. This was changed for several reasons, one of which was that it is generally better for an application to control when a database gets created rather than having it happen automatically and potentially unexpectedly. Along the same lines, EnsureCreated should usually only really be used for quick prototyping and testing. For other situations, we recommend using Migrations with an appropriate deployment strategy to properly create and manage the database.

thank you !

authors: ajcvickers tomwangliming


text:
Consider an RC3 schedule extension

Thank you for the wonderful open source project, and especially the opportunity to watch it happen, and even participate. I really appreciate the changing attitudes and commitments Microsoft continues to deliver on a broad front.
I would like to ask that the appropriate parties who make schedule and release decisions for ASP.NET Core consider a change in schedule to allow time for a full RC3, which I understand is not currently the plan. I'm sure this is already being discussed internally, but I would like to provide an outside perspective.
I would also mention that the ASP.NET team on the live standup respectfully discussed this issue based on submitted questions, and did not ask for community involvement explicitly. I appreciate the opportunity to provide feedback on this project.
I believe this project would benefit from an additional RC for a variety of reasons:

This project covers three platforms for the first time, which adds significant challenges. It is an “ambassador” for Microsoft and .NET on these platforms. Complexity takes time, and getting it right up front has higher than usual value.
This project is reliant upon and is coordinating with several other cross platform projects now under the “core” banner. These projects are also new, and coordination adds complexity.
The rename is deep, and is being carried across packages. Other projects are renaming as well.
Infrastructure has shifted significantly since RC1, DNX -> dotnet CLI and similar.
This is (now more clearly) a new 1.0 product, which will ship APIs, interfaces, names, and other forms of contracts that will need to be respected carefully moving forward. Issues with these are inevitable, you never get everything right, but because errors here will potentially be felt for years or even decades, it is worth an extra RC for these to settle as much as possible, especially considering the platform and renaming impacts.

Some cons:

There may be events on the schedule that want to show off ASP.NET Core 1.0
This is your vocal early adopter community, which may not represent many mainstream developers
People like new things, regular releases are healthy
The project will benefit greatly from feedback that only a full release will bring, especially on Mac and Linux

I believe several factors make delaying a release more appropriate than usual

This is no longer “ASP.NET 5” e.g. “What’s taking you so long with the next version?” it’s been renamed as “ASP.NET Core” a new 1.0 product. This more clearly reflects how it has always been.
This project is open source, and people can get the bits any time they like. The RCs have “go live” licensing available with support from Microsoft. People are not being completely forced to wait for a release.
This project is open source, and has been excellent about communicating status and involving the community. This means outside observers understand the status of the project better, and can more clearly see why another RC might be beneficial. They can also understand that the bits for RC3 would be similar to bits in an RTM, and can choose to use those bits now if they like.

In my opinion as a developer, the balance of these factors make an RC3 schedule change worth while.
I also do not currently have any explicit stake on ASP.NET Core RTM, which could significantly change my perspective. I'm a fan of the project, and I'll pitch it at work for web use down the road, but I don't have any projects relying on it right now. I would like to hear from anyone who is explicitly waiting for RTM for a current project!
I understand that there are many complicated factors in deciding release timelines, not all of which are public, and only ask that this feedback be considered. You’ve earned my trust and respect for any decision made, including sticking to the current schedule.
I would love to hear others reasons and thoughts for or against adding an RC3.

Thank you very much for such a considered post. I can't argue with any of your logic (as it's, you know, logical) but for now the team is focused solely on delivering a quality RC2 release. Once that's under our belt we'll circle back to the question of the releases that follow.

authors: ColinDabritz DamianEdwards

repo: aspnet/Home


text:
AddIdentity should check if IUserSecurityStampStore is implemented before registering a check on securityStamp

If the UserStore does not implement IUserSecurityStampStore, most functionality regarding security stamps will be skipped, but AddIdentity() does register a validation on the securityStamp every 30 minutes.
This results in the confusing behaviour that the user is logged out after 30 minutes, even though the cookies did not expire.
AddIdentity should check whether the UserSecurityStampStore is supported before registering the check, and either throw, or skip the check.
See also #1425

@HaoK

Moving to preview1 since this is a product issue not a intrastructure/mq type thing

@blowdart @ajcvickers we actually can't stop registering the security stamp since this is all during configure services, we don't have the final store until the service provider is built, so we must always register the validator.
Today we reject all cookies when the store doesn't support security stamp, so that is why the cookies are invalidated every 30 minutes.  Maybe the tactical fix we can make here is to just consider cookies always valid when security stamps aren't supported, so instead of getting logged out every validation interval, they will just get a new cookie at that time always.
Sound reasonable?

Yea that seems the right way to go

Agreed,

Fixed via https://github.com/aspnet/Identity/pull/1941

authors: HaoK ajcvickers blowdart tiljanssen

repo: aspnet/Identity


text:
Move web.config and use ANCM

Review: @Tratcher
RC2 Approval: @Eilon @DamianEdwards

@HaoK

:shipit:

:+1:

source: gharchive/pull-request

authors: JunTaoLuo Tratcher divega


text:
Reduce locking contention per LibuvThread.Post

Use ConcurrentQueue for Work and CloseHandle items; many threads Post, should be low contention for single thread dequing.
Don't trigger uv_async_send syscall while the loop woken up and about to or processing that type of element; or on step prior.
Use empty struct VoidResult for TaskCompletionSource<VoidResult> as don't care about result; no need for a memory barrier write for object

OSX
Failed   ConnectionResetMidRequestIsLoggedAsDebug
Error Message:
 Logged event should not have been higher than debug.
Expected: False
Actual:   True
Stack Trace:
   at Microsoft.AspNetCore.Server.Kestrel.FunctionalTests.RequestTests.<ConnectionResetMidRequestIsLoggedAsDebug>d__15.MoveNext() in /_/test/Kestrel.FunctionalTests/RequestTests.cs:line 462
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
--- End of stack trace from previous location where exception was thrown ---
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
Standard Output Messages:
 Debug: Connection id "0HLBHL33ILSS3" started.
 Debug: Connection id "0HLBHL33ILSS3" reset.
 Debug: Connection id "0HLBHL33ILSS3" disconnecting.
 Information: Connection id "0HLBHL33ILSS3" communication error.
 Debug: Connection id "0HLBHL33ILSS3" sending FIN.
 Debug: Connection id "0HLBHL33ILSS3" stopped.

Any perf results to verify this does what it claims 😄 ?

Two linux Standard D64 v3 battle...
Pre
  64 threads and 256 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency     3.84ms   11.94ms 269.22ms   88.62%
    Req/Sec    44.70k    16.16k   99.02k    69.40%
  28792380 requests in 10.10s, 3.54GB read
Requests/sec: 2850821.02
Transfer/sec:    358.88MB

  64 threads and 1024 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency     9.89ms   23.88ms 576.58ms   94.51%
    Req/Sec    55.16k    21.28k  236.51k    74.30%
  35003078 requests in 10.10s, 4.30GB read
Requests/sec: 3465630.70
Transfer/sec:    436.27MB

  64 threads and 4096 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency    52.15ms  107.04ms   1.99s    90.73%
    Req/Sec    48.43k    24.34k  340.59k    70.66%
  31626097 requests in 10.10s, 3.89GB read
  Socket errors: connect 0, read 0, write 0, timeout 1
Requests/sec: 3131147.62
Transfer/sec:    394.16MB

  64 threads and 16384 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency   246.84ms  343.47ms   2.00s    86.88%
    Req/Sec    41.20k    37.25k  365.30k    72.11%
  24531512 requests in 10.10s, 3.02GB read
  Socket errors: connect 0, read 138, write 0, timeout 4873
Requests/sec: 2428899.37
Transfer/sec:    305.76MB

Post
  64 threads and 256 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency    14.90ms   23.81ms 329.58ms   88.74%
    Req/Sec     8.35k     2.03k   35.24k    74.29%
  5376579 requests in 10.10s, 676.83MB read
Requests/sec: 532355.06
Transfer/sec:     67.02MB

  64 threads and 1024 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency    21.85ms   54.05ms 856.01ms   93.18%
    Req/Sec    34.40k    25.08k  199.77k    62.28%
  21578292 requests in 10.10s, 2.65GB read
Requests/sec: 2136509.40
Transfer/sec:    268.95MB

  64 threads and 4096 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency    77.30ms  163.23ms   1.99s    92.62%
    Req/Sec    45.79k    24.18k  308.08k    66.73%
  28715331 requests in 10.10s, 3.53GB read
  Socket errors: connect 0, read 0, write 0, timeout 54
Requests/sec: 2844263.72
Transfer/sec:    358.05MB

  64 threads and 16384 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency   219.31ms  307.53ms   2.00s    88.65%
    Req/Sec    26.65k    24.69k  322.97k    83.80%
  16916975 requests in 10.10s, 2.08GB read
  Socket errors: connect 0, read 34, write 0, timeout 6631
Requests/sec: 1674993.46
Transfer/sec:    210.86MB

😢

Not value for change

authors: benaadams davidfowl

repo: aspnet/KestrelHttpServer


text:
Add the ability to flow log scope manually

Today when you call ILogger.CreateScope the scope is tracked using the thread context until you dispose it.  There are several places where the thread context does not naturally flow and needs to be updated manually (TaskCompletionSource.TrySetResult, Task.Run, Task.Factory.StartNew, etc.).
WebListener is the worst example so far. We want to have it establish a scope around the lifetime of a request, but there are a few explicit thread hops before the request enters the application pipeline. Figure out how to flow the context across those hops. See:
https://github.com/aspnet/WebListener/blob/dev/src/Microsoft.Net.Http.Server/AsyncAcceptContext.cs#L98
https://github.com/aspnet/WebListener/blob/dev/src/Microsoft.AspNet.Server.WebListener/MessagePump.cs#L139

@Tratcher let's sync up on this cc @kichalla

authors: Tratcher muratg

repo: aspnet/Logging


text:
FilePathResult WriteFileAsync uses SendFile feature incorrectly

The logic should be:

Get file info from file provider
If file is physical AND SendFile feature exists, use SendFile
Else (either file isn't physical, or SendFile feature doesn't exist), use the CopyStream implementation

The current issue is that even for non-physical files it sometimes tries to use the SendFile feature.

repo: aspnet/Mvc


text:
Change the tag helpers FileVersion property to something clearer

We have a few tag helpers (Link, Script, and the upcoming Image) that have a FileVersion property that indicates whether to add a "version" to the URL to help with cache busting.
The property name is a bit confusing: it looks like it is a file version, as opposed to saying whether to append a file version.
I recommend changing the property to be AppendVersion or similar because that'll be a lot clearer about what it does.

@DamianEdwards thoughts?

Sure

Any objection to me tackling this one on the weekend?

Yeah that would be great. Let's settle on a name. Here are a few ideas:

AppendFileVersion / AddFileVersion
AppendVersion / AddVersion
AppendFileHash / AddFileHash
AppendHash / AddHash
CacheBust

I do kind of like my original suggestion of AppendVersion because it's concise and reasonably clear about what it does.
Thoughts?

I can live with AppendVersion. I also like AddFileVersion.

I like AppendVersion

Is this about just the property name?  Note that's irrelevant in every scenario except unit testing.  The attribute name (what users see in the Razor source) is currently asp-file-version.
If we're going to change the attribute as well, would the name there be asp-append-version?

Yup.

@dougbu yes it's just the property name and yes we'd rename the tag helper attribute name.
Sounds like everyone wants to go with AppendVersion!

:+1:

3fe0490

The web app template in Visual Studio still uses asp-file-version, looks like it wasn't updated.

/cc @rustd

https://github.com/aspnet/Templates/issues/142

I get a 404 on that link; is it a private repo?

Yeah, sorry about that. Removing the link to avoid further confusion.

authors: DamianEdwards Daniel15 Eilon NTaylorMullen danroth27 dougbu dpaquette


text:
Should FormTagHelper include an antiforgery token when action is specified

Currently the <form> tag helper isn't active for cases like
<form action="">
</form>

Which is a post back to the same URL.
The reason I mention it is that it's pretty similar to .BeginForm() - which would include a token.
Of course when you test your app, you will see that an antiforgery token wasn't included. So you'd need to add asp-antiforgery="true".

I'd say no, if a <form> tag has an action then the only other server side attribute you can add is asp-antiforgery.
When we first wrote FormTagHelper it applied to every form tag and added antiforgery tokens by default. We then went back on the idea because many users weren't trying to use TagHelper based form tags but were auto-opted into them. Also resulted in lots of purple form tags :smile:

Yeah don't think we need this.

authors: Eilon NTaylorMullen rynowak


text:
Added DiagnosticsSource events for ViewComponent

#3274
@rynowak

/cc @avanderhoorn

Updated.

Updated.

:watch:

Updated.

:shipit:

Quick question, for VC's, is there something like the ActionId which can be used for correlating all of the VC events like we do for Actions?

Quick question, for VC's, is there something like the ActionId which can be used for correlating all of the VC events like we do for Actions?

You can use the type name (on the descriptor). Have a gander at that and we'll talk if that doesn't meet your requirements.

Updated. (Added extension methods)

Looking good... just a couple of questions in general about the objects that I'm getting.

ViewComponentContext

Is Arguments the arguments that matchup to what is being passed into the VC?

If so, is there any way to match these back to the names of the arguments like we do for action?

Is ViewContext the root view context... as in the view that corresponds the the action that started the whole show?

ViewComponentDescriptor

The same way that ActionDescriptor has an id, can the VS one have this as well... it will help with corilation
Currently the VC Descriptor is accessible in any of the ViewComponentDiagnosticSourceExtensions events... is it possible to have it accessible via the view events that executed as a result a VC running? This will help with correlation

ViewComponent

At the moment we don't have access tot he ViewComponent itself, how important is this? Meaning the main things of interest are things like ViewData, ModelState, etc... is this going to be the same as the root view, or can it be different for each VC? If its the later, it would be good to have access to it.

If so, is there any way to match these back to the names of the arguments like we do for action?

You can look at the VCD and get the MethodInfo I believe.

Is ViewContext the root view context... as in the view that corresponds the the action that started the whole show?

Not likely, what do you need?

The same way that ActionDescriptor has an id, can the VS one have this as well... it will help with corilation (sic)

We can certainly add something like this, but the class name should be able to do the same. Isn't that better since it's readable? If you still want it, let's do it in a follow up.

is it possible to have it accessible via the view events that executed as a result a VC running? This will help with correlation

Can you give a source reference to what you're talking about?

At the moment we don't have access tot he ViewComponent itself, how important is this? Meaning the main things of interest are things like ViewData, ModelState, etc... is this going to be the same as the root view, or can it be different for each VC? If its the later, it would be good to have access to it.

Yeah, we should find a way to do this @ajaybhargavb

If so, is there any way to match these back to the names of the arguments like we do for action?
You can look at the VCD and get the MethodInfo I believe.

Pity, would have been nice if it was just there like it is for action and not have to handle this independently.

Is ViewContext the root view context... as in the view that corresponds the the action that started the whole show?
Not likely, what do you need?

No, it was just a general question.

The same way that ActionDescriptor has an id, can the VS one have this as well... it will help with correlation (sic)
We can certainly add something like this, but the class name should be able to do the same. Isn't that better since it's readable? If you still want it, let's do it in a follow up.

Was more for consistency with Actions and how correlation is done generally... For actions I was using the Id and here, if it doesn't have an id, I'm probably best to update my action logic to match. But not a huge huge deal.

is it possible to have it accessible via the view events that executed as a result a VC running? This will help with correlation
Can you give a source reference to what you're talking about?

In cases like this where we are rendering the view for a View Component, it would be nice to be able to correlate it back to the VC... I was thinking ViewComponentDescriptor would be the easiest way to do this.

At the moment we don't have access tot he ViewComponent itself, how important is this? Meaning the main things of interest are things like ViewData, ModelState, etc... is this going to be the same as the root view, or can it be different for each VC? If its the later, it would be good to have access to it.
Yeah, we should find a way to do this

Great!

Updated (Added ViewComponent object to the notification)

:shipit:
@avanderhoorn - I'm currently working on adding an Id and DisplayName to VCD in another PR

@ajaybhargavb Great!
@rynowak Great again!
Looks like it :clap:'s all around :D

authors: ajaybhargavb avanderhoorn rynowak


text:
Visual Studio can't find dotnet-aspnet-codegenerator-design

Hi, I'm currently learning ASP.NET. I have been following the tutorials at https://docs.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/adding-model. When I try to create a Controller as described in the tutorial, I run into this error:

I have googled about this and found this SO question, but the suggestions didn't seem to work. I also tried creating a new VS project.
Additional info: I'm using Visual Studio 2017 with a .csproj project file. My project targets .NET Core 1.0.

@jamesqo, for csproj based project system, you need to have the below in your project:
<ItemGroup>
  <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="1.0.0-msbuild3-final" />
  <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0-msbuild3-final" />
</ItemGroup>

Also make sure that the below packages are not referenced in the project as PackageReferences:
Microsoft.VisualStudio.Web.CodeGenerators.Mvc
Microsoft.VisualStudio.Web.CodeGeneration.Tools
Let me know if this helps.

@prafullbhosale Thank you very much for your help. I followed your advice and this error isn't occurring anymore. However, now I'm getting a different stack trace:

Here is what I had to do to get this library working using .csproj. using VS Code with cli 1.0.0-rc4-004771.

Add @prafullbhosale example for adding the design package.
Add the following to fix the "Microsoft.Composition 1.0.27 is not compatible with netcoreapp1.0" error I was receiving. @jamesqo I am not sure if this step will help in VS but who knows...

<PropertyGroup>
    <TargetFramework>netcoreapp1.1</TargetFramework>
    <PackageTargetFallback>portable-net45;win8;wp8;wpa81</PackageTargetFallback>
  </PropertyGroup>

My final product looked like this for a basic Mvc app:
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp1.1</TargetFramework>
    <PackageTargetFallback>portable-net45;win8;wp8;wpa81</PackageTargetFallback>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore" Version="1.1.0" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.1" />
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.0" />
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.0" />
  </ItemGroup>
  <ItemGroup>
      <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="1.0.0-msbuild3-final" />
      <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0-msbuild3-final" />
  </ItemGroup>
</Project>

dotnet tool install --global dotnet-aspnet-codegenerator --version 3.1.2

authors: SahadatHHredoy jamesqo jamiewest prafullbhosale

repo: aspnet/Scaffolding


text:
OpenID middleware defaulting to http

Given the following config in ConfigureServices--
services.AddAuthentication(sharedOptions =>
            {
                sharedOptions.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                sharedOptions.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            })

            .AddCookie()
            .AddOpenIdConnect(options =>
            {
                options.Authority = Configuration["OIDC:Authority"];
                options.ClientId = Configuration["OIDC:ClientID"];
                options.ClientSecret = Configuration["OIDC:ClientSecret"];
                options.Scope.Add("openid");
                options.ResponseType = OpenIdConnectResponseType.Code;
                options.GetClaimsFromUserInfoEndpoint = true;
                options.AuthenticationMethod = OpenIdConnectRedirectBehavior.FormPost;
                options.CallbackPath = new PathString("/login");
                options.SaveTokens = true;

And the following ChallengeAsync call--
            await HttpContext.ChallengeAsync(new AuthenticationProperties()
            {
                RedirectUri = "/"
            });

When I run from localhost on https, I have no issues.  However when I run from a cloud foundry instance, the middleware is sending a redirect using the http address instead of https which is what the current browser session is using.  Any ideas?

Duplicate. See prior discussions linked from https://github.com/aspnet/Docs/issues/2384

authors: Tratcher mjnorman

repo: aspnet/Security


text:
Make CookieAuthenticationDefaults and FacebookDefaults fields static readonly

Many of them are currently const, which seems wrong.

The cookie middleware and the FB provider are not the only ones using constants: Google, JWT/Bearer, MSFT, OIDC, Twitter also all use constants.
I'm not saying constants are more appropriate, but they have at least one merit for the default schemes: you can use them with AuthorizeAttribute:
[Authorize(ActiveAuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]

Is the attribute scenario a common one?
The problem with these consts is that they are logically not constant, so that bugs me :smile:

Ah, we can keep the schemes const for this scenario. We should change just about everything else, though.

@Eilon @PinpointTownes const => will not change over time, readonly => fixed for this instance. Is this the reason to change to readonly?

835903892771b9e833985c43bc3b967f66f31892

authors: Eilon HaoK PinpointTownes brentschmaltz


text:
How to use cellphone to login

you provide using the email to login.
but if i want to using the cellphone to login.how to do this?

Do you mean two factor login? If so, you can do that yourself. AspNet Identity has two-factor auth feature.

no,I  want to use [username or cellphone] to login, not use  [username or email] to login which is default.

Phone numbers are not guaranteed to be unique today, they are not  #keys
#https://github.com/aspnet/Identity/pull/1055

AbpLoginManager does not support this, but you may change AccountController.Login method to handle it yourself (query database for cellphone, find user, check password and make login).

I know this way,but I am not tend to use this.
it's perfect when you can define such methods in your source code ,

In  _logInManager.LoginAsync ,it call UserManager.AbpStore.FindByNameOrEmailAsync
so you can override FindByNameOrEmailAsync like
 public override async Task<User> FindByNameOrEmailAsync(string userNameOrEmailAddress)
 {
     return await _userRepository.FirstOrDefaultAsync(
        user => (user.UserName == userNameOrEmailAddress
            || user.EmailAddress == userNameOrEmailAddress
            || user.PhoneNumber == userNameOrEmailAddress));
 }

thanks,I know this way.  but the method name is not match the content

authors: ChiakiYu hikalkan maliming xyfy

repo: aspnetboilerplate/module-zero

license: mit

license_source: bigquery


text:
NoSuchMethodException trying to use soft assertions with XmlUnit

Describe the bug
When trying to combine a custom assertion provided by XmlUnit with soft assertions, I get the following NoSuchMethodException:
java.lang.NoSuchMethodException: org.xmlunit.assertj3.XmlAssert$ByteBuddy$t9ocrkSa.<init>(java.lang.Object)
java.lang.RuntimeException: java.lang.NoSuchMethodException: org.xmlunit.assertj3.XmlAssert$ByteBuddy$t9ocrkSa.<init>(java.lang.Object)
	at org.assertj.core.api.SoftProxies.createSoftAssertionProxy(SoftProxies.java:127)
	at org.assertj.core.api.ProxifyMethodChangingTheObjectUnderTest.createAssertProxy(ProxifyMethodChangingTheObjectUnderTest.java:90)
	at org.assertj.core.api.ProxifyMethodChangingTheObjectUnderTest.intercept(ProxifyMethodChangingTheObjectUnderTest.java:79)
	at org.assertj.core.api.StringAssert$ByteBuddy$XNc4Hshb.asInstanceOf(Unknown Source)
	at foo.BarTest.narrowedSoftAssertion(BarTest.java:48)

assertj core version: 3.23.1
java version: 17
test framework version: JUnit Jupiter 5.8.2
os (if relevant):

Full stack traces
java.lang.NoSuchMethodException: org.xmlunit.assertj3.XmlAssert$ByteBuddy$t9ocrkSa.<init>(java.lang.Object)
java.lang.RuntimeException: java.lang.NoSuchMethodException: org.xmlunit.assertj3.XmlAssert$ByteBuddy$t9ocrkSa.<init>(java.lang.Object)
	at org.assertj.core.api.SoftProxies.createSoftAssertionProxy(SoftProxies.java:127)
	at org.assertj.core.api.ProxifyMethodChangingTheObjectUnderTest.createAssertProxy(ProxifyMethodChangingTheObjectUnderTest.java:90)
	at org.assertj.core.api.ProxifyMethodChangingTheObjectUnderTest.intercept(ProxifyMethodChangingTheObjectUnderTest.java:79)
	at org.assertj.core.api.StringAssert$ByteBuddy$XNc4Hshb.asInstanceOf(Unknown Source)
	at foo.BarTest.narrowedSoftAssertion(BarTest.java:48)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:568)
	at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725)
	at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
	at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
	at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
	at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
	at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
	at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
	at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
	at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
	at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
	at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
	at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
	at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
	at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:214)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:210)
	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
	at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
	at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
	at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
	at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
	at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
	at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
	at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
	at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
	at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
	at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
	at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
	at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:99)
	at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)
	at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)
	at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:568)
	at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
	at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
	at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
	at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
	at jdk.proxy1/jdk.proxy1.$Proxy2.stop(Unknown Source)
	at org.gradle.api.internal.tasks.testing.worker.TestWorker$3.run(TestWorker.java:193)
	at org.gradle.api.internal.tasks.testing.worker.TestWorker.executeAndMaintainThreadName(TestWorker.java:129)
	at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:100)
	at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:60)
	at org.gradle.process.internal.worker.child.ActionExecutionWorker.execute(ActionExecutionWorker.java:56)
	at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:133)
	at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:71)
	at worker.org.gradle.process.internal.worker.GradleWorkerMain.run(GradleWorkerMain.java:69)
	at worker.org.gradle.process.internal.worker.GradleWorkerMain.main(GradleWorkerMain.java:74)
Caused by: java.lang.NoSuchMethodException: org.xmlunit.assertj3.XmlAssert$ByteBuddy$t9ocrkSa.<init>(java.lang.Object)
	at java.base/java.lang.Class.getConstructor0(Class.java:3585)
	at java.base/java.lang.Class.getConstructor(Class.java:2271)
	at org.assertj.core.api.SoftProxies.createSoftAssertionProxy(SoftProxies.java:121)
	... 89 more

java.lang.NoSuchMethodException: org.xmlunit.assertj3.XmlAssert$ByteBuddy$t9ocrkSa.<init>(java.lang.Object)
java.lang.RuntimeException: java.lang.NoSuchMethodException: org.xmlunit.assertj3.XmlAssert$ByteBuddy$t9ocrkSa.<init>(java.lang.Object)
	at org.assertj.core.api.SoftProxies.createSoftAssertionProxy(SoftProxies.java:127)
	at org.assertj.core.api.AbstractSoftAssertions.proxy(AbstractSoftAssertions.java:48)
	at foo.MySoftAssertions.assertThatXml(BarTest.java:63)
	at foo.BarTest.softAssertions(BarTest.java:39)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:568)
	at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725)
	at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
	at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
	at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
	at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
	at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
	at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
	at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
	at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
	at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
	at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
	at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
	at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
	at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:214)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:210)
	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
	at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
	at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
	at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
	at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
	at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
	at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
	at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
	at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
	at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
	at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
	at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
	at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:99)
	at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)
	at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)
	at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:77)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:568)
	at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
	at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
	at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
	at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
	at jdk.proxy1/jdk.proxy1.$Proxy2.stop(Unknown Source)
	at org.gradle.api.internal.tasks.testing.worker.TestWorker$3.run(TestWorker.java:193)
	at org.gradle.api.internal.tasks.testing.worker.TestWorker.executeAndMaintainThreadName(TestWorker.java:129)
	at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:100)
	at org.gradle.api.internal.tasks.testing.worker.TestWorker.execute(TestWorker.java:60)
	at org.gradle.process.internal.worker.child.ActionExecutionWorker.execute(ActionExecutionWorker.java:56)
	at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:133)
	at org.gradle.process.internal.worker.child.SystemApplicationClassLoaderWorker.call(SystemApplicationClassLoaderWorker.java:71)
	at worker.org.gradle.process.internal.worker.GradleWorkerMain.run(GradleWorkerMain.java:69)
	at worker.org.gradle.process.internal.worker.GradleWorkerMain.main(GradleWorkerMain.java:74)
Caused by: java.lang.NoSuchMethodException: org.xmlunit.assertj3.XmlAssert$ByteBuddy$t9ocrkSa.<init>(java.lang.Object)
	at java.base/java.lang.Class.getConstructor0(Class.java:3585)
	at java.base/java.lang.Class.getConstructor(Class.java:2271)
	at org.assertj.core.api.SoftProxies.createSoftAssertionProxy(SoftProxies.java:121)
	... 88 more

Test case reproducing the bug
package foo;

import org.assertj.core.api.Assertions;
import org.assertj.core.api.InstanceOfAssertFactory;
import org.assertj.core.api.SoftAssertions;
import org.assertj.core.api.junit.jupiter.SoftAssertionsExtension;
import org.assertj.core.util.CheckReturnValue;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.xmlunit.assertj3.XmlAssert;

@ExtendWith(SoftAssertionsExtension.class)
class BarTest {
    private static final String XML_STRING = """
            <foo>
                <bar>baz</bar>
            </foo>
            """;

    @Test
    void hardAssertions() {
        XmlAssert.assertThat(XML_STRING)
                .valueByXPath("/foo/bar")
                .isEqualTo("baz")
        ;
    }
    @Test
    void narrowedHardAssertions() {
        Assertions.assertThat(XML_STRING)
                .asInstanceOf(new InstanceOfAssertFactory<>(Object.class, XmlAssert::assertThat))
                .valueByXPath("/foo/bar")
                .isEqualTo("baz")
        ;
    }

    @Test
    void softAssertions(MySoftAssertions softly) {
        softly.assertThatXml(XML_STRING)
                .valueByXPath("/foo/bar")
                .isEqualTo("baz")
        ;
    }

    @Test
    void narrowedSoftAssertion(SoftAssertions softly) {
        softly.assertThat(XML_STRING)
                .asInstanceOf(new InstanceOfAssertFactory<>(Object.class, XmlAssert::assertThat))
                .valueByXPath("/foo/bar")
                .isEqualTo("baz")
        ;
    }
}

// inspired from https://github.com/assertj/assertj-examples/blob/0868b5d724374ca0eb3f6c2456b27acd5ac740e0/assertions-examples/src/test/generated-assertions/org/assertj/SoftAssertions.java
class MySoftAssertions extends SoftAssertions {
    /**
     * @implNote Cannot name it {@code assertThat} because of signature overload with {@link SoftAssertions#assertThat(Object)},
     * but on the other hand, {@link XmlAssert#assertThat(Object)} takes an {@link Object} argument
     */
    @CheckReturnValue
    XmlAssert assertThatXml(Object actual) {
        return proxy(XmlAssert.class, Object.class, actual);
    }
}

(from the above test class, only tests with "hard" assertions work fine)
build.gradle.kts
plugins {
    `java-library`
}

repositories {
    mavenCentral()
}

dependencies {
    testImplementation(platform("org.junit:junit-bom:5.8.2"))
    testImplementation("org.junit.jupiter:junit-jupiter-engine")
    testImplementation("org.assertj:assertj-core:3.23.1")
    testImplementation("org.xmlunit:xmlunit-assertj3:2.9.0")
}

java {
    toolchain {
        languageVersion.set(JavaLanguageVersion.of(17))
    }
}

tasks {
    wrapper {
        gradleVersion = "7.5"
    }
    test {
        useJUnitPlatform()
    }
}

Notes

The documentation regarding soft assertions with custom assertions (such as the one here provided by XmlUnit) is missing https://github.com/assertj/doc/blob/01467a591f4f54c1bc67ea3c98245bdeae303184/src/docs/asciidoc/user-guide/assertj-core-extension.adoc?plain=1#L143, so I'm not sure whether the problem is here, the custom assertion provider, or me trying to combine it with soft assertions
I took inspiration from https://github.com/assertj/assertj-examples/blob/0868b5d724374ca0eb3f6c2456b27acd5ac740e0/assertions-examples/src/test/generated-assertions/org/assertj/SoftAssertions.java#L7-L18

Looking at createSoftAssertionProxy:
https://github.com/assertj/assertj-core/blob/88d32b64ff68797e0c7d9cf51af4b1cec34d2c51/src/main/java/org/assertj/core/api/SoftProxies.java#L116-L129
on line 121 it tries to get the public constructor, but XmlAssert has only a private constructor:
    private XmlAssert(Object o) {
        super(o, XmlAssert.class);
        this.config = new XmlAssertConfig(getWritableAssertionInfo());
    }

It seems you're not the first one hit by this: xmlunit/xmlunit#148
The request was rejected a few years ago. You might try asking the project if they are willing to reconsider that decision.
We might work together with XMLUnit in case changes in AssertJ are needed for easier support of soft assertions in third-party libraries.
/cc @bodewig

Thank you @scordio, I missed that issue.
I am wondering whether this public single argument constructor requirement is an official AssertJ requirement for implementing a compliant custom assertion, or is it just an implementation heuristic that needs more tuning on AssertJ side (e.g. with some Byte Buddy bytecode manipulation)?
The missing documentation section might explain why some assertion providers may not know that they have to provide a public 1-arg constructor.
If it is confirmed that it is the responsibility of the assertion provider to implement such constructors, would you have a recommended pattern for sharing a state between assertions? As alluded, XMLUnit use constructors for passing some state around due to the nested nature of their assertions. This can be seen here or here.

I am wondering whether this public single argument constructor requirement is an official AssertJ requirement for implementing a compliant custom assertion, or is it just an implementation heuristic that needs more tuning on AssertJ side (e.g. with some Byte Buddy bytecode manipulation)?
The missing documentation section might explain why some assertion providers may not know that they have to provide a public 1-arg constructor.

We should consider the following points:

Custom assertions do not require a public 1-arg constructor to work as hard assertions.
AssertJ has no concrete documentation or guidelines on how third-party libraries should write custom assertions to be compatible with soft assertions.
Connecting assertion classes with AssertJ core components to get soft assertions support is currently a burden on users and there is no guarantee that it will work (as with XMLUnit).

If it is confirmed that it is the responsibility of the assertion provider to implement such constructors, would you have a recommended pattern for sharing a state between assertions?

Unfortunately not yet. We should discuss in the team how we want to support such a use case.

Superseded by #2625.

authors: Fiouz scordio

repo: assertj/assertj-core


text:
#2239 added AbstractCharSequenceAssert.isMixedCase method

Check List:

Fixes #2239
Unit tests : YES
Javadoc with a code example (on API only) : YES
PR meets the contributing guidelines

Merged, thanks @nach-o-man!

authors: nach-o-man scordio


text:
Installation error "Failed to extract source distribution" on Azure Artifacts when using cache, works correctly with --no-cache

EDIT: cannot repro after uv cache clean
Hello,
I am seeing some strange behavior when trying to pip-install various packages, including anyconfig==0.14.0. https://github.com/ssato/python-anyconfig
The installation fails when using using a private Azure Artifacts registry when trying to reuse cache, but if I pass the --no-cache flag, it installs correctly.
The installation also works on previous versions of anyconfig with uv and our internal feed. Here is the summary of all the different "variables" and the result. pip succeeds in all the cases.

registry
cache
anyconf version
result

pypi
yes
0.14.0
✅

pypi
no
0.14.0
✅

internal
yes
0.14.0
❌

internal
no
0.14.0
✅

internal
yes
0.13.0
✅

internal
no
0.13.0
✅

I have the full trace log which I can supply, but I don't feel comfortable sharing it openly as I can't fully verify there's no sensitive info contained in the Rust logs. Here is the final lines including the failure:
              0.179758s  98ms TRACE hyper::client::pool put; add idle connection for ("https", pyvvsblobprodsu6weus63.blob.core.windows.net)
              0.179788s  98ms DEBUG hyper::client::pool pooling idle connection for ("https", pyvvsblobprodsu6weus63.blob.core.windows.net)
            0.179824s  98ms DEBUG uv_client::cached_client Found modified response for: https://pkgs.dev.azure.com/redacted/_packaging/b94dc4ba-1037-423e-8797-179e29b340a8/pypi/download/anyconfig/0.14/anyconfig-0.14.0.tar.gz#sha256=2cdf54af5dae8e91743ded82c54ed9d8aaefa3a9722f5d45e9b5f74b603e014d
            0.179835s  98ms TRACE uv_client::httpcache cached request https://pkgs.dev.azure.com/redacted/_packaging/b94dc4ba-1037-423e-8797-179e29b340a8/pypi/download/anyconfig/0.14/anyconfig-0.14.0.tar.gz#sha256=2cdf54af5dae8e91743ded82c54ed9d8aaefa3a9722f5d45e9b5f74b603e014d is not storable because its response has unsupported status code 304
         uv_client::cached_client::new_cache file=/home/jovyan/.cache/uv/built-wheels-v0/index/11e94138ffcdd103/anyconfig/0.14.0/manifest.msgpack
         uv_distribution::source::download source_dist=anyconfig==0.14.0
              0.179895s   0ms DEBUG uv_distribution::source Downloading source distribution: anyconfig==0.14.0
           uv_distribution::source::download_source_dist filename="anyconfig-0.14.0.tar.gz", source_dist=anyconfig==0.14.0
    0.180447s TRACE hyper::proto::h2::client client::dispatch::Sender dropped
           h2::proto::connection::poll
                0.180469s   0ms TRACE h2::proto::connection connection.state=Open
             h2::codec::framed_write::FramedWrite::buffer frame=GoAway { error_code: NO_ERROR, last_stream_id: StreamId(0) }
                  0.180486s   0ms DEBUG h2::codec::framed_write send, frame=GoAway { error_code: NO_ERROR, last_stream_id: StreamId(0) }
    0.180492s TRACE hyper::proto::h1::dispatch client tx closed
    0.180523s TRACE hyper::proto::h1::conn State::close_read()
    0.180528s TRACE hyper::proto::h1::conn State::close_write()
    0.180532s TRACE hyper::proto::h1::conn flushed({role=client}): State { reading: Closed, writing: Closed, keep_alive: Disabled }
    0.180539s DEBUG rustls::common_state Sending warning alert CloseNotify
                  0.180555s   0ms TRACE h2::frame::go_away encoding GO_AWAY; code=NO_ERROR
                  0.180579s   0ms TRACE h2::codec::framed_write encoded go_away, rem=17
                0.180597s   0ms DEBUG h2::proto::connection Connection::poll; connection error, error=GoAway(b"", NO_ERROR, Library)
                0.180613s   0ms TRACE h2::proto::connection     -> already going away
    0.180618s TRACE hyper::proto::h1::conn shut down IO complete
                0.180770s   0ms TRACE h2::proto::connection connection.state=Closing(NO_ERROR, Library)
                0.180798s   0ms TRACE h2::proto::connection connection closing after flush
             h2::codec::framed_write::FramedWrite::flush
                  0.180829s   0ms TRACE h2::codec::framed_write queued_data_frame=false
                  0.180886s   0ms TRACE h2::codec::framed_write flushing buffer
                0.180898s   0ms DEBUG rustls::common_state Sending warning alert CloseNotify
                0.180941s   0ms TRACE h2::proto::connection connection.state=Closed(NO_ERROR, Library)
    0.180971s TRACE h2::proto::streams::streams Streams::recv_eof
 h2::proto::streams::prioritize::clear_pending_capacity
error: Failed to download and build: anyconfig==0.14.0
  Caused by: Failed to extract source distribution
  Caused by: unexpected end of file

I can also provide the .tar.gz, but from what I can tell, the hashes match the public ones on PyPI.
One difference between the versions is that I can no longer see the package's dependencies on the artifacts page for it:
0.13.0

0.14.0

Updating OP: uv pip install anyconf==0.14.0 --no-cache works

cannot repro after uv cache clean

Oh, that's great, thanks for following up!

authors: charliermarsh inigohidalgo

repo: astral-sh/uv