Full Trust European Hosting

BLOG about Full Trust Hosting and Its Technology - Dedicated to European Windows Hosting Customer

Node.js Hosting - HostForLIFE :: .Net Core Vs Node

clock February 15, 2023 09:18 by author Peter

.NET Core and Node.js are two popular technologies for building APIs (Application Programming Interfaces). Both have their strengths and weaknesses, and the choice between them depends on the specific requirements of a project.

.NET Core is a cross-platform, open-source framework for building modern applications. It is developed by Microsoft and is part of the .NET ecosystem. .NET Core is based on C#, a statically-typed language. It supports LINQ (Language Integrated Query) and Entity Framework, making it easier to query data. .NET Core also provides a strong security model, built-in support for WebSockets, and the ability to run on Windows, Linux, and macOS.

Node.js, on the other hand, is an open-source, cross-platform JavaScript runtime environment. It is event-driven and non-blocking, making it highly efficient for real-time applications. Node.js has a vast and growing ecosystem, with numerous packages and tools available for a variety of purposes, including building APIs.

When it comes to building APIs, .NET Core is a good choice if you're looking for a framework with a strong security model, good performance, and the ability to handle large amounts of data. .NET Core is also a good choice if you're already familiar with C# and the .NET ecosystem, as this will reduce the learning curve.

Node.js, on the other hand, is a good choice if you're looking for a fast and efficient API that can handle real-time data and can be scaled horizontally. Node.js is also a good choice if you're already familiar with JavaScript and the Node.js ecosystem, as this will reduce the learning curve.

Similarities between .Net Core and Node

Despite their differences, .NET Core and Node.js have some similarities as well. Here are some of the most notable similarities between the two technologies:

Cross-platform compatibility
Both .NET Core and Node.js are cross-platform technologies, which means that they can run on multiple operating systems, including Windows, Linux, and macOS.

Open-source

Both .NET Core and Node.js are open-source technologies, which means that their source code is available for anyone to use, modify, or contribute to.

Large and active communities
Both .NET Core and Node.js have large and active communities of developers, which means that there is a wealth of knowledge, tools, and resources available for these technologies.

Fast and efficient

Both .NET Core and Node.js are designed to be fast and efficient, making them well-suited for building high-performance applications, including APIs.

Support for modern web technologies
Both .NET Core and Node.js support modern web technologies, such as REST and WebSockets, making it easy to build modern, scalable APIs.

Difference between .Net Core and Node

While .NET Core and Node.js have some similarities, they also have some notable differences that make them well-suited for different types of projects. Here are some of the most important differences between the two technologies,

Language
.NET Core is based on C#, a statically-typed language, while Node.js is based on JavaScript, a dynamically-typed language. This can impact the development experience and the performance of the resulting application.

Performance

.NET Core is generally considered to be a more performant framework, especially for applications that require handling large amounts of data. Node.js, on the other hand, is designed for real-time, event-driven applications and is highly efficient for these types of applications.

Ecosystem
.NET Core is part of the .NET ecosystem, which includes a large number of libraries, tools, and frameworks for building applications. Node.js has a growing and vibrant ecosystem of its own, with a large number of packages and tools available for a wide range of purposes.

Security
.NET Core provides a strong security model, with built-in support for authentication, authorization, and encryption. Node.js, while secure, does not provide the same level of security features out-of-the-box as .NET Core.

Scalability
Node.js is designed to be highly scalable, with the ability to run multiple instances of the application on multiple machines to handle increased traffic. .NET Core also supports scalability, but it may require additional work to achieve the same level of scalability as Node.js.

.NET Core and Node.js are both powerful technologies for building APIs, but they have some important differences that make them well-suited for different types of projects. The choice between the two will depend on the specific requirements of a project, including the desired performance, security, scalability, and skills of the development team.

In conclusion, despite the differences between .NET Core and Node.js, the two technologies have some similarities, including cross-platform compatibility, open-source nature, large and active communities, fast and efficient performance, and support for modern web technologies.

Conclusion

In conclusion, the choice between .NET Core and Node.js depends on the specific requirements of a project. .NET Core is a good choice for projects that require a strong security model and good performance, while Node.js is a good choice for projects that require real-time data and scalability. Before making a choice, it is important to consider the specific requirements of a project and the skills of the development team.

Thanks for reading my article.



AngularJS Hosting Europe - HostForLIFE :: Component Communication In Angular

clock February 14, 2023 07:32 by author Peter

In this article, we will discuss two important decorators that we use to send data from one component to another or send data from child to parent component or vice-versa.


For a better understanding, we take one example: we will send data from the parent component to the child component using the input decorator and then send data from the child component to the parent component using the output decorator.

Let’s start with the input decorator
@Input

Input decorator is used to send data from parent to child component.

Let’s start with a practical demo
    First, create an angular application and one child component inside the newly created application.
    Import input decorator from the angular core package.
    Next, add one property with some messages which need to pass the child component.

import { Component } from '@angular/core';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    title = 'demo';
    parentMessage: string = "Hello from parent component..";
}


After that, add the same property to the child component selector.
<nav class="navbar navbar-light bg-light" style="padding: 30px;margin: 40px; justify-content:center">
  <span class="navbar-brand mb-0 h1">Angular Component Communication</span>
</nav>

<app-child [parentMessageData]="parentMessage"></app-child>
<div class="divider"><div>

Here, we pass the newly created property by the parent app component inside the child component selector and the syntax is like first need to mention the child component property in the square bracket which gets the data, and in double quote parent component property.

After that, inside the child component, we just receive that message using the input decorator as shown in below and display the same inside the child template.
import { Component, EventEmitter, Input, Output } from '@angular/core';

@Component({
    selector: 'app-child',
    templateUrl: './child.component.html',
    styleUrls: ['./child.component.css']
})
export class ChildComponent {
    @Input() parentMessageData: string = "";
}

Finally, display the message by parent inside the template using string interpolation
<div class="alert alert-secondary" role="alert" style="padding: 30px;margin: 40px;">
    <h3>Child Component</h3>
    <h5>{{parentMessageData}}</h5>
</div>


The output decorator is used to send data from the child component to the parent component.

Component Communication in Angular
The property with output decorator is initialized with an event emitter that flows event data from the child to the parent component.
The type of output decorator should be an event emitter and here we pass a string with an event emitter which indicates the event is stored string type of data.
import { Component, EventEmitter, Input, Output } from '@angular/core';
@Component({
    selector: 'app-child',
    templateUrl: './child.component.html',
    styleUrls: ['./child.component.css']
})
export class ChildComponent {
    @Output() childMessage: EventEmitter < string > = new EventEmitter < string > ();
    dataHandler() {
        this.childMessage.emit("Hello from child component....")
    }
}


The child component raises an event so the parent component knows some things are changed by a child component and received the event.

For the output decorator, first, we create one button inside the child component and that will create one event and one handler function to emit that event.
<div class="alert alert-secondary" role="alert" style="padding: 30px;margin: 40px;">
    <h3>Child Component</h3>
    <button (click)="dataHandler()">Send Data To Parent Component</button>
</div>


After that, in the parent component template and inside the child component selector we bind the parent method with the child component event.
<nav class="navbar navbar-light bg-light" style="padding: 30px;margin: 40px; justify-content:center">
  <span class="navbar-brand mb-0 h1">Angular Component Communication</span>
</nav>
<div class="alert alert-primary" role="alert" style="padding: 30px;margin: 40px;">
  <h3>Parent Component:</h3>
  <h5>{{childMessage}}</h5>
</div>
<app-child (childMessage)="GetMessage($event)"></app-child>
<div class="divider"><div>


Next, create one function which handles the event and store them inside a new property in the parent component.
import { Component } from '@angular/core';

@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {
    title = 'demo';
    childMessage: string = "";
    GetMessage(res: any) {
        this.childMessage = res;
    }
}


Basically, the child component notifies the parent component about the newly generated event.

Let’s run the application,

Here as we can see in the above image, the message is displayed inside the child component section which is sent by the parent with the help of the input decorator.
Below the message, there is one button that generates one event and in the TS file, the event emitter emits the same and sends a notification to the parent and after that, the event message is displayed in the parent component section as shown in the below image.

This is all about input and output decorators.



AngularJS Hosting Europe - HostForLIFE :: File Download In Angular

clock February 9, 2023 07:01 by author Peter

In this article, I will introduce how to download a file in Angular with a button click and show an example. For this article, I have created an Angular project using Angular 12. For creating an Angular project, we need to follow the following steps:


Create an Angular Project
Let's create a new angular project by using the following command.
ng new fileDownloadExample

Open a project in Visual Studio Code using the following commands.
cd fileDownloadExample
Code .

Now in Visual Studio, your project looks as below.

App.Component.html
<a [href]="fileUrl" download="file.txt">DownloadFile</a>

App.Component.ts
import { Component, OnInit } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
    name = 'Angular 5';
    fileUrl;
    constructor(private sanitizer: DomSanitizer) {}
    ngOnInit() {
        const data = 'some text';
        const blob = new Blob([data], {
            type: 'application/octet-stream'
        });
        this.fileUrl = this.sanitizer.bypassSecurityTrustResourceUrl(window.URL.createObjectURL(blob));
    }
}

Now Run the project using the following command
npm start

and click on the link and you will see the downloaded file

 



AngularJS Hosting Europe - HostForLIFE :: How To Implement Lazy Loading In Angular?

clock January 31, 2023 07:38 by author Peter

This article explains one of the key concepts in Angular - Lazy Loading. By going through this article, we will understand:
    What is Lazy Loading in Angular?
    When Lazy Loading is useful?
    How to Lazy Load a Component in Angular?


What is Lazy Loading in Angular?
Lazy loading in Angular refers to the ability to load components as needed, rather than loading all components at once during the initial application load.

Lazy loading modules helps us decrease the start-up time as Application does not need to load everything at start-up and modules that are lazily loaded will only be loaded when the user navigates to their routes.

The following image represents the resulting build artifacts between default loading vs Lazy loading of some of the features:

Using Lazy loading, some of the feature modules (feature-n) are separated into different chunks, and these are only loaded if the user navigates to that specific route.

When Lazy Loading is useful?
When NgModule launches the angular application, it loads all the components and modules which are declared within, due to this application start up time will be increased and this will impact on the performance of our application.
Lazy loading is useful in Angular when an application has many components, and not all of them are needed for the initial load of the application.

By only loading the necessary components as they are needed, lazy loading can help improve the performance of an Angular application in several ways:
    Reducing the initial load time of the application by loading only the necessary components.
    Reducing the overall size of the main.js file by splitting the application bundle into smaller chunks.
    Increase the modularity of the applications.
    Improving the user experience by loading the components which are needed for the initial views only.
    It’s allowing developers to break up the application into smaller, more manageable chunks, making the development, and maintenance easier.

How to Lazy Load a Component in Angular?

To implement lazy loading in an Angular application, we can use the Angular Router module, which allows us to specify a component to load lazily by using the "loadChildren" property in the route configuration.

Here's an example demonstration of how we can implement lazy loading for a component.

Step 1 - Create a new module and a component
Create a new module you want to load lazily, in this case, "AdminModule" and created component called "Home" inside admin module.

Step 2 - Define and Import Router module in Lazy Load module
In the "AdminModule" module, import the component you want to load lazily and add it to the "declarations" and "imports" arrays of the module. When registering routes in sub-modules and lazy loaded submodules then we need to use forChild(routes) as follows.

In the declarations, add the component that you want to load lazily.

Step 3 - Import the Angular Router module and configure the route
In the routing module of your application, import the Angular Router module and configure the route for the " AdminModule" component to be loaded lazily.

Step 4 - Verify lazy loading in Browser
Angular will load the module and component on demand when a specific route is activated in the browser. We can verify from the Network tab that a module is indeed being lazy loaded.

Lazy loading is a technique that allows angular components to load asynchronously when a specific route is activated and useful for angular applications with a large number of components, where not all of them are needed for the initial load of the application, to improve the overall performance, load time and user experience.

Happy Learning!



AngularJS Hosting Europe - HostForLIFE :: Understanding @Input(), @Ouput() And @ViewChild() In Angular

clock January 26, 2023 06:32 by author Peter

This article demonstrates how to share data between components using @Input(), @Output(), and @ViewChild().


In Angular, @Input() and @Output() are decorators that allow a component to share data with its parent or child components, respectively. @ViewChild() is a decorator that allows a component to access a child component, directive, or DOM element.

Understanding the use of @Input()
@Input() allows a component to receive data from its parent component. For example, a child component might use @Input() to receive data from its parent component like this:

Here, whenever I added a new entry as "Add Customer", the updated information is passed to the child component (e.g. Customer Table) and the child is acting as a term component. And the parent is acting like smart component.


customer-add.component acts as a Parent Component
In this example, the parent component contains Add customer sections and a sub-component like a customer table. When we click on Add Customer that information being passed to the child component (customers table) and displayed on the table.


customer-table.component acts as a Child Component,

In the above example, the parent component uses the @Input() decorator to bind the "customers" property to a value passed from the parent component.

And the child component uses the @Input() decorator to receive the value passed from the parent component.

So, @Input() decorator is used to pass the data from the parent to the child component with help of property.
Understanding the use of @Output()

@Output() allows a component to emit events to its parent component. For example, a child component might use @Output() to emit an event when a button is clicked like this:

In the above example, whenever we select data from the customer table which acts as a child, that data should pass to the customer’s name textbox which acts as the parent. It’s basically sending data from child to parent. To do that, we need to expose an event with an output decorator.

 

@Output() decorator to listen for an event emitted by the child component, which is then handled in the parent component.


So, @Ouput() decorator is used to pass the data from child to parent with the help of the event.
Understanding the use of @ViewChild()

@ViewChild() allows a component to access a child component or DOM element. For example, a parent component might use @ViewChild() to access a child component like this:

In order to use the @ViewChild() decorator, we need to reference the child component in the parent component's class, and then we can use to query the child component's properties and methods or manipulate the DOM directly.

Another example where @ViewChild() can be used to access the DOM element as like below:

In summary, ViewChild is used to access child components or elements in the template, while @Input and @Output are used to pass data between components. If you need to access a specific child component or element in the template, ViewChild will be more useful, while if you need to pass data between components, @Input and @Output will be more useful.



AngularJS Hosting Europe - HostForLIFE :: How to use Virtual Scrolling using Angular CDK?

clock January 17, 2023 07:09 by author Peter

Sometimes while working with web-based Angular applications you might find yourself in a situation where you need to render thousands of records inside a list. However, rendering that many records directly in the DOM can be a memory-expensive operation and can lead to performance issues or even can cause lag while scrolling through the list.


However, the Angular CDK library, fortunately, comes bundled with a feature called Virtual Scrolling that can be used to fix this issue. This component only the number of records that can fit in the viewport i.e. is visible to the user. And keeps changing the records as the user starts scrolling through the list. This feature was introduced with Angular CDK version 7.

Let's understand this technique in detail with an example.

First, create a dead simple Angular application using Angular CLI.
ng new sample

next, install the Angular CDK package either with Angular CLI or npm.
ng add @angular/cdk

or,

npm install @angular/cdk

Now first inside the app.component.ts file let's generate 500,000 rows and try to render it without the virtual scroll feature.

To generate an array we'll simply use the Array.from method.
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  rows: string[] = Array.from(Array(500000)).map((_, i) => `Row #${i}`);
}

Next, we'll try to render the rows in the template.
<div class="box">
  <div class="row" *ngFor="let row of rows">{{ row }}</div>
</div>


We'll also add some styling to the CSS file of this template.
.box {
  height: 250px;
  width: 250px;
  border: 1px solid #e3e3e3;
  overflow: scroll;
}
.row {
  height: 50px;
}


Immediately you'll notice that it is taking a while to render that many rows. And if you try to inspect the element you'll notice that the browser is literally rendering 500,000 rows in the DOM.

Now, let's do the same thing using the Virtual Scrolling technique.

First, we need to import the ScrollingModule inside the AppModule and add it to the imports array.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ScrollingModule } from '@angular/cdk/scrolling';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    ScrollingModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Importing this module gives us access to cdk-virtual-scroll-viewport components and the cdkVirtualFor directive which we'll be using to implement the virtual scroll strategy.
<cdk-virtual-scroll-viewport itemSize="50" class="box">
  <div class="row" *cdkVirtualFor="let row of rows">
    {{ row }}
  </div>
</cdk-virtual-scroll-viewport>


we're using cdkVirtualFor instead of the ngFor loop to iterate over the rows and itemSize is simply the height of individual elements which in our case is 50px (see the styling for .row class).

As soon as you complete the above implementation you'll notice the rendering time is reduced next to none, and if you inspect the DOM element you'll notice that component has rendered a very limited number of elements and it simply replaces existing rows with new rows as the user scrolls through the list.

 



AngularJS Hosting Europe - HostForLIFE :: Convert Byte Array Into PDF And Open It Inside Custom Dialog box In Angular

clock January 13, 2023 06:41 by author Peter

Mostly on the internet, you can find how to open PDF via window.open(“”) Javascript way.

So what is here?
Well, opening PDF in a separate window is available but is not in our custom control, especially in Angular.

So here we will open this PDF inside our custom dialog (in our control) and can do event firing on the closing of POP up for further business requirements.

Prerequisite(not mandatory)
I am using a ready-made dialog box from prime-ng <p-dialog> control.
But that is not required you can use any material bootstrap or custom div even. This is just to showcase because behind the scene the logic is the same.

Opening PDF In Angular
Opening PDF inside a dialog can be done in a few ways. The Idea/concept behind this is we need to get elementID from DOM and attach our PDF to its inner body. Using below ways
    Using <a href =”url”>.
    Using the same anchor tag by dynamic code and click it.
    Using <iframe/> and appending to DOM body.
    Using .getElementById(“”) and binding to its innerHTML.


Problem
Many times you use “ElementRef, Renderer2” packages which we generally use but you get errors like this:

a. Use @Viewchild()

Alternate Solution
b. Use @inject(document)

Steps
Step 1. Inject the document in the constructor and import it from the library like this.
@Inject(DOCUMENT) private document: Document

Import Library
import { DOCUMENT } from '@angular/common';

Step 2. Use it like this, here I am creating DOM <Frame> element and binding it to Element ID where I want it to display behind the HTML side

Ts Code

Html code

Step 3. It should open like this when you open it inside HTML similar can be done in dialog or popup container:

In Main Body

In POP up

Attachment
Full project will not help as Angular has many packages, so I am giving this simple JavaScript version POC used for angular application. Kindly refer to angular code screenshots (typescript version for reference)

Client-Side coding with a new framework is always fun, Let me know if you have any queries.



Node.js Hosting - HostForLIFE.eu :: How To Setup A Express.js Project?

clock January 6, 2023 06:36 by author Peter

Express.js is one of the most popular frameworks for building web applications using Node.js. It provides features that make creating a robust and scalable web application easy. This step-by-step guide will go over all the steps for setting up an Express.js project from scratch.

Installation is pretty straightforward. Before we get started, you will need to have Node.js installed on your system. You can download the latest version of Node.js from the official website. Once installation is complete, you can run the following commands to verify if Node.js and npm are working correctly on your computer.
npm -v

node -v

You're good to go if you see the versions of Node.js and npm in the command line.

Initializing the project
Let's start by creating a new directory for your project and navigate to it:
mkdir my-express-project
cd my-express-project

Next, initialize the Node.js project by running the following command:
npm init -y

This will create a package.json file in your project directory. The package.json file stores metadata about your project, including the dependencies it needs to run. the -y parameter is used to skip the questionnaire altogether. It'll implicitly set yes to all the questions during the npm init command.

Installing Express.js
To install Express.js, run the following command:
npm install express

This will install Express.js and add it as a dependency in your package.json file.

Creating an entry point for the application
Next, we'll create an entry point for your application. This file will be run when you start the application. First, let's create an src directory in the root of our application and then create a file called index.js inside the src folder and add the following code inside that file:
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
    res.send('Hello Express!');
});
app.listen(port, () => {
    console.log(`App is running on port ${port}`);
});

The above code creates an instance of an Express.js app and sets up a route that listens for GET requests to the app's root path (/). When a request is received, it sends a response with the message "Hello Express!". The application is also set to listen on port 3000.

Adding start script
Next, open your package.json file and add look for scripts section. In this section, add the following script.
"scripts": {
  "start": "node src/index.js"
},

Starting the app

Now from the root of your application, run the following command
npm start

This will start the app, and you should see the message "App is running on port 3000" in the console.
To test the app, open your web browser and navigate to http://localhost:3000. You should see the message "Hello Express!" displayed in the browser.

And That's it! I hope you found this article enjoyable. If you've any queries or feedback, feel free to comment.



AngularJS Hosting Europe - HostForLIFE :: How To Create A Download Progress Bar With Angular And Material Design?

clock December 20, 2022 07:03 by author Peter

To create a download progress bar with a percentage in Angular, you can use the HttpClient module to request a server and track the download's progress. Here is an example of how this can be done,
    First, install the @angular/material and @angular/cdk packages in your Angular project:
    npm install @angular/material @angular/cdk


Import the MatProgressBarModule and MatProgressSpinnerModule modules from the @angular/material package in your Angular module:
import { MatProgressBarModule, MatProgressSpinnerModule } from '@angular/material';

@NgModule({
  imports: [
    MatProgressBarModule,
    MatProgressSpinnerModule
  ],
  // ...
})
export class AppModule { }


Now, import the HttpClient module and the HttpEventType enum from the @angular/common/http package:
import { HttpClient, HttpEventType } from '@angular/common/http';

Inject the HttpClient service into your component or service using the constructor:
constructor(private http: HttpClient) {}

Create a function to make the download request and track the progress:
public percentDone: number = 0;

public downloadFile() {
  this.http.get('https://example.com/file.zip', { responseType: 'blob' })
    .subscribe(event => {
      if (event.type === HttpEventType.DownloadProgress) {
        // Update the progress bar with the download percentage
        const this.percentDone = Math.round(100 * event.loaded / event.total);
        console.log(`Downloaded ${this.percentDone}%`);
      } else if (event.type === HttpEventType.Response) {
        // Save the downloaded file
        const file = new Blob([event.body], { type: 'application/zip' });
        const fileURL = URL.createObjectURL(file);
        window.open(fileURL);
      }
    });
}


In your component's template, use the mat-progress-bar and mat-progress-spinner components to display the progress bar and percentage:
<mat-progress-bar mode="determinate" [value]="percentDone"></mat-progress-bar>
<mat-progress-spinner mode="determinate" [value]="percentDone"></mat-progress-spinner>
<p>{{percentDone}}%</p>

You can use the percentDone property to bind to the value attribute of the mat-progress-bar and mat-progress-spinner components, as well as to display the percentage as text.

This is an example of how you can create a material design download progress bar with a percentage in Angular. You can customize the appearance and behaviour of the progress bar and percentage by using the various options and styles available for the mat-progress-bar and mat-progress-spinner components.



European Entity Framework Hosting - HostForLIFE :: Get Started With Entity Framework Core Using SQLite

clock December 14, 2022 06:38 by author Peter

In my previous article Simple Way To Create Sqlite Database, I talked about the choice of the database and I focused on the simplest one which is Sqlite. But even if we choose the right one, we still need to work on the design and on its integration in the application side.


The old way of doing things was to use a database driver in your application, define the connexion and then execute the SQL command and queries from your code. When you get the data from the query execution, you need to parse them and then insert them to your objects. And this was a heavy task.

Later in time appeared Object-Relational Mapping. The ORM.

The ORM is the object-relational Mapping Tool. To make it simple, it's a tool that helps you to translate your database tables to a class Model in your application and vice versa. It also provides you with the methods to perform all the CRUD operation

The approach of creating the database then generating the class model is called Database First. The approach of creating the model in your application and then generating the database is called Code First.

In this article, we will focus on the database first part.

Entity Framework
Entity framework is the most commonly used ORM in .NET projects. It doesn't only allow you to access the database from your application. But also it also simplifies your life by giving you advanced possibilities like managing the concurrency and configuring your model. It has also the advantage of the use of the Language Integrated Query LINQ which is a powerful tool to perform your queries and filters.

Step 1: Nuget packages
    Create a new console project in visual studio.
    Open the commad line: Go to Tools => NuGet Package Manager => Package Manager Console and then you will get the command line displayed in your editor.

Install the required libraries by executing the following commands :

    PM>  Install-Package Microsoft.EntityFrameworkCore.Tools
    PM> install-Package Microsoft.EntityFrameworkCore.Sqlite
    Once you installed all packages you should have the following references in your solution

Step 2: Model generation

    To generate the model, you need to use also the command line
    You need to copy the needed database to your project folder and choose the right mode of copy to output directory:



Now you can generate your classes using the following command. You need to specify the output path, in our case it will be the folder Models
Scaffold-DbContext "Data Source=.\Database\products.db" Microsoft.EntityFrameworkCore.Sqlite -OutputDir Models
if everything is ok, you should get the classes generated under the folder Models and the following message in the package manager console should appear

The warning is there because the generator hardcoded the database's connection string in the code. You need to consider moving it in a protected way to a configuration file. But let's ignore it because it's not the main topic of this article.

Step 3: Check your generated classes
Now you should have the Context that contains the model creation and for each table you will get a class. In our case we have only one entity.

The Context class,
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore;
namespace EntityFrameworkDbFirst.Models;
public partial class ProductsContext: DbContext {
    public ProductsContext() {}
    public ProductsContext(DbContextOptions < ProductsContext > options): base(options) {}
    public virtual DbSet < Item > Items {
        get;
        set;
    }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    #warning To protect potentially sensitive information in your connection string, you should move it out of source code.You can avoid scaffolding the connection string by using the Name = syntax to read it from configuration - see https: //go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
        => optionsBuilder.UseSqlite("Data Source=.\\Database\\products.db");
    protected override void OnModelCreating(ModelBuilder modelBuilder) {
        modelBuilder.Entity < Item > (entity => {
            entity.HasKey(e => e.Barcode);
            entity.Property(e => e.Barcode).HasColumnType("VARCHAR");
            entity.Property(e => e.Brand).HasColumnType("VARCHAR");
            entity.Property(e => e.Name).HasColumnType("VARCHAR");
            entity.Property(e => e.PruchasePrice).HasColumnType("DOUBLE");
            entity.Property(e => e.SellingPrice).HasColumnType("DOUBLE");
        });
        OnModelCreatingPartial(modelBuilder);
    }
    partial void OnModelCreatingPartial(ModelBuilder modelBuilder);
}


The class Item,
using System;
using System.Collections.Generic;
namespace EntityFrameworkDbFirst.Models;
public partial class Item {
    public string Barcode {
        get;
        set;
    } = null!;
    public string ? Name {
        get;
        set;
    }
    public string ? Brand {
        get;
        set;
    }
    public double ? PruchasePrice {
        get;
        set;
    }
    public double ? SellingPrice {
        get;
        set;
    }
}

Step 4: Write your cruds
Once you have created your model, you can now start performing operations on it. The following code in program.cs allows to add / update or delete an item.
You can test it and then see the results in the database directly.

It's a simple call to every method of the crud. You can play with it by changing the data and adding more controls.
For example if you call the AddItem twice without modifying it you will get an exception related to the constraint of the primary key
// See https://aka.ms/new-console-template for more information
using EntityFrameworkDbFirst.Models;
using System.Runtime.CompilerServices;
using static System.Net.Mime.MediaTypeNames;
using System.Xml.Linq;
try {
    Item item = new Item() {
        Barcode = "B12345678",
            Brand = "Milky Way",
            Name = "Milk",
            PruchasePrice = 20.5,
            SellingPrice = 25.5
    };
    // Uncomment this line if you want to test the delete method
    //DeleteItem("B12345678");
    AddItem(item);
    ////Uncomment this line if you want to test the update method
    //item.SellingPrice = 30;
    //UpdateItem(item);
    Console.WriteLine("Everything is Ok !");
} catch (Exception e) {
    Console.WriteLine(e.Message);
    if (e.InnerException != null) Console.WriteLine(e.InnerException.Message);
}
void AddItem(Item item) {
    using(var db = new ProductsContext()) {
        db.Items.Add(item);
        db.SaveChanges();
    }
}
//Delete the item
void DeleteItem(string Barcode) {
    using(var db = new ProductsContext()) {
        var item = db.Items.Find(Barcode);
        if (item == null) return;
        db.Items.Remove(item);
        db.SaveChanges();
    }
}
//Update the price of the item
void UpdateItem(Item item) {
    using(var db = new ProductsContext()) {
        db.Items.Update(item);
        db.SaveChanges();
    }
}


Step 4: And finally check your database
If you remember, we have set the property of the database in the solution explorer to "Copy if newer" so the file products.db is copied to the binary folder.
Open the database and browse your file then you will see the inserted item. Ensure that you left at least one product after testing the add and the delete



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Tag cloud

Sign in