How to use Blazor WASM gradually as part of existing Asp.Net Core Angular project
I have an application with Asp.Net core back-end and Angular front-end I want to convert the front-end part of it to Blazor WASM because it is very big I need to convert the frontend part of it gradually now my question is,Is there any way to use Blazor WASM component in Asp.Net Angular project or even further is there any way to use Blazor component inside an Angular component?
See also questions close to this topic
-
Cascading databound <ajaxtoolkit:combobox> and <asp:dropdownlist> in asp.net
I have an
asp.net
search form that includes anajaxToolkit Combobox
and a standardasp DropDownList
. Both controls are bound to two separatedSqlDatasource
components.Something like this:
<ajaxToolkit:ComboBox ID="cbConvenzionato" runat="server" AutoCompleteMode="SuggestAppend" DropDownStyle="DropDownList" DataSourceID="sdsConvenzionati" DataTextField="nome" DataValueField="id" AutoPostBack="true" OnSelectedIndexChanged="cbConvenzionato_SelectedIndexChanged" /> <asp:DropDownList ID="ddlVeicoli" DataSourceID="sdsVeicoli" DataTextField="targa" DataValueField="id" runat="server" AutoPostBack="true" OnSelectedIndexChanged="ddlVeicoli_SelectedIndexChanged" AppendDataBoundItems="true"> <asp:ListItem Text="TUTTI" Value="" Selected="True" /> </asp:DropDownList> <asp:SqlDataSource ID="sdsConvenzionati" runat="server" ConnectionString="<%$ ConnectionStrings:db %>" ProviderName="<%$ ConnectionStrings:db.ProviderName %>" SelectCommand=" SELECT id, nome FROM anag_convenzionati ORDER BY nome;" /> <asp:SqlDataSource ID="sdsVeicoli" runat="server" EnableCaching="false" CancelSelectOnNullParameter="false" ConnectionString="<%$ ConnectionStrings:db %>" ProviderName="<%$ ConnectionStrings:db.ProviderName %>" SelectCommand=" SELECT id, targa FROM veicoli_contratti WHERE ((@id_convenzionato IS NULL) OR (id_convenzionato = @id_convenzionato)) ORDER BY targa;"> <SelectParameters> <asp:ControlParameter Name="id_convenzionato" ControlID="cbConvenzionato" PropertyName="SelectedValue" Direction="Input" ConvertEmptyStringToNull="true" DbType="Int32" DefaultValue="" /> </SelectParameters> </asp:SqlDataSource>
There's also a third
sqldatasource
(sdsNoleggi
) that feeds agridview
but this's not a problem right now.In code behind I have two event handlers:
protected void cbConvenzionato_SelectedIndexChanged(object sender, EventArgs e) { sdsVeicoli.Select(DataSourceSelectArguments.Empty); Search(); } protected void ddlVeicoli_SelectedIndexChanged(object sender, EventArgs e) { Search(); } private void Search() { sdsNoleggi.Select(DataSourceSelectArguments.Empty); }
I tought in this way I should filter
ddlVeicoli
items after selecting an item incbConvenzionato
... but it's not working... why?If I look into
sdsVeicoli
SelectParameters
in debug I can seeid_convenzionato
being correctly set to selected value (id coming fromcbConvenzionato
) I bet also thatsdsNoleggi
dataset wiil be correctly updated with new values since I did this many times before. So why bound control it's not? I tried also to force addlVeicoli.DataBind()
aftersdsVeicoli.Select()
call ... but this had no effect. -
Swagger UI not working for REST API (asp.net web api2) application
I have asp.net mvc project with .NET Framework 4.7.2 and the same project contains asp.net web api2 controller in a separate folder : Controllers. The solution is legacy. The API are already in use in the PRODUCTION environment. Now I added the Swagger nuget package (Install-Package Swashbuckle -Version 5.6.0) to this existing project. Post that I see a SwaggerConfig.cs added to the App_Start folder of the Solution Explorer.
Here the asp.net mvc controllers are used by App1 pointing to the server: www.app1.com and asp.net web api2 controllers are used by another frontend angular app: App2 pointing to the server : www.app2.com
The complete deployment package for both App1 and App2 are hosted in IIS
Any request related to App1 is handled by www.app1.com and any api request related to App2 (Angular frontend) is handled by App1 only using IIS Rewrite rules at App2 level which redirect any api request to App1 only.
Now in this case when I tried to navigate to www.app1.com/swagger , I see it is loading the SwaggerUI for me, but when I tried to navigate to www.app2.com/swagger it is not working and instead of that it is loading the Angular frontend application
Here goes the App1 and App2 at IIS level:
Can anyone help me here by providing their guidance to fix this issue?
-
Cors error missing allow origin header. MailKit
I have
cors error missing allow origin header
error only on ONE post request. My CORS Policypublic void ConfigureServices(IServiceCollection services) { services.AddCors(options => { options.AddPolicy("AllowAllOrigins", builder => { builder.SetIsOriginAllowed(_ => true) .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); }); }
Every request work fine, but one POST request fails, it's really weird. Code in controller action which failed use MailKit and SMTP to send email, maybe that's cause
-
Ionic/Angular + Firebase with emulator on Android device = auth/network-request-failed
I have to improve existing Ionic app using firebase as auth method for users login into app. For purpose don't touch existing list of previously registered users in production firebase app, I have to create new locally using firebase emulator. After adding and setup local auth & DB emulator extensions, I have added this into
app.module.ts
:if (window.location.hostname === 'localhost') { firebase.auth().useEmulator('http://localhost:9099'); }
After continue with adding new UI and logical features, using web browser to test my work, I switch to Android platform. After running app and executing
firebase.auth().signInWithEmailAndPassword(email, password);
I got following error:
{ "code": "auth/network-request-failed", "message": "A network error (such as timeout, interrupted connection or unreachable host) has occurred." }
I have spent some time to figure out what is wrong, why all previously worked fine in browser, but not on real device.
-
Promise not resolved even when the request is done
I have a function that returns a promise from an HTTP Request:
getToken(id: string): Promise<string> { return this.service .getToken(id) .pipe( take(1) //catchError(() => of(null)) ) .toPromise(); }
And I want to know if the call failed (I won't have any token in this case), but the promise doesn't seem to complete because the IF statement is never reached if an error has occurred (BadRequest, Forbidden, etc.)
... const token = await this.getToken(id); if (!token) { console.log('no token'); } ...
But if I'm using
catchError(() => of(null))
, the promise completes even if the call failed and I can't understand the behavior. -
Socket.io connection to different mySQL tables, Angular front end
I have an angular app that displays a table of data (mySQL database) and updates whenever anything is added to the database. I feel that I should add I'm very inexperienced, i know angular but trying to learn more about backened operations.
I'm using a websocket (socket.io) on a node.js server to achieve this. It works fine but I'd like to add a second unrelated table of data that will appear in a different part of my app. . Should I set up another websocket to achieve this? Or can one websocket interact with 2 different table in the one database.
All of the SQL queries are handled in the backend and look like this.
// Create MySQLEvents const instance = new MySQLEvents(connection, { startAtEnd: true // to record only new binary logs }); await instance.start(); instance.addTrigger({ name: 'Monitor all SQL Statements', expression: 'mydb.*', // listen to database statement: MySQLEvents.STATEMENTS.ALL, onEvent: e => { currentData = e.affectedRows; let newData; switch (e.type) { case "INSERT": database.table('products') .withFields(['id', 'title', 'quantity', 'price']) .sort({id: -1}) .getAll() .then(prods => { data = prods; io.sockets.emit('update', {prods: [...data]}); }) .catch(err => console.log(err)); .....
My front end just accepts and displays the incoming data. I'd be unsure of how to add a second socket to it.
Here is my socket.service.ts in angular.
export class SocketService { constructor(private socket: Socket) { } getInitialData() { return this.createObserver('initial'); } getUpdatedData() { return this.createObserver('update'); } private createObserver(event: string) { return this.socket.fromEvent(event); }
and here is the component.ts
export class DashboardComponent implements OnInit, OnDestroy { private subs: Subscription[] = []; localData: any[] = []; constructor(private socketService: SocketService) { } ngOnInit() { this.subs.push( this.socketService.getInitialData().subscribe((data: ServerResponse) => { this.localData = data.prods; }) ); this.subs.push( this.socketService.getUpdatedData().subscribe((data: ServerResponse) => { this.localData = data.prods; }) ); } ngOnDestroy() { this.subs.forEach(s => s.unsubscribe()); } } interface ServerResponse { prods: any[]; type?: string; }
I just iterate over localData to display the table.
My ideal outcome would be to have the one websocket with multiple endpoints. I just don't know how to handle this with mySQL events.
Similarly if I had 2 completely separate websockets I'm unsure how to handle that on the angular side.
-
The entity type was not found. Ensure that the entity type has been added to the model
I'm new to ASP.NET Core and i'm trying to insert an entity into an Entity Framework Core model scaffolded from a simple existing MariaDB database.
This is the entity model:
public class ScrapeAsincroni { public int Id { get; set; } public string Paese { get; set; } public string Engine { get; set; } public string Keywords { get; set; } }
This is the controller action that is supposed to add the entity:
public JsonResult create(string paese, string engine, string keywords) { ScrapeAsincroni scrapeAsincrono = new ScrapeAsincroni { Paese = paese, Engine = engine, Keywords = keywords }; _context.Add(scrapeAsincrono); try { _context.SaveChangesAsync(); } catch (Exception ex) { return Json(new Dictionary<string, int?> { { "id", null } }); } return Json(new Dictionary<string, int?>{ {"id", scrapeAsincrono.Id} }); }
The database context (_context) has been initialized on the controller's constructor. the line
_context.Add(scrapeAsincrono);
throws the following exception:
System.InvalidOperationException: The entity type 'ScrapeAsincroni' was not found. Ensure that the entity type has been added to the model.
This is the modelBuilder code relative to this model
public partial class ScraperDbContext : DbContext { public ScraperDbContext() { } public ScraperDbContext(DbContextOptions<ScraperDbContext> options) : base(options) { } public virtual DbSet<ScrapeAsincroni> ScrapeAsincroni { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { #warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings. optionsBuilder.UseMySql("server=51.255.74.100;port=3306;user=luca.ceccagnoli;password=Hb93#2ql;database=scraper_db", x => x.ServerVersion("10.3.25-mariadb")); } } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<ScrapeAsincroni>(entity => { entity.HasComment("Informazioni su una ricerca asincrona dello Scraper"); entity.Property(e => e.Id) .HasColumnName("id") .HasColumnType("int(11)"); entity.Property(e => e.Engine) .HasColumnName("engine") .HasColumnType("varchar(255)") .HasCharSet("utf8") .HasCollation("utf8_general_ci"); entity.Property(e => e.Keywords) .IsRequired() .HasColumnName("keywords") .HasColumnType("text") .HasCharSet("utf8") .HasCollation("utf8_general_ci"); entity.Property(e => e.Paese) .HasColumnName("paese") .HasColumnType("varchar(255)") .HasCharSet("utf8") .HasCollation("utf8_general_ci"); }); OnModelCreatingPartial(modelBuilder); } partial void OnModelCreatingPartial(ModelBuilder modelBuilder); }
I can't seem to understand why this happens, and couldn't find any solutions online.
-
Unique Id for .Net Core actions
I need to have an ID for my actions to save them in DB and retrieve them for security issues. I thought this is a unique and constant Id but it is different in every run:
var items = _actionDescriptorCollectionProvider .ActionDescriptors.Items .OfType<ControllerActionDescriptor>() .Select(a => new { a.ControllerName, a.ActionName, a.Id })
Any idea for a unique and fixed ID for each action?
-
Why is my Blazor date input type not working properly?
I am trying to create a page with a date picker, but I cannot get the Blazor to work properly. This is what I have going on:
Page.razor:
<div> <label for="from">From</label> <input id="from" type="date" @bind="fromDate" /> </div> @code { private DateTime fromDate; }
However, when I run the project the date field reads
01/01/0001
and I cannot click into the box to edit the fields; I can, though, tab to the fields to edit them. When I click the calendar icon, it brings up the date picker starting at year0001
and I am forced to scroll to 2021.When I remove the
@bind="fromDate"
tag, the date picker widget works properly, but I, obviously, cannot retrieve the date for use.I don't want to bind this to a model, I just want to grab the
DateTime
and manipulate it within my@code{}
block.
EDIT:
I am also using Bootstrap 5.x, but that shouldn't really make a difference.
EDIT #2:
I removed the Bootstrap modifiers from that
input
and it still doesn't work, so Bootstrap is not the issue. -
Access variable from a Blazor component
is it possible to get access to variables from another component in Blazor? In this case /Shared/client.razor.cs needs to get to access to var_1-var_3 in /source.razor.
/source.razor
... @code { [Parameter] public string var_1 { get; set; } [Parameter] public string var_2 { get; set; } [Parameter] public string var_3 { get; set; } }
-
Microsoft.JSInterop.JSRuntime.InvokeWithDefaultCancellation Error, What Happens?
we are new in using both Blazor and AmChart4. We add data every few second to our series and we would like to let run our application for few hours.
Usually after a couple of hours of running we get the following exception:
A task was canceled. at Microsoft.JSInterop.JSRuntime.InvokeWithDefaultCancellation[T](String identifier, Object[] args) at Microsoft.JSInterop.JSRuntimeExtensions.InvokeVoidAsync(IJSRuntime jsRuntime, String identifier, Object[] args) at amCharts.Pages.Index.CountDownTimer(Object source, ElapsedEventArgs e) in D:\ProgettiBlazor\amCharts_V3\amCharts\Pages\Index.razor:line 97
Does anyone have any suggestion on how to prevent this problem?
In a File.blazor ther is a thread that run every 5 seconds calling this function: '''
public async void CountDownTimer(Object source, System.Timers.ElapsedEventArgs e) { try { counter += 1; writeLog(string.Format("CountDownTimer {0} ", counter)); await JS.InvokeVoidAsync("AggiungiPunti_Random"); await InvokeAsync(StateHasChanged); } catch (Exception ex) { writeLog(string.Format("CountDownTimer - eccezione: {0} {1}", ex.Message, ex.StackTrace)); } }
''' From a File js we have:
''' function AggiungiPunti_Random() {
am4core.ready(function () { var dati = generateChartData_Random(new Date()); chart.addData(dati); });
} '''
Where generate data random creates an object with date and few values.
-
Blazor WASM Standalone Debug stopped working
I've been developing blazor wasm apps in vscode for the past few months without incident. All of a sudden, I can't debug via F5 any longer. I'm literally starting with a brand new app (dotnet new blazorwasm) and when I hit F5 I get the following error:
I've uninstalled/reinstalled vscode, chrome, updated .net core 5, tried Edge put things into my launch and launchsettings.json that have helped others and plenty of other things things that I can't recall. Even created a new account on my computer to eliminate possible plugins or settings, same problem.
One thing that does work is that I can debug the old way where I would run Chrome from the command line: open /Applications/Google\ Chrome.app --args --remote-debugging-port=9222
Then you can hit Cmd+Shift+D in Chrome to start debugging within Chrome. This is a stop gap, but I'd really like to figure out how/why this just stopped working.
I created repo that reproduces it on my machine.
I'm not finding a lot of ways to gather diagnostic details that might help me determine the cause, so would appreciate any tips that would help me solve this.
Using latest chrome and vscode, even tried the insider build. No luck. I'm not sure what I did or how to fix it. Any help is greatly appreciated!
-
Why I'm getting Runtime error when upgrading Hosted Wasm Blazor App to .Net 5
I'm getting this runtime error after I upgraded a Hosted Wasm from .Net Core 3.1 to .Net 5. Can anyone help ?
untimeError: table index is out of bounds at do_debugger_tramp (<anonymous>:wasm-function[3306]:0x79e2e) at interp_exec_method (<anonymous>:wasm-function[2155]:0x5103b) at interp_runtime_invoke (<anonymous>:wasm-function[7862]:0x12efff) at mono_jit_runtime_invoke (<anonymous>:wasm-function[7347]:0x118e5f) at do_runtime_invoke (<anonymous>:wasm-function[3304]:0x79d42) at mono_runtime_invoke_checked (<anonymous>:wasm-function[493]:0xf65d) at mono_runtime_try_invoke_array (<anonymous>:wasm-function[7114]:0x10e831) at ves_icall_InternalInvoke (<anonymous>:wasm-function[6226]:0xed492) at ves_icall_InternalInvoke_raw (<anonymous>:wasm-function[6225]:0xecf57) at do_icall (<anonymous>:wasm-function[10596]:0x194ddb) d.printErr @ blazor.webassembly.js:1 (anonymous) @ blazor.webassembly.js:1 Promise.catch (async) (anonymous) @ blazor.webassembly.js:1 n @ blazor.webassembly.js:1 (anonymous) @ blazor.webassembly.js:1 (anonymous) @ blazor.webassembly.js:1
-
Add health check for Nginx in docker file
I have a
WebAssmebly Blazor
App that runs locally, I deploy it to Azure K8s cluster using Helm,The app pod keeps restarting when I checked the logs its complaining about health check that are missing
[21/Apr/2021:11:23:55 +0000] "GET /health/liveness HTTP/1.1" 404 153 "-" "kube-probe/1.17" "-" 2021/04/21 11:23:55 [error] 31#31: *3 open() "/usr/share/nginx/html/health/liveness" failed (2: No such file or directory), client: 10.244.0.1, server: localhost, request: "GET /health/liveness HTTP/1.1", host: "10.244.0.230:80"
Since
WebAssmebly Blazor
runs on the client side, a health isnt needed.So, Im trying to write some static health check at Nginx level.
This is the docker file:
FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build WORKDIR /source FROM build AS publish WORKDIR /source/app.CustomerApplication/ RUN dotnet publish -c release FROM nginx AS runtime COPY --from=publish /source/app.CustomerApplication/bin/release/netstandard2.1/publish/wwwroot/. /usr/share/nginx/html/. COPY ./app.CustomerApplication/nginx.conf /etc/nginx/nginx.conf RUN rm /etc/nginx/conf.d/default.conf
and Nginx config file:
server { location / { root /usr/share/nginx/html; } location //health/liveness { return 200 'alive'; add_header Content-Type text/plain; } }
I keep getting this error
cust-app /docker-entrypoint.sh: Configuration complete; ready for start up cust-app | 2021/04/20 23:56:16 [emerg] 1#1: unknown directive "server" in /etc/nginx/nginx.conf:1 cust-app | nginx: [emerg] unknown directive "server" in /etc/nginx/nginx.conf:1