Recognize barcodes in image in ASP.NET Core application with Angular
In This Topic
This tutorial shows how to create a blank ASP.NET Core Web application in Visual Studio .NET 2022 and recognize barcodes in image in ASP.NET Core application with Angular.
Here are steps, which must be done:
-
Create a blank ASP.NET Core Web application.
Open Visual Studio .NET 2022 and create a new project, of ASP.NET Core with Angular application type:
Configure the project to use .NET 8.0:
-
Server side: Add references to the Vintasoft assemblies to ASP.NET Core Web application.
Add references to the Vintasoft.Barcode.dll, Vintasoft.Barcode.SkiaSharp.dll, Vintasoft.Shared.dll, Vintasoft.Shared.Web.dll, Vintasoft.Barcode.Web.Services.dll and Vintasoft.Barcode.AspNetCore.ApiControllers.dll assemblies from "<InstallPath>\VintaSoft Barcode .NET v15.1\Bin\DotNet8\AnyCPU\" folder in ASP.NET Core Web application.
-
Server side: Create web service for barcode recognition.
-
Press the right mouse button on the "Controllers" folder and select the "Add => Controller..." menu from context menu
-
Select Empty API controller template, set the controller name to the "MyVintasoftBarcodeApiController" and press the "Add" button
-
Specify that MyVintasoftBarcodeApiController class is derived from Vintasoft.Barcode.AspNetCore.ApiControllers.VintasoftBarcodeApiController class
Here are source codes of MyVintasoftBarcodeApiController class:
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Vintasoft.Barcode.AspNetCore.ApiControllers;
namespace WebApplication1.Controllers
{
public class MyVintasoftBarcodeApiController : VintasoftBarcodeApiController
{
public MyVintasoftBarcodeApiController(IWebHostEnvironment hostingEnvironment)
: base(hostingEnvironment)
{
}
}
}
-
Server side: Add Newtonsoft JSON for deserialization of barcode recognition results.
Add reference to the Microsoft.AspNetCore.Mvc.NewtonsoftJson nuget-package:
Open the "Program.cs" file and add code line "services.AddControllersWithViews().AddNewtonsoftJson();". This is necessary for correct deserialization of barcode recognition results.
Here are source codes of Program.cs:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews().AddNewtonsoftJson();
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
app.MapFallbackToFile("index.html");
app.Run();
Compile the project for restoring dependencies using 'npm'.
-
Client side: Delete files, which are not necessary in this demo.
Delete directories "ClientApp\src\app\counter\", "ClientApp\src\app\fetch-data\", "ClientApp\src\app\home\", "ClientApp\src\app\nav-menu\" - these Angular components are not necessary in this demo.
Delete files "WeatherForecast.cs" and "Controllers\WeatherForecastController.cs" - the WeatherForecast Web API controller is not necessary in this demo.
Open file "ClientApp\src\app\app.component.html" and delete line "<app-nav-menu></app-nav-menu>" from HTML markup - this demo does not need navigation menu.
Open file "ClientApp\src\app\app.module.ts" and delete code that uses the following Angular components: NavMenuComponent, HomeComponent, CounterComponent, FetchDataComponent - these Angular components are not necessary in this demo.
Here are source codes of "app.module.ts" file after update:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
HttpClientModule,
FormsModule,
RouterModule.forRoot([
])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
-
Client side: Add JavaScript files and TypeScript modules to the ASP.NET Core Web application.
Add the "assets" folder to the "ClientApp\src\app\" folder.
Copy Vintasoft.Shared.js, Vintasoft.Shared.d.ts, Vintasoft.Barcode.js and Vintasoft.Barcode.d.ts files from "<InstallPath>\VintaSoft Barcode .NET v15.1\Bin\JavaScript\" folder to the "ClientApp\src\app\assets\" folder.
Set "Build Action" to the "TypeScript file" for Vintasoft.Shared.d.ts and Vintasoft.Barcode.d.ts files:
Add references to Vintasoft JavaScript files to the "projects => Demo => architect => build => options => scripts" section in "ClientApp\angular.json" file:
...
"scripts": [
"src/app/assets/Vintasoft.Shared.js",
"src/app/assets/Vintasoft.Barcode.js"
]
...
-
Client side: Create Angular component that recognizes barcodes in image.
-
Create folder "wwwroot\UploadedImageFiles\SessionID" and copy image file with barcodes "<InstallPath>VintaSoft\Barcode .NET v15.1\Images\AllSupportedBarcodes.png" to the folder. We will recognize barcodes in this image.
Create folder "ClientApp\src\app\barcode-reader-demo\".
Create "barcode-reader-demo.component.html" file that will contain HTML markup of Angular component:
- Select "Add => New Item..." context menu for folder "ClientApp\src\app\barcode-reader-demo\" => "Add new item" dialog will appear
- Select "HTML Page" type for new item
- Set "barcode-reader-demo.component.html" as element name
- Click the "Add" button => dialog will be closed and file "barcode-reader-demo.component.html" will be added into folder "ClientApp\src\app\barcode-reader-demo\"
Add HTML markup (demo header and image element that will display barcode recognition result) to the "barcode-reader-demo.component.html" file:
<h1>Angular Barcode Reader Demo</h1>
<div id="barcodeInformation" ></div>
Create "barcode-reader-demo.component.ts" file that will contain code of Angular component:
- Select "Add => New Item..." context menu for folder "ClientApp\src\app\barcode-reader-demo\" => "Add new item" dialog will appear
- Select "TypeScript File" type for new item
- Set "barcode-reader-demo.component.ts" as element name
- Click the "Add" button => dialog will be closed and file "barcode-reader-demo.component.ts" will be added into folder "ClientApp\src\app\barcode-reader-demo\"
Add TypeScript code to the "barcode-reader-demo.component.cs" file:
import { Component } from '@angular/core';
@Component({
selector: 'barcode-reader-demo',
templateUrl: './barcode-reader-demo.component.html'
})
export class BarcodeReaderDemoComponent {
ngOnInit() {
// set the session identifier
Vintasoft.Shared.WebImagingEnviromentJS.set_SessionId("SessionID");
// create service that allows to recognize barcodes
let barcodeService: Vintasoft.Shared.WebServiceControllerJS = new Vintasoft.Shared.WebServiceControllerJS("vintasoft/api/MyVintasoftBarcodeApi");
// create the barcode reader
let barcodeReader: Vintasoft.Barcode.WebBarcodeReaderJS = new Vintasoft.Barcode.WebBarcodeReaderJS(barcodeService);
// specify that Code39 barcode must be searched
barcodeReader.get_Settings().set_BarcodeType(new Vintasoft.Barcode.WebBarcodeTypeEnumJS("Code39"));
// create web image that references to a file "AllSupportedBarcodes.png" in directory "/UploadedImageFiles/SessionID/"
let imageSource: Vintasoft.Shared.WebImageSourceJS = new Vintasoft.Shared.WebImageSourceJS("AllSupportedBarcodes.png");
let image: Vintasoft.Shared.WebImageJS = new Vintasoft.Shared.WebImageJS(imageSource, 0);
// send an asynchronous request for barcode recognition
barcodeReader.readBarcodes(image, this.__readBarcodes_success, this.__readBarcodes_fail);
}
/**
* Barcodes are recognized successfully.
* @param {object} data Object with information about recognized barcodes.
*/
private __readBarcodes_success(data: Vintasoft.Barcode.WebBarcodeReadResponseParamsJS) {
if (data.success) {
// get the barcode recognition result
let barcodeRecognitionResults: Vintasoft.Barcode.WebBarcodeRecognitionResultJS[] = data.results;
let htmlMarkup: string = '';
// if no barcodes found
if (barcodeRecognitionResults.length == 0) {
htmlMarkup = 'No barcodes found.';
}
// if barcodes are found
else {
htmlMarkup = barcodeRecognitionResults.length.toString() + ' barcodes are found.<br />';
htmlMarkup += '<br />';
// for each recognized barcode
for (let i: number = 0; i < barcodeRecognitionResults.length; i++) {
// get the barcode recognition result
let barcodeRecognitionResult: Vintasoft.Barcode.WebBarcodeRecognitionResultJS = barcodeRecognitionResults[i];
// output information about recognized barcode
htmlMarkup += '[' + (i + 1) + ':' + barcodeRecognitionResult.barcodeType + ']<br />';
htmlMarkup += ' Value: ' + barcodeRecognitionResult.value + '<br />';
htmlMarkup += ' Confidence: ' + barcodeRecognitionResult.confidence + '<br />';
htmlMarkup += ' Reading quality: ' + barcodeRecognitionResult.readingQuality.toFixed(2) + '<br />';
htmlMarkup += ' Threshold: ' + barcodeRecognitionResult.threshold + '<br />';
htmlMarkup += ' Region: ' +
'LT=(' + barcodeRecognitionResult.region.leftTop.x + ',' + barcodeRecognitionResult.region.leftTop.y + '); ' +
'RT=(' + barcodeRecognitionResult.region.rightTop.x + ',' + barcodeRecognitionResult.region.rightTop.y + '); ' +
'LB=(' + barcodeRecognitionResult.region.leftBottom.x + ',' + barcodeRecognitionResult.region.leftBottom.y + '); ' +
'RB=(' + barcodeRecognitionResult.region.rightBottom.x + ',' + barcodeRecognitionResult.region.rightBottom.y + '); ' +
'Angle=' + barcodeRecognitionResult.region.angle.toFixed(1) + '°<br />';
htmlMarkup += '<br />';
}
}
let barcodeInformationElement: HTMLDivElement = document.getElementById("barcodeInformation") as HTMLDivElement;
barcodeInformationElement.innerHTML = htmlMarkup;
}
}
/**
* Barcode recognition is failed.
* @param {object} data Object with information about error.
*/
private __readBarcodes_fail(data) {
// show information about error
alert(data.errorMessage);
}
}
-
Add created Angular component to the Angular application module - "ClientApp\src\app\app.module.ts" file.
Here are source codes of "app.module.ts" file after update:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { BarcodeReaderDemoComponent } from './barcode-reader-demo/barcode-reader-demo.component';
@NgModule({
declarations: [
AppComponent,
BarcodeReaderDemoComponent
],
imports: [
BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
HttpClientModule,
FormsModule,
RouterModule.forRoot([
{ path: '', component: BarcodeReaderDemoComponent, pathMatch: 'full' },
])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
-
Run the ASP.NET Core Web application with Angular and see the result.