VintaSoft Barcode .NET SDK 12.5 for Web
In This Topic
    Recognize barcodes in image in ASP.NET Core application with React.js and Redux
    In This Topic
    This tutorial shows how to create a blank ASP.NET Core Web application in Visual Studio .NET 2019 and
    recognize barcodes in image in ASP.NET Core application with React.js and Redux.

    Here are steps, which must be done:
    1. Create a blank ASP.NET Core Web application.

      Open Visual Studio .NET 2019 and create a new project, of ASP.NET Core Web application type:
      Open Visual Studio .NET 2019 and create a new project, of ASP.NET Core Web Application type
      Select the "React.js and Redux" template for ASP.NET Core Web application and configure the project to use ASP.NET Core 3.1:
      Select the React template for ASP.NET Core Web Application and configure the project to use ASP.NET Core 3.1
    2. Server side: Add references to the Vintasoft assemblies to ASP.NET Core Web application.

      Add references to the Vintasoft.Barcode.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 v12.5\Bin\DotNetCore3\AnyCPU\" folder in ASP.NET Core Web application.

      Add references to the Vintasoft assemblies
    3. Server side: Add Web API controller that allows to recognize barcodes.

      • Press the right mouse button on the "Controllers" folder and select the "Add => Controller..." menu from context menu
        Select 'Add => Controller' context menu for 'Controllers' folder
      • Select Empty API controller template, set the controller name to the "MyVintasoftBarcodeApiController" and press the "Add" button
        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
        Source codes of Barcode API controller
        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)
                {
                }
        
            }
        }
        
    4. Server side: Add Newtonsoft JSON for deserialization of barcode recognition results.

      Add reference to the Microsoft.AspNetCore.Mvc.NewtonsoftJson nuget-package:
      Add reference to the Microsoft.AspNetCore.Mvc.NewtonsoftJson nuget-package

      Open the "Startup.cs" file and add code line "services.AddControllersWithViews().AddNewtonsoftJson();" at the beginning of ConfigureServices method. This is necessary for correct deserialization of barcode recognition results.
      Add Newtonsoft JSON deserialization for barcode recognition results
      Here are source codes of Startup.ConfigureServices method:
      // This method gets called by the runtime. Use this method to add services to the container.
      public void ConfigureServices(IServiceCollection services)
      {
          services.AddControllersWithViews().AddNewtonsoftJson();
      
          // In production, the Angular files will be served from this directory
          services.AddSpaStaticFiles(configuration =>
          {
              configuration.RootPath = "ClientApp/dist";
          });
      }
      
    5. Compile the project for restoring dependencies using 'npm'.

    6. Client side: Delete code and files, which are not necessary in this demo.

      • Delete files "ClientApp\src\components\Counter.tsx", "ClientApp\src\components\FetchData.tsx", "ClientApp\src\components\Home.rsx", "ClientApp\src\components\NavMenu.tsx", "ClientApp\src\components\NavMenu.css", "ClientApp\src\store\Counter.ts", "ClientApp\src\store\WeatherForecasts.ts" - these files 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\components\Layout.tsx" and delete lines "import NavMenu from './NavMenu';" and "<NavMenu/>" - this demo does not need navigation menu.

      • Open file "ClientApp\src\store\index.ts" and delete lines: "import * as WeatherForecasts from './WeatherForecasts';", "import * as Counter from './Counter';", "counter: Counter.CounterState | undefined;", "weatherForecasts: WeatherForecasts.WeatherForecastsState | undefined;", "counter: Counter.reducer," and "weatherForecasts: WeatherForecasts.reducer" - this demo does not use these components.

      • Open file "ClientApp\src\App.tsx" and delete code that uses the following React components: Home, FetchData, Counter - these React components are not necessary in this demo.
        Here are source codes of "App.tsx" file after update:
        import * as React from 'react';
        import { Route } from 'react-router';
        import Layout from './components/Layout';
        
        import './custom.css'
        
        export default () => (
            <Layout>
            </Layout>
        );
        
    7. Client side: Add JavaScript and TypeScript files to the ASP.NET Core Web application.

      • Copy jQuery (version 3 or higher) file into "ClientApp\public\" folder.
        You can use jquery-3.4.1.min.js file from "<InstallPath>\VintaSoft Barcode .NET v12.5\Examples\ASP.NET MVC\CSharp\AspNetMvcBarcodeDemo\Scripts\External\" folder or jQuery (version 3 or higher) file from any other source.

        Copy Vintasoft.Shared.js and Vintasoft.Barcode.js files from "<InstallPath>\VintaSoft Barcode .NET v12.5\Bin\JavaScript\" folder into the "ClientApp\public\" folder.

        Add references to Vintasoft JavaScript files
      • Copy Vintasoft.Shared.d.ts and Vintasoft.Barcode.d.ts files from "<InstallPath>\VintaSoft Barcode .NET v12.5\Bin\JavaScript\" folder into the "ClientApp\src\store\" folder.

        Add references to Vintasoft TypeScript files
      • Add references to jQuery and Vintasoft JavaScript files to the header of "ClientApp\public\index.html" file:
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="utf-8">
            <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
            <meta name="theme-color" content="#000000">
            <base href="%PUBLIC_URL%/" />
            <!--
              manifest.json provides metadata used when your web app is added to the
              homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
        -->
            <link rel="manifest" href="%PUBLIC_URL%/manifest.json">
            <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
            <!--
              Notice the use of %PUBLIC_URL% in the tags above.
              It will be replaced with the URL of the `public` folder during the build.
              Only files inside the `public` folder can be referenced from the HTML.
        
              Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
              work correctly both with client-side routing and a non-root public URL.
              Learn how to configure a non-root public URL by running `npm run build`.
        -->
        
            <script src="jquery-3.4.1.min.js" type="text/javascript"></script>
            <script src="Vintasoft.Shared.js" type="text/javascript"></script>
            <script src="Vintasoft.Barcode.js" type="text/javascript"></script>
        
            <title>WebApplication1</title>
        </head>
          <body>
            <noscript>
              You need to enable JavaScript to run this app.
            </noscript>
            <div id="root"></div>
            <!--
              This HTML file is a template.
              If you open it directly in the browser, you will see an empty page.
        
              You can add webfonts, meta tags, or analytics to this file.
              The build step will place the bundled scripts into the <body> tag.
        
              To begin the development, run `npm start` or `yarn start`.
              To create a production bundle, use `npm run build` or `yarn build`.
        -->
          </body>
        </html>
        

        Add references to jQuery and Vintasoft JavaScript files to the header of index.html file
    8. Client side: Create React.js component that recognizes barcodes and displays barcode recognition result.

      • Create folder "wwwroot\UploadedImageFiles\SessionID" and copy image file with barcodes "<InstallPath>VintaSoft\Barcode .NET v12.5\Images\AllSupportedBarcodes.png" to the folder. We will recognize barcodes in this image.

      • Create "BarcodeReaderDemo.tsx" file that will contain source codes of React.js component (BarcodeReaderDemo class):
        • Select "Add => New Item..." context menu for folder "ClientApp\src\components\" => "Add new item" dialog will appear
        • Select "TypeScript JSX File" type for new item
        • Set "BarcodeReaderDemo.tsx" as element name
        • Click the "Add" button => dialog will be closed and file "BarcodeReaderDemo.tsx" will be added into folder "ClientApp\src\components\"

        Add BarcodeReaderDemo class declaration with 'render' function (renders demo header and div element that will display barcode recognition result) to the "BarcodeReaderDemo.tsx" file:
        BarcodeReaderDemo React.js component with 'render' function

        Add 'componentDidMount' function (contains TypeScript code that recognizes barcodes and displays barcode recognition result) to the BarcodeReaderDemo class:
        BarcodeReaderDemo React.js component with 'componentDidMount' function

        Here is TypeScript code of React.js component (BarcodeReaderDemo class):
        import React, { Component } from 'react';
        import { connect } from 'react-redux';
        
        export class BarcodeReaderDemo extends Component {
        
            render() {
                return (
                    <div>
                        <h1>React.js+Redux Barcode Reader Demo</h1>
        
                        <div id="barcodeInformation" ></div>
                    </div>
                );
            }
        
            componentDidMount() {
                // 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: any) {
                // show information about error
                alert(data.errorMessage);
            }
        
        }
        
        export default connect()(BarcodeReaderDemo);
        
      • Add created React.js component to the React.js application code - "ClientApp\src\App.tsx" file.
        Add created React.js component to the React.js application

        Here are source codes of "App.tsx" file after update:
        import * as React from 'react';
        import { Route } from 'react-router';
        import Layout from './components/Layout';
        import BarcodeReaderDemo from './components/BarcodeReaderDemo';
        
        import './custom.css'
        
        export default () => (
            <Layout>
                <Route exact path='/' component={BarcodeReaderDemo} />
            </Layout>
        );
        
    9. Run the ASP.NET Core Web application with React.js+Redux and see the result.

      Barcode recognition result in ASP.NET Core Web application with React.js and Redux