text:
js_binary + ESM + hermeticity

Assuming something like this in a BUILD file:
load("@aspect_rules_ts//ts:defs.bzl", "ts_project")
load("@aspect_rules_js//js:defs.bzl", "js_binary")
load("@aspect_rules_swc//swc:defs.bzl", "swc_transpiler")
load("@bazel_skylib//lib:partial.bzl", "partial")

ts_project(
    name = "src",
    srcs = [
        "src.ts",
    ],
    declaration = True,
    transpiler = partial.make(
        swc_transpiler,
        source_maps = "true",
        swcrc = "//:swcrc_esm",
    ),
    tsconfig = "//:tsconfig",
    deps = [
        "//:node_modules/@types/node",
    ],
)

js_binary(
    name = "src_bin",
    entry_point = ":src.js",
)

And assuming that the transpilation of src.ts makes an ESM bundle in bazel-dist, running the js_binary fails because the generated src.js file is neither src.mjs, nor does Node know to run as "type": "module".
In other words, bazel run //src:src_bin will fail:
(node:92736) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.

However, if in the source tree I update the package.json file to have "type": "module", the js_binary will now run.
I'm not sure if this is a bug or a question, but I'm surprised that a change to the package.json file in the source tree affects the js_binary. I assumed (perhaps incorrectly) that there would be a sandbox for the node process underpinning js_binary, and that it wouldn't have access to a package.json in the source tree.
Am I missing something?

Ah, I see. Happy to close this if it's a dupe... wdyt?


text:
Update descriptions for API docs

Fixes #2197
This has the smell :nose: of an auto-generated document. If so, plz close. If not, this fills in the MIA descriptions.

@guardrex,
Thanks for having already signed the Contribution License Agreement. Your agreement was validated by .NET Foundation. We will now review your pull request.
Thanks,
.NET Foundation Pull Request Bot

Looks like it's covered by https://github.com/aspnet/ApiDocs/pull/23.

source: gharchive/pull-request

authors: dnfclas guardrex

repo: aspnet/ApiDocs

license_type: permissive

license_source: github-api


text:
Hosted services package reference

Fixes #15649

I think we can merely call out the package is added/present for the Worker SDK and implicit for the Web SDK.
Strip out the bits on a Web Host and Generic Host pair of samples. Those went away recently (3.0 updates era), so those bits no longer apply.

How about that :point_up"?


text:
Blazor Server-Side: Api-Controllers of an other assembly got not mapped

I'm running a blazor server side application on the latest .net core preview6.
When i'm moving the api controllers to an other referenced assembly
the controller got not mapped to any route at runtime. It works when i move them
back to the host or when i remove all the blazor server hosting stuff.

Thank you for filing this issue. In order for us to investigate this issue, please provide a minimalistic repro project that illustrates the problem.

I have provided a sample here: https://1drv.ms/u/s!AvfU-VGBgXuLg-o4LRpQynSJvInKcA?e=Pb00ls
There is an API Project with the moved Controller. By loading the FetchData Page you'll see that the controller was not found. By removing the external controler and activating the original one on the server project you'll see that the FetchData Page is working.

We're closing this as  this seems to be a dupe of https://github.com/aspnet/AspNetCore/issues/11921

source: gharchive/issue

authors: endeffects mkArtakMSFT

repo: aspnet/AspNetCore

license: MIT


text:
StreamId Map should be cleared when connection is stopped

Currently we don't clear the internal dictionary for mapping stream ids to active streams when the client disconnects. It's a silent issue because we will override any stale values with new streams, but regardless, we should be clearing out the map on connection close.

And removing on stream closes?

We could. We'd have to have another map though correlating invocation ids to their stream ids. So we'd have to push the invocation id into the checkUploadStreamlogic where we allocate the stream Ids so we could group them together.  I don't feel to strongly about this tbh.

Sure, but it's technically a memory leak on the client.

*sighs in agreement

Consider for preview 8, relatively low priority.

authors: BrennanConroy anurse mikaelm12


text:
Blazor - Javascript interop in thread from Invoke() breaks.

Hi,
If you try to change the pages html from any function/thread starting from Invoke() it breaks the page with no errors.
e.g.

public void ButtonClicked()
{
    // do stuff...

    Invoke(() => {
        this.StateHasChanged();
        UpdateHTMLDOM();  // <---------- this breaks the entire page.
    });
}

private async void UpdateHTMLDOM()
{
    await JSRuntime.invokemethod<>("CreateImage", "myImageString.png");
}

Can you provide a minimal example that reproduces the problem? Given the default project template, what is the minimal set of steps needed to update it to show the problem you're describing?

Using the default project template "Server-side razor" given in the visual studio 2019 preview version. Using netcore sdk version "3.0.0-preview6-27804-01".
Replace the counter.razor code with the following:
@page "/counter"
@inject IJSRuntime JSRuntime

Counter

Current count: @currentCount

<button @onclick="@ButtonClicked">Increment Counter.</button>

@code {
    private int currentCount = 0;
    private string Title = "";

    bool PreventRenderLoop = false;
    protected override void OnAfterRender()
    {
        if (PreventRenderLoop) return; // stop the page from entering a render loop.

        Task getDataTask = Task.Run(GetData);
        getDataTask.Wait();
    }

    public async void GetData()
    {
        // demo just load some variables.
        Title = "Hello World";
        // e.g. data = MyService.LoadData();

        PreventRenderLoop = true;
        // refresh the page after loading new values
        Invoke(() =>
        {
            this.StateHasChanged();

            // now the page has the new values loaded from the service
            // we want to display the DOM which is relavent
            Task.Run(DisplayDOM).Wait();
        });
    }

    public async Task DisplayDOM()
    {
        currentCount = -1;

        await JSRuntime.InvokeAsync<string>("Notify", "Successfully displayed dom!", "success");
    }

    public void ButtonClicked()
    {
        currentCount++;
    }
}

And the code for the javascript notification (which goes in wwwroot/js and you reference in _Host.cshtml) is:

function Notify(pStrMessage, pStrMode)
{
    alert(pStrMessage + " _ " + pStrMode);
}

If you run the above code, when you click the button to increment the counter, nothing happens. I resolved this by changing it to this:
@page "/counter"
@inject IJSRuntime JSRuntime

Counter

Current count: @currentCount

<button @onclick="@ButtonClicked">Increment Counter.</button>

@code {
    private int currentCount = 0;
    private string Title = "";

    bool PreventRenderLoop = false;
    protected override void OnAfterRender()
    {
        if (PreventRenderLoop) return; // stop the page from entering a render loop.

        Task getDataTask = Task.Run(GetData);
        getDataTask.Wait();
    }

    public async void GetData()
    {
        // demo just load some variables.
        Title = "Hello World";
        // e.g. data = MyService.LoadData();

        PreventRenderLoop = true;
        // refresh the page after loading new values
        await Invoke(() =>
        {
            this.StateHasChanged();
        });

        // now the page has the new values loaded from the service
        // we want to display the DOM which is relavent
        Task domTask = Task.Run(DisplayDOM);
        await domTask;
    }

    public async Task DisplayDOM()
    {
        currentCount = -1;

        await JSRuntime.InvokeAsync<string>("Notify", "Successfully displayed dom!", "success");
    }

    public void ButtonClicked()
    {
        currentCount++;
    }
}

I notice now that i set the PreventRender boolean and never unset it, therefore the OnAfterRender() function is constantly blocked. Could that cause the rest of the program to stop working? if so why does the above code allow the counter to work?
Cheers! Richard

Thanks for contacting us, @Bambofy.
It's not clear what you're trying to do as it most probably be simpler than this. Give us some more context, so that we are able to guide you better.

i'm trying to load data from a service in the OnAfterRender function and then refreshing the page to update the values.

Why use OnAfterRender? Typically the pattern for loading data asynchronously in Blazor looks like this:
@if (myData == null)
{

something to show while data is loading

}
else
{

show your data here

}

@code {

    private MyData myData;

    protected override async Task OnInitialized()
    {
          myData = await LoadMyData();
    }
}

This pattern will render twice, once to show a "loading" UI and then again after the LoadMyData() method completes.
Do you have something special that you're trying to do here?

Why use OnAfterRender? Typically the pattern for loading data asynchronously in Blazor looks like this:
@if (myData == null)
{

something to show while data is loading

}
else
{

show your data here

}

@code {

    private MyData myData;

    protected override async Task OnInitialized()
    {
          myData = await LoadMyData();
    }
}

This pattern will render twice, once to show a "loading" UI and then again after the LoadMyData() method completes.
Do you have something special that you're trying to do here?

Hey i did not find the root cause of the original problem to be honest!
The way i'm making it work at the moment is like this:
    private static Type AccountType = null;
    private static string EmailHash = "";
    private static string PasswordHash = "";

    protected override async Task OnAfterRenderAsync()
    {
        // Ensure user is authenticated.
        if (AccountType == null)
        {
            await Authenticate();

            // Show new data.
            await Invoke(() =>
            {
                this.StateHasChanged();
            });
        }

        await JSRuntime.InvokeAsync<string>("WebpageReady");
    }

    protected async Task Authenticate()
    {
        /*
         * This authorization check can potentially be overriden since this code is clientside
         * Therefore we only use this clientside authorization check to render the page's DOM.
         */
        EmailHash = await JSRuntime.InvokeAsync<string>("GetSessionStorage", "EMAIL");
        PasswordHash = await JSRuntime.InvokeAsync<string>("GetSessionStorage", "PASSWORD");

        // Get the account type.
        AccountType = AccountService.GetAccountType(EmailHash, PasswordHash);
    }

authors: Bambofy SteveSandersonMS mkArtakMSFT rynowak


text:
Visual Studio 2019 Preview miss Blazor Template

Clean new INstall of Visual Studio 2019 Preivew- with all updates
Create Blazor Server App
.Razor files are uncolored in edtor
Visual Studio installer dialog comes up- is already running-
closing dialog- see nothing happen
Starting Project "Missing asp.net core-modul for hosting … iis express"
2nd machine everything works fine

Thanks for contacting us, @hannespreishuber.
This is not something runtime related. Please use VS Feedback to report this issue so the appropriate team can investigate this further.

authors: hannespreishuber mkArtakMSFT


text:
Don't swallow IHostedService.StartAsync exceptions

As discussed briefly in https://github.com/aspnet/Hosting/issues/1085#issuecomment-305717425 I propose that the HostedServiceExecutor should not catch exceptions in StartAsync.
By swallowing exceptions, the hosting-layer forces all services to be optional which is undesired IMO. By not swallowing exceptions we give services the option to decide this on its own. If a service is truly optional, it can swallow exceptions in its own StartAsync code.
I also think that StartAsync-exceptions should not be combined into an AggregateException. Instead it should just stop on the first exception.
One thing to consider is that right now this code is executed AFTER the server has been started. Not sure what effects this has when exceptions are no longer caught?!
I still hold the opinion that hosted services should be started before the server is started (a service could always decide to kick off another task in its StartAsync if it wants to be delayed) but this has also been discussed briefly in #1085 and declined.

Workaround for the 2.x version
public static class ServiceCollectionUtils
{
    public static void AddCriticalHostedService<TService, TImplementation>(this IServiceCollection services)
        where TService : class
        where TImplementation : class, IHostedService, TService
    {
        services.AddSingleton<TService, TImplementation>();
        services.AddHostedService<CriticalHostedServiceWrapper<TService>>();
    }

    private class CriticalHostedServiceWrapper<TService> : IHostedService
    {
        private readonly IHostedService _hostedService;
        private readonly ILogger _logger;

        public CriticalHostedServiceWrapper(TService hostedService, ILoggerFactory loggerFactory)
        {
            _hostedService = (IHostedService)hostedService;
            _logger = loggerFactory.CreateLogger(_hostedService.GetType());
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            try
            {
                await _hostedService.StartAsync(cancellationToken);
            }
            catch (Exception e)
            {
                _logger.LogCritical(e, "Cannot start critical service. The application will exit.");
                Environment.Exit(1);
            }
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            return _hostedService.StopAsync(cancellationToken);
        }
    }
}

Looks like behavior still the same in 3.0.

Update to use the generic host?

It works with generic host. Damn, I'm so far behind..

authors: AsValeO cwe1ss davidfowl srollinet


text:
Remove CodeGenerator metadata in default service reference experience

Aim here is to remove the current requirement to specify the CodeGenerator metadata on <Service...Reference> (soon <OpenApiReference> and <ProtobufReference>) items in a project file.
Some metadata must remain to say "give me TypeScript" (instead of project's default language) but this should be the exception and not the rule. Fortunately, the type of document is going to be explicit (again <OpenApiReference> and <ProtobufReference>) and we won't have to choose among multiple tools. Probably best to make TargetLanguage the main override we provide in this area. (@glennc agreed?)
This change will require our Open API code generation partners (NSwag, AutoRest, ...) either all implement the same target name or include a well-known property specifying their target's prefix. Either way, the last file that declares a target or updates a property wins. So, unless our partners object, let's avoid the indirection and go with a single Open API target name. (gRPC doesn't have multiple partners for the foreseeable future and should be fine with a single target for that scenario.)

@glennc I put this in Preview4. That make sense to you?
@mkArtakMSFT the "Small" cost here doesn't mean calendar time due to the need for NSwag changes.

From discussion today. Generator tag isn't required by default. There will be a language property a customer can add with the values "Default", and "TypeScript" where default means whatever the extensions/language the project is for and TypeScript is TypeScript.

Partially addressed in ce8f053af7e9. Will add language metadata soon.

After offline discussion with @glennc, we've decided to close this issue and await custom input on the feature's overall usability

authors: dougbu glennc


text:
Assembly Load Context throws errors in Blazor App 0.8

Describe the bug
When trying to load an assembly using the AssemblyLoadContext.Default a NotImplementedException is thrown. The Static property Default and it's other static methods don't seem to have any implementations.
To Reproduce
Steps to reproduce the behavior:

Download Sample code from: fred-perkins/BlazorLoading
Run application
Select Fetch Assembly in the left panel
Click "Fetch Assembly using AssemblyLoadContext" Button
Observe error in console: WASM: [System.NotImplementedException] The method or operation is not implemented.

Expected behavior
AssemblyLoadContext should attempt to load the DLL in the default context.
Additional context
We need to be able to dynamically load libraries one at a time within Blazor. Using Assembly.Load to read from bytes presents a problem where assemblies can be loaded several times, which causes a InvalidCastException to be thrown when resolving a type from one of those libraries.
Using AssemblyLoadContext it is possible to avoid this, however it seems unsupported when running in Webassembly on Blazor - But functions within a console application.
This is likely a mono issue:
Looking at mono it seems there are two implementations of the class: AssemblyLoadContext Facade
& AssemblyLoadContext.

@danroth27 - We spoke about this a week ago (Part of a derivco call). This is blocking us from migrating our framework to Blazor for our POC, as we need to be able to dynamically load libraries in the background. Is there a known alternative we could use other than Assembly.Load - Which doesn't solve our problem

@fred-perkins Thanks for sharing this feedback with us!
@SteveSandersonMS @lewing Thoughts on this one? Do we have any support currently for dynamically loading .NET assemblies in a Blazor app? Is this really all part of supporting lazy loading of application areas?

Could you clarify what the problem with Assembly.Load is? If your code caches the results of loading the assembly, is that not sufficient to ensure you only load each one once?

@SteveSandersonMS / @danroth27  So after a bit of testing I got Assembly.Load(byte[]) to work for me as i wanted. I think there was a misunderstanding about how Assembly.Load varies compared to the API on DotNet core - Where a byte array loaded assembly is anonymous and causes issues where assemblies would be loaded twice. This occurred when one was manually loaded, and the second where an assembly used a type for a dependent assembly - Which results in a InvalidCastException with duplicate types.
This means that for me to work around the issue I've had to use AssemblyLoadContext in .Net Core & Assembly.Load for the web assembly portion.
Ideally i'd prefer to use the AssemblyLoadContext Api across the board so i don't have to do fallback code in my .NetStandard libraries like the following:
public Assembly LoadFromStream(byte[] assemblySource)
{
    if (AssemblyLoadContext.Default != null)
    {
        return AssemblyLoadContext.Default.LoadFromStream(new MemoryStream(assemblySource))
    }
    return Assembly.Load(assemblySource);
}

I did have a dig through the mono source code in the end. It looks like they don't fully support the AssemblyLoadContext Api, and where they have partial support it only works for when you specify the assemblyName or filePath - The LoadFromStream throws a not supported exception as mentioned above.

Thanks for the update, @fred-perkins! I'm glad you have a workable solution for now.
Longer term, any inconsistencies between .NET Core and Mono are definitely worth reporting. In this specific case it sounds like Mono ideally would support more of AssemblyLoadContext, and might even want tweaks to ensure that Assembly.Load behaves the same as it does on .NET Core (even if that behavior isn't what you wanted in your scenario, it should still be consistent). If you were able to report any such API gaps or inconsistencies to http://github.com/mono/mono that would be really helpful.

I'll close this as external since it's really about the underlying runtime, not about Blazor.

@SteveSandersonMS Awesome, thanks for the reply. I'll get a ticket raised with the Mono guys :)

@fred-perkins
Can you link to the related mono issue?
I'm struggling to properly resolve a type existing in Assembly A, that depends on Assembly B.
Both are loaded into the default context already, but I'm looking to ensure A uses the type from B, rather than what's already loaded.

authors: SteveSandersonMS danroth27 fred-perkins tylerhartwig


text:
Add a FetchHttpClient

Fixes https://github.com/aspnet/AspNetCore/issues/9444
Taking over PR #12599, I'll try to keep the two original commits when merging.

Bueller


text:
Remove Newtonsoft JSON.NET from Blazor WASM template

Addresses #13422

@adrianwright109 could you cherry-pick your commit on the release/3.1 branch?

Closing this PR in favour of #14061 that correctly targets release/3.1 branch.


text:
Harden trigger and callback registrations in CacheEntry

There are possible race conditions in CacheEntry between AttachTriggers and DetatchTriggers. Similar for the callback APIs.  These need to be hardened to prevent potential stress/race crashes.

Every call to InvokeEvictionCallbacks is wrapped in the ReaderWriterLock in MemoryCache so it looks impossible to invoke more than once

#126 and #132

authors: BrennanConroy Tratcher

repo: aspnet/Caching


text:
new topic RUNNING ASP.NET CORE APPLICATIONS WITH IIS AND ANTARES (AZURE WEBSITES)

[ ] New article focused on Azure websites. Get info from RUNNING ASP.NET CORE APPLICATIONS WITH IIS AND ANTARES (AZURE WEBSITES)

https://docs.asp.net/en/latest/publishing/iis.html could also include some of these details.

@Tratcher There are a few nice troubleshooting adds for sure. I'll open an issue and make a list, including talking about the publish-iis tooling, which still isn't in that doc. Given that people assume it actually publishes apps to IIS, yeah, it probably should get a few words.

authors: GuardRex Rick-Anderson Tratcher

repo: aspnet/Docs


text:
aspnetcore/hosting/directory-structure.md

https://docs.microsoft.com/en-us/aspnet/core/hosting/directory-structure

fixed by https://github.com/aspnet/Docs/commit/b6ff637c34bca1eba67c5a1cb7a4892ca201edc9


text:
Missing "Select Department" line of code, or, code description is inaccurate.

There appears to be one line of code missing in the following section:
https://docs.microsoft.com/en-us/aspnet/core/data/ef-rp/update-related-data?view=aspnetcore-2.1#update-the-courses-edit-page
Under the section that instructs us to "Update Pages/Courses/Edit.cshtml" the instructions state that the "preceding markup" has added a "Select Department" statement to the pull-down list.  However, it appears that the line of code to add the statement is left out in the example.
On the other hand, it may have been intentionally left out for editing section as a Department would have already been selected when the Course was created.  If this is the case, then the statement describing what the preceding code has added should not include the statement:
"Adds the "Select Department" option. This change renders "Select Department" rather than the first department.
Removing the "Select Department" option would also seem to render the validation statement unnecessary, as there would be no way to unselect a department before saving changes.
Once again, thank you for the great tutorials.

Document Details
⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

ID: 140ce637-4d58-995f-c69e-b1de51f1dbb5
Version Independent ID: 9bc46ffa-60db-bdee-0984-fab183c8f503
Content: Razor Pages with EF Core in ASP.NET Core - Update Related Data - 7 of 8
Content Source: aspnetcore/data/ef-rp/update-related-data.md
Product: asp.net-core
GitHub Login: @Rick-Anderson
Microsoft Alias: riande

@Rick-Anderson can you assign this issue to me so I can fix it up and submit a PR?

@m-henderson  sorry missed this. I got it fixed. Thanks for the offer.

authors: Rick-Anderson m-henderson yamazaroon


text:
"Add providers" example doesn't match current ASP.NET Core Template

None of the configuration examples matches the code found in the current ASP.NET Core template used by Visual Studio.
public static class Program
{
    /// Creates the web host builder.
    /// <param name="args">The arguments.</param>
    /// <returns></returns>
    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();

    /// Defines the entry point of the application.
    /// <param name="args">The arguments.</param>
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args)
            .Build().Run();
    }
}

Document Details
⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

ID: 7184a308-a254-9350-a5cd-5bced1f369ae
Version Independent ID: 726e3bf1-f367-d733-8933-bccc04da0e16
Content: Logging in ASP.NET Core
Content Source: aspnetcore/fundamentals/logging/index.md
Product: aspnet-core
GitHub Login: @tdykstra
Microsoft Alias: tdykstra

@Grauenwolf ... It's somewhat common across the repo for a few reasons. For one thing, the sample apps trail the framework releases. Another is that samples concentrate on the concepts that the topics cover, which often don't strictly require the app to follow the template conventions. In this case (logging), the common thread is just hanging the ConfigureLogging method calls off of the host builder ... that's the same pattern regardless of the 2.x flavor.
I'll mark this issue on the sample update tracking issue. The doc author who takes on the 2.2 updates for this sample will see this at that time. Thanks for commenting on the topic.

authors: Grauenwolf guardrex


text:
Update dependency-injection.rst

ASP.NET 5 to ASP.NET Core 1

Thanks for your interest. Closing as this will be updated in the next sweep.
Show all checks

authors: Rick-Anderson SychevIgor


text:
Fixed instructions for configuring social logins

Fixes #648

Fixes instructions on how to dnvm use 1.0.0-beta 8
Fixes instructions on how to install user-secrets

Will have to update these instructions for RC too, but can deal with that after it's released.

Hi @bitcrazed, I'm your friendly neighborhood .NET Foundation Pull Request Bot (You can call me DNFBOT). Thanks for your contribution!

This seems like a small (but important) contribution, so no Contribution License Agreement is required at this point. Real humans will now evaluate your PR.

TTYL, DNFBOT;

@rustd @Rick-Anderson Please review

Looks good :shipit:

Thanks! 05fc5fd2b5d92dc48f89cb696e1adedc522dad76

authors: Rick-Anderson bitcrazed danroth27 dnfclas


text:
Migration qa - index/toc fixes

I also removed the _Files too.

Hi @v-anpasi, I'm your friendly neighborhood .NET Foundation Pull Request Bot (You can call me DNFBOT). Thanks for your contribution!

In order for us to evaluate and accept your PR, we ask that you sign a contribution license agreement. It's all electronic and will take just minutes. I promise there's no faxing. https://cla2.dotnetfoundation.org.

TTYL, DNFBOT;

authors: dnfclas v-anpasi


text:
Include() ThenInclude() throws “Sequence contains more than one matching element” exception

I have a model which involves parent-child relations on 3 levels :

Corporations have companies
Companies belong to a corporation and have factories
Factories belong to a company

Since these 3 entities share a lot in common, they all inherit from an abstract BaseOrganization entity.
When I try to list all the factories, including their mother companies, and then including their mother corporations, I have these two different scenarios :

Without including BaseOrganization into the context, code-first creates three tables (TPC). Include() and ThenInclude() work fine, and I can list factories and traverse relations as expected.
Including BaseOrganization into the context, code-first creates one table (TPH) with a discriminator field. Include() and ThenInclude() throw a Sequence contains more than one matching element exception.

This issue (without the inheritance pattern) was already adressed here ( https://github.com/aspnet/EntityFramework/issues/1460).
So I think there is an issue with multi-level relations Include when these relations involve same base types AND when the tables are generated along the Table Per Hierarchy strategy.
Below is the full reproduction code :
	using System;
	using System.Collections.Generic;
	using System.Linq;
	using Microsoft.Data.Entity;

	namespace MultiLevelTest
	{
		// All places share name and Id
		public abstract class BaseOrganization
		{
			public int Id { get; set; }
			public string Name { get; set; }
		}

		// a corporation (eg : Airbus Group)
		public class Corporation : BaseOrganization
		{
			public virtual ICollection<Company> Companies { get; set; } = new List<Company>();
		}

		// a company (eg : Airbus, Airbus Helicopters, Arianespace)
		public class Company : BaseOrganization
		{
			public virtual Corporation Corporation { get; set; }
			public virtual ICollection<Factory> Factories { get; set; } = new List<Factory>();
		}

		// a factory of a company (Airbus Toulouse, Airbus US...)
		public class Factory : BaseOrganization
		{
			public virtual Company Company { get; set; }
		}

		// setup DbContext
		public class MyContext : DbContext
		{
            // if this line is commented, then code first creates 3 tables instead of one, and everything works fine.
			public DbSet<BaseOrganization> BaseOrganizationCollection { get; set; }
			public DbSet<Corporation> Corporations { get; set; }
			public DbSet<Company> Companies { get; set; }
			public DbSet<Factory> Factories { get; set; }

			protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
			{
				optionsBuilder.UseSqlServer(
					@"Server=(localdb)\mssqllocaldb;Database=MultiLevelTest;Trusted_Connection=True;MultipleActiveResultSets=true");
			}

			protected override void OnModelCreating(ModelBuilder modelBuilder)
			{
				base.OnModelCreating(modelBuilder);

				modelBuilder.Entity<Corporation>().HasMany(c => c.Companies).WithOne(c => c.Corporation);
				modelBuilder.Entity<Company>().HasMany(c => c.Factories).WithOne(c => c.Company);
				modelBuilder.Entity<Factory>().HasOne(f => f.Company);
			}
		}

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

					// Add a corporation with companies then factories (this works fine)
					if (!ctx.Corporations.Any()) CreateOrganizationGraph(ctx);

					// Get all the factories without including anything (this is still working fine)
					var simpleFactories = ctx.Factories.ToList();
					foreach(var f in simpleFactories) Console.WriteLine(f.Name);

					// Get all the factories including their mother company, then their mother corporation
					var fullFactories = ctx.Factories
						.Include(f => f.Company)
						.ThenInclude(c => c.Corporation)
						.ToList();
					foreach (var f in fullFactories) Console.WriteLine($"{f.Company.Corporation.Name} > {f.Company.Name} > {f.Name}");
				}
			}

			public static void CreateOrganizationGraph(MyContext ctx)
			{
				var airbusCorp = new Corporation()
				{
					Name = "Airbus Group",
					Companies = new List<Company>()
							{
								new Company
								{
									Name = "Airbus",
									Factories = new List<Factory>()
									{
										new Factory {Name = "Airbus Toulouse (FR)"},
										new Factory {Name = "Airbus Hambourg (DE)"}
									}
								},
								new Company
								{
									Name = "Airbus Helicopters",
									Factories = new List<Factory>()
									{
										new Factory {Name = "Eurocopter Marignane (FR)"},
										new Factory {Name = "Eurocopter Deutschland (DE)"}
									}
								}
							}
				};

				ctx.Corporations.Add(airbusCorp);
				ctx.SaveChanges();

			}
		}
	}

Has anyone had the opportunity to reproduce, and state if that is an actual bug, or an improper approach on my own ?

@kall2sollies I ran the scenario on our current bits and it seems to be working. I guess it must have been addressed in one of the Include improvements that we did after RC1 was released. Repro produces the following output:
Airbus Toulouse (FR)
Airbus Hambourg (DE)
Eurocopter Marignane (FR)
Eurocopter Deutschland (DE)
Airbus Group > Airbus > Airbus Toulouse (FR)
Airbus Group > Airbus > Airbus Hambourg (DE)
Airbus Group > Airbus Helicopters > Eurocopter Marignane (FR)
Airbus Group > Airbus Helicopters > Eurocopter Deutschland (DE)

Hello,
It must be as you say, since my code was run against rc1, and also ef7rc1.
So the next release will probably solve that.
Thanks for the reply.
Calendau GUQUET
Via mon iPhone

Le 20 avr. 2016 à 23:57, Maurycy Markowski notifications@github.com a écrit :
@kall2sollies I ran the scenario on our current bits and it seems to be working. I guess it must have been addressed in one of the Include improvements that we did after RC1 was released. Repro produces the following output:
Airbus Toulouse (FR)
Airbus Hambourg (DE)
Eurocopter Marignane (FR)
Eurocopter Deutschland (DE)
Airbus Group > Airbus > Airbus Toulouse (FR)
Airbus Group > Airbus > Airbus Hambourg (DE)
Airbus Group > Airbus Helicopters > Eurocopter Marignane (FR)
Airbus Group > Airbus Helicopters > Eurocopter Deutschland (DE)
—
You are receiving this because you were mentioned.
Reply to this email directly or view it on GitHub

I am unable to migrate my test project to RC2 (ou RC3) builds of EF.
Here's what I did:

Added rererence to the beta nuget channel (https://www.myget.org/F/aspnetvnext/api/v3/index.json)
Changed package names to reflect the new naming and version reset

Here's my project.json file:
{
  "version": "1.0.0-*",
  "description": "LinqKitIssue Console Application",
  "authors": [ "cguquet" ],
  "tags": [ "" ],
  "projectUrl": "",
  "licenseUrl": "",

  "compilationOptions": {
	"emitEntryPoint": true
  },

  "dependencies": {
	"LinqKit": "1.1.3.1",
	"Microsoft.EntityFrameworkCore": "1.0.0-rc2-*",
	"Microsoft.EntityFrameworkCore.Commands": "1.0.0-rc2-*",
	"Microsoft.EntityFrameworkCore.SqlServer": "1.0.0-rc2-*",
	"Microsoft.Extensions.Caching.Abstractions": "1.0.0-rc2-*"
  },

  "commands": {
	"LinqKitIssue": "LinqKitIssue"
  },

  "frameworks": {
	"dnx451": { }
  }
}

It results in having unresolved dependencies, because they are not compatible with DNX version 4.5.1.
I have tried to change the framework to everything possible or impossible (net451, dnx46, net46, dnx462, net462) but the result would always be the same. Here's the output of dnu list:
Microsoft .NET Development Utility Clr-x86-1.0.0-rc1-16609

Listing dependencies for LinqKitIssue (D:\Documents\Visual Studio 2015\Projects\LinqKitIssue\src\LinqKitIssue\project.json)

[Target framework DNX,Version=v4.6.2 (dnx462)]

Framework references:
  fx/Microsoft.CSharp
  fx/mscorlib
  fx/System
  fx/System.ComponentModel.DataAnnotations
  fx/System.Core
  fx/System.Data
  fx/System.Transactions

Package references:
  EntityFramework 6.1.3
  Ix-Async 1.2.5
* LinqKit 1.1.3.1
  Microsoft.AspNetCore.Hosting.Abstractions 1.0.0-rc2-20466
  Microsoft.AspNetCore.Hosting.Server.Abstractions 1.0.0-rc2-20466
  Microsoft.AspNetCore.Http.Abstractions 1.0.0-rc2-20466
  Microsoft.AspNetCore.Http.Features 1.0.0-rc2-20466
* Microsoft.EntityFrameworkCore 1.0.0-rc2-20466
* Microsoft.EntityFrameworkCore.Commands 1.0.0-rc2-20466
  Microsoft.EntityFrameworkCore.Relational 1.0.0-rc2-20466
  Microsoft.EntityFrameworkCore.Relational.Design 1.0.0-rc2-20466
* Microsoft.EntityFrameworkCore.SqlServer 1.0.0-rc2-20466
* Microsoft.Extensions.Caching.Abstractions 1.0.0-rc2-20466 - Unresolved
  Microsoft.Extensions.Caching.Memory 1.0.0-rc2-20466
  Microsoft.Extensions.Configuration.Abstractions 1.0.0-rc2-20466 - Unresolved
  Microsoft.Extensions.DependencyInjection 1.0.0-rc2-20466 - Unresolved
  Microsoft.Extensions.DependencyInjection.Abstractions 1.0.0-rc2-20466 - Unresolved
  Microsoft.Extensions.FileProviders.Abstractions 1.0.0-rc2-20466 - Unresolved
  Microsoft.Extensions.Logging 1.0.0-rc2-20466 - Unresolved
  Microsoft.Extensions.Logging.Abstractions 1.0.0-rc2-20466 - Unresolved
  Microsoft.Extensions.Options 1.0.0-rc2-20466 - Unresolved
  Microsoft.Extensions.PlatformAbstractions 1.0.0-rc2-20466
  Microsoft.Extensions.Primitives 1.0.0-rc2-20466 - Unresolved
  Remotion.Linq 2.0.2
  System.Diagnostics.DiagnosticSource 4.0.0-rc2-23931
  System.Text.Encodings.Web 4.0.0-rc2-23931 - Unresolved

@kall2sollies Visual Studio is missing the tooling support for RC2 stuff, you can try using .NET cli  which is the replacement for dnx, and a command line. Here is the link to the project, which contains some getting started instructions:
http://dotnet.github.io/getting-started/

Among all the things I thought I could try, it has been the only one I didn't, because I thought it was a lightweight version of the runtime, and not the future runtime itself, so ok tomorrow I'll go for it, thanks!

Ok I have installed the redist installer and can now run the .Net CLI with dotnet commands (.NET Command Line Tools (1.0.0-beta-001598).
No problem scaffolding a new projet with the dotnet new command, but I am still unable to build or run this simple project mentioned above.
Below is my current project.json file. Current framework moniker is set to net46, but I also tried net461, netcore50 (as in default CLI hello world project, but it still fails because it either cannot resolve dependencies (when targetting net46), or tells dependencies are not compatible with netcore50 (especially LinqKit, which brings EF6 with).
{
"version": "1.0.0-*",
"description": "LinqKitIssue Console Application",
"authors": [ "cguquet" ],
"tags": [ "" ],
"projectUrl": "",
"licenseUrl": "",
"compilationOptions": {
  "emitEntryPoint": true
},

"dependencies": {
  "NETStandard.Library": "1.0.0-rc2-23811",
  "LinqKit": "1.1.3.1",
  "Microsoft.EntityFrameworkCore": "1.0.0-rc3-20637",
  "Microsoft.EntityFrameworkCore.Commands": "1.0.0-rc3-20637",
  "Microsoft.EntityFrameworkCore.SqlServer": "1.0.0-rc3-20637",
  "Microsoft.Extensions.Caching.Abstractions": "1.0.0-rc3-20637"
},

"commands": {
  "LinqKitIssue": "LinqKitIssue"
},

"frameworks": {
  "net46": { }
}

}

repo: aspnet/EntityFramework


text:
Explicit loading for list of entries: context.Entries(...)...Load()

For explicit loading EF Core offers (from docs):
var blog = context.Blogs
        .Single(b => b.BlogId == 1);

context.Entry(blog)
        .Reference(b => b.Owner)
        .Load();

If I have, for expample, list of 10 entries, I need to 10 times call Reference(...).Load() in foreach, that generate 10 SQL queries to DB.
How about optimized method Entries():
var blogs = context.Blogs
        .Where(...)
        .ToList();

context.Entries(blogs)
        .Reference(b => b.Owner)
        .Load();

which make a single SQL query like: select .... where [BlogOwner].[BlogId] in (?, ?, ?, ?, ?, ?)
Sorry, but I have not found similar functionality. Thanks

To things you can try:

Use eager loading, i.e. Include(b => b.Owner)
Write a query like this (I haven't actually tested it, but it should work):

var ids = context.ChangeTracker
    .Entries<Blog>()
    .Select(e => e.Property(b => b.BlogId))
    .ToList();
context.Owner.Where(o => ids.Contains(o.BlogId)).Load();

@Remleo BTW, we would be interested in understanding your scenario better, e.g. why didn't you use eager loading in this case.

Sometimes may need to eager/explicit load a relationship after the parent model has already been retrieved. For example, this may be useful if I need to dynamically decide whether to load related models:
// This code is responsible for retrieve specific blog entities
// But it have no idea about logic in BlackBox.SomeMethod()
// That is why it dont load Navigations
var neededBlogs = context.Blogs.Where(....).ToList();

....

class BlackBox {
        public void SomeMethod(IEnumerable<Blog> blogs)
        {
            // There might be code that ensure Owner loading,
            // because this method have no idea about is `blogs` was load `Owners` or not.
            // Also `Loader` should be intelligent enough for load only empty Navigations
            // so calling this method multiple times is safe
            context.Entries(blogs).Reference(b => b.Owner).Load();

            foreach (var blog in blogs)
            {
                if (someDynamicCondition && blog.Owner != null)
                {
                    SendNotificationToOwner(blog.Owner.email, "Alert!");
                }
            }
        }
}

This code works:
var ids = context.ChangeTracker
    .Entries<Blog>()
    .Select(e => e.Property(b => b.BlogId))
    .ToList();
context.Owner.Where(o => ids.Contains(o.BlogId)).Load();

but code is not "dry". where statement need to be hardcoded and match FK for Navigation-property. Context knows about FK and it is his "job" to load Navigation-properties.
Sorry for my english (

Reopening so we can visit this in triage.

Closing but will reconsider if we see more requests. We would consider a PR with the feature. You could also look at implementing it as an extension method.

+1
This is totally valid example for any TPT inheritance. Base model does not contains navigation properties and if we woluld like to display list with all inherited types with the common property fe. "Name", but loaded from different related entities of derivered models. We can't use include because there is no navigation property to do so, and if we load directly EF is not clever enough just to get related entites IDs by FK, but it will get whole tables, and performance will be not acceptable. In that case we have to change whole structure to TPH or create view, map it to new model and at the end we will end up with two different models to describe exactly the same entity :/
Visualisation ;):
A (entity with all 3 digit numbers - like dictionary of all of them)
B (base model to keep numbers assigments - abstract)
--> C (derived) --> User (additional relation to entity with Name)
--> D (derived) --> Company (additional relation to entity with Name)
--> etc.

I would like to see this as there are many query methods that use the same query but don't use the same included references therefore if you have one method to return the query and add all references that are used in all instances then you end up with a method that works but is really inefficient. For example:
public IQueryable<Account> GetAccountsCreatedOnDate(DateTime time) {
    context.Account.Where(x => x.CreatedDateTime == time);
}

public IEnumerable<Post> GetPostsByUsersCreatedOnDate(DateTime time) {
    var users = GetAccountsCreatedOnDate(time);
    context.Entries(users).Reference(b => b.Posts).Load();
    return users.SelectMany(x => x.Posts);
}

@KieranDevlinSycous - Just try this.
public IEnumerable<Post> GetPostsByUsersCreatedOnDate(DateTime time) {
    return GetAccountsCreatedOnDate(time).SelectMany(x => x.Posts).AsEnumerable();
}

I find this feature very useful. For example if you don't want to use eager loading too much, because it generates JOIN queries and if some other query already fetched the data, you are still stuck with lot of joins instead of simple selects. For example you have entity A with property C and entity B with property C and you eager load A with C and then you still have too eager load C with B instead of just selecting B. So you either have costly queries or you have many many methods on your repositories. So it would be much simpler to just  load the necessary references in place. I would love this feature to be implemented. Now I use this instead
public Query<TEntity> LoadBy<TForeignEntity>(
            IEnumerable<TForeignEntity> foreignEntities,
            Func<TForeignEntity, TEntity> entitySelector,
            Func<TForeignEntity, Guid?> entityIdSelector,
            bool unrestricted = false)
        {
            var ids = foreignEntities.Where(e => entitySelector(e) == null).Select(e => entityIdSelector(e).ToOption());
            return Select(unrestricted).Where(e => e.Id, ids);
        }

Our team would really need this feature, instead of it we must manually download entries by using id of a main entry and set its collection state to be loaded (Context.Entry(obj).Collection(c => c.Collections).IsLoaded = true)

authors: KieranDevlinSycous Remleo adduss ajcvickers divega romfir rowanmiller smitpatel starychfojtu


text:
Implement complex type usages and properties

A ComplexTypeUsage represents the reference to a complex type on an entity type or on another complex type. It contains the ComplexProperty instances that represent the properties of the complex type and their facets in this usage.
/cc @AndriySvyryd (But anyone can review...)

Agreed. We probably should review it with others--I'll make a note to talk about it when we discuss in the design meeting.


text:
Implementing IDataErrorInfo break the database creation

When I try to implement IDataErrorInfo interface in my base entity the ORM fail to create the database due to reflection TargetParameterCountException
Exception message:"Parameter count mismatch."
Stack trace:
   at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)\r\n   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)\r\n   at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)\r\n   at System.Reflection.RuntimePropertyInfo.GetValue(Object obj, Object[] index)\r\n   at Microsoft.EntityFrameworkCore.Metadata.Internal.EntityType.GetData(Boolean providerValues)\r\n   at Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.ValidateData(IModel model)\r\n   at Microsoft.EntityFrameworkCore.Infrastructure.ModelValidator.Validate(IModel model)\r\n   at Microsoft.EntityFrameworkCore.Infrastructure.RelationalModelValidator.Validate(IModel model)\r\n   at Microsoft.EntityFrameworkCore.Internal.SqlServerModelValidator.Validate(IModel model)\r\n   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.CreateModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)\r\n   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.<>c__DisplayClass5_0.<GetModel>b__1()\r\n   at System.Lazy`1.CreateValue()\r\n   at System.Lazy`1.LazyInitValue()\r\n   at System.Lazy`1.get_Value()\r\n   at Microsoft.EntityFrameworkCore.Infrastructure.ModelSource.GetModel(DbContext context, IConventionSetBuilder conventionSetBuilder, IModelValidator validator)\r\n   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.CreateModel()\r\n   at Microsoft.EntityFrameworkCore.Internal.DbContextServices.get_Model()\r\n   at Microsoft.EntityFrameworkCore.Infrastructure.EntityFrameworkServicesBuilder.<>c.<TryAddCoreServices>b__7_1(IServiceProvider p)\r\n   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, ServiceProviderEngineScope scope)\r\n   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)\r\n   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope)\r\n   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)\r\n   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProviderEngineScope scope)\r\n   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)\r\n   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProviderEngineScope scope)\r\n   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)\r\n   at Microsoft.Extensions.DependencyInjection.ServiceLookup.DynamicServiceProviderEngine.<>c__DisplayClass1_0.<RealizeService>b__0(ServiceProviderEngineScope scope)\r\n   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngine.GetService(Type serviceType, ServiceProviderEngineScope serviceProviderEngineScope)\r\n   at Microsoft.Extensions.DependencyInjection.ServiceLookup.ServiceProviderEngineScope.GetService(Type serviceType)\r\n   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)\r\n   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)\r\n   at Microsoft.EntityFrameworkCore.DbContext.get_DbContextDependencies()\r\n   at Microsoft.EntityFrameworkCore.DbContext.get_InternalServiceProvider()\r\n   at Microsoft.EntityFrameworkCore.DbContext.Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure<System.IServiceProvider>.get_Instance()\r\n   at Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.Microsoft.EntityFrameworkCore.Infrastructure.IInfrastructure<System.IServiceProvider>.get_Instance()\r\n   at Microsoft.EntityFrameworkCore.Internal.InternalAccessorExtensions.GetService[TService](IInfrastructure`1 accessor)\r\n   at Microsoft.EntityFrameworkCore.Infrastructure.AccessorExtensions.GetService[TService](IInfrastructure`1 accessor)\r\n   at Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.get_DatabaseCreator()\r\n   at Microsoft.EntityFrameworkCore.Infrastructure.DatabaseFacade.EnsureDeleted()\r\n   at CM.DataContext.GetLogin(String userName, String password)\r\n   at CM.Contexts.Users.GetLogin(String userName, String password)\r\n   at CM.Contexts.Users.<>c__DisplayClass3_0.<GetLoginAsync>b__0()\r\n   at System.Threading.Tasks.Task`1.InnerInvoke()\r\n   at System.Threading.Tasks.Task.Execute()

Steps to reproduce

Create a.NET Standard project and add Microsoft.EntityFrameworkCore.SqlServer package.
Create a base entity class that implement IDataErrorInfo interface.
Create entity using your base entity.
Create your DbContext and expose your main entity in it (Not the base entity).
Create another project to consume your library and you will get the exception.

    public class BaseEntity : INotifyPropertyChanged, IDataErrorInfo
    {
        #region IDataErrorInfo
        [NotMapped] string IDataErrorInfo.this[string propertyName] => "";
        [NotMapped] string IDataErrorInfo.Error => "";
        #endregion

        #region INotifyPropertyChanged
        event PropertyChangedEventHandler PropertyChanged;
        event PropertyChangedEventHandler INotifyPropertyChanged.PropertyChanged
        {
            add => PropertyChanged += value;
            remove => PropertyChanged -= value;
        }

        protected virtual bool Set<TValue>(ref TValue oldValue, TValue newValue,
            string relatedProperty = null, [CallerMemberName]string propertyName = null)
        {
            if (Equals(oldValue, newValue)) return false;
            oldValue = newValue;
            NotifyPropertyChanged(propertyName);
            if (!string.IsNullOrWhiteSpace(relatedProperty)) NotifyPropertyChanged(relatedProperty);
            return true;
        }
        protected virtual bool Set<TValue>(ref TValue oldValue, TValue newValue,
            IEnumerable<string> relatedProperties, [CallerMemberName]string propertyName = null)
        {
            if (Equals(oldValue, newValue)) return false;
            oldValue = newValue;
            NotifyPropertyChanged(propertyName);
            foreach (var item in relatedProperties)
                if (!string.IsNullOrWhiteSpace(item)) NotifyPropertyChanged(item);
            return true;
        }

        protected virtual void NotifyPropertyChanged(string propertyName) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        #endregion
    }
    public class User : BaseEntity
    {
        Guid _Id = Guid.NewGuid();
        [Key]
        public Guid ID { get => _Id; set => Set(ref _Id, value); }

        string _Name;
        [StringLength(250, MinimumLength = 3), Required(AllowEmptyStrings = false)]
        public string Name { get => _Name; set => Set(ref _Name, value); }

        string _Password;
        [StringLength(250, MinimumLength = 3), Required(AllowEmptyStrings = false)]
        public string Password { get => _Password; set => Set(ref _Password, value); }

        string _DisplayName;
        [StringLength(250, MinimumLength = 3), Required(AllowEmptyStrings = false)]
        public string DisplayName { get => _DisplayName; set => Set(ref _DisplayName, value); }

        bool _IsEnabled = true;
        public bool IsEnabled { get => _IsEnabled; set => Set(ref _IsEnabled, value); }
    }
    class DataContext : DbContext
    {
        #region Configures
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=CM;Trusted_Connection=True;");
            //base.OnConfiguring(optionsBuilder);
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            var users = modelBuilder.Entity<User>();
            users.HasData(new User() { Name = "admin", Password = "1234", DisplayName = "Administrator", IsEnabled = true });
            users.HasIndex(u => u.Name).IsUnique();
            users.HasIndex(u => u.DisplayName).IsUnique();
            base.OnModelCreating(modelBuilder);
        }
        #endregion
        #region Tables
        public DbSet<User> Users { get; set; }
        #endregion

        #region Static Methods
        public static User GetLogin(string userName, string password)
        {
            using (var cxt = new DataContext())
            {
                cxt.Database.EnsureDeleted();
                cxt.Database.EnsureCreated();
                LoginUser = cxt.Users.AsNoTracking().FirstOrDefault(u => u.IsEnabled &&
                                                                         u.Name == userName &&
                                                                         u.Password == password);
            }
            return LoginUser;
        }
        #endregion
    }

Further technical details
EF Core version: Microsoft.EntityFrameworkCore (2.1.2)
Database Provider: Microsoft.EntityFrameworkCore.SqlServer
Operating system: Windows 10
IDE: Visual Studio 2017 15.8.1

Duplicate of #12605

authors: ajcvickers eiadxp

repo: aspnet/EntityFrameworkCore


text:
EntityQueryModelVisitor does not properly use CreateTransparentIdentifierType

As a 3rd-party EF Core provider maintainer, I need to be able to control the transparent identifier type used by EntityQueryModelVisitor. I can override CreatetTransparentIdentifierType, but this has no effect on VisitAdditionalFromClause because it does not properly call that method:
https://github.com/aspnet/EntityFrameworkCore/blob/146863a3bdc25c1ea1cb224ba0611594398c8459/src/EFCore/Query/EntityQueryModelVisitor.cs#L983
Instead, it directly references the internal TransparentIdentifier<,> type.
This causes type mismatches when overriding CreateTransparentIdentifierType and attempting to use that type in other visitor methods. The net effect is having to override more methods that strictly necessary just to ensure that the correct type is used.
Further technical details
EF Core version: ALL historical versions
Database Provider: Non-specific (problem is in EFCore)

Tracking this for 3.0 as part of the the larger query refactoring that is tracked by #12795

authors: ajcvickers crhairr


text:
Getting a string[] from a UDF

I can't seem to find anything about table valued functions in EF core is this even possible.
Here's a sample of what I would like to achieve ...
I have a role class that looks like this ...
[Table("Roles", Schema = "Security")]
public class Role
{
     [Key]
     public Guid Id { get; set; }

     // this is a csv list of "privilege keys" that the role grants
     public string Privs { get; set; }
     ...
}

Add this to my DbContext ...
[DbFunction("[DMS].[GetFolderPrivList]")]
public static string[] GetFolderPrivList(string userId, Guid folderId)
{
    throw new Exception();
}

Then I have a UDF like this to compute a list of privs for a folder "path" (which recursively crawls the tree for inherited permissions) ...
CREATE FUNCTION [DMS].[GetFolderPrivList]
(	@UserId nvarchar(450),
	@FolderId uniqueidentifier
)
RETURNS @PrivList TABLE ( priv nvarchar(100) NOT NULL)
AS
BEGIN
	INSERT INTO @PrivList (priv)
		SELECT DISTINCT *
		  FROM STRING_SPLIT((SELECT R.Privs FROM DMS.Folders P
		  JOIN [Security].FolderRoles PR ON FR.FolderId= P.Id
		  JOIN [Security].Roles R ON R.Id= FR.RoleId
		  JOIN [Security].UserRoles UR ON UR.RoleId = R.Id
		  WHERE P.Id=@FolderId AND UR.UserId=@UserId),',');

	IF (SELECT ParentId FROM [DMS].[Folders] WHERE Id=@FolderId) IS NOT NULL
	BEGIN
		INSERT INTO @PrivList (priv)
			SELECT priv
			  FROM [DMS].[GetFolderPrivList](@UserId,(SELECT ParentId FROM CMS.Pages WHERE Id=@FolderId))
			  WHERE priv NOT IN (SELECT priv FROM @PrivList)
	END	--*/
	RETURN
END;

I can't get EF to accept this such that I can make the call in a linq query, for example ...
db.GetAll<Folder>().FirstOrDefault(f => f.AppId == app.Id && f.Path.ToLower() == path.Lowered && CoreDataContext.GetFolderPrivList(user.Id, f.Id).Contains(privKey))

Duplicate of #4319

authors: TehWardy ajcvickers


text:
Strange DI behaviour with ASPNETCORE_ENVIRONMENT

Describe the bug
I have aspnetcore application, where singleton type has a dependency on scoped type. When a variable is defined ASPNETCORE_ENVIRONMENT=Development, I get an InvalidOperationException: Cannot consume scoped service 'B' from singleton 'A', but when the ASPNETCORE_ENVIRONMENT='Anything', an exception is not raised and application started.
To Reproduce
Steps to reproduce the behavior:

Using this version of ASP.NET Core '2.2.6'
Run this code https://gist.github.com/DenisPimenov/fbde9d1f91170d2423cee1089a29028c
With these arguments ASPNETCORE_ENVIRONMENT="Production"
Application started without exceptions

Expected behavior
Application should be terminated with InvalidOperationException
Additional context
dotnet --info
.NET Core SDK (reflecting any global.json):
Version:   2.2.301
Commit:    70d6be0814
Runtime Environment:
OS Name:     Mac OS X
OS Version:  10.14
OS Platform: Darwin
RID:         osx.10.14-x64
Base Path:   /usr/local/share/dotnet/sdk/2.2.301/

In development mode we run some extra validations as the container is built. The fact that you're seeing an error means that something is wrong.
In this case you're using a scoped service from a singleton - meaning that you're creating a long-lived instance of something that you expect to be scoped.
We don't run this validation at startup time in production scenarios because it's slow.

This validations has public api?

@pakrym

You can use UseDefaultServiceProvider method to configure the scope validation to always be on:
  public static IWebHostBuilder CreateHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseDefaultServiceProvider(options => options.ValidateScopes = true)
                .UseStartup<Startup>();

Thank you for your comments.

authors: DenisPimenov pakrym rynowak

repo: aspnet/Extensions


text:
Unlisted Dependency

Hi ASPNet Team,
I am trying to use the HttpSysServer in a project and I'm getting the error message below.
Itseems as though my project is missing a reference, but I'm noticing that System.Threading.Overlapped is not listed as a package dependency for this project.  Are there any other unlisted dependencies I should add?
System.IO.FileNotFoundException: Could not load file or assembly 'System.Threading.Overlapped, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
File name: 'System.Threading.Overlapped, Version=0.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'
   at Microsoft.AspNetCore.Server.HttpSys.RequestQueue..ctor(UrlGroup urlGroup, ILogger logger)
   at Microsoft.AspNetCore.Server.HttpSys.HttpSysListener..ctor(HttpSysOptions options, ILoggerFactory loggerFactory)
   at Microsoft.AspNetCore.Server.HttpSys.MessagePump..ctor(IOptions`1 options, ILoggerFactory loggerFactory, IAuthenticationSchemeProvider authentication)
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitSingleton(SingletonCallSite singletonCallSite, ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass22_0.<RealizeService>b__0(ServiceProvider provider)
   at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
   at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureServer()
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
   at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
   at AlphaDrive.Services.AspNetCore.AspNetCoreExtension.<Start>d__14.MoveNext() in C:\Users\Tony Valenti\source\repos\AlphaDrive\AlphaDrive.Services.AspNetCore\AspNetCoreExtension.cs:line 60

What package version is this?

I am using this DLL:
C:\Users\Tony Valenti\source\repos\AlphaDrive\packages\Microsoft.AspNetCore.Server.HttpSys.2.0.3\lib\netstandard2.0\Microsoft.AspNetCore.Server.HttpSys.dll
and it has this version:
2.0.3.0

And you're running on .NET Core 2 or .NET 4.x?

I'm not sure how to answer that question.  The library is a cross platform library that I'm compiling for .NET 4.6.1.
Oddly, my app works fine on Windows 10, but on Windows 7 I get the error mentioned.

Actually, I guess I see the error happening on windows 10 too. Apparently it is just not happening on my dev box.

This seems like an issue specific to your project dependency setup. Can you share a dummy project on github that reproduces it?

authors: TonyValenti Tratcher

repo: aspnet/HttpSysServer


text:
Webdeploy parameter file support/tool

Hello,
I've been working on deploying a asp.net core app to azure via webdeploy (in vsts) recently and I think the tooling could be improved here, in particular with respects to webdeploy and its parameter file syntax.
The current docs recommends simply zipping up the publish contents and this works fine if you don't want to use the parameters file support provided by web deploy and the vsts website tasks. however a very nice feature webdeloy is to be able to specify a Setparameters.xml file at release time for different environments. When building with msbuild this file is generated by the publish target, but to my knowledge this is not supported with the dotnet cli.
Proposal: Add a new tool to Microsoft.AspNetCore.Server.IISIntegration.Tools that generates a SetParameter.xml file
In addition to doing this I think it would be nice to have tools for actually managing web deploy parameters, but that is kind of an aside.
I went looking for the code for publish-iis and I did found it in the master branch in this repo, but not in the dev branch, has it moved somewhere else? (also, do you think this is a worth while idea at all?)
I know webdeploy isn't very cutting edge but it is a very useful tool especially combined with the vsts tooling.

/cc @vijayrkn
I think a better repo to report this is https://github.com/aspnet/websdk. This is also a new home for the publish-iis tool which was converted to an MSBuild task (https://github.com/aspnet/websdk/tree/dev/src/Publish/Microsoft.NETCore.Sdk.Publish.Tasks)

We have added support for adding parameters file for web deploy publish. https://github.com/aspnet/websdk/blob/dev/src/Publish/Microsoft.NET.Sdk.Publish.Targets/netstandard1.0/PublishTargets/Microsoft.NET.Sdk.Publish.MSDeploy.targets#L237
The next VS 2017 release should have this.

aha nice to see it coming! also I didn't know they opened up the websdk repo, that's great!

authors: aL3891 moozzyk vijayrkn

repo: aspnet/IISIntegration


text:
Make UseIISIntegration idempotent

@Tratcher

:shipit:

authors: Tratcher pakrym


text:
Upgrade projects to netcoreapp3.0

Changes:

Upgrade dependencies
Change TFM on Microsoft.AspNetCore.Identity to netcoreapp3.0
Remove .NET Framework tests

Part of https://github.com/aspnet/AspNetCore/issues/3754

Whoa, lots of test failures. Are these already known issues @HaoK?

That looks to be errors from the razor UI stuff, maybe the upgrade to 3.0 broke something there?  @javiercn @pranavkm any ideas?

Can't find'C:\projects\identity\test\Identity.FunctionalTests\bin\Release\netcoreapp3.0\Identity.DefaultUI.WebSite.deps.json'

Does the 3.0 Sdk no longer generate a deps file?

Does the 3.0 Sdk no longer generate a deps file?

This sounds like something @ryanbrandenburg was investigating. Is this the issue you were seeing, Ryan?

I don't recall having missing deps.json files.

This might have been it: https://github.com/aspnet/Identity/pull/2072/commits/43bae5e91f15bffa63eadef179d7292ff7384a64 Tests pass locally now.

authors: HaoK natemcmaster pranavkm ryanbrandenburg

repo: aspnet/Identity


text:
Patching of dictionaries should be case sensitive on keys

The current code handles all (dynamic(example: ExpandoObject implements IDictionary<string,object>) or not) dictionaries which implement IDictionary<string, object> in a case Insensitive way. This is an incorrect behavior.
For example:

When Json.net deserializes data into a regular IDictionary<,> it considers the keys case-sensitive.
When Json.net deserializes data into a regular Poco type, it considers the property names case-Insensitive.

Considering the above behavior, we should do the following in json patch:

For dynamic types (like ExpandoObject, DynamicObject etc.), the matching of keys should be case-Insensitive. This is to keep the behavior consistent with a Poco type where the property names are considered case-Insensitive.
For dictionaries, keep the default json.net behavior, i.e. keep them case sensitive.

@dougbu @rynowak

@kichalla can you link to the PR/commit where you previously fixed this and then close this? Thanks!

81931e75d48370cf9163254523b1f6c4bcc92acb

authors: Eilon kichalla

repo: aspnet/JsonPatch


text:
Using command-line options in RC2?

My blog is currently running on ASP.NET 5 RC1. I have commands for live vs staging configured in project.json:
  "commands": {
    "web-live": "Microsoft.AspNet.Server.Kestrel --server.urls http://unix:/run/dan-live.sock",
    "web-staging": "Microsoft.AspNet.Server.Kestrel --server.urls http://unix:/run/dan-staging.sock"
  },

And then I run a command like this to actually run the site:
/var/www/.dnx/runtimes/dnx-mono.1.0.0-rc1-final/bin/dnx --appbase /var/www/dan.cx/live/site/approot/packages/Daniel15.Web/1.0.0/root Microsoft.Dnx.ApplicationHost --configuration Release web-live

With RC2, it looks like my site compiles into a .exe file that I can execute directly via mono:
% mono Daniel15.Web.exe
Hosting environment: Production
Content root path: /var/www/dan.cx/staging/site
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.

However, I can't figure out how to specify the server.urls. Do I need to have separate config files for staging vs live? How do I specify which one to use?
(note that my site is currently not compatible with .NET Core, so I am using Mono + .NET Framework 4.5.1)

https://github.com/aspnet/Hosting/issues/737

Thanks @davidfowl! Once I added the config:
var config = new ConfigurationBuilder()
	.AddCommandLine(args)
	.Build();

var host = new WebHostBuilder()
	.UseConfiguration(config)
	// ......
	.Build();

It worked as expected :smile:

repo: aspnet/KestrelHttpServer


text:
Gracefully handle exceptions thrown from OnStarting callbacks

If OnStarting is being called after the app func has completed, return a 500.
If Onstarting is being called due to a call to write, throw from write.

Addresses #25

:shipit: :tanabata_tree:


text:
rc2 postback very slow on first execution

I recently upgraded my asp.net 5 application to asp.net core 1.0.
The postbacks are very slow, it takes 45 seconds for the postback objected to be created and till the first breakpoint in the postback method is reached. After that the breakpoint is hit and the request is executed normaly. If I execute the same method again, the postback is very fast.
It only happens if I post back objects created by the entity framework with dependencies to other object.
For Instance:
public class PostbackObject
{

public virtual Object1 Object1 {get;set;}
public int Object1ID {get;set;}
}

If I comment out Object1
public class PostbackObject
{

//public virtual Object1 Object1 {get;set;}
public int Object1ID {get;set;}
}

I don't have any issues.

See https://github.com/aspnet/Mvc/issues/4666

@rynowak does this sound the same as #4666 and this is a dup?

It is the same. The fix from #4666 worked for me. Thank you.

authors: Eilon azimmerer davidfowl

repo: aspnet/Mvc


text:
Add an option to inline css file inside a Razor page

Hi,
I just wrote a small TagHelper that inlines css files as it's one of the recommendations of PageSpeed by Google:
https://developers.google.com/speed/docs/insights/InlineCSS
https://developers.google.com/speed/docs/insights/OptimizeCSSDelivery
It would be nice if ASP.NET would have something like that baked into the framework and the existing LinkTagHelper which surely will be much more robust than my extremely simple, couple of minutes work:
[HtmlTargetElement("embedCss")]
public class EmbedCssTagHelper : TagHelper
{
    private readonly IMemoryCache _memoryCache;
    private readonly IHostingEnvironment _hostingEnvironment;
    private const string CacheKeyPrefix = "EmbedCss_";
    public string Href { get; set; }

    public EmbedCssTagHelper(IMemoryCache memoryCache, IHostingEnvironment hostingEnvironment)
    {
        _memoryCache = memoryCache;
        _hostingEnvironment = hostingEnvironment;
    }

    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        var cacheKey = CacheKeyPrefix + Href;
        output.TagName = "style";
        var content = _memoryCache.GetOrCreate(cacheKey, entry =>
        {
            if (_hostingEnvironment.IsStaging() || _hostingEnvironment.IsProduction())
            {
                Href = Href.Replace(".css", ".min.css");
            }

            var path = _hostingEnvironment.WebRootPath+ Href;
            var result = File.ReadAllText(path);
            // Surely there are other ways, like watching the file system for changes...
            // If you could reference a resource that shows how to do that it would be great!
            entry.SetAbsoluteExpiration(TimeSpan.FromMinutes(1));
            entry.SetValue(result);
            return result;
        });

        output.Content.SetHtmlContent(content);
        output.TagMode = TagMode.StartTagAndEndTag;
    }
}

What do you think about it @Eilon?
BTW, while writing the TagHelper was easy, I couldn't find why my TagHelper didn't get fire until I added [HtmlTargetElement("embedCss")], what should be the element name in the HTML if it wasn't specified?

@DamianEdwards can you share thoughts on how important a feature like this is? Especially considering HTTP2, where making multiple requests shouldn't be as expensive as it is today from a latency perspective.

Still worthwhile. I did it on live.asp.net. HTTP2 is a while away from normal, especially given it requires Windows Server 2016 for IIS.
We should have this built in to both the link and script tag helpers.

@DamianEdwards  Awesome, thanks!

One of the big problems we're concerned about is that embedding CSS is tricky when you have URLs inside the CSS (e.g. to images). The URLs have to be re-pathed based on the current request's URL.
The code would have to parse the CSS and re-path every URL inside it. This would affect the ability to cache the CSS because there can't be one canonical copy of it - there would have to be a copy for every URL where it's used (or at least for every "group" of similar URLs).

That's a very good point. We could simply say "not supported" in that case, but I agree it's less than ideal. There are many cases when this would still be useful, as plenty of CSS doesn't contain URLs to images or fonts, but it's not clear what the correct behavior here should be.

@Eilon @DamianEdwards
It's easily solved with having only URI "absolute relative" (totally made this term up right now) paths in the CSS files:
Good:
/static/images/kitchen.jpeg
@font-face {
  font-family: 'MyWebFont';
  src: url('/static/fonts/webfont.woff2') format('woff2')
}

Bad:
../images/kitchen.jpeg
@font-face {
  font-family: 'MyWebFont';
  src: url('../fonts/webfont.woff2') format('woff2')
}

In fact, this is how we currently use CSS on our website.
We create the website in a very components fashion, like a SPA, with tons of partial views, and each partial view has its own independent SCSS file. So it's impossible to have tons of HTTP requests for css files for each and every partial view in a page (can be a dozen for a page).
The only drawback of this is every request for the page, all the CSS needs to be included in the HTML and can't be cached locally on the client browser.
I thought about ways to solve it: every page loads the global css file (all the SCSS files, combined) asynchronously and set a cookie with the last time it was received / ETAG.
When rendering the page, using <embedCss>, we'll check the cookie, if its ETAG is the newest, we won't include inline CSS but rely on the external CSS file.
We didn't implement it yet as we are busy with writing our entire client side from scratch, but that's the idea.

@gdoron using only absolute URLs is a "restriction," not a "solution" 😄 Using relative paths in CSS is extremely common because in "normal" CSS files it's the safest to use. It's quite normal for the author of the CSS file to require some of their own images, yet not know the final path where the CSS file and related images will be placed. For example, Bootstrap.css has tons of relative url() values.
But anyway, we're definitely not saying this is a bad feature - as @DamianEdwards said it's quite interesting. The concern is that there's a lot of work required to call it "done". Not the least of which is doing actual browser perf measurements to see whether this feature even improves performance in several common scenarios. (We all know that just making various "site optimization" checklists happy is not necessarily actually good for the site.)

@Eilon @DamianEdwards
I agree, using relative paths in CSS is extremely common and useful BUT only for external resources (like bootstrap you mentioned).
This is because the authors of the CSS framework can't enforce a specific website, application and folders structure, so they must use relative paths to link the fonts and images.
Inline large chuck for CSS file is actually a bad pattern and discouraged by page speed:

Be careful when inlining data URIs in CSS files. While selective use of small data URIs in your CSS may make sense, inlining large data URIs can cause the size of your above-the-fold CSS to be larger, which will slow down page render time.

So It really only makes sense to inline homemade CSS, which doesn't benefit at all from using relative paths, and sometimes it's even more resilient to use absolute paths since you can move the CSS file around and it work break anything (for example, serving from a CDN or moving the .min.css to a different folder).

Not the least of which is doing actual browser perf measurements to see whether this feature even improves performance in several common scenarios.

Make sure to test on mobile devices and slow networks, inline resources on these have a huge impact, because of browsers' parallel request limitation and TCP (HTTP) slow start
See more on performance and mobile:
Presentation YouTube lecture both of Ilya Grigorik, a web performance engineer at Google, co-chair of the W3C Web Performance Working group.

@Eilon Curious to know whether you agree with the the above or not.

@gdoron those are all good points, but still no plans to have this feature built-in. If you end up building this tag helper you can release a package on NuGet, and we'd be happy to link to it.

@Eilon Problem is, I think it shouldn't really be a new tagHelper but a boolean property on LinkTagHelper.
Should I really copy paste the entire code (with great features) from LinkTagHelper?
That's bad practice.
Is there a DRY way of extending TagHelpers in MVC Core?

To include this in the framework I think we'd want to try resolving some of the issues mentioned earlier. As of right now I think some of these issues are a "pit of failure" where it's very easy to lead a user into doing things that won't work.
As far as extending the current tag helpers, it's a matter of whether the tag helper in question was designed to support any particular extensibility, and in this case what's being discussed is a whole new feature, so I'm not surprised that it doesn't have that extensibility.

@Eilon So what do you suggest? It seems like the community is blocked by the framework, unless we are going to copy paste the entire LinkTagHelper class (and its dependencies) which is really bad for maintenance.
Thanks.

@gdoron I looked at LinkTagHelper and I'm not sure this is a good fit for the existing tag helper. The existing tag helper is all about doing file globbing (not very useful here) and resource/CDN fallback (clearly not applicable here).
So this sounds to me like it fits best as a separate tag helper.
If this tag helper requires some core pieces of functionality from some existing tag helper we would certainly be open to exposing some of that functionality somewhere - it's a matter of identifying what should be made reusable. Do you have thoughts on that?

@Eilon I think you're probably right regarding LinkTagHelper not fitting to embeding css, but that's (at least from my understanding) is the only way we can still use the known HTML element <link> and just having a flag to embed the content.
Regarding something common, I guess the only the thing that might be common is the FileVersionProvider which is in a separate class anyway.
BTW, do you think it's a good idea storing the CSS file content in the MemoryCache and invalidate it when the content changes?
Or is it better reading it from disk every time?

@gdoron you can have multiple tag helpers targeting the same element, though you're right that it wouldn't be the same as having just one extra switch.
Regarding loading from disk vs. using a memory cache, the best way to answer that is to not implement caching, use a profiler to measure the behavior, and then optimize whatever the slowest part is, and then finally measure again to see that the behavior improved in the expected way. Then repeat.

Closing this as we have no plans to do this.

authors: DamianEdwards Eilon gdoron mkArtakMSFT


text:
JSonInputFormatter throws two exceptions when I receive invalid json as JObject

Given the input
{
   scheduleType: "simple",
   scheduleDetail: {
       RepeatInterval: "0.01:00:00.0000"
   },
   arguments: {
		   AgeHours: 7,
		   TransStatus: a,
		   PersonUserID: "CENTRALADMIN"
   },
   description: 333
}
I get this back
{
  "arguments.TransStatus": [
    "The input was not valid.",
    "The input was not valid."
  ]
}
In my model I receive arguments as JObject because it can be different with every request.
I enabled logging in MVC and I see exception thrown twice.
2017-03-15 16:30:26.8313|DEBUG|Microsoft.AspNetCore.Mvc.Formatters.JsonInputFormatter|JSON input formatter threw an exception.|Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: a. Path 'arguments.TransStatus', line 8, position 17.
   at Newtonsoft.Json.JsonTextReader.ParseValue()
   at Newtonsoft.Json.JsonWriter.WriteToken(JsonReader reader, Boolean writeChildren, Boolean writeDateConstructorAsDate, Boolean writeComments)
   at Newtonsoft.Json.JsonWriter.WriteToken(JsonReader reader, Boolean writeChildren)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateJToken(JsonReader reader, JsonContract contract)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.SetPropertyValue(JsonProperty property, JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, Object target)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)
2017-03-15 16:30:26.8453|DEBUG|Microsoft.AspNetCore.Mvc.Formatters.JsonInputFormatter|JSON input formatter threw an exception.|Newtonsoft.Json.JsonReaderException: Unexpected character encountered while parsing value: a. Path 'arguments.TransStatus', line 8, position 17.
   at Newtonsoft.Json.JsonTextReader.ParseValue()
   at Newtonsoft.Json.JsonReader.Skip()
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.HandleError(JsonReader reader, Boolean readPastError, Int32 initialDepth)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.Deserialize(JsonReader reader, Type objectType, Boolean checkAdditionalContent)
When I change value of TransStatus to 2a it tries to parse it as number and throws only one exception and one "The input was not valid." message in response. Stack trace is:
2017-03-15 16:37:01.8970|DEBUG|Microsoft.AspNetCore.Mvc.Formatters.JsonInputFormatter|JSON input formatter threw an exception.|Newtonsoft.Json.JsonReaderException: Input string '2a' is not a valid number. Path 'arguments.TransStatus', line 8, position 19.
   at Newtonsoft.Json.JsonTextReader.ParseNumber(ReadType readType)
   at Newtonsoft.Json.JsonTextReader.ParseValue()
   at Newtonsoft.Json.JsonWriter.WriteToken(JsonReader reader, Boolean writeChildren, Boolean writeDateConstructorAsDate, Boolean writeComments)
   at Newtonsoft.Json.JsonWriter.WriteToken(JsonReader reader, Boolean writeChildren)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateJToken(JsonReader reader, JsonContract contract)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.SetPropertyValue(JsonProperty property, JsonConverter propertyConverter, JsonContainerContract containerContract, JsonProperty containerProperty, JsonReader reader, Object target)
   at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.PopulateObject(Object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty member, String id)
I'm not sure if this is a bug or not. But I don't think returning same message twice is good.

@kichalla Could you please try to reproduce this?

@PiotrPerak I am unable to repro this issue in the 1.0.3, 1.1.2 and latest versions of MVC. Could you share a simple repro project?

[HttpPost("{jobName}/trigger")]
    public async Task<IActionResult> Trigger(string jobName, [FromBody] JobArguments jobArgs)
    {
        if (!ModelState.IsValid || string.IsNullOrEmpty(jobName) || jobArgs == null)
             return BadRequest(ModelState);
        return Ok();
    }

    public class JobArguments
    {
        public JObject Arguments { get; set; }
    }```

Thanks @PiotrPerak. I am able to repro it. We will get back to you regarding this.
I see that this issue happens outside the context of ASP.NET, for example here the error would be printed 2 times.
public class Program
{
    public static void Main(string[] args)
    {
        EventHandler<Newtonsoft.Json.Serialization.ErrorEventArgs> errorHandler = (sender, eventArgs) =>
        {
            Console.WriteLine(eventArgs.ErrorContext.Error.ToString());
            Console.WriteLine("-----------------------------");
            eventArgs.ErrorContext.Handled = true;
        };

        using (var streamReader = new StreamReader(File.OpenRead("input.txt")))
        {
            using (var jsonReader = new JsonTextReader(streamReader))
            {
                var jsonSerializer = new JsonSerializer();
                jsonSerializer.Error += errorHandler;
                var jobArgs = jsonSerializer.Deserialize<JobArguments>(jsonReader);
            }
        }
    }
}

public class JobArguments
{
    public JObject Arguments { get; set; }
}

input above was:
{
"arguments": {
    personUserId: "CENTRALADMIN",
	ageHours: 2,
	transStatus: a,
	userType: 2
	}
}

@rynowak @dougbu what do you suggest we should be doing here?

@kichalla I suggest we treat this issue as External and ensure the correct issue is filed in https://github.com/JamesNK/Newtonsoft.Json. The JsonSerializerInternalReader.HandleError() should be better-protected to avoid repeating the Exception that method is handling.

Thanks @dougbu ...I filed here: https://github.com/JamesNK/Newtonsoft.Json/issues/1262

authors: PiotrPerak danroth27 dougbu kichalla


text:
Storing Empty list in TempData cookies results in a Jarray object when read

I have code that may store an empty list object in the tempdata property of the controller.
When using the default tempdata provider (cookies) after I redirect to the MVC action that consumes the data it will be read as a Jarray instead of the intended type List

@Tarig0, can you please share a sample code to repro the issue?

Just had a thought, could we add generics so we can get an empty list.
TempData<List<Int>>("Test");

Key Exists
Value
Result

No
null
Throw key not found

Yes
null
null

Yes
[]
Empty List

Yes
["Hello","World"]
Throw cast error

Yes
[1,2,3,4]
List with values

The problem is any change to the interface ITempDataDictionary would be a breaking change and we wouldn't be able to make it until the next major release. But yes, perhaps the idea that you'd pass in the type of the the value to the dictionary would be to make the type support more complex types among other things.

authors: Tarig0 mkArtakMSFT pranavkm


text:
Format Date issue with querystring return get, change format

From @shpsyte on February 2, 2018 16:6
Date format issue for GET METHOD ON CONTROLLER
I'm developing an application and I get this "error", I have a data model and I have datetime properties set.
In the first GET on the page, Date format is correct, eg: dd/mm/yyyy (as defined in the data model)
But after the Second GET  the date format is changed to mm/dd/yyyy (in back end) but in view is dd/mm/yyyy
in post I receive mm/dd/yyy but in View I see dd/mm/yyyy
It's vary crazy
General
I'm using .Net Core 2.0 + Bootstrap (No using any jquery, but i try too)...
For some issues, chek and details i put on GIT for reproduce this issue REP ISSUE DATE
Copied from original issue: dotnet/core#1252

From @shpsyte on February 3, 2018 13:37
any ?

From @Petermarcu on March 11, 2018 16:24
@muratg @Eilon @ajcvickers Is this somewhere in MVC/EF?

@shpsyte I suspect this is because of the following behavior in MVC:

Model binding (the thing that generates the parameters for your action method) will use the Invariant Culture for parsing dates from the query string
But rendering the output in <input type="text" asp-for="dueDateStart" class="form-control"> will use the current culture

Because these two cultures are often different, this can create unexpected results.
I think you can change the <input> tag to remove the type="text" and MVC will generate the correct date markup, which I think will work correctly.
cc @dougbu @rynowak

@shpsyte removing type="text" may allow the browser to use date widgets for your DateTime fields. Whether that happens depends on the browser. The widgets hide any formatting (while making the formatting more constrained due to browser restrictions). Either way, MVC will generate the correct HTML for those widgets without type="text".
Also recommend using <form method="form"> to consistently use the current culture for all user input, not just DateTime fields.

@dougbu what's <form method="form"> ?

I'had the same problem.
I've resolved with this code:
I've created the model binder that parse correctly date time
public class DateTimeModelBinder : IModelBinder
    {
        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }

            if (bindingContext.ModelType != typeof(DateTime?))
            {
                return Task.CompletedTask;
            }

            var modelName = GetModelName(bindingContext);

            var valueProviderResult = bindingContext.ValueProvider.GetValue(modelName);
            if (valueProviderResult == ValueProviderResult.None)
            {
                return Task.CompletedTask;
            }

            bindingContext.ModelState.SetModelValue(modelName, valueProviderResult);

            var dateToParse = valueProviderResult.FirstValue;

            if (string.IsNullOrEmpty(dateToParse))
            {
                return Task.CompletedTask;
            }

            var dateTime = ParseDate(bindingContext, dateToParse);

            bindingContext.Result = ModelBindingResult.Success(dateTime);

            return Task.CompletedTask;
        }

        private DateTime? ParseDate(ModelBindingContext bindingContext, string dateToParse)
        {
            string[] dateFormats = new string[] {
                "dd/MM/yyyy",
                "dd/MM/yyyy HH\\:mm\\:ss"
            };

            if (dateFormats == null)
            {
                return ParseDateTime(dateToParse);
            }

            return ParseDateTime(dateToParse, dateFormats );
        }

        private string GetModelName(ModelBindingContext bindingContext)
        {
            // The "Name" property of the ModelBinder attribute can be used to specify the
            // route parameter name when the action parameter name is different from the route parameter name.
            // For instance, when the route is /api/{birthDate} and the action parameter name is "date".
            // We can add this attribute with a Name property [DateTimeModelBinder(Name ="birthDate")]
            // Now bindingContext.BinderModelName will be "birthDate" and bindingContext.ModelName will be "date"
            if (!string.IsNullOrEmpty(bindingContext.BinderModelName))
            {
                return bindingContext.BinderModelName;
            }

            return bindingContext.ModelName;
        }

        public DateTime? ParseDateTime(
            string dateToParse,
            string[] formats = null,
            IFormatProvider provider = null,
            DateTimeStyles styles = DateTimeStyles.AssumeLocal)
        {
            var CUSTOM_DATE_FORMATS = new string[]
                {
                "dd/MM/yyyy",
                "dd/MM/yyyy HH\\:mm\\:ss"
                };

            if (formats == null)
            {
                formats = CUSTOM_DATE_FORMATS;
            }

            DateTime validDate;

            foreach (var format in formats)
            {
                if (format.EndsWith("Z"))
                {
                    if (DateTime.TryParseExact(dateToParse, format,
                             provider,
                             DateTimeStyles.AssumeUniversal,
                             out validDate))
                    {
                        return validDate;
                    }
                }

                if (DateTime.TryParseExact(dateToParse, format,
                         provider, styles, out validDate))
                {
                    return validDate;
                }
            }

            return null;
        }
    }

Then i've created a modelbinder provider that use model binder.
public class DateCultureItaliaModelBinderProvider : IModelBinderProvider
    {
        public IModelBinder GetBinder(ModelBinderProviderContext context)
        {
            if (context.Metadata.ModelType == typeof(DateTime?))
            {
                return new DateTimeModelBinder();
            }

            return null;
        }
    }

Then i've configured my services:
 services.AddMvc(o =>
           {
               // Date time format
               o.ModelBinderProviders.Insert(0, new DateCultureItaliaModelBinderProvider());
           })

This way every date is well parsed in all my models in all actions.

It works Thanks

authors: Eilon alvisemion dougbu jigarce


text:
Connection Timeout on packets loss

Hello I'm using proxy on the azure VM connected to internal network via VPN.
It works all right most of the time however periodically I experience TCP packet loss (with tcp retransmission)  when sending POST request. This leads to TaskCancelledException (operation timed out) in the following line:
    HttpResponseMessage responseMessage =                     await                         _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, context.RequestAborted);
I set HttpClient Timeout period to 15 minutes (which is more than necessary) but it seems when I start getting packet send problems following with (RST, ACK), connection stuck forever and terminates on timeout.
Sometimes I have the same Timeout error after 15-20 seconds no matter that I set ReceiveHeadersTimeout and SendTimeout to 900 seconds.
I never see the same problem when I run proxy on local network. With VPN, about 2-5 POST requests of 100 are failed. I'm not sure if I will have the same problem on full .net 4.5.

I experienced similar results with .net 4.5 proxy and direct website POST. I guess it is expected behavior to have timeout on DNS query (15 seconds) no matter what timeout is set for entire httpClient.
Closing this issue.

repo: aspnet/Proxy