Aspnetcore: Hot reload for Blazor

Created on 25 Jan 2018  ·  130Comments  ·  Source: dotnet/aspnetcore

  • [ ] [Build performance optimization](https://github.com/dotnet/aspnetcore/issues/22566)
  • [ ] Via dotnet watch
  • [ ] Development middleware (websocket connection to receive updates)
Components Big Rock Design affected-most area-blazor enhancement severity-major

Most helpful comment

This is planned for .NET 5, which is scheduled for Nov 2020. We're still having lots of discussions on what approach we want to take here.

All 130 comments

See https://github.com/aspnet/blazor/issues/193 for status updates on this work item.

For now, we can use dotnet watch run and recompile every time when the change occurs.
Just using this in csproj file :
<DotNetCliToolReference Include="Microsoft.DotNet.Watcher.Tools" Version="2.0.0" />
<Watch Include="**\*.cshtml"/>

We've hit a snag with live reload for 0.2.0, so moving this out until we can work through a more robust design.

Hi, I'm using dotnet sdk 2.2.100-preview1-009349 and blazor 0.5.1 under Mac.
Live reload doesn't work using "dotnet blazor serve". If I change some html markup in a cshtml file, the app doesn't reload itself and ever after a manual browser reload, the app display the old html content. How can I solve this?

@danroth27, what's https://github.com/aspnet/AspNetCore/issues/4056 then? Should it be closed?

Few questions!
1 Does this track live reload for both server side blazor and client side blazor?

  1. Will live reload ship in go live release (i.e in net core 3.0) ?
  2. Will live reload mechanism lose page state (I.e equivalent to an f5 refresh) or will it behave similar to Hot Module Replacement in javascript land - I.e only the changed Components UI will re-render? If the latter, will there be a mechanism to preserve component state on the client between updates?

Does this track live reload for both server side blazor and client side blazor?

Yes

Will live reload ship in go live release (i.e in net core 3.0) ?

For .NET Core 3.0 we expect to support auto rebuild based on file changes, but you will still need to manually refresh the browser.

Will live reload mechanism lose page state (I.e equivalent to an f5 refresh) or will it behave similar to Hot Module Replacement in javascript land - I.e only the changed Components UI will re-render? If the latter, will there be a mechanism to preserve component state on the client between updates?

We don't currently have a plan for supporting hot module replacement in a way that preserves client state.

We don't currently have a plan for supporting hot module replacement in a way that preserves client state.

At least, not automagically. Theoretically if you follow a Redux-like architecture, or anything else that strictly decouples state from display, then you could serialize that state out before unload and restore on reload. However this isn't something we're planning to bake in as a feature, as not everyone wants to follow that kind of architecture.

then you could serialize that state out before unload and restore on reload.

Thanks. Please, once ready, would you be able to document the appropriate hooks (before unload / reload etc) provided in the design to facilitate this. I'd like to start on an implementation / helper nuget package to enable this pattern for those that want it!

Couldn't get the dotnet watch run to work, tried following and other options too,

dotnet watch --project "Portfolio.Client" run --project "Portfolio.Server"

Just ended up with the following crude solution using nodemon:

npx nodemon --watch "Portfolio.Client" -e razor,css,html,cs --exec 'dotnet run --project "Portfolio.Server"'

I thought i was supposed to run:
dotnet watch --project BlazorTest.Client run
But that gave me an error.

If I used:
dotnet watch --project BlazorTest.Server run

With the following in the project BlazorTest.Server.csproj file:

<ItemGroup>
    <Watch Include="..\**\*.razor" />
    <Watch Include="..\**\*.scss" />
    <Watch Include="..\**\*.cs" />
</ItemGroup>

It picked up changes in the BlazorTest.Client project and restarted the server, so I only had to do a manual refresh in the browser.

It picked up changes in the BlazorTest.Client project and restarted the server, so I only had to do a manual refresh in the browser.

Does that mean the server restarts everytime there is a a css, html change?

@dazinator, yes :-)

.. ok just checking but that is a bad thing right? I.e server restart should be unnecessary for a html or css file change as a browser refresh (with cache invalidated) should suffice?

You are right, that is not necessary. Just add or remove the file extensions you are interested in within the <ItemGroup>. Updated my answer to avoid confusion.

Sorry if off-topic, is there anyway to live reload from Visual Studio right now (Blazor client-side)? Right now for every change excluding wwwroot files, I have to Build the project (Ctrl Shift B) and reload the browser. Would be wonderful if VS can auto build on saving changes.

@datvm We've enabled this for server-side Blazor projects, but we need to do some work to enable this again for client-side Blazor projects and Razor class libraries. It will probably be a bit before we get to this as we are focused right now at shipping .NET Core 3.0.

For client side, you can probably use anything that just does a full page refresh when something changes on the server. Shameless plug: check out NetPack - run the sample project and navigate to the /BrowserReload example: https://github.com/dazinator/NetPack/blob/develop/src/NetPack.Web/Views/Home/BrowserReload.cshtml - that might help you. If not, there are other solutions out there for triggering a client side page reload based on server side file changes if you can't wait for an out of the box solution.

Thanks for the solution, may actually be useful for someone else. For me it will just be a QoL improvement, nothing critical. Still love the product and the effort everyone is putting in. Extra pressing of Ctrl Shift B works for me (now).

My solution currently looks like this:
I have a separate exe BlazorDebugLauncher which gets started by launchsettings.json parameterized with the port and hostname that the browser shall be opened.
It then

  • starts a separat small exe DebugAttacher which detaches and reattaches Visual studio
  • starts dotnet watch run on the project folder
  • refreshes the browser as soon as the server process is up (works fine with MS Edge :-) )

If anyone is interested, I can put this somewhere...

@AdmiralSnyder sure I'd be interested to see that if you feel like sharing!

this is my solution. a little hacky, but works: https://github.com/AdmiralSnyder/BlazorAutoRebuildDemo
(I'll cleanup and add a readme next week…)

@dazinator did you happen to have a look?

@AdmiralSnyder I had a look and thanks for sharing, I was keen to see how / whether you were attaching the debugger - I've got a bit of a vs extension development background you see :-)
i've settled on this approach for browser reload though (it's my own library unsurprisingly) https://github.com/dazinator/NetPack/blob/develop/src/NetPack.Web.Blazor.Host/Startup.cs - which runs the watcher within the app itself (using IFileProvider) rather than launching any external processes, and it triggers a reload using signal r and a blazor client side component that you add to your blazor layout. It has been working well for me in preview6 and I'll soon upgrade to preview7 and hope it continues to work :-)

I didn't want to bring the refreshing features into the project. How do you gap the detach-rebuild-restart-reattach gap without having an external process?

I didn't want to bring the refreshing features into the project

You dont have to bring them into the project in a strict sense. For example you can include the package references with a condition on a compilation symbol (I.e debug = true) and you can put the startup code in a compilation directive (#if debug) - and now when you run the app in release mode you wont have the design time packages or code in it.

How do you gap the detach-rebuild-restart-reattach gap without having an external process?

Because I run the host project from VS, it can rebuild the referenced blazor client project as needed (netpack watches the blazor projects IFileProvider) without having to stop or detach from the host process. The only time there is a "gap" is if I need to make a code change to my host application itself (not the blazor client). In that case - I sorely hope one day "Edit and Continue" will work again as that will solve this last problem. However without that, there are two options for my aproach:

  1. Don't use VS to run the host, use dotnet run watch and then attach the debugger manually (a pain)
  2. Stop VS, make the change to the host, start Vs again (this is typically what I do)
    @AdmiralSnyder have edited this to hopefully better address your questions

I am seeing ~10 seconds for a rebuild using dotnet watch. Are there any plans to speed up incremental builds? That is fairly painful when iterating on components.

It looks like much of the time is spent building the razor components, so does that mean these build times are going to scale ~linearly? (with more complex apps taking 30+ seconds to build?)

Are there any plans to speed up incremental builds? That is fairly painful when iterating on components.

If this is client-side Blazor, consider disabling linking for Debug builds.

  <PropertyGroup Condition="'$(Configuration)' == 'Debug'">
    <BlazorLinkOnBuild>false</BlazorLinkOnBuild>
  </PropertyGroup>

I have talked to a few people who are confused about auto-rebuild and auto-refresh.
This mainly is due to the fact that when you change code in Visual Studio the auto-rebuild feature kicks in and you also see that "something" is hapening in the browser. This something is often mistaken for a live reload attempt.
Then (due to the fact that the signal-r connection can not reconnect to the old state) you get the "Failed to reconnect to the server." error. However for people new to Blazor it looks like the system has tried an auto-refresh it fails in doing so which is bad experience.

Since there is no ETA on the Live Reload feature is it possible to not try an auto-reconnect if the connection broke due to a build? Or at least give a better error message, so instead of "Failed to reconnect to the server" something like "Refresh Browser"?

@chucker thanks for the disable linker tip. That does up the build marginally but then the subsequent browser reload is much slower as it now downloads much more chaff- I'm not sure whether overall it has helped or not :-) but worth knowing.
If anyone is curious to see blazor reload in action (for blazor client / wasm) projects, you can run this project here to see what I mean: https://github.com/dazinator/NetPack/blob/develop/src/NetPack.Web.Blazor.Host/Startup.cs

@Postlagerkarte We do try to reconnect, but since the server state is gone when the process is recycled the reconnection fails. We've done some work in this space to try to improve the user experience. See the "Improved reconnection logic for Blazor Server apps" section in the Preview 8 announcement blog post.

@Postlagerkarte improved that error message in preview8

Depending on the horizon / timeline for live reload, Is it worth considering a separate issue to improve compile speed? Perhaps via a caching strategy similar to how MVC/cshtml works (I believe only views that have changed get recompiled)? Are there any potential low hanging fruit here?

Right now the 10 second cycle time between making a change and seeing it in the browser is just a really big issue, and is significantly larger than webpack based platforms at similar application scale. And to be clear, I'm just talking about server side blazor here.

Is it worth considering a separate issue to improve compile speed?

Yes, if you are seeing slow build times please file an issue with details of your build environment.

Having to reload the entire blazor client application (re-download all dll's) when you make a minor "html only" change to a component (for example, change some static html content) is... not very optimal.

Do the team have anything to track improvements to that experience or should I open a new issue?

@dazinator It's not very clear from the issue title, but we are using this issue to track hot module replacement as well as live reload. We have a bunch of investments that we plan to make in the .NET 5 time frame in this area.

Personally I don't mind hitting F5 and thus do not consider hot reloading a top prio feature,
However to get into the flow I find it crucial that the
change code , f5 , change code , f5 , change code workflow is blazing (pun intented) fast. Please work on that first :)

We've enabled this for server-side Blazor projects, but we need to do some work to enable this again for client-side Blazor projects and Razor class libraries. It will probably be a bit before we get to this as we are focused right now at shipping .NET Core 3.0.

From what I've been able to gather from various GitHub issues is that live-reload only works on server-side Blazor that is run without debugging (and the developer must force refresh the page). Is that correct? I couldn't find any definitive documentation on the subject.

What we have right now is really auto-rebuild support for ASP.NET Core projects, where VS will watch the file system for changes and then automatically rebuild and rerun the project. It only works when the debugger is not attached and for files in the current project (dependent projects are not watched).

Is it possible to disable the auto-reconnect attempt in case the reason for the connection loss was a build? Or maybe disable the auto-reconnect at all while developing? I just want to get rid of the those failing re-connect attempts because they bug me and I press F5 anyways :)

So it should be rather easy to have VS detach and reattach automatically, right?

Can I get the final solution for Live Reloading for Blazor Server Apps with debugging ?

@bansalankit2601 To be implemented in .NET 5.0

I run the watcher as dotnet watch run and use VS to edit the code. When I save, the code is recompiled and the browser locks up, telling me I should reload.

I got tired of pressing F5 and prefer to stay in VS while adjusting things, so TamperMonkey to the rescue:

```// ==UserScript==
// @name Reload the page
// @namespace http://tampermonkey.net/
// @version 0.1
// @description try to take over the world!
// @author You
// @match http://localhost:5000/*
// @grant none
// ==/UserScript==

const reloader = () => {
    if (document.body.innerText.indexOf("Reload the page") >= 0) document.location = document.location;
    else setTimeout(reloader, 300);
}
console.log('Blazor reloader installed');
setTimeout(reloader, 300);

```
Allow the script to run on http://localhost:5000/*

This works for server side: https://github.com/martasp/BlazorLiveReload

The client pings the server every 200ms. When the server goes down due to being recompiled from dotnet watch run, a flag is toggled, and when the server comes back it automatically F5s.

The repo didn't work for me, but I opened an issue with some javascript that does work (at least for me on 3.0)

What is the status of "Live reload" at the moment. Is it supported (without F5 in browser)?
If not, are there any plans on releasing this feature?

@moemar in the latest community standup David Fowler says there are plans for it for possibly the next version but nothing has been put in place yet. https://youtu.be/bBc_NTUVtbE?list=PL1rZQsJPBU2St9-Mz1Kaa7rofciyrwWVx&t=5010

What is the latest on this? 2.5 months since last update...

I am also waiting for the same.

This is planned for .NET 5, which is scheduled for Nov 2020. We're still having lots of discussions on what approach we want to take here.

For Blazor serverside, what about using the mechanism that handle disconnections :

@dharmaturtle presented a solution that fetches the server every 200ms. It works but it is annoying because it constantly fires requests even when the server runs.

If you override Blazor.defaultReconnectionHandler._reconnectionDisplay from the javascript blazor client, you can catch disconnections and start to fetch the server and wait for it to become live again.

The advantage is that you only have requests when the server is disconnected.

The drawback is that '_reconnectionDisplay' is a private member and you know... this is evil.

As a mitigation, enclose the javascript code in <environment include="Development">. It won't bleed in production server.

Full repo here.

I just switched to this solution a few minutes ago: https://remibou.github.io/Make-your-Blazor-development-faster/

It doesn't continuously ping the server, and it doesn't recompile the entire .sln if the change is in a .html, a .css or a .js file; it merely reloads the page, which is great.

Just linking another example here that's a bit different from above approaches. Just run the project - it doesnt require dotnet watch on the client wasm project. It will reload immediately if you change any css, html or js file in the wwwroot folder of the client wasm. It will rebuild and then reload, if you change any code in the client wasm project like a razor file etc. You have control of this in your startup.cs which is why this is a bit different to other solutions. If you also happen to still be using javascript or other static files that must be pre processed in your project, then you can also find other examples in the same repo that might be useful, such as SystemJS HMR, rollup etc.

https://github.com/dazinator/NetPack/blob/develop/src/NetPack.Web.Blazor.Host/Startup.cs

Made a library that compiles razor components in runtime.

LivePreview

In react we have hot module replacement this feature allows us to change code and see changes immediately in your browser. We can make a similar feature in blazor using Roslyn compiler. Compiling down razor components in runtime and serving with WebSockets on every file change using file watcher.

How it works

It uses razor engine version 3 to compile components to c# classes. Then using Roslyn compiler I compiled down those classes to assembly. Finally, I loaded the app.razor component from an assembly with reflection and with Steve Sanderson Test host modified library I turned component to plain HTML. To serve HTML files in realtime I used WebSockets to have a full-duplex communication.

How can it be better 

Fixing routes instead of using /preview, this could be implemented by injecting WebSocket client into every HTTP request context.

In Blazor web assembly maybe we can load and unload assemblies in the browser?

Using two build servers one for fast previewing and another server with dotnet watch build for actual real longer builds.

In Blazor web assembly maybe we can load and unload assemblies in the browser?

Source: https://github.com/martasp/BlazorLiveReload

@martasp

In Blazor web assembly maybe we can load and unload assemblies in the browser?

It's a version of mono runtime executing blazor wasm apps, but unfortunately you can't create new AppDomains (to my knowledge) and you can't unload assemblies from the default AppDomain.

You can lazy load assemblies, which is how I'm currently dynamically loading component assemblies only on first use (to speed up initial app load time), but once they are loaded the only way to load a new version that I can see is maybe to load a new version of the same assembly into the same AppDomain and switch all references to that new one - leaving the old one there- not sure if that is supported as I'm yet to try it. If you do make in roads; let me know!

I hope one day we might get the .net core runtime running in the browser instead with its support for AssemblyLoadContexts and Assembly.Unload()

Hi @danroth27 ,
have you seen https://www.livesharp.net/?
It replaces the code while it is running.

There is a showcase where it updates Blazor on-the-fly (though one needs to navigate away and back to the current route).
And also a showcase where even a console output text in a loop is replaced _while its running_!

This is very close to the experience I would wish for!

@warappa that is awesome. I wonder how it works! I can think of a few possible mechanisms replacing methods with dynamic proxies.
However it works, kudos to the developer/s. I'd also like an experience like this but preferably without a seperate dev server, I'd prefer to just click play in VS.

@dazinator LiveSharp Server serializes updated code and sends it to the application. Then, the application deserializes it into Expression Tree and injects it into updated methods. There is much more going on inside, but that is the gist of it.

By the way, LiveSharp Server needs to be only started once. After that, you just start the app as you usually do.

Here is a demo of stateful Blazor hot-reload with LiveSharp: https://www.youtube.com/watch?v=MCh5-44UBpM

Disclaimer: I'm the author of LiveSharp

@ionoy kudos that's some nice work there!

The experience developing for blazor as of now is very painful. Edit, rebuild, refresh, debug...
Would gladly pay 9$ per month until this gets fixed, would boost productivity at least 5x.

When designing this please take into account that not all of us use visual studio. Thanks

@wocar LiveSharp is already cross-platform and doesn't depend on any IDE. So you could theoretically use it with notepad.exe

@wocar If you're not using VS, then also consider dotnet watch: https://docs.microsoft.com/en-us/aspnet/core/tutorials/dotnet-watch

@SteveSandersonMS - dotnet watch kills the state, as you undoubtedly know. LiveSharp actually pushes the changes without forcing a reload and so allows fine-tuning of the UI with instant feedback loop. I really wish you guys would implement something equivalent soon, it's sorely needed.

Yes of course. I wasn’t suggesting it’s the same as LiveSharp. Just making sure that @wocar was aware of the option.

Thanks. Already downloaded Livesharp and works very well, would like to see something like that implemented.

Don’t get me wrong you guys have done an amazing work, however if you want honest feedback debugging blazor is a pain. I’ve used dotnet watch and it kinda works (it is slow) and I can’t debug (at least not with Rider) so as much as I would like to use blazor I can’t because of productivit. So I decided to stick with razor pages instead.

Thank you.

Thanks for the feedback, @wocar! I know that hot reload is important. It's something we strongly want to add, and are looking into ways it can be brought to .NET 5 in general.

I can’t debug (at least not with Rider)

You might already be aware, but just in case not, it is possible to debug in an IDE-independent way by using the browser as the .NET debugger: https://docs.microsoft.com/en-us/aspnet/core/blazor/debug?view=aspnetcore-3.1#debug-in-the-browser

You might already be aware, but just in case not, it is possible to debug in an IDE-independent way by using the browser as the .NET debugger: https://docs.microsoft.com/en-us/aspnet/core/blazor/debug?view=aspnetcore-3.1#debug-in-the-browser

Thank you wasn't aware.

If I use razor pages (.cshtml) and modify the HTML and press F5 at least I can see the changes. Why this is not possible with Razor Components (.razor)

I would love to get a faster development cycle too. Once we had hot-reload working for Vue, it was so nice to make a change and see it 1.0-2.0 seconds later in the browser. Now I see the need for something like that here.

dotnet watch run gets us part of the way here--would there be a simpler intermediate answer, perhaps some way to speed up the build so that it is faster when nothing but a .razor file has changed? It wouldn't avoid the need to restart the web host and reload the page, as dbulic said above, but having to wait 1 second rather than 20 seconds for the build would be big.

Are there any plans to address this by having a kind of "runtime compilation" for .razor files running in the browser, analogous to the runtime compilation of .cshtml files that is available on the server? E.g so that .razor files themselves are directly loaded into the browser (instead of the precompiled assemblies) and then compiled there, and then if they are edited on the server, the changed .razor file can be reloaded into the browser and recompiled there? I like the parallels here with cshtml and wondered if this is a path at all in consideration?

This is planned for .NET 5, which is scheduled for Nov 2020. We're still having lots of discussions on what approach we want to take here.

Hi @danroth27, has a direction taken shape? If nothing to share yet, possible we will see something at Build 2020?

Hi @mrlife. We expect to primarily be focused on the Blazor WebAssembly release at BUILD. Support for hot reload is something we expect to look at for .NET 5. The specific direction for how this will be achieved has not yet been determined.

I think about this issue a lot. Every day, I use Pattern 1. Pattern 2 is a paradigm change in practice compared to Pattern 1; this makes it less easy to adopt compared to improving Pattern 1 directly. I hope Pattern 3 is close to what is achievable. I feel like Pattern 4 is only aspirational based on comments above, however, after seeing what's possible in MAUI, Pattern 6 looks really good.

Pattern 1 (current out of the box):

  1. Save changes to any number of files
  2. Click a button or press keyboard command to compile
  3. Refresh the browser

Pattern 2 (dotnet watch run):

  1. Save changes to one file
  2. Automatic recompile
  3. Save any other files needed and wait for additional recompiles
  4. Refresh the browser

Pattern 3:

  1. Save changes to any number of files
  2. Partial or no recompile needed
  3. Refresh the browser

Pattern 4:

  1. Save changes to any number of files
  2. Browser reflects changes in its current state

Pattern 5 (like MAUI hot reload):

  1. Don't save changes to a file
  2. Browser reflects changes in its current state

What's achievable?

My current pattern with dotnet watch run:

  1. Save changes to all files with Ctrl Shift S
  2. Automatic recompile
  3. Automatic browser refresh described here.

Is this issue tracking hot build/reload for both Blazer Server and Web Assembly, or is there a separate one for Web Assembly?

Whats the status on this? Currently using https://github.com/OYIon/LiveSharp

this is all very uncomfortable. I also can't get the dotnet watch workaround to work from a .dcproj aka docker-compose project.
I hope that something will happen in the near term feature. it's currently a pain in the *
* to work with blazor from my pov. no live update, things are constantly highlighted in red and intellisense only works very modestly.

great technology also needs great tooling!

things are constantly highlighted in red and intellisense only works very modestly.

Same here, my workaround:

  • Kill devenv.exe
  • remove .vs\ folder
  • Restart project

Tooling will work again. Do this a couple of times per day. With refactoring, couple of times per hour. Try combining it with your trip to the coffee machine

things are constantly highlighted in red and intellisense only works very modestly.

I know this is difficult, but do you have any repro steps for this? For example, do you have some project code that you can share which, on a specific version of VS or VS Code, reliably produces incorrect intellisense or errors? We definitely want to track down and fix any issues like that.

cc @NTaylorMullen - do you know of any diagnostic steps that could be taken here to help us track this down?

@SteveSandersonMS

Easy:

  • Rename a existing razor component file

image
(files with same prefix will also be renamed)

image

  • Update class name in the partial class

  • Update/rename references in other components (manual, highly missed tooling feature)

  • Build works

  • Tooling broken

image

  • After deleting .\vs folder vs recovers

things are constantly highlighted in red and intellisense only works very modestly.

I know this is difficult, but do you have any repro steps for this? For example, do you have some project code that you can share which, on a specific version of VS or VS Code, reliably produces incorrect intellisense or errors? We definitely want to track down and fix any issues like that.

cc @NTaylorMullen - do you know of any diagnostic steps that could be taken here to help us track this down?

thanks for the response, I will keep an eye on it. every kind of refactoring is definitely problematic as JvanderStad already gave as example. otherwise I could not see any pattern so far.
e.g. i just opened a 219 lines file and got 167 intellisense errors. rules: CS0121 CS0229 CS1503

would it perhaps be useful to create an extra github issue to collect the intellisense problems? or does this already exist? because this issue is definitely the wrong place.

thanks for the response, I will keep an eye on it. every kind of refactoring is definitely problematic as JvanderStad already gave as example. otherwise I could not see any pattern so far.
e.g. i just opened a 219 lines file and got 167 intellisense errors. rules: CS0121 CS0229 CS1503

would it perhaps be useful to create an extra github issue to collect the intellisense problems? or does this already exist? because this issue is definitely the wrong place.

It's almost if the intellisense db gets corrupted / language service crashes, it persists after VS restart

  <entry>
    <record>1268</record>
    <time>2020/07/08 14:35:36.779</time>
    <type>Error</type>
    <source>Editor or Editor Extension</source>
    <description>System.TimeoutException: The operation has timed out.&#x000D;&#x000A;   at Microsoft.WebTools.Languages.Html.VS.ContainedLanguage.Server.DotNetCoreServerContainedLanguageSupport.OnIdle(Object sender, EventArgs e)</description>
  </entry>

I’m using rider instead of vs and seems to work very well. Also I’m using this tool called livesharp, while its not that good or that reliable, it gets the job done and I can get UI updates without having to recompile.

@cubed-it This PowerShell kills Visual Studio, removes the .vs\ folder, restarts the solution. Less coffee trips required.

$start = New-Object Collections.Generic.List[string]

Write-Host "Looking for Visual Studio"  -BackgroundColor DarkGreen
$devenvs = Get-CimInstance Win32_Process -Filter "name = 'devenv.exe'" | Select-Object CommandLine, ProcessId

foreach ($devenv in $devenvs) {

    Write-Host $devenv

    $index = $devenv.CommandLine.IndexOf("devenv.exe`" `"")
    if ($index -eq -1)
    {
        Write-Host "No params"  -BackgroundColor DarkRed
        continue
    }

    $param = $devenv.CommandLine.Substring($index + 12).Trim()
    $project = $param.Trim('"')
    if ($project.Length -eq 0)
    {
        continue
    }

    #allowed project files
    $slnTypes = New-Object System.Collections.Generic.HashSet[string]
    [void]$slnTypes.Add(".sln")
    [void]$slnTypes.Add(".slnf")

    #
    Write-Host "Project: $project"

    $extension = [System.IO.Path]::GetExtension($project)
    if (-not $slnTypes.Contains($extension))
    {
        Write-Host "No solution" -BackgroundColor DarkRed
        continue;
    }


    $vsFolder = [System.IO.Path]::GetDirectoryName($project)
    $vsFolder = "$vsFolder\.vs\"

    if ([System.IO.Directory]::Exists($vsFolder) -eq $false)
    {
        Write-Host ".vs\ folder does not exist" -BackgroundColor DarkRed
        continue
    }

    #we will restart later
    [void]$start.Add($devenv.CommandLine)

    #kill visual studio
    Write-Host "Kill: $devenv" -BackgroundColor DarkGreen
    Stop-Process -id $devenv.ProcessId -Force

    #remove devenv folder
    Write-Host "Removing: $vsFolder" -BackgroundColor DarkGreen
    Remove-Item -Recurse -Force $vsFolder
}


foreach ($devenv in $start) {

    $program =  $devenv.Substring(0, $index + 11)
    $arguments =  $devenv.Substring($index + 12)

    Write-Host "Starting: '$program'"  -BackgroundColor DarkGreen
    Write-Host "Arguments: '$arguments'"  -BackgroundColor DarkGreen

    Start-Process -FilePath $program -ArgumentList $arguments
}

To those who wants to stick to VS, you can use this extension for the work around (https://marketplace.visualstudio.com/items?itemName=pragmatrix.BuildOnSave) that automatically builds on save & can only be enabled to startup project (this case your blazor project). For better experience, turn off "Lunch Browser" in the VS so that it doesn't close the browser automatically. But you will have to hit F5 on the browser :-(

Totally feel all of your pain in regards to the Razor tooling. Thankfully it's something we're looking to address in the .NET 5 time frame. If you'd like to try this tooling (warning it's super experimental currently) you can download the latest VS preview release and check the following preview feature checkbox (Tools -> Options -> Environment -> Preview Features):

image

It's very likely that will resolve many of the Razor editor issues mentioned in this issue . That being said we know the new editor has several gaps and even a few bad bugs when comparing to the existing editor but we'd be curious to hear your feedback regardless on if it was an overall better experience for your needs.

download the latest VS preview release
https://visualstudio.microsoft.com/vs/preview/

@NTaylorMullen Is there an issue where I can log errors regarding the Razor tooling? The latest preview does not work at all :(

image

@JvanderStad I believe the syntax should be "@(row => ...

@JvanderStad I believe the syntax should be "@(row => ...

Works fine in the current version

image

@JvanderStad ah, if you're talking about colors, that's currently broken, as are many other things

https://devblogs.microsoft.com/aspnet/new-experimental-razor-editor-for-visual-studio/

I missed Daniels' blogpost. I know now what to expect. Thnx

@NTaylorMullen Is there an issue where I can log errors regarding the Razor tooling? The latest preview does not work at all :(

Ya C# semantic colorization is something we haven't implemented yet in the new editor 😄

@danroth27 If hot reload for blazor wasm is tricky due to architecture, do you think hot-reload for blazor server can do the trick. The idea is to seamlessly render razor components (from blazor wasm project) via server-renderer during development keeping all of the compatibility checks that ensure blazor wasm deployment and do the final stage test and deployment in actual wasm model.

are there any updates for hot reloading, would it be out in .net5, or is it already out in the preview?

@qin-guan Hot reload is not planned for .NET 5 due to the limited time left in that release. We're hoping to deliver hot reload for .NET 6.

@danroth27 ahhhh booooooo!!

Please forgive my perhaps biased and perhaps woefully ignorant opinion, but I sometimes feel like productivity improvements take a back seat to performance enhancements (of which there has been a lot of work invested)

I'd love to see the blog about the 250 productivity improvements you've made this release to your tooling for example.
From my personal perspective, if developers don't get the productive tool chain they need, they won't be able to churn out the software quick enough to beat competitors to market, and the upshot is, that their applications won't survive in the marketplace to reap the benefit of all those nice shiny performance enhancements. So from that perspective it's a little aggravating.

However I love the look of the perf improvements.. I just really hope .NET 6 isn't too far behind .NET 5 and we see productivity in Blazor start to catch up with other frameworks!

@qin-guan Hot reload is not planned for .NET 5 due to the limited time left in that release. We're hoping to deliver hot reload for .NET 6.

that's so sad, I was waiting this feature for .net5 😭😭😭

@dazinator @buster95 We share your disappointment! Hot reload was pretty much at the top of our list of stuff we wanted to do in .NET 5 and it still is near the top of our backlog. It was originally expected to be part of a broader hot reload effort across .NET, but that was all pushed out to .NET 6. Doing hot reload well is a tricky problem - it means finding reliable ways to update the running app as quickly as possible and with high fidelity. It just requires more time to do well than we had available in .NET 5.

For developer productivity we are are completely revamping the Razor editor, which should enable a whole host of productivity features for Blazor development (refactoring, go to def/impl, code actions, etc.). We made the new editor available as an optional preview feature for the first time earlier this month, and we expect to make it the default Razor editor probably early next year.

We also have a number of other Blazor framework features coming in .NET 5 including CSS isolation, lazy loading, set UI focus, modify HTML Head, file upload, protected browser storage, virtualization, etc.

@dazinator @buster95 We share your disappointment! Hot reload was pretty much at the top of our list of stuff we wanted to do in .NET 5 and it still is near the top of our backlog. It was originally expected to be part of a broader hot reload effort across .NET, but that was all pushed out to .NET 6. Doing hot reload well is a tricky problem - it means finding reliable ways to update the running app as quickly as possible and with high fidelity. It just requires more time to do well than we had available in .NET 5.

For developer productivity we are are completely revamping the Razor editor, which should enable a whole host of productivity features for Blazor development (refactoring, go to def/impl, code actions, etc.). We made the new editor available as an optional preview feature for the first time earlier this month, and we expect to make it the default Razor editor probably early next year.

We also have a number of other Blazor framework features coming in .NET 5 including CSS isolation, lazy loading, set UI focus, modify HTML Head, file upload, protected browser storage, virtualization, etc.

Is there a possibility to create a free extension like https://www.livesharp.net and be free for all?
image
this extension is simple to configure but for now I'm using 15days trial version 😢

I have a question, is hot reload going to work for MacOS as of how is currently planned? Because edit and continue doesn't work as of now.

https://github.com/dotnet/runtime/issues/12409

@wocar Yes, whatever solution we ship will be cross platform and work on macOS.

@danroth27 can you provide a not so well perfoming solution, also being easy to work with?
For example having a Development middleware with websocket connection that refresh the page after a slow complete rebuild?

@danroth27 can you provide a not so well perfoming solution, also being easy to work with?
For example having a Development middleware with websocket connection that refresh the page after a slow complete rebuild?

@xrkolovos if you have VS you can use ctrl-shift-b, ctrl-alt-enter (manually after build) if you have BrowserLink installed: https://docs.microsoft.com/en-us/aspnet/core/client-side/using-browserlink?view=aspnetcore-3.1

can you provide a not so well perfoming solution, also being easy to work with?
For example having a Development middleware with websocket connection that refresh the page after a slow complete rebuild?

We are working on doing exactly that with dotnet watch for .NET 5: https://github.com/dotnet/aspnetcore/pull/24574

@dazinator @buster95 We share your disappointment! Hot reload was pretty much at the top of our list of stuff we wanted to do in .NET 5 and it still is near the top of our backlog. It was originally expected to be part of a broader hot reload effort across .NET, but that was all pushed out to .NET 6. Doing hot reload well is a tricky problem - it means finding reliable ways to update the running app as quickly as possible and with high fidelity. It just requires more time to do well than we had available in .NET 5.

@danroth27 Is the "broader hot reload" for .NET also supposed to work for non-web projects? And is there any issue where I could track that?

We've moved this issue to the Backlog milestone. This means that it is not going to be worked on for the coming release. We will reassess the backlog following the current release and consider this item at that time. To learn more about our issue management process and to have better expectation regarding different types of issues you can read our Triage Process.

Thanks for contacting us.
We're moving this issue to the Next sprint planning milestone for future evaluation / consideration. We will evaluate the request when we are planning the work for the next milestone. To learn more about what to expect next and how this issue will be handled you can read more about our triage process here.

Now it's available on .NET5 how can i activate it ?

Now it's available on .NET5 how can i activate

Dudeee check comments above, this was planning for .net 6-preview 😢 Screenshot_20201112-071336__01.jpg

@buster95 then what the heck steve sanderson did in .NET Conf 2020 day 1 in 2h38mm36ss to refresh the page auto?
Link to the video : https://www.youtube.com/watch?v=mS6ykjdOVRg

in 2h38mm36ss

@yasserss, at that time Safia Abdalla was talking about the <Virtualize>component. You can send the proper video link at the specified time by clicking on YouTube's share button.

@BrunoBlanes sorry here is it : https://youtu.be/mS6ykjdOVRg?t=8917

I am pretty sure he is using dotnet watch.

If you check the video in 2h:25m:40s he is using dotnet watch run to run the app maybe we have a improve in dotnet watch run, I remember the last time I used dotnet watch performance was bad I don't know now

Yes, we did work in .NET 5 to improve the performance of dotnet watch. For example, it's now smarter about not running dotnet restore each time you make a source change, and it's able to trigger reloads in the browser.

This is not the ultimate vision for hot reload. We still plan to make a true hot reload feature in .NET 6, but the dotnet watch perf improvements in .NET 5 are a step forwards in the meantime.

We also enabled support for auto refreshing the browser in both dotnet watch and in VS. To turn this feature on in VS, you need to set this option:

vs-auto-refresh

This is different from hot reload, in that the app is still getting restarted and the app reloaded in the browser. But it does enable you to focus on editing the code while tooling rebuilds and refreshes the browser for you.

@danroth27 Any news on auto refresh with Visual Studio for Mac?

@mrlife something we're looking in to adding support for very soon. FYI @jongalloway

@danroth27

We also enabled support for auto refreshing the browser in both dotnet watch and in VS. To turn this feature on in VS, you need to set this option:

vs-auto-refresh

This is different from hot reload, in that the app is still getting restarted and the app reloaded in the browser. But it does enable you to focus on editing the code while tooling rebuilds and refreshes the browser for you.

With this enabled should be enough to have debugging and reload on save in VS2019? I mean, I have this enabled with the option that you mentioned, and when I hit F5 and start debugging and make a change in my code, the browser does not reload. It does though when I run dotnet watch from the package manager console. How can I achieve this functionality just pressing F5 while debugging?

Given by the Auto refresh with dotnet watch section of the ASP.NET Core 5 Release notes, I don't think dotnet watch auto refresh is available within Visual Studio just yet:

We hope to bring the auto refresh functionality to Visual Studio in the future.

@BrunoBlanes The auto refresh support is now available with Visual Studio with the 16.8 update. You just have to turn it on using the option I pointed out above. I'll get the release notes updated to remove that comment.

@porkopek Auto rebuild and auto refresh only work when you are not running with the debugger.

Auto refresh/build is not working even selecting an option in visual studio 2019 16.8. Sometimes I get null reference exception in visual studio pop up when I select Auto build and refresh browser after saving changes. is there anything else needs to be changed in visual studio 2019 16.8 to make it work. @danroth27

I understand that it will be full experience in .NET 6. What about current .NET 5 and Blazor Webassembly?

Should this option "Auto build and refresh option" be also working for Blazor Webassemblies? What should i do more (than setting this option to : "Auto build and refresh..." and going to Filename.razor file, changing something and CTRL+S?:) Should it reload the browser?

How (or is it) correlated with Browser link?

@MussaratAziz The information about this hot-reload information is incomplete nor a msdn page is available.
In my case I had to stick to IIS Express profile and run the project without the debugger.
This made the hot-reload or rather hot-restart going but only for Blazor Server project. I haven't tested the WASM version.

I really hope ASP Core Dev Team (You are awesome!!) will include this, since tweaking UI without hotreload is quite painful.

Hope that helps :)

USE LIVESHARP... can’t believe a kid in his basement managed to do something that Microsoft can’t.

Edit: sorry don’t get me wrong, Microsoft has done a terrific job.. but this feature is a must ... just to change a DIV or an attribute is like 45 secs minimum

BTW: for the time being, I am using LiveSharp. Yes, it may be expensive for hobbyists and I would also like to see official support from the team in Redmond.
However, the product is great, the support is very good, and it just works.
https://www.livesharp.net/blazor/

Cheers!

@wocar @ChristianWeyer Really appreciate your support, guys! But please don't downplay MS efforts. It's almost always easier for a 3rd-party to create a completely new solution because I'm not accountable to anyone. This allows me to take risks.

Anyways, more cooperation, less antagonizing.

No, I am not downplaying - au contraire :-) In the end, it is about prios.

Was this page helpful?
0 / 5 - 0 ratings