text:
Remove redunant "dotnet restore"

"dotnet new" automatically runs "dotnet restore" unless the "--no-restore" option is passed:
> dotnet new web
Getting ready...
The template "ASP.NET Core Empty" was created successfully.
This template contains technologies from parties other than Microsoft, see https://aka.ms/template-3pn for details.

Processing post-creation actions...
Running 'dotnet restore' on C:\Temp\aspnetcoreapp\aspnetcoreapp.csproj...
  Restoring packages for C:\Temp\aspnetcoreapp\aspnetcoreapp.csproj...
  Generating MSBuild file C:\Temp\aspnetcoreapp\obj\aspnetcoreapp.csproj.nuget.g.props.
  Generating MSBuild file C:\Temp\aspnetcoreapp\obj\aspnetcoreapp.csproj.nuget.g.targets.
  Restore completed in 7.22 sec for C:\Temp\aspnetcoreapp\aspnetcoreapp.csproj.

@mikeharder  Do you want me to add ASP.NET Core 1.x and ASP.NET Core 2.x tabs. You still need restore for 1.x - right? See this doc

The extra dotnet restore doesn't hurt anything on 2.0, but it's also not necessary.  So the question is whether it's better to simplify the 2.X instructions at the expense of needing different instructions for 1.X, or just use a single set of instructions which contain a redundant step on 2.X.
I would lean towards keeping a single set of instructions, since learning about dotnet restore may be useful for other scenarios, even if it's not needed after dotnet new on 2.X.  Another option would be to add a note to the dotnet restore step that it's not required on 2.X.
But I defer to your judgement on which is better overall.  I don't want to over-complicate the "Getting Started" page, but someone using the current docs on 2.X may question why they are told to restore twice.

@mikeharder  created #3793  - I think a bigger problem for windows is it sends you to the VS 2017 installer, not the CLI installer.

@mikeharder  also note on this page I had to add the following because of folks running older versions and following this tutorial:
Notes:
- Previous versions of .NET Core required a t parameter, that is   dotnet new -t web. If you get an error running dotnet new web, install the latest .NET Core.  dotnet (with no parameters)  will display the .NET Core version.

authors: Rick-Anderson mikeharder


text:
Azure preview site extension

Fixes #5840
Preview URL

Only one small comment, DockerHub will presumably always have the latest releases. So this doc lasts longer if the bit about DockerHub having preview1 just says that preview releases are available on DockerHub, or something. Remove the preview1 bit :).

source: gharchive/pull-request

authors: Rick-Anderson glennc

repo: aspnet/Docs

license_type: permissive

license_source: github-api


text:
Eager Loading sometimes not loading data for Navigation Properties

The property is a one to one relationship with another class; most of time it loads correctly but sometime it loads a class with no values at all, just nulls. But if you look in the database the record does exist and should be loaded.

Plz show us ze codez!

Here are the classes in question:
public class ProductModel
{
    public int EntityKey { get; set; }

    public ICollection<ProductMetaDataModel> MetaData { get; set; }
}

public class ProductMetaDataModel
{
    public int EntityKey { get; set; }

    public ProductModel Product { get; set; }

    public UrlRecordModel UrlRecord { get; set; }
}

public class ProductConfig : EntityTypeConfiguration<ProductModel>
{
    public ProductConfig()
    {
        HasKey(x => x.EntityKey);
        HasMany(x => x.MetaData).WithRequired(x => x.Product).WillCascadeOnDelete();
    }
}

public class ProductMetaDataConfig : EntityTypeConfiguration<ProductMetaDataModel>
{
    public ProductMetaDataConfig()
    {
        HasKey(x => x.EntityKey);
        HasRequired(x => x.Product).WithMany(x => x.MetaData).HasForeignKey(x => x.ParentEntityKey).WillCascadeOnDelete();
    }
}

public class UrlRecordModel
{
    public int EntityKey { get; set; }

    public string UrlSlug { get; set; }
}

We load the ProductModels from a service, which uses includes to load the collection of ProductMetaDataModels and in turn loads the UrlRecordModel for each of those. The UrlRecordModel usually loads properly with the UrlSlug property populating most of the time, but some of the time it returns a blank class with only null values. When we look in the database, the record does exist and should have been loaded. Even if you make an SQL query to load the class, inside of SQL Server, it loads it correctly.

Is that EF7?

We are using EF6.

@alexyoungman given this is an EF6 issue could you open an issue on the EF6 project https://entityframework.codeplex.com/.
To be able to address this we are going to need some code we can run to reproduce the issue. So please include some for of application/service we can run. I realize this is an intermittent issue so we may need to run your code for some period of time to see the issue.
One thing we did want to check is that you do not have multiple threads using the same context instance. The context is not thread safe, and this is the kind of issue we would expect to see if multiple threads were sharing a context.

source: gharchive/issue

authors: ErikEJ alexyoungman rowanmiller

repo: aspnet/EntityFramework

license: MIT


text:
Remove command logging extensions from LoggingExtensions

LoggingExtensions is a shared file and so should only contain methods that are generally useful.

I would have put them in Relational.Design, but that isn't available on uwp10.0 projects... I suppose I could use a shared (but not globally) source file.

That sounds good.

Discussed and decided this doesn't matter

authors: anpete bricelam rowanmiller


text:
Specified cast is not valid

In my example, I have a Time class with a Minutes field defined using the short data type.
If I try to get the total decimal hours like this:
var totalHours = _dbContext.Times.Sum(t => t.Minutes / 60m);
I get the error:
An exception of type 'System.InvalidCastException' occurred in EntityFramework.Core.dll but was not handled in user code. Additional information: Specified cast is not valid.
This, however, works fine:
var totalHours = _dbContext.Times.Sum(t => t.Minutes / 60);

Can someone tell me if this is a bug? It just seems too simple to be an undocumented issue, but it's cropping up everywhere in my project.

This seems to work:
var test = _dbContext.Times.Sum(t => (decimal?)Convert.ToDecimal(t.Minutes) / 60m);
I suppose it makes sense - you have to explicitly convert it to a decimal to get EF to do so. EF6 was able to infer this I guess. I need the (decimal?) in case there are no times, but that's not necessary for this particular issue. I just wanted to show that it looks a bit odd to have to cast twice. But I can live with that.


text:
A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.

I am built a web server with Nancy(.net core), and have a async action like this:
Post("/resource", async args =>
{
    var course = Context.Items["course"] as Course;
    var user = (Context.CurrentUser.Identity as Identity).Info;

    #region 获取资源属性

    string title = Request.Form.title;
    long size = Request.Form.size;
    string url = Request.Form.url;
    string md5 = Request.Form.md5;

    if (string.IsNullOrWhiteSpace(title)) return new { code = -100, msg = "资源的标题不能为空" };
    if (string.IsNullOrWhiteSpace(url)) return new { code = -100, msg = "资源的地址不能为空" };
    if (string.IsNullOrWhiteSpace(md5)) return new { code = -100, msg = "资源的MD5不能为空" };

    #endregion

    var doc = new Resource();

    doc.Id = StringUtil.UniqueId();
    doc.DateCreated = DateTime.Now;
    doc.CreatorId = user.Id;

    doc.CourseId = course.Id;
    doc.Title = Path.GetFileNameWithoutExtension(title).Trim();
    doc.Url = url.Trim();
    doc.MD5 = md5.Trim();
    doc.Size = size;
    doc.Extension = Path.GetExtension(title);

    db_course.Resources.Add(doc);
    await db_course.SaveChangesAsync();

    return new { code = 1, msg = "上传成功" };
});

I Post more than 5 requests at one time, but got this error:
System.InvalidOperationException: A second operation started on this context before a previous operation completed. Any instance members are not guaranteed to be thread safe.
   at Microsoft.EntityFrameworkCore.Internal.ConcurrencyDetector.EnterCriticalSection()
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.<SaveChangesAsync>d__54.MoveNext()
--- 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)
   at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.<SaveChangesAsync>d__52.MoveNext()
--- 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)
   at Microsoft.EntityFrameworkCore.DbContext.<SaveChangesAsync>d__35.MoveNext()

Further technical details
EF Core version:  1.1.2
Database Provider: Pomelo.EntityFrameworkCore.MySql 1.1.2
Operating system:  Windows 10 15063
IDE:  Visual Studio 2017

@leixu2txtek Make sure each request has a separate instance of db_course.


text:
Customize Migration names in code

I have multiple DbContexts. When I create migrations; e.g. called 'Init' for each of them, they appear with same name and different timestamps in the same MigrationHistory Table. E.g I can have 2 migrations belonging to 2 different DbContexts which have the same name Init, and they would look like Init_487474923 and Init_475649393 in the table. They appear under correct folder structure in code though, which is good, but not good enough.
I want to be able to customize the name, add a prefix may be, to give my migration names a context so that later when someone looks at them in the migration history table, they know what those migrations refer to. It would be nice to have them look like:
abc_init_timestamp1
xyz_init_timestamp2
This was not a problem in EF6 which had a column for ContextKey so it was clear which DbContext it belonged to. Adding a new column name to MigrationHistory table is a road I want to avoid.
I tried to implement the IDesignTimeServices and added it to my startup project
public sealed class MyDesignTimeServices : IDesignTimeServices
    {
        public void ConfigureDesignTimeServices(IServiceCollection serviceCollection)
        {
            serviceCollection.AddSingleton<IMigrationsIdGenerator, CustomDbMigrationsIdGenerator>();
        }
    }

    public sealed class CustomDbMigrationsIdGenerator: MigrationsIdGenerator
    {
        public override string GenerateId(string name)
        {
            return base.GenerateId(<my-custom-prefix> + name);
        }
    }

It works great if I have a single DbContext. The problem occurs when I have multiple DbContexts. Whenever a migration is ran, same instance gets called for all DbContexts (obviously because there is just one instance added via the MyDesignTimeServices above), and adds the same prefix to every migration, although they belong to a different DbContext.
So I suppose 2 things can be done:

If its possible to get a reference to the name of the DbContext that triggered the GenerateId method, I can do a switch case or an if-else block inside GenerateId method above, to select the prefix I want to use, for that particular MigrationId generation.
Add a IMigrationsIdGenerator implementation for each DbContext, and somehow trigger the correct one based on which DbContext is invoked by Migrations

I believe 1 should be easier to do.
Any thoughts?

@ajcvickers Yes I can but, that way, every time I add a migration, I would have to go to a specific migrations folder, copy a prefix from a previous migration and then paste it to my CLI command. This is a manual process and a pain when I have multiple db contexts.
But anyhow, I dug up the EF Core APIs and found a way which resolves my issue. I see good things coming in the .net core 2.1 preview for Design Time customizations but this works for me till then. Here is how I did it:
 public sealed class MyDesignTimeServices : IDesignTimeServices
    {
        public void ConfigureDesignTimeServices(IServiceCollection serviceCollection)
        {
            serviceCollection.AddSingleton<IMigrationsIdGenerator, CustomMigrationsIdGenerator>();
            serviceCollection.AddSingleton<MigrationsScaffolder, MyMigrationsScaffolder>();
        }
    }

Followed by custom implementations of MigrationsIdGenerator and MigrationsScaffolder:
public sealed class CustomMigrationsIdGenerator : MigrationsIdGenerator
    {
        public string Prefix { get; set; }

        public override string GenerateId(string name)
        {
            return base.GenerateId(Prefix +"_" + name);
        }
    }

    public sealed class MyMigrationsScaffolder : MigrationsScaffolder
    {
        public MyMigrationsScaffolder(MigrationsScaffolderDependencies dependencies) : base(dependencies)
        {
            CustomMigrationsIdGenerator idGenerator =(CustomMigrationsIdGenerator) dependencies.MigrationsIdGenerator;

            switch (dependencies.CurrentDbContext.Context.GetType().Name)
            {
                case "AbcDbContext":
                    idGenerator.Prefix = MigrationPrefix.Abc.ToString();
                    break;
                case "DefDbContext":
                    idGenerator.Prefix = MigrationPrefix.Def.ToString();
                    break;
                case "GhiDbContext":
                    idGenerator.Prefix = MigrationPrefix.Ids.ToString();
                    break;
            }
        }
    }

    public enum MigrationPrefix
    {
        Abc,
        Def,
        Ghi
    }
}

repo: aspnet/EntityFrameworkCore


text:
One-to-Many Realtionship works only after querying from "many" entity

If you believe you have an issue that affects the security of the platform please do NOT create an issue and instead email your issue details to secure@microsoft.com. Your report may be eligible for our bug bounty but ONLY if it is reported through email.
Describe what is not working as expected.
If you are seeing an exception, include the full exceptions details (message and stack trace).
Exception message: System.ArgumentNullException: 'Value cannot be null.
Parameter name: source'
Stack trace:
System.Linq.ThrowHelper.ThrowArgumentNullException(ExceptionArgument argument)
System.Linq.Enumerable.ToList<TSource>(IEnumerable<TSource> source)
Stock.Controllers.WarehouseController.Info(string id) in WarehouseController.cs
+
                var model = new WarehouseInfoViewModel { Warehouse = Warehouse, Items = Warehouse.Items.ToList() };
lambda_method(Closure , object , object[] )
Microsoft.Extensions.Internal.ObjectMethodExecutor.Execute(object target, object[] parameters)
Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor+SyncActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeActionMethodAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeNextActionFilterAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

The Code:
First, I'm using ASP.NET Core 3-preview6. I'm also using Identity, and EF Core version's also 3.0-preview6. I setted up Identity, and everything is configured correctly in Startup.cs file.
I created 2 models: Warehouse and Item, defined:
public class Item
    {
        [Key]
        [Editable(false)]
        public string Id { get; set; }
        [Required]
        [MinLength(4)]
        [DataType(DataType.Text)]
        public string Name { get; set; }
        [Required]
        public int Quantity { get; set; }
        [Editable(false)]
        public string WarehouseId { get; set; }
        public Warehouse Warehouse { get; set; }
    }

public class Warehouse
    {
        [Key]
        public string Id { get; set; }
        public string Name { get; set; }
        public string Location { get; set; }
        public List<Item> Items { get; set; }
    }

And I defained One-to-Many Relationship using fluent API, and I'm also seeding data.
Here's my DbContext:
 public class AppDbContext : IdentityDbContext<AppUser>
    {
        public AppDbContext(DbContextOptions options) : base(options)
        {

        }
        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);

            // Relationship Here
            builder.Entity<Item>().HasOne(i => i.Warehouse).WithMany(w => w.Items).HasForeignKey(i => i.WarehouseId);

            // Seed data here
            Guid WarehouseId = Guid.NewGuid();
            builder.Entity<Warehouse>().HasData(new Warehouse
            {
                Id = WarehouseId.ToString(),
                Name = "Main Rabin Storage",
                Location = "Room 18, Rabin High"
            });
            builder.Entity<Item>().HasData(new Item {
                Id = Guid.NewGuid().ToString(),
                Name = "Innova 22.5'' Monitor",
                Quantity = 18,
                WarehouseId = WarehouseId.ToString()
            });

        }
        public DbSet<Item> Items { get; set; }
        public DbSet<Warehouse> Warehouses { get; set; }

    }

And when I use the DbContext in the controller for the "first" time for the Warehouse Entity like:
 var Warehouse = _dbContext.Warehouses.FirstOrDefault(w => w.Id == id);
            if (Warehouse != null)
            {
                var model = new WarehouseInfoViewModel { Warehouse = Warehouse, Items = Warehouse.Items.ToList() };
                return View(model);
            }
            return NotFound();

I get an exception on Warehouse.Items.ToList() that Items property isn't defined.
So, Using VS immediate windows, I checked the values in this order, including the outputs:
Warehouse
{Stock.Models.Warehouse}
    Id: "750792ad-4444-4e87-a7ea-922b87cf5524"
    Items: null
    Location: "Room 18, Rabin High"
    Name: "Main Rabin Storage"
_dbContext.Items
{Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1[Stock.Models.Item]}
    Local: {Microsoft.EntityFrameworkCore.ChangeTracking.LocalView<Stock.Models.Item>}
    Results View: Expanding the Results View will enumerate the IEnumerable
_dbContext.Items[0]
error CS0021: Cannot apply indexing with [] to an expression of type 'DbSet<Item>'
_dbContext.Items.ToList()[0]
{Stock.Models.Item}
    Id: "bc17ca61-1413-44f6-9b21-4ab1b2f8f586"
    Name: "Innova 22.5'' Monitor"
    Quantity: 18
    Warehouse: {Stock.Models.Warehouse}
    WarehouseId: "750792ad-4444-4e87-a7ea-922b87cf5524"
Warehouse
{Stock.Models.Warehouse}
    Id: "750792ad-4444-4e87-a7ea-922b87cf5524"
    Items: Count = 1
    Location: "Room 18, Rabin High"
    Name: "Main Rabin Storage"

And in the second time, I checked again:
Warehouse
{Stock.Models.Warehouse}
    Id: "750792ad-4444-4e87-a7ea-922b87cf5524"
    Items: null
    Location: "Room 18, Rabin High"
    Name: "Main Rabin Storage"
Warehouse.Items
null
id
"750792ad-4444-4e87-a7ea-922b87cf5524"
_dbContext.Items
{Microsoft.EntityFrameworkCore.Internal.InternalDbSet`1[Stock.Models.Item]}
    Local: {Microsoft.EntityFrameworkCore.ChangeTracking.LocalView<Stock.Models.Item>}
    Results View: Expanding the Results View will enumerate the IEnumerable
_dbContext.Items.ToList()
Count = 1
    [0]: {Stock.Models.Item}
_dbContext.Items.ToList()[0]
{Stock.Models.Item}
    Id: "bc17ca61-1413-44f6-9b21-4ab1b2f8f586"
    Name: "Innova 22.5'' Monitor"
    Quantity: 18
    Warehouse: {Stock.Models.Warehouse}
    WarehouseId: "750792ad-4444-4e87-a7ea-922b87cf5524"
Warehouse
{Stock.Models.Warehouse}
    Id: "750792ad-4444-4e87-a7ea-922b87cf5524"
    Items: Count = 1
    Location: "Room 18, Rabin High"
    Name: "Main Rabin Storage"
Warehouse.items
error CS1061: 'Warehouse' does not contain a definition for 'items' and no accessible extension method 'items' accepting a first argument of type 'Warehouse' could be found (are you missing a using directive or an assembly reference?)
Warehouse.Items
Count = 1
    [0]: {Stock.Models.Item}

Means that EF doesn't query by relationship until the FK queried IN THE CURRENT CONTEXT!
Further technical details
EF Core version: 3.0.0-preview6.19304.10
Database Provider: (e.g. Microsoft.EntityFrameworkCore.SqlServer)
Operating system:  Windows 10 Pro 1903
IDE: Visual Studio 2019 16.2
Sql Server Developer Edition 2017

@avivnaaman preview 6 is quite out-of-date. Please update to preview 8 or better yet the daily builds.

There is no include in the query. Why would related data be loaded?

authors: ajcvickers avivnaaman smitpatel


text:
Upgrade Tfm to netcoreapp2.2

netcoreapp2.1 -> netcoreapp2.2
Also moved around tfm ordering since VS for Mac supports custom SDKs.

@dotnet-bot test windows release x64 build


text:
Using real objects for configuration, not arbitary and complex magic strings

Proposal:
Instead of using arbitrarily and complex strings to get elements from your configuration, I propose to use objects, after all we are using an OO language.
I thought we were gradually removing these types of magic strings from the framework.
To achieve this, base one’s configuration on POCO style simple objects. They can then be used to configure / build the runtime. They dont need to be POCO objects, they could also be the underlying objects that .NET uses, eg, BasicHttpBinding. Though, in this example, this means one's configuration is dependent on System.ServiceModel, which might not be ideal. If one uses simple POCO objects this dependency is removed until one needs to create the Binding in code that is alread dependent on System.ServiceModel..
Thus, all .NET configuration sections can easily be converted to these POCO objects. Thus adding the configuration of all aspects of .NET.
To achieve this one needs:
. POCO simple objects to represent the configuration required of the .NET runtime.
. An appsettings.json file that is structured in a way that it matches the POCO objects.
. Some implementations of ConfigurationProvider, IConfigurationSource to process the json file.
. A DynamicObject to cast the loaded json configuration to the POCO objects.
. Then one can have code to configure the application, eg, in your inplementation of ClientBase.
Proposal.docx
The attached file has some code samples.

Why does this need to be coupled to the configuration system? We build pocos on top of the low level name value pairs using options all the time. What do we gain by smushing those layers together?

Tried and tested code that everyone can depend on, and not have to re-write again and again.

Also, it provides a base of replacing all app.config sections across the entier code base.

Sorry that's not a convincing reason to change the existing API.

Also, it provides a base of replacing all app.config sections across the entier code base.

Is this the goal? To replace app configuration strongly typed configuration? Why not do that specificially instead of trying to bake it into a configuration model that wasn't designed for that?

Also, it removes the dependency on complex and arbitary string like "CommonKey1:CommonKey2:CommonKey3:CommonKey4".
If you chnage the POCO structure you still neeed to changer the json layout, but you dont have to find all occurances to magic strings across you whole code base.

The goal is to replace all config sections with simple objects. Currently most of the framework has ignored all config file initialization because it has been conveniently ignored (AFAIK).
It doesnt need to be a part of the configuration extensions, but what better place to put it to be available across all the rest of the.NET frasmework.

authors: davidfowl mgwalm

repo: aspnet/Extensions


text:
Can't reference a '.NET Framework 4.6 + ASP.NET Core 5.0' PCL from a 'Console application (Package)' project

Repro

VS 2015.
ASP.NET RC 1.
Add a Console application (package project) to a solution, I'll call it NetCoreApp from now on.
Remove "dnx451" from project.json/"frameworks" (not necessary, but let's simplify things a bit).
Add a PCL library that targets .NET Framework 4.6 and ASP.NET Core 5.0 to a solution. I'll call it PortableLibrary46 from now on.
Try to add a reference from NetCoreApp to PortableLibrary46.

The package restore will fail with the following written to the output:
Microsoft .NET Development Utility Clr-x86-1.0.0-rc1-16202
Wrapping project 'PortableLibrary46' for '.NETPortable,Version=v5.0'
  Source F:\Software\NetCoreRC\PortableLibrary46\PortableLibrary46.csproj
  Target F:\Software\NetCoreRC\PortableLibrary46\project.json
Error: Value cannot be null.
Parameter name: profileValue
PATH=.\node_modules\.bin;C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\Web Tools\External;%PATH%;C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\Microsoft\Web Tools\External\git
C:\Users\HellBrick\.dnx\runtimes\dnx-clr-win-x86.1.0.0-rc1-final\bin\dnx.exe "C:\Users\HellBrick\.dnx\runtimes\dnx-clr-win-x86.1.0.0-rc1-final\bin\lib\Microsoft.Dnx.Tooling\Microsoft.Dnx.Tooling.dll" restore "F:\Software\NetCoreRC\src\NetCoreApp" -f "C:\Program Files (x86)\Microsoft Web Tools\DNU"
Microsoft .NET Development Utility Clr-x86-1.0.0-rc1-16202
  CACHE https://www.nuget.org/api/v2/
  CACHE https://www.myget.org/F/hellbrick/
  CACHE https://www.myget.org/F/aspnetvnext/api/v2/
Restoring packages for F:\Software\NetCoreRC\src\NetCoreApp\project.json
  CACHE https://www.nuget.org/api/v2/FindPackagesById()?id='PortableLibrary46'
  CACHE https://www.myget.org/F/hellbrick/FindPackagesById()?id='PortableLibrary46'
  CACHE https://www.myget.org/F/aspnetvnext/api/v2/FindPackagesById()?id='PortableLibrary46'
Unable to locate Dependency PortableLibrary46 >= 1.0.0-*
Writing lock file F:\Software\NetCoreRC\src\NetCoreApp\project.lock.json
Restore complete, 287ms elapsed
Errors in F:\Software\NetCoreRC\src\NetCoreApp\project.json
    Unable to locate Dependency PortableLibrary46 >= 1.0.0-*
NuGet Config files used:
    C:\Users\HellBrick\AppData\Roaming\NuGet\nuget.config
Feeds used:
    https://www.nuget.org/api/v2/
    https://www.myget.org/F/hellbrick/
    https://www.myget.org/F/aspnetvnext/api/v2/
    F:\Software\~nuget
    C:\Program Files (x86)\Microsoft Web Tools\DNU

Background
I'm exploring porting some parts of a big .NET 4.6 solution to .NET Core + DNX to use them in a cross-platform way. In order to do that I need to figure out how to share class libraries between .NET 4.6 apps and .NET Core apps (porting everything simultaneously is not an option). Is there an alternative way to do that? So far I've managed to kinda sorta make it work by downgrading class libraries to 4.5.1 PCLs, but it would be nice to keep using 4.6 API if possible.

I'm no expert on this subject, but where are you trying to reference PortableLibrary46 from? It kind of looks like the package restore is looking for a Nuget package when it perhaps should be looking somewhere else.

This happens when I'm trying to reference PortableLibrary46 from any modern ASP.NET 5 project, whether it's a console app, a class library or a website. dnu wrap fails and everything goes wrong from that moment on.

I'm experiencing the same issue. Our primary, cross-application domain logic is contained in PCLs so they can be used in ASP.NET applications, mobile applications and Windows Universal. This is a blocker for ASP.NET 5 adoption.
I can easily reproduce the issue by creating a new ASP.NET 5 Web Application solution, adding a new PCL class library targeting .NET 4.6 + ASP.NET Core 5 + Windows Universal 10 to the solution's .\src directory, then finally adding a reference within the web project targeting the PCL.
Any known workarounds or anticipated resolutions?

Any updates on this? Just tried to do it in a similar fashion as JeremiahSanders suggests and i've got the same problem with rc1

I guess we have to wait until dnu retires and proper support for both xproj > csproj and csproj > xproj references on top for the dotnet cli is shipped.

This issue is being closed because it has not been updated in 3 months.
We apologize if this causes any inconvenience. We ask that if you are still encountering this issue, please log a new issue with updated information and we will investigate.

authors: HellBrick JeremiahSanders aspnet-hello sjdixon taori

repo: aspnet/Home


text:
RequireHttpsMetadata set to false failed

I'm building a asp.net core 2.0 solution with some projects. On my dev machine, I use OpenIdConnect and set RequireHttpsMetadata to false for testing, i get the exception as described below. If I set it to true, there is no problem.
System.InvalidOperationException: The MetadataAddress or Authority must use HTTPS unless disabled for development by setting RequireHttpsMetadata=false.
   at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerPostConfigureOptions.PostConfigure(String name, JwtBearerOptions options)
   at Microsoft.Extensions.Options.OptionsFactory`1.Create(String name)
   at Microsoft.Extensions.Options.OptionsMonitor`1.<>c__DisplayClass10_0.<Get>b__0()
   at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
   at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
   at System.Lazy`1.CreateValue()
   at Microsoft.Extensions.Options.OptionsCache`1.GetOrAdd(String name, Func`1 createOptions)
   at Microsoft.Extensions.Options.OptionsMonitor`1.Get(String name)
   at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.<InitializeAsync>d__42.MoveNext()
--- 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)
   at Microsoft.AspNetCore.Authentication.AuthenticationHandlerProvider.<GetHandlerAsync>d__5.MoveNext()
--- 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)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.AspNetCore.Authentication.AuthenticationService.<AuthenticateAsync>d__10.MoveNext()
--- 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)
   at IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationHandler.<HandleAuthenticateAsync>d__2.MoveNext() in C:\local\identity\server4\AccessTokenValidation\src\IdentityServer4.AccessTokenValidation\IdentityServerAuthenticationHandler.cs:line 61
--- 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)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.<AuthenticateAsync>d__47.MoveNext()
--- 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)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.AspNetCore.Authentication.AuthenticationService.<AuthenticateAsync>d__10.MoveNext()
--- 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)
   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.<Invoke>d__6.MoveNext()
--- 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)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIIndexMiddleware.<Invoke>d__3.MoveNext()
--- 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)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.<Invoke>d__6.MoveNext()
--- 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)
   at Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.<Invoke>d__3.MoveNext()
--- 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)
   at Microsoft.AspNetCore.Server.IISIntegration.IISMiddleware.<Invoke>d__11.MoveNext()
--- 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)
   at Microsoft.AspNetCore.Hosting.Internal.RequestServicesContainerMiddleware.<Invoke>d__3.MoveNext()
--- 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)
   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Frame`1.<ProcessRequestsAsync>d__2.MoveNext()
Application Insights Telemetry (unconfigured): {"name":"Microsoft.ApplicationInsights.Dev.Exception","time":"2018-03-08T03:41:17.7238969Z","tags":{"ai.application.ver":"1.0.0.0","ai.cloud.roleInstance":"HUYTRAN-PC","ai.operation.id":"868b0d85-46e57ed115249134","ai.operation.parentId":"|868b0d85-46e57ed115249134.1.129137ed_","ai.operation.name":"GET /api/tickets","ai.location.ip":"::1","ai.internal.sdkVersion":"aspnet5c:2.2.1","ai.internal.nodeName":"HUYTRAN-PC"},"data":{"baseType":"ExceptionData","baseData":{"ver":2,"properties":{"{OriginalFormat}":"Connection id \"{ConnectionId}\", Request id \"{TraceIdentifier}\": An unhandled exception was thrown by the application.","DeveloperMode":"true","CategoryName":"Microsoft.AspNetCore.Server.Kestrel","AspNetCoreEnvironment":"Development","TraceIdentifier":"0HLC4KPJB1MJM:00000003","ConnectionId":"0HLC4KPJB1MJM","Exception":"System.InvalidOperationException: The MetadataAddress or Authority must use HTTPS unless disabled for development by setting RequireHttpsMetadata=false.\r\n   at Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerPostConfigureOptions.PostConfigure(String name, JwtBearerOptions options)\r\n   at Microsoft.Extensions.Options.OptionsFactory`1.Create(String name)\r\n   at Microsoft.Extensions.Options.OptionsMonitor`1.<>c__DisplayClass10_0.<Get>b__0()\r\n   at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)\r\n   at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)\r\n   at System.Lazy`1.CreateValue()\r\n   at Microsoft.Extensions.Options.OptionsCache`1.GetOrAdd(String name, Func`1 createOptions)\r\n   at Microsoft.Extensions.Options.OptionsMonitor`1.Get(String name)\r\n   at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.<InitializeAsync>d__42.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Microsoft.AspNetCore.Authentication.AuthenticationHandlerProvider.<GetHandlerAsync>d__5.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at Microsoft.AspNetCore.Authentication.AuthenticationService.<AuthenticateAsync>d__10.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationHandler.<HandleAuthenticateAsync>d__2.MoveNext() in C:\\local\\identity\\server4\\AccessTokenValidation\\src\\IdentityServer4.AccessTokenValidation\\IdentityServerAuthenticationHandler.cs:line 61\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.<AuthenticateAsync>d__47.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at Microsoft.AspNetCore.Authentication.AuthenticationService.<AuthenticateAsync>d__10.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()\r\n   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.<Invoke>d__6.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIIndexMiddleware.<Invoke>d__3.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.<Invoke>d__6.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware.<Invoke>d__3.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Microsoft.AspNetCore.Server.IISIntegration.IISMiddleware.<Invoke>d__11.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Microsoft.AspNetCore.Hosting.Internal.RequestServicesContainerMiddleware.<Invoke>d__3.MoveNext()\r\n--- End of stack trace from previous location where exception was thrown ---\r\n   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()\r\n   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Frame`1.<ProcessRequestsAsync>d__2.MoveNext()"},"exceptions":[{"id":21889970,"typeName":"System.InvalidOperationException","message":"Connection id \"0HLC4KPJB1MJM\", Request id \"0HLC4KPJB1MJM:00000003\": An unhandled exception was thrown by the application.","hasFullStack":true,"parsedStack":[{"level":0,"method":"Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerPostConfigureOptions.PostConfigure","assembly":"Microsoft.AspNetCore.Authentication.JwtBearer, Version=2.0.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60"},{"level":1,"method":"Microsoft.Extensions.Options.OptionsFactory`1.Create","assembly":"Microsoft.Extensions.Options, Version=2.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60"},{"level":2,"method":"Microsoft.Extensions.Options.OptionsMonitor`1+<>c__DisplayClass10_0.<Get>b__0","assembly":"Microsoft.Extensions.Options, Version=2.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60"},{"level":3,"method":"System.Lazy`1.ViaFactory","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"},{"level":4,"method":"System.Lazy`1.ExecutionAndPublication","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"},{"level":5,"method":"System.Lazy`1.CreateValue","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"},{"level":6,"method":"Microsoft.Extensions.Options.OptionsCache`1.GetOrAdd","assembly":"Microsoft.Extensions.Options, Version=2.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60"},{"level":7,"method":"Microsoft.Extensions.Options.OptionsMonitor`1.Get","assembly":"Microsoft.Extensions.Options, Version=2.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60"},{"level":8,"method":"Microsoft.AspNetCore.Authentication.AuthenticationHandler`1+<InitializeAsync>d__42.MoveNext","assembly":"Microsoft.AspNetCore.Authentication, Version=2.0.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60"},{"level":9,"method":"System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"},{"level":10,"method":"System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"},{"level":11,"method":"Microsoft.AspNetCore.Authentication.AuthenticationHandlerProvider+<GetHandlerAsync>d__5.MoveNext","assembly":"Microsoft.AspNetCore.Authentication.Core, Version=2.0.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60"},{"level":12,"method":"System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"},{"level":13,"method":"System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"},{"level":14,"method":"System.Runtime.CompilerServices.TaskAwaiter`1.GetResult","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"},{"level":15,"method":"Microsoft.AspNetCore.Authentication.AuthenticationService+<AuthenticateAsync>d__10.MoveNext","assembly":"Microsoft.AspNetCore.Authentication.Core, Version=2.0.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60"},{"level":16,"method":"System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"},{"level":17,"method":"System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"},{"level":18,"method":"IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationHandler+<HandleAuthenticateAsync>d__2.MoveNext","assembly":"IdentityServer4.AccessTokenValidation, Version=2.4.0.0, Culture=neutral, PublicKeyToken=null","fileName":"C:\\local\\identity\\server4\\AccessTokenValidation\\src\\IdentityServer4.AccessTokenValidation\\IdentityServerAuthenticationHandler.cs","line":61},{"level":19,"method":"System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"},{"level":20,"method":"System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"},{"level":21,"method":"System.Runtime.CompilerServices.TaskAwaiter`1.GetResult","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"},{"level":22,"method":"Microsoft.AspNetCore.Authentication.AuthenticationHandler`1+<AuthenticateAsync>d__47.MoveNext","assembly":"Microsoft.AspNetCore.Authentication, Version=2.0.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60"},{"level":23,"method":"System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"},{"level":24,"method":"System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"},{"level":25,"method":"System.Runtime.CompilerServices.TaskAwaiter`1.GetResult","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"},{"level":26,"method":"Microsoft.AspNetCore.Authentication.AuthenticationService+<AuthenticateAsync>d__10.MoveNext","assembly":"Microsoft.AspNetCore.Authentication.Core, Version=2.0.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60"},{"level":27,"method":"System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"},{"level":28,"method":"System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"},{"level":29,"method":"System.Runtime.CompilerServices.TaskAwaiter`1.GetResult","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"},{"level":30,"method":"Microsoft.AspNetCore.Authentication.AuthenticationMiddleware+<Invoke>d__6.MoveNext","assembly":"Microsoft.AspNetCore.Authentication, Version=2.0.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60"},{"level":31,"method":"System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"},{"level":32,"method":"System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"},{"level":33,"method":"Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIIndexMiddleware+<Invoke>d__3.MoveNext","assembly":"Swashbuckle.AspNetCore.SwaggerUI, Version=2.2.0.0, Culture=neutral, PublicKeyToken=4232c99127b3c254"},{"level":34,"method":"System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"},{"level":35,"method":"System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"},{"level":36,"method":"Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware+<Invoke>d__6.MoveNext","assembly":"Swashbuckle.AspNetCore.Swagger, Version=2.2.0.0, Culture=neutral, PublicKeyToken=62657d7474907593"},{"level":37,"method":"System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"},{"level":38,"method":"System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"},{"level":39,"method":"Microsoft.AspNetCore.Diagnostics.StatusCodePagesMiddleware+<Invoke>d__3.MoveNext","assembly":"Microsoft.AspNetCore.Diagnostics, Version=2.0.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60"},{"level":40,"method":"System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"},{"level":41,"method":"System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"},{"level":42,"method":"Microsoft.AspNetCore.Server.IISIntegration.IISMiddleware+<Invoke>d__11.MoveNext","assembly":"Microsoft.AspNetCore.Server.IISIntegration, Version=2.0.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60"},{"level":43,"method":"System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"},{"level":44,"method":"System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"},{"level":45,"method":"Microsoft.AspNetCore.Hosting.Internal.RequestServicesContainerMiddleware+<Invoke>d__3.MoveNext","assembly":"Microsoft.AspNetCore.Hosting, Version=2.0.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60"},{"level":46,"method":"System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"},{"level":47,"method":"System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification","assembly":"System.Private.CoreLib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e"},{"level":48,"method":"Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Frame`1+<ProcessRequestsAsync>d__2.MoveNext","assembly":"Microsoft.AspNetCore.Server.Kestrel.Core, Version=2.0.1.0, Culture=neutral, PublicKeyToken=adb9793829ddae60"}]}],"severityLevel":"Error"}}}
Microsoft.AspNetCore.Server.Kestrel:Error: Connection id "0HLC4KPJB1MJM", Request id "0HLC4KPJB1MJM:00000003": An unhandled exception was thrown by the application.

Any suggestion for this problem? Thank you.

Duplicate of https://github.com/aspnet/Security/issues/1684

authors: Tratcher huytnd


text:
dnx coreclr/windows universal class library & AllJoyn

are there any plans to support hosting/consuming Windows Universal class libraries under the dnx coreclr ? eg. sharing the generated AllJoyn libraries in both Windows Universal applications and dnx coreclr web/console applications?

This issue is being closed because it has not been updated in 3 months.
We apologize if this causes any inconvenience. We ask that if you are still encountering this issue, please log a new issue with updated information and we will investigate.

authors: aspnet-hello grahamehorner


text:
Sync+error complete combined

The two PRs had merge conflicts, so this is them combined
SocketOutput exception completes all waiting tasks #567
Write chunks async; unblock sync-waits directly #586
Resolves #572
Resolves #565
Resolves #566
Resolves #590
Closes #567
Closes #586

Throughput check still looking good (large async chunked requests)

Running 10s test @ http://.../plaintext
  32 threads and 1024 connections
  Thread Stats   Avg      Stdev     Max   +/- Stdev
    Latency   200.80ms  183.95ms   2.00s    76.91%
    Req/Sec   146.90     62.94   400.00     67.41%
  46299 requests in 10.10s, 13.36GB read
  Socket errors: connect 35, read 0, write 0, timeout 47
Requests/sec:   4583.76
Transfer/sec:      1.32GB

Some occasional dips over a longer run (GC); though @halter73 had something for that.

Eugh, sync not so good. Investigating.

Probably additionally needs some way to bump up minThreads for ThreadPool for people that do a lot of sync calls - but that's a hosting thing? (e.g. dnx, dotnet cli, etc)

@benaadams I think increasing the ThreadPool's minimum threads is something that users will have to do themselves if they have to make a lot of sync calls.

@halter73 yeah, don't think there is a facility to do it - will have a quick scan of https://github.com/dotnet/cli and raise issue if not. I think that's the right place?

Raised issue for threadpool size https://github.com/dotnet/cli/issues/889

Code change feedback on the original issues so will be changing them rather than this. @halter73 feel free to close - though it has more info, like the code I ran for the tests and the results.

@halter73 threadpool setting currently by switching the environment variable
set ComPlus_ThreadPool_ForceMinWorkerThreads=1000

repo: aspnet/KestrelHttpServer


text:
Decimal binding problem on non English Culture

Hi everyone. I have an aspnet core app that runs with a non english configuration (spanish):
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory
{
    ......
    app.UseRequestLocalization(new RequestLocalizationOptions
    {
        DefaultRequestCulture = new RequestCulture(new CultureInfo("es-AR"))
        ,SupportedCultures = new List<CultureInfo>
        {
             new CultureInfo("es-AR")
         }
         ,SupportedUICultures = new List<CultureInfo>
         {
               new CultureInfo("es")
         }
     });

      .........
}

In english a decimal number has its decimal part delimited with a dot, but in spanish a comma is used:

10256.35 english
10256,35 spanish

I have this action in a controller:
 [HttpPost]
 public decimal Test(decimal val)
 {
     return val;
 }

If I use postman and send to that action a json like this {val: 15.30}, then val in the action recives a 0 (binding not working because of the culture). If I send a json like this {val: 15,30} then in the action I recive 15.30
The problem I have is, I need the action to accept decimals with commas, because that is the format that comes from inputs type text in the app's forms. But i also need to accept decimal with a dot that comes from request in json format.  There is no way to specify a decimal/float in json that accepts a comma (send it as string is not an option). How can I do this??? I'm driving my self crazy with this.
Thanks!!

Could we see a bit more of your app? In particular

Is the app.UseRequestLocalization() call before or after app.UseMvc()?
Does your action use [FromBody] i.e. public decimal Test([FromBody] decimal val)?

Here is what you asked me:
This is the configure method:
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug(LogLevel.Trace);

    app.UseRequestLocalization(new RequestLocalizationOptions
    {
        DefaultRequestCulture = new RequestCulture(new CultureInfo("es-AR"))
        ,SupportedCultures = new List<CultureInfo>
        {
            new CultureInfo("es-AR")
        }
        ,SupportedUICultures = new List<CultureInfo>
        {
            new CultureInfo("es")
        }
    });

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        //app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Site/Error");
    }

    app.UseStaticFiles();

    app.UseAppAuthentication(Configuration);

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "areaRoute",
            template: "{area:exists}/{controller=Site}/{action=Index}/{id?}");

        routes.MapRoute(
            name: "default",
            template: "{controller=Site}/{action=Index}/{id?}");
    });
}

I don't use [FromBody] anywhere, should I? all my POST actions look like this:
[HttpPost]
public CLASS ACTION_NAME(TYPE OBJECT)
{
    return XXXX;
}

Example:
[HttpPost]
public decimal prueba(decimal val)
{
    return val;
}

How can I accept numbers in json format in my culture that does not accept numbers in that format?

I've used [FromBody] and still the same result. It only accepts decimals with comma.
[HttpPost]
public decimal prueba([FromBody] decimal val)
{
    return val;
}

This is the request the app accepts:

This is the request the app does not accept:

I need the app to accept both on my current culture (es-AR). When the data comes from a html form, it comes already formatted with comma. When I send it through json it must accept the dot as a decimal separator.

I'm not sure how your application is working w/o [FromBody].
You need to make a change in the JsonSerializerSettings when you are using [FromBody]. It's a slight Json.NET reconfiguration: The default JsonSerializerSettings.Culture is CultureInfo.InvariantCulture and that controls the "culture used when reading JSON".
Suggest the following in your Startup.ConfigureServices() method:
services
    .AddMvc()
    .AddJsonOptions(options => options.SerializerSettings.Culture = CultureInfo.CurrentCulture);

that's a really surprising default :disappointed:

Still does not work. It doesn't accept numbers with dot due the current culture. What is failing is the model binder.

You mentioned JSON earlier - but your example screenshots show x-www-form-urlencoded
I re-read your first post, and it sounds like what you need is two different actions.
MVC core does not treat JSON and form-data as the same. [FromBody] is used for JSON and normal model binding handles form-data.
I'd try something like this:
[HttpPost]
[ActionName("prueba")]
[Consumes("application/x-www-url-formencoded")]
public decimal TestForm([FromBody] decimal val)
{
    return val;
}

[HttpPost]
[ActionName("prueba")]
[Consumes("application/json")]
public decimal TestJson([FromBody] TestModel val)
{
    return val;
}

public class TestModel
{
    public decimal Val { get; set; }
}

[Consumes] will dispatch to the correct action based on the the content type of the submitted request. You could also use different URLs/action-names if you'd prefer.
I think the issues that you're seeing with the JSON aren't related to the culture - it's actually that the object submitted in JSON is { val = 3.14 }, and object with the property val. You need to use a class that matches.
You could alternative use JObject in your JSON action if you want a dynamic view of the data.
============================
With all of that said, tread very carefully if you're trying to expose the same functionality over JSON and HTML form. The primary reason why we separated these is that there are a number of concerns that you will want to handle separate (mostly security-related) for an HTML form, an ajax client or a 3rd part arbitrary HTTP client.
If this is intended to be used by a browser, you'll also need antiforgery/CSRF protection for any reason site.

@dougbu @rynowak the JSON RFC specifies that the decimal point should be used:

A fraction part is a decimal point followed by one or more digits.

Changing the culture of the JSON serializer settings as suggested is likely to reduce interoperability.

OK than that makes more sense about why InvariantCulture is the default, I stand corrected.

@rynowak  I tested it. Using:

[Consumes("application/x-www-url-formencoded")] : accepts number with comma, but not number with dot

[Consumes("application/json")]: accepts numbers with dot, but not number with comma.

Honestly i didn´t know the use of [FromBody], now i know.
Where is my problem? I have certain type of functionality where I send a post to the server using jquery like this:
 $.ajax({
    url: '..........................',
    type: 'post',
    data: $form.serialize() + '&' + $.param(data),
    dataType: 'json'
})

data is a json array of objects, and the form is a standard form. I'm sending a form and an array of json to an action. In the form I have numbers with comma and in the array I have numbers with dot. So when the request goes to the action, the binding only happens with the numbers with comma, and the numbers with dot are not binded. The problem I see now with your explanation is that I'm mixing the the form and json data in one action. Right now it can't be all data from a form or all the data in json, it is mixing both. Is there any way to accept the data the way I'm sending it. Meanwhile I solved it with a custom model binder that reads both, number with comma and number with dot as a valid decimal, but I don't want to do that.
Did I explained the problem or it is still unclear? Thanks a lot for your help.

A custom model binder is about the only way to handle either decimal format in a JSON submission.

I'm not sure how your application is working w/o [FromBody].
You need to make a change in the JsonSerializerSettings when you are using [FromBody]. It's a slight Json.NET reconfiguration: The default JsonSerializerSettings.Culture is CultureInfo.InvariantCulture and that controls the "culture used when reading JSON".
Suggest the following in your Startup.ConfigureServices() method:
services
    .AddMvc()
    .AddJsonOptions(options => options.SerializerSettings.Culture = CultureInfo.CurrentCulture);

It has worked for me. Thank you @dougbu

authors: airomero dougbu gustavomoutella nil4 rynowak

repo: aspnet/Mvc


text:
Supporting open generic models in Views

The story:
The idea came to my mind when summarizing multiple views using partials. I thought it would be great if we could define partial views with open generic models.
I thought at first to post the idea in ASP.NET uservoice website. When I searched there, I noticed the idea was suggested a few years ago https://aspnet.uservoice.com/forums/41201-asp-net-mvc/suggestions/2706166-support-for-generics-in-razor-view.
There, @danroth27 had directed users to a new track ( #727 ) in ASP.NET github and asked users to comment practical examples/use cases of the suggestions.
After visiting the issue, I noticed it is closed, because nobody had given any comment. I didn't know if someone is still allowed to comment on a closed issue or not, but I dared to try it.
I was happy to see @Eilon's quick reply some hours later still welcoming use cases for this idea.
As the scenario I wanted to mention was a little long, He suggested to post it as new issue.
So, here am I.
The scenario involves multiple pieces of code fragments (C#, Razor views), but I do my best to make it short and only mention the meat.

Intro
Suppose we need to implement an administration panel for a website consisting of various modules, such as Blogs, Photos, News, Products, etc.
Data Layer
We are using EF code first for our models and data layer.
Model objects
We use a base class for all of our model classes as below.
public class BaseEntity
{
   public int Id { get; set; }
   public bool IsDeleted { get; set; }
   public DateTime? CreatedDate { get; set; }
   public virtual User CreatedBy {  get; set; }
   public DateTime? ModifiedDate { get; set; }
   public virtual User ModifiedBy {  get; set; }
   [Timestamp]
   public byte[] RowVersion { get; set; }
}

We use this structure to provide the following features:

Auditing : when a record is inserted, by whom it is inserted, when it is last updated, who has updated it (CreatedDate, CreatedBy, ModifiedDate, ModifiedBy)
Logical deletion of records (IsDeleted property)
Concurrency management (RowVersion property)

This is our model classes:
public class Blog: EntityBase
{
   public string Title { get; set; }
   public string Content { get; set; }
   public string ImageUrl { get; set; }
}
public class Photo: EntityBase
{
   public string Title { get; set; }
   public string SmallImageUrl { get; set; }
   public string LargeImageUrl { get; set; }
}
public class News: EntityBase
{
   public string Title { get; set; }
   public string Content { get; set; }
   public string Source { get; set; }
   public string ThumbnailUrl { get; set; }
}
public class Product: EntityBase
{
   public string Title { get; set; }
   public decimal Price { get; set; }
   public string SmallImageUrl { get; set; }
   public string LargeImageUrl { get; set; }
}

We don't add a BlogDate, NewsDate or Author property to Blog and News models. We use CreatedDate and CreatedBy properties to satisfy this need.

For the administration panel we create an "Admin" area in our MVC application.
There, for each module, we create a controller. So, we have a BlogController, NewsController, PhotoController and ProductController.
I don't go through the code of the data layer, repositories, the controllers and their actions. They are not our concern.
I go right to the Views which is the topic of this post.
Views
We use HTML tables to provide a data grid for each module.
This is the View of Index action in our BlogController:
@model IEnumerable<Blog>
@{
    ViewBag.Title = "Blogs";
}

            Id
            Title
            Image
            Created Date
            Created By
            Modified Date
            Modified By

@foreach (var item in Model)
{

            @item.Id
            @item.Title

            @item.CreatedDate
            @(item.CreatedBy?.UserName)
            @item.ModifiedDate
            @(item.ModifiedBy?.UserName)
            @Html.Action("Edit", new { Id = item.Id })
            @Html.Action("Delete", new { Id = item.Id })

}

@Html.Pager(ViewBag,CurrentPage, ViewBag.PageSize, ViewBag.PageCount, ViewBag.RecordCount)

Not surprisingly, the Views for the Index action in all our other controllers, (NewsController, PhotoController and ProductController) follow a similar code.
For example, this is the view for the Index action of ProductController.
@model IEnumerable<Product>
@{
    ViewBag.Title = "Products";
}

            Id
            Title
            Price
            Image
            Created Date
            Created By
            Modified Date
            Modified By

@foreach (var item in Model)
{

            @item.Id
            @item.Title
            @item.Price

            @item.CreatedDate
            @(item.CreatedBy?.UserName)
            @item.ModifiedDate
            @(item.ModifiedBy?.UserName)
            @Html.Action("Edit", new { Id = item.Id })
            @Html.Action("Delete", new { Id = item.Id })

}

@Html.Pager(ViewBag,CurrentPage, ViewBag.PageSize, ViewBag.PageCount, ViewBag.RecordCount)

This is now, when the idea/requested features starts.
It would be a great help if we could define a generic View like AdminGrid.cstml this way:
@model IEnumerable<T> where T: EntityBase

            Id
            @Html.Partial<T>("AdminGridHead")
            Created Date
            Created By
            Modified Date
            Modified By

@foreach (var item in Model)
{

            @item.Id
            @Html.Partial<T>("AdminGridBody", item)
            @item.CreatedDate
            @(item.CreatedBy?.UserName)
            @item.ModifiedDate
            @(item.ModifiedBy?.UserName)
            @Html.Action("Edit", new { Id = item.Id })
            @Html.Action("Delete", new { Id = item.Id })

}

@Html.Pager(ViewBag,CurrentPage, ViewBag.PageSize, ViewBag.PageCount, ViewBag.RecordCount)

This way we are extracting the repetitive or common HTML code out of all of our views into this single View. This is somehow following the DRY principle.
Notice that I used two generic Html.Partial() method calls in this AdminGrid View, namely AdminGridHead and AdminGridBody to provide a way for the developer to implement the custom HTML code based on each T type.
The tricky thing is, although we have a single AdminGrid.cshtml, we should have separate AdminGridHead and AdminGridBody partial views, each one for a type that will be used for the generic T parameter in AdminGrid's model part.
These views could be defined using a file naming convention like below (use the name of the concrete type in the partial view filename):

AdminGridHead.Blog.cshtml
AdminGridBody.Blog.cshtml
AdminGridHead.News.cshtml
AdminGridBody.News.cshtml
AdminGridHead.Photo.cshtml
AdminGridBody.Photo.cshtml
AdminGridHead.Product.cshtml
AdminGridBody.Product.cshtml

Although, these Views will have concrete models objects, not a generic model, but based on the fact that they are called using a generic Html.Partial() extnsion method (which we don't have such a thing at the moment), they in turn aim to the topic of this post (supporting generic models in Views).
Now, supposing we have the ability of defining Views with generic models, in our Index actions we should return the model using a generic View().
public class BlogController: Controller
{
// ...
public ActionResult Index(int page = 1, int pagesize = 5)
{
var model = BlogRepository.GetPage(page, pagesize);
  return View<Blog>(model);

}
}
Using a generic View() not a View(), is necessary. I explain the reason why a little further later.

This was the whole scenario.
I will explain potential problems we have in front of us when implementing this feature in future comments.
Because, when I looked at MVC's source code, I noticed that it's not that easy to implement this feature as it seems in the first glance (what I personally thought too at first!).
The key point is, we need to carry the generic T, from the top api, like View() method in Controller class or Html.Partial() extension method down to the ViewEngine, BuildManager and other classes that play role in creating the C# class of the views, finding the files of views, instantiating from the view classes and binding ViewDicitonary and Model to them.

Now, why we need a generic View<T>() method in our controllers? Why we can't call the old View() method in our actions to return a View whose model is generic?
The reason is that, the View cannot be instantiated without its generic parameters known.
Suppose the following View which has a generic IEnumerable model.
@model IEnumeranle<T>

@foreach (var item in Model)
{

@item.ToString()

}

Let's suppose these Views are supported now.
The generated C# class that is required for this view and it should inherit WebViewPage would be something like this:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using System.Web.WebPages;

public partial class _Areas_Admin_Views_Shared_AdminGrid_cshtml<T> : System.Web.Mvc.WebViewPage<IEnumerable<T>>
{
	public _Areas_Admin_Views_Shared_AdminGrid_cshtml()
	{
	}
	public override void Execute()
	{
		WriteLiteral("<ul");

		foreach (var item in Model)
		{
			WriteLiteral("
");
			Write(item.ToString());
			WriteLiteral("
");
		}

		WriteLiteral("</ul");
	}
}

The important thing in this class is that despite other classes that is generated for other Views it is still a generic class with a T generic parameter.
This class cannot be instantiated unless we provide its generic parameter.
This is why we need to have a generic View<T>() method in our controllers and specify the generic parameter, so that the underlying ViewEngine is able to instantiate the view from its generated class.

I was thinking that what happens if our view has a generic model with multiple generic types.
@model MyModel<T, U> // ...
Clearly, we can no longer use the generic View<()> method in Controller class.
I think the correct way to implement this feature is to add overload methods with a Type[] array argument to which we can pass an array of types that are required when instiating from the class of the generic Views. This way we can support a model with any number of generic type parameters.
This also applies to IViewPageActivator that is responsible for instantiating views. In fact, we need to add another Create() method to the interface with a Type[] parameter.
public interface IViewPageActivator
{
   object Create(ControllerContext controllerContext, Type type);
   object Create(ControllerContext controllerContext, Type type, Type[] genericTypes);
}

The following could be the implementation of this new method in the DefaultViewPageActivator:
public object Create(ControllerContext controllerContext, Type type, Type[] genericTypes)
{
	try
	{
		var genericType = type.MakeGenericType(genericTypes);
		return Activator.CreateInstance(genericType);
	}
	catch (MissingMethodException exception)
	{
		// ...
	}
}

+1 to this, I just spent a little while puzzling out that you can't do this (trying to setup a partial view to render pagination controls for various pages with different models, taking a PaginatedList). You can do this without explicitly specifying the @model type but it would be nice to have support for @model to check it.

From a Milestone to the Backlog on May 14?  Where is this?  I can't believe I haven't seen what I consider to be an overwhelming Use Case for this, albeit one at which I am fully aware of the countless eyes that will roll.  Send in a generic model collection, reflect on its items' property names for column headers and then iterate through the list to display those items' values.  Reflection, slow, I get it.  But how much dev time would be saved for simple key/value lookup lists, like Country?  Let the eye rolling begin.

+1
Generics is not a cutting edge feature anymore, this is a must have in C#, and I cannot imagine an enterprise grade C# project without generics now. I'm really surprised that we don't hear much more noises about it.
Maybe for some reasons implementing this missing feature on Razor views is really hard for the MS team?

Actually I made my hands dirty a little to implement this feature.
As far as the codes were in MVC source code I handled the changes and applied appropriate changes to provide open generics feature in views.
But when I went deeper I reached to Razor Engine source code and there I stuck. The Razor Engine source code was very sophisticated. I couldn't invest more time on that. So, I dropped the case.
Clearly the folks in Razor Engine project can apply the needed changes faster.

@mansoor-omrani Can you upload your progress to GitHub? And point out where in the Razor Engine it's complicated?

Yes. Sure. I'll upload the changes I applied.

I tried to push the changes. But it failed. This is the messages I received.
Authentication failed. You may not have permission to access the repository or the repository may have been archived. Open options and verify that you're signed in with an account that has permission to access this repository.
By the way, I was working on "https://github.com/aspnet/AspNetWebStack" repository.

I opened a new issue in the aforementioned branch.
https://github.com/aspnet/AspNetWebStack/issues/200

@mansoor-omrani Can you upload your progress to GitHub? And point out where in the Razor Engine it's complicated?

I created a pull request for code changes in my fork. I was working on legacy MVC.

authors: RemiGaudin ashleybaldock jzabroski kramffud mansoor-omrani


text:
Ensure CompatibilityVersion documentation is current

There's a list of bullet points associated with CompatibilityVersion here - https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNetCore.Mvc.Core/CompatibilityVersion.cs#L60. Pretty easy to miss updating this. This tracking item is meant to ensure this list is up-to-date at the end of an RTM release

Dup of https://github.com/aspnet/Mvc/issues/8595


text:
Custom Tag Helper not discovered/applied from a NuGet package

I have a modified (better, really :wink:) @DamianEdwards styles+scripts inlining custom Tag Helper that works just fine when the class is part of the application ...
[HtmlTargetElement("style", Attributes = "inline")]
[HtmlTargetElement("script", Attributes = "inline")]
public class StyleScriptInliningTagHelper : TagHelper
{
    ...
    public override void Process(TagHelperContext context, TagHelperOutput output)
    { ... }
}

However, when I pulled this code out into a NuGet package and then consumed the package in the app, it was not applied on Razor compilation.
Perhaps I didn't wire something up properly? ... or is it not working via a NuGet package "by design?"

@davidfowl ah ha ... I think I changed the name of it in the package. I'll check and close in disgrace if that's what happened.

@davidfowl Jeebers McScreebers! Of course, I changed the namespace, so a simple update to ...
@{
    @addTagHelper *, StyleScriptInlining
}

... fixed it. Closing in disgrace now. [At least give me cred for my 6th NuGet package in two days ... I'm a NuGet-dropping MACHINE!]

repo: aspnet/Razor


text:
Handle null entries correctly for IsEmptyOrWhiteSpace

#2497

dotnet test Ubuntu 16.04 Release Build


text:
Using C#8 features causes error while scaffolding razorpage

Steps to reproduce:
Follow this series of tutorials up to and including this step.
Also logged here: https://github.com/aspnet/AspNetCore.Docs/issues/14044
Update:
This issue was originally demonstrated with a C#8 switch expression (as opposed to a traditional switch statement). @jessicah then reported the issue with C#8 using declaration (as opposed to a traditional using statement). It seems likely that this issue is related to using C#8 features in general, so I have updated the title accordingly.
Update:
I had forgotten that I had applied a VS analyzer code change suggestion to convert a switch statement to a switch expression. After following the tutorials as noted above, at Pages/Students/Index.cshtml.cs line 52, change as follows to reproduce the problem:
Before:
switch (sortOrder)
            {
                case "name_desc":
                    studentsIQ = studentsIQ.OrderByDescending(s => s.LastName);
                    break;
                case "Date":
                    studentsIQ = studentsIQ.OrderBy(s => s.EnrollmentDate);
                    break;
                case "date_desc":
                    studentsIQ = studentsIQ.OrderByDescending(s => s.EnrollmentDate);
                    break;
                default:
                    studentsIQ = studentsIQ.OrderBy(s => s.LastName);
                    break;
            }

After:
            studentsIQ = sortOrder switch
            {
                "name_desc" => studentsIQ.OrderByDescending(s => s.LastName),
                "Date" => studentsIQ.OrderBy(s => s.EnrollmentDate),
                "date_desc" => studentsIQ.OrderByDescending(s => s.EnrollmentDate),
                _ => studentsIQ.OrderBy(s => s.LastName),
            };

Without the switch expression, scaffolding works. I have updated the title of this issue accordingly.
Expected behavior:
The Courses folder is successfully scaffolded.
Actual behavior:
From dotnet cli:
PS> dotnet aspnet-codegenerator razorpage -m Course -dc SchoolContext -udl -outDir Pages\Courses --referenceScriptLibraries
Building project ...
Finding the generator 'razorpage'...
Running the generator 'razorpage'...
Attempting to compile the application in memory.
Could not get the reflection type for DbContext : ContosoUniversity.Data.SchoolContext
   at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.<BuildCommandLine>b__6_0()
   at Microsoft.Extensions.CommandLineUtils.CommandLineApplication.Execute(String[] args)
   at Microsoft.VisualStudio.Web.CodeGeneration.ActionInvoker.Execute(String[] args)
   at Microsoft.VisualStudio.Web.CodeGeneration.CodeGenCommand.Execute(String[] args)
RunTime 00:00:08.47

In VS 2019 16.3.0 Preview 2.0:

Could be related to #430 and #682. I've tried adding explicit ref to Microsoft.CodeAnalysis.CSharp.Workspaces as suggested in those issues, full rebuild of project, reload of VS etc, but it does not help.
Additional information about the project being scaffolded, such as:
Target framework(s):
.NET Core 3.0
Package version of Microsoft.AspNetCore.App or Microsoft.AspNetCore.All (if applicable):
3.0.0-preview8.19405.7
Package version of Microsoft.VisualStudio.Web.CodeGeneration.Design - this may be added to your project by scaffolding:
3.0.0-preview8-19413-06

This also happens with new forms of C# 8 using declarations as well.

It seems likely that this issue is related to using C#8 features in general, so I have updated the title accordingly.

This should be fixed in the latest rc1 versions.

authors: jessicah tg73 vijayrkn

repo: aspnet/Scaffolding


text:
The command line View help lists --controllerNamespace|-namespace as an option

It shouldn't 😄

Stale issue from 2017. Please re-open if this is still relevant. Closing.

authors: NTaylorMullen vijayrkn


text:
Changing IdentityModel package versions to beta5

Shouldn't this be in release?

It's against release - I created a bad PR on GitHub.

:shipit:

authors: Tratcher pranavkm

repo: aspnet/Security


text:
Flaky tests: CanCloseStreamMethodEarly, CanInvokeClientMethodFromServer, etc

I set:

CanCloseStreamMethodEarly
CanInvokeClientMethodFromServer
CanSendAndReceiveMessage
CanStopAndStartConnection
ExceptionFromStreamingSentToClient
ServerThrowsHubExceptionIfHubMethodCannotBeResolved
ServerThrowsHubExceptionIfSteamingHubMethodCannotBeResolved
ServerThrowsHubExceptionOnHubMethodARgumentTypeMismatch
ServerThrowsHubExceptionOnStreamingHubMethodArgumentTypeMismatch_messagepack_LongPolling_dynamic
StreamDoesNotStartIfTokenAlreadyCanceled_json_WebSockets_dynamic

to ignore for now because they fail on OSX sometimes. It should be investigated and re-enabled once fixed.

Ignore on the CI?

Sorry, was delayed in pushing the change. I create the issue before the PR so that I can put the issue number in the Skip reason.

Looking at the test failures on the CI, the logs aren't very helpful because they were run before https://github.com/aspnet/Logging/pull/760, which means the logs for one framework overwrote the logs for a different framework. We should do some runs with the latest logging to see if that fixes things. I'll see about doing that.

Sounds good to me, I'll let you know if there's a new one to examine.

https://github.com/aspnet/SignalR/issues/1214

With the sync context disabled I'm seeing SSETransportStopsSendAndReceiveLoopsWhenTransportStopped fail repeatedly.

That test is fixed in https://github.com/aspnet/SignalR/pull/1279
But it has a null-ref on netcoreapp2.0

Ah hah, I disabled it for now.

I'm seeing this one fail randomly. I might have an idea why but I'll look into it after more refactoring.
ConnectionCanSendAndReceiveDifferentMessageSizesWebSocketsTransport_4096032
I have logs, it looks we might just need to extend the timeout.

In general I push back when people say "just increase the timeout". Why is it that things aren't ready when we think they should be? Could we just await the completion of some call or process instead? Is the timeout in this case just unexpectedly short?

I'm going to take these

I removed the timeout entirely. I'm going to close this issue @ryanbrandenburg, let me know if you're still seeing failures.

Failures continue.

@ryanbrandenburg all of them?

authors: BrennanConroy anurse davidfowl ryanbrandenburg

repo: aspnet/SignalR


text:
Releases page - latest one is 1.0.0-alpha2

This issue is similar to https://github.com/aspnet/EntityFrameworkCore/issues/12550.
When navigating to https://github.com/aspnet/SignalR/releases latest release is 1.0.0-alpha2,

@danroth27 who manages this, is it still you? I notice other repos (https://github.com/aspnet/Mvc/releases) have the same problem.

Yeah, we stopped generating releases on individual repos when we moved issue tracking for a bunch of repos into the Home repo. I guess technically we could still generate releases in repos that still maintain their own issue trackers.

authors: Misiu anurse danroth27


text:
Handle back pressure from slow clients when application complete

If an application is complete but the transport is currently writing to a slow connection, it's possible we'll miss the notification that the application is complete for an indeterminate amount of time, leaking resources. We need to handle this situation by checking the channel's task and completing the outgoing send after some timeout.
This needs to be handled in all 3 transports:

LP - https://github.com/aspnet/SignalR/blob/d19ed0070c25478c6ed23c2490e700f1452e8a68/src/Microsoft.AspNetCore.Sockets/Transports/LongPollingTransport.cs#L69
SSE - https://github.com/aspnet/SignalR/blob/d19ed0070c25478c6ed23c2490e700f1452e8a68/src/Microsoft.AspNetCore.Sockets/Transports/ServerSentEventsTransport.cs#L65
WS - https://github.com/aspnet/SignalR/blob/d19ed0070c25478c6ed23c2490e700f1452e8a68/src/Microsoft.AspNetCore.Sockets/Transports/WebSocketsTransport.cs#L194

/cc @anurse

Closing in favor of #820

@halter73 Kestrel's drain timeout will cover this right?

Re-opening this one separately, I need to do some investigation.

Turns out we don't need to handle this!

authors: anurse davidfowl


text:
Likely stable release date for 1.0.0

Hey there
We're really interested in integrating with the aspnet core version of Signal R. Unfortunately due to company politics we wont be able to build the alpha release into our product.
Does the team have a release date/milestone in mind? Would be great to know if a build would likely be ready by the end of this year.
Many thanks

The stable release will be released with ASP.NET Core 2.1 which is planned for Q1/Q2 next year.

@moozzyk you planed Next PreRelease 2.1.0-preview1 or 1.0.0-alpha3?

We are planning to ship the next preview as part of ASP.NET Core 2.1.0 preview1

authors: KANekT dubs999 moozzyk


text:
Committing changes required to have SignalR depend on the centralized Microsoft BOM file for Java libraries

For discussion with the Java client engineering team, @anurse @BrennanConroy @mikaelm12 @davidfowl. This is a proposal to externalise your dependency version management to an external POM. We are gradually rolling this out to all Java SDKs, and I am keen to hear your thoughts, feedback, concerns, or whatever else may be running through your mind 😄
All versions that have been removed from your Gradle file are now represented in the Maven parent POM file, and as your dependencies have not yet been encountered (and were therefore not included up to now), I have taken the exact same version numbers as you use. There will therefore be no functional difference.

 Thank you for your submission, we really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.:x: JonathanGiles sign nowYou have signed the CLA already but the status is still pending? Let us recheck it.

Just so I understand what's going on here. This is basically externalizing the version numbers of the dependencies we use so that we're aligned with the ones used by other Microsoft Java libraries? I think that sounds like a good idea.
What's the process we should follow if we need to update one of these dependencies? If it's urgent, can we override the version from com.microsoft.maven:java-8-parent with our own version locally?

Thanks guys for your questions. I have answered these elsewhere for other teams and I realise I really should centralise the answers to these kinds of questions. I'll do that and then get back to you.

authors: JonathanGiles anurse dnfclas


text:
Cannot compile the documentation

Trying to compile the documentation.
Created a virtual environment for Olympus, cloned the olympus repo, installed olympus.
Installed requirements at documentation, missing modules in the requirements:

No module named 'sklearn' (installing manually)
Sqlite databases require sqlalchemy (missing module) (installing manually)
Plotter requires matplotlib, seaborn (installing manually)
No module named m2r (installing manually)

Error after installing these modules:
sphinx/registry.py", line 266, in add_source_parser     for filetype in parser.supported: AttributeError: 'str' object has no attribute 'supported' make: *** [Makefile:21: html] Error 2

I can confirm I have encountered the same issue. Interestingly I can compile the docs on my Mac in a conda env with python==3.7.3 and sphinx==2.3.1. I can share the whole env details if this may help.

This issue seemed to be caused by this:
https://github.com/sphinx-doc/sphinx/issues/8395
I updated the master branch to use m2r2 and the docs should compile now - I managed to compile them with m2r2==0.2.7

This issue seemed to be caused by this:
https://github.com/sphinx-doc/sphinx/issues/8395
I updated the master branch to use m2r2 and the docs should compile now - I managed to compile them with m2r2==0.2.7

authors: JurgisR matteoaldeghi

repo: aspuru-guzik-group/olympus


text:
[bug] Escape problem in String

⏯ Playground Link

Playground link with relevant code
💻 Code

Code:
r'^[A-Za-z0-9_-]+\\$'

Pattern:
r'^[A-Za-z0-9_-]+\\$'

🙁 Actual behavior

Not matched
🙂 Expected behavior

Should be matched
If the string starts with a string start like "r', "f", and "b" in Python, then escape does not work. Both in the playground and in CLI.
Remove the double "\" is the same.

It is caused by meta variable character replacement. You can use YAML rule instead.
https://ast-grep.github.io/playground.html#eyJtb2RlIjoiQ29uZmlnIiwibGFuZyI6InB5dGhvbiIsInF1ZXJ5IjoicideW0EtWmEtejAtOV8tXSsnIiwicmV3cml0ZSI6IiIsImNvbmZpZyI6InJ1bGU6XG4gICAga2luZDogc3RyaW5nXG4gICAgcmVnZXg6IFwicicuKydcIiIsInNvdXJjZSI6InInXltBLVphLXowLTlfLV0rXFxcXCQnIn0=

OK, thank you

I think the behavior can be improved by replacing $ only in meta variable.

repo: ast-grep/ast-grep


text:
google-drive-ocamlfuse command not found during auth in headless mode

opam says its installed and Ive tried removing it and reinstalling it using opam, Ive tried type google-drive-ocamlfuse and still no luck.
A reboot fixed this

Do you have these lines in ~/.profile?
# OPAM configuration
. $HOME/.opam/opam-init/init.sh > /dev/null 2> /dev/null || true

What's the content of file ~/.opam/opam-init/variables.sh?

On ~/.profile im getting file not found
and the contents of ~/.opam/opam-init/variables.sh is:
CAML_LD_LIBRARY_PATH=/home/Bertie/.opam/4.01.0/lib/stublibs; export CAML_LD_LIBRARY_PATH;
MANPATH=$MANPATH:/home/Bertie/.opam/4.01.0/man; export MANPATH;
MAKELEVEL=; export MAKELEVEL;
MAKEFLAGS=; export MAKEFLAGS;
PERL5LIB=/home/Bertie/.opam/4.01.0/lib/perl5:$PERL5LIB; export PERL5LIB;
OCAML_TOPLEVEL_PATH=/home/Bertie/.opam/4.01.0/lib/toplevel; export OCAML_TOPLEVEL_PATH;
PATH=/home/Bertie/.opam/4.01.0/bin:$PATH; export PATH;

Then OPAM will build your executables in /home/Bertie/.opam/4.01.0/bin. Check that, in the folder, you find google-drive-ocamlfuse executable. Then check that your $PATH environment variable contains OPAM bin dir (running echo $PATH).

All of them are in the right places and the $PATH files are correct

What's the output of command:
$ which google-drive-ocamlfuse

~/.opam/4.01.0/bin/google-drive-ocamlfuse

And when you run:
$ google-drive-ocamlfuse

gives you "command not found"?

No thats fixed but now its not syncing. Sorry I edited my first post to say a reboot fixed it.

Sorry, but what do you mean when you say that it's not syncing?

I run google-drive-ocamlfuse and nothing happens, It worked originally after a restart but I had to restart again and I stopped being able to access gdrive

Have you tried running the command with -debug command line option, and then check the log files?

authors: Bertieio astrada

repo: astrada/google-drive-ocamlfuse

license: mit

license_source: bigquery


text:
No new releases after v0.0.282

This repo is missing releases after v0.0.282 - https://github.com/astral-sh/ruff-pre-commit/releases/
But the tags are present: https://github.com/astral-sh/ruff-pre-commit/tags

v0.0.283
v0.0.284
v0.0.285

Thanks! I've published those versions.

authors: lukasz-mitka zanieb

repo: astral-sh/ruff-pre-commit


text:
RUF013 undocumented limitation x: CustomClass = None is not caught

It seems like the following should be caught or at least be added to the documented limitations:
from enum import Enum
from typing import Optional

class Letter(Enum):
    """ok."""

    A = "A"

class CatchMe:
    """class."""

def f(
    letter: Letter = None,  # <--- should be caught
    word: Optional[str] = None,
    catch: CatchMe = None,  # <--- should be caught
) -> None:
    """Doc."""

List of keywords you searched for before creating this issue: RUF013
A minimal code snippet that reproduces the bug: https://play.ruff.rs/afaf262e-0615-4732-83aa-4cc32af930c2
The command you invoked: ruff check file.py --select RUF013
The current Ruff settings: in the snippet.
The current Ruff version: 0.7.1

I assume this is "intentional" because Ruff doesn't know to what types Letter resolves. E.g. Letter could be defined as type Letter = str | None in which case the assignment is valid. Not sure if there's another reason for it as well

Yeah, I think this is pretty much the reason. The logic considers all custom type to be similar to Any which is the case here.
For context, the fallback branch tries to resolve the name Letter to a qualified name which doesn't exists and thus fallback to using Unknown (similar to Any).
https://github.com/astral-sh/ruff/blob/4ece8e5c1e674eb0d751fa55b5a72950aa9d20f0/crates/ruff_linter/src/rules/ruff/typing.rs#L116-L119

repo: astral-sh/ruff