Full Trust European Hosting

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

AngularJS Hosting Europe - HostForLIFE :: Using Route-Based Angular to Dynamically Highlight the Active Menu Item

clock July 8, 2024 10:08 by author Peter

Angular's built-in Router module can be used to dynamically highlight the active menu item in an Angular application based on the current path. You can now apply a class to the active link as a result.


Here's how to accomplish it.

First, import the RouterModule

Ensure that your Angular module—typically app.module.ts—has the RouterModule set.

import { RouterModule } from '@angular/router';
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Step 2. Update your HTML
Use the routerLinkActive directive to dynamically apply a class to the active menu item. Here’s how you can update your navigation HTML.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Navbar Example</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
  <style>
    .navbar-nav .nav-item a {
      color: black;
      text-decoration: none;
    }
    .navbar-nav .nav-item a:hover {
      color: #0056b3; /* Optional: Change color on hover */
    }
    .navbar-nav .home-link i {
      color: blue;
    }
    .active-link {
      color: blue !important; /* Customize the active link color */
    }
  </style>
</head>
<body>

<section class="wrapper megamenu-wraper">
  <div class="">
    <nav class="container navbar navbar-expand-lg main-menu">
      <div class="">
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
          <ul class="navbar-nav mr-auto">
            <li class="nav-item">
              <a routerLink="/private/po" routerLinkActive="active-link" class="home-link active">
                <i class="fa fa-home"></i>
              </a>
            </li>
            <li class="nav-item">
              <a routerLink="dashboard" routerLinkActive="active-link">Dashboard</a>
            </li>
            <li class="nav-item">
              <a routerLink="default" routerLinkActive="active-link">Student List</a>
            </li>
            <li class="nav-item">
              <a routerLink="camps" routerLinkActive="active-link">Activities</a>
            </li>
            <li class="nav-item">
              <a routerLink="camp-attendence" routerLinkActive="active-link">Attendance</a>
            </li>
            <li class="nav-item">
              <a [routerLink]="['/private/po/actvity-camp', 0]" routerLinkActive="active-link">Create Activity</a>
            </li>
          </ul>
        </div>
      </div>
    </nav>
  </div>
</section>

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
</body>
</html>


Explanation
routerLinkActive Directive: This directive applies the specified class (active-link in this case) to the link that matches the current route.
routerLink Directive: This binds the link to the router path.
CSS: The active-link class is styled to indicate the active state.

Step 3. Ensure router module configuration
Make sure your Angular router is correctly configured in your application module (usually app-routing.module.ts).
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { DashboardComponent } from './dashboard/dashboard.component';
import { StudentListComponent } from './student-list/student-list.component';
import { ActivitiesComponent } from './activities/activities.component';
import { AttendanceComponent } from './attendance/attendance.component';
import { CreateActivityComponent } from './create-activity/create-activity.component';
const routes: Routes = [
  { path: 'dashboard', component: DashboardComponent },
  { path: 'default', component: StudentListComponent },
  { path: 'camps', component: ActivitiesComponent },
  { path: 'camp-attendence', component: AttendanceComponent },
  { path: 'private/po/actvity-camp/:id', component: CreateActivityComponent },
  { path: '**', redirectTo: 'dashboard', pathMatch: 'full' }
];
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

This setup ensures that when you navigate through your app, the active link will be highlighted, providing a better user experience.



AngularJS Hosting Europe - HostForLIFE :: Dependency Injection System in Angular 18

clock July 4, 2024 07:59 by author Peter

There are many of fascinating new features and enhancements in Angular 18. A notable improvement is the revamped Dependency Injection (DI) framework. Managing the dependencies of components and services is essential to creating scalable and maintainable applications using Angular's DI paradigm. To experience the new DI features in Angular 18, let's explore them in detail and work through an example.

What's New in the DI System of Angular 18?

  • Enhanced Tree-Shakability: Angular 18 makes sure that the final bundle contains only the code that is required. Smaller, more effective applications result from this.
  • Injection Contexts: With the introduction of new injection contexts, developers now have greater power and flexibility in defining and managing various dependency injection contexts.
  • Provider Scopes: Enhancing resource management and efficiency, this new feature gives you more precise control over the lifecycle of dependencies.
  • Simplified Provider Syntax: In Angular 18, a more understandable and maintainable syntax for declaring providers is introduced.

Using the New Dependency Injection Features in Angular 18 as an Example
Let's create a basic Angular 18 application to showcase these latest features in DI. We'll build a service, integrate it with a component, and investigate the recently added DI features.

First Step: Configuring the Angular 18 Project

First, use the Angular CLI to create a new Angular 18 project.

Step 1. Setting Up the Angular 18 Project
First, set up a new Angular 18 project using the Angular CLI
ng new angular18-di-demo
cd angular18-di-demo


Step 2. Creating a Service
We'll create a new service to provide some data to our component. Run the following command to generate the service:
ng generate service data

Open data.service.ts and implement the service like this:
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class DataService {
  private data = ['Angular 18', 'Dependency Injection', 'New Features'];

  constructor() {}

  getData(): string[] {
    return this.data;
  }
}

Here, the @Injectable decorator with providedIn: 'root' makes this service available throughout the application.

Step 3. Creating a Component
Next, we'll create a component to display the data provided by DataService. Run the following command.
ng generate component data-display

Open data-display.component.ts and inject DataService.
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
  selector: 'app-data-display',
  templateUrl: './data-display.component.html',
  styleUrls: ['./data-display.component.css']
})
export class DataDisplayComponent implements OnInit {
  data: string[] = [];

  constructor(private dataService: DataService) {}

  ngOnInit(): void {
    this.data = this.dataService.getData();
  }
}

In this component, we inject DataService in the constructor and use it to fetch data in the ngOnInit lifecycle hook.

Step 4. Displaying the Data

Open data-display.component.html and update the template to display the data:
<div>
  <h2>Data from DataService</h2>
  <ul>
    <li *ngFor="let item of data">{{ item }}</li>
  </ul>
</div>

Step 5. Using the Component
Include the DataDisplayComponent in your main application component. Open app.component.html and add the following.
<app-data-display></app-data-display>

Step 6. Running the Application
Run the application using the Angular CLI.

ng serve

Navigate to http://localhost:4200 in your browser. You should see the data displayed from DataService.

Summary

In this article, we've explored the new Dependency Injection features in Angular 18. By creating a simple service and component, we've seen how to use DI in Angular 18. The enhancements in the DI system, such as improved tree-shakability, injection contexts, provider scopes, and simplified syntax, make managing dependencies in Angular applications easier and more efficient. These features will help you maintain a clean and scalable codebase as you build more complex applications.



AngularJS Hosting Europe - HostForLIFE :: Apply Dynamically Changing Filters to Kendo Grid in Angular

clock June 26, 2024 07:59 by author Peter

You may use the built-in features of the Kendo Grid in conjunction with Angular's component lifecycle hooks to apply dynamic filters in a Kendo Grid based on the data type of each column. Here's how you can make this happen.


Install the required packages
Make sure the Angular Grid package's Kendo UI is installed.

npm install @progress/kendo-angular-grid \
            @progress/kendo-angular-inputs \
            @progress/kendo-angular-l10n \
            @progress/kendo-angular-dateinputs \
            @progress/kendo-angular-dropdowns --save


Import Kendo Modules
Import the necessary Kendo UI modules into your Angular module.
import { GridModule } from '@progress/kendo-angular-grid';
import { DateInputsModule } from '@progress/kendo-angular-dateinputs';
import { InputsModule } from '@progress/kendo-angular-inputs';
import { DropDownsModule } from '@progress/kendo-angular-dropdowns';
@NgModule({
  imports: [
    GridModule,
    DateInputsModule,
    InputsModule,
    DropDownsModule
    // other imports
  ],
  // other configurations
})
export class AppModule {}


Define the grid in your component template
Create the Kendo Grid in your component template and bind it to a data source.
<kendo-grid [data]="gridData" [filterable]="true">
  <kendo-grid-column *ngFor="let column of columns"
                     [field]="column.field"
                     [title]="column.title"
                     [filter]="getFilterType(column)">
  </kendo-grid-column>
</kendo-grid>


Determine the filter type dynamically
In your component, write a method to return the filter type based on the column's data type.
import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-dynamic-filter-grid',
  templateUrl: './dynamic-filter-grid.component.html',
  styleUrls: ['./dynamic-filter-grid.component.css']
})
export class DynamicFilterGridComponent implements OnInit {
  public gridData: any[] = [
    { name: 'John', age: 30, birthday: new Date(1990, 1, 1) },
    { name: 'Jane', age: 25, birthday: new Date(1995, 2, 1) },
    // more data
  ];

  public columns: any[] = [
    { field: 'name', title: 'Name', type: 'string' },
    { field: 'age', title: 'Age', type: 'number' },
    { field: 'birthday', title: 'Birthday', type: 'date' }
  ];
  constructor() { }
  ngOnInit(): void { }
  getFilterType(column: any): string {
    switch (column.type) {
      case 'date':
        return 'date';
      case 'number':
        return 'numeric';
      default:
        return 'text';
    }
  }
}


Add the component template

In your component HTML file, use the Kendo Grid and call the dynamic filter method.
<kendo-grid [data]="gridData" [filterable]="true">
  <kendo-grid-column *ngFor="let column of columns"
                     [field]="column.field"
                     [title]="column.title"
                     [filter]="getFilterType(column)">
  </kendo-grid-column>
</kendo-grid>


Conclusion
With these steps, your Kendo Grid will apply filters dynamically based on the data type of each column.



European Node.js Hosting - HostForLIFE :: How to Automate MySQL Database Updates with Cron Jobs in Node.js?

clock June 14, 2024 09:17 by author Peter

Automating repetitive operations is essential for streamlining workflows and increasing productivity in the digital age. An in-depth tutorial on using Node.js and cron jobs to automate MySQL database updates can be found in "How to Automate MySQL Database Updates with Cron Jobs in Node.js: A Step-by-Step Guide".

This article offers developers a workable method for putting scheduled activities into practice, guaranteeing accurate and timely data changes without the need for manual intervention. This book gives you the tools to efficiently use automation, regardless of your level of experience. Whether you're a newbie hoping to improve your backend programming skills or an experienced developer wishing to streamline database administration operations, this guide will help you. Together, let's set out on this path to effective database automation.

Steps for creating a project
Step 1. Setting Up the Project

Use my previous article for setting up Node.js, "How to upload file in Node.js" In this article, we mentioned important commands for uploading files in Node.js.

Step 2. Install the necessary dependencies (mysql2 and node-cron)
npm install mysql2 node-cron

Step 3. Setting Up the Server
Create the Server File. Create a file named app.js.
const cron = require('node-cron');
const mysql = require('mysql2');

// Create a connection to the MySQL database
const connection = mysql.createConnection({
   host: 'localhost',
  user: 'your_mysql_username',
  password: 'your_mysql_password',
  database: 'your_database_name'
});

// Function to update the MySQL database
const updateDatabase = () => {
  const sql = 'UPDATE users SET last_notification = CURRENT_TIMESTAMP';

  connection.query(sql, (err, result) => {
    if (err) {
      console.error('Error updating database:', err);
      return;
    }
    console.log('Database updated:', result.affectedRows, 'row(s) affected');
  });
};

// Schedule a cron job to update the database every minute
cron.schedule('* * * * *', () => {
  console.log('Scheduling database update...');
  updateDatabase();
}, {
  scheduled: true,
  timezone: 'America/New_York'
});

Step 4. Create a table in the database
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    last_notification TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

Step 5. Insert some value manually in the Database

INSERT INTO users (name, last_notification) VALUES
('John Doe', NOW()),
('Jane Smith', NOW());

Step 6. Running the Application
Run the command in CMD.
node app.js

Output

illustrates seamless database management automation. Post-execution, the tutorial ensures continuous updates to the "last_notification" column every minute, facilitating efficient data maintenance and enhancing productivity. Experience streamlined database automation with this comprehensive guide.

Conclusion

The automation of MySQL database updates using Node.js and cron jobs offers significant advantages in streamlining workflows. By implementing the techniques outlined in this guide, developers can ensure continuous and timely updates to their databases, minimizing manual intervention and maximizing efficiency. Embrace the power of automation to unlock greater productivity and reliability in database management.

HostForLIFE.eu Node.js Hosting
HostForLIFE.eu 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 customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.

 

 

 



AngularJS Hosting Europe - HostForLIFE :: Using Entity Framework to Begin With HTTP Client Get Request in Angular 8

clock June 6, 2024 08:53 by author Peter

In this post, I'll explain how to use the HttpClient module in Angular 8 to consume RESfFul API and how to use the entity framework to get requests. Requests for GET, POST, PUT, PATCH, and DELETE are handled by the HttpClient module. HTTP can be used by an Angular application to communicate with backend services.

RxJs observable-based API is available with Angular HTTP. When an HTTP request is unsuccessful, Observable generates an error.

Note: I won't go over the CRUD process in this post. This article aims to clarify things for newcomers.

Step 1. Create tables in the database
Consider the simple example of employees in a hotel. We will show the name & email ID of the employee in a hotel on the view in the last step of this article.

I am going to create one database & will add the table with some values. Use the below script for more information. Note that you can create a database structure as per your requirements.

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Employee](
    [Id] [int] IDENTITY(1,1) NOT NULL,
      NULL,
      NULL,
      NULL,
    CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
    (
        [Id] ASC
    ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[Employee] ON
INSERT [dbo].[Employee] ([Id], [Name], [Email], [Password]) VALUES (1, N'Rupesh', N'[email protected]', N'123')
INSERT [dbo].[Employee] ([Id], [Name], [Email], [Password]) VALUES (2, N'Ashish', N'[email protected]', N'123')
INSERT [dbo].[Employee] ([Id], [Name], [Email], [Password]) VALUES (3, N'Sam', N'[email protected]', N'123')
INSERT [dbo].[Employee] ([Id], [Name], [Email], [Password]) VALUES (4, N'Ajit', N'[email protected]', N'123')
SET IDENTITY_INSERT [dbo].[Employee] OFF

Step 2: Establish a Web Application
First, we'll use Visual Studio to construct a WebAPI application. Navigate to File => New => Project after opening Visual Studio. Open a new project, choose an empty ASP.NET + WebAPI project from the template, and give it a name.

In our project, create the entity data model (.edmx) file by right-clicking on the solution, selecting Add, then New Item, and then choosing ADO.NET Entity Data Model from the Visual C# installed template in Data. Give it a name.

Create a web API controller by using the Entity framework. Use the Web API controller with REST actions to perform a CRUD operation from the entity framework context.

Give our controller a name. From the drop-down, choose the name of the context class.

We need to enable the CORS attribute on the above controller level as per the below syntax. CORS stands for Cross-Origin Resource Sharing. For more information refer to this article.
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class EmployeesController : ApiController
{
    // Our CRUD operation code here
}

The whole controller code is as shown below.
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class EmployeesController : ApiController
{
    private HotelEntities db = new HotelEntities();
    // GET: api/Employees
    public List<Employee> GetAllEmployees()
    {
        return db.Employees.ToList();
    }
    // GET: api/Employees/5
    [ResponseType(typeof(Employee))]
    public IHttpActionResult GetEmployee(int id)
    {
        Employee employee = db.Employees.Find(id);
        if (employee == null)
        {
            return NotFound();
        }
        return Ok(employee);
    }
    // PUT: api/Employees/5
    [ResponseType(typeof(void))]
    public IHttpActionResult PutEmployee(int id, Employee employee)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        if (id != employee.Id)
        {
            return BadRequest();
        }
        db.Entry(employee).State = EntityState.Modified;
        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!EmployeeExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }
        return StatusCode(HttpStatusCode.NoContent);
    }
    // POST: api/Employees
    [ResponseType(typeof(Employee))]
    public IHttpActionResult PostEmployee(Employee employee)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        db.Employees.Add(employee);
        db.SaveChanges();
        return CreatedAtRoute("DefaultApi", new { id = employee.Id }, employee);
    }
    // DELETE: api/Employees/5
    [ResponseType(typeof(Employee))]
    public IHttpActionResult DeleteEmployee(int id)
    {
        Employee employee = db.Employees.Find(id);
        if (employee == null)
        {
            return NotFound();
        }
        db.Employees.Remove(employee);
        db.SaveChanges();

        return Ok(employee);
    }
    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
    private bool EmployeeExists(int id)
    {
        return db.Employees.Count(e => e.Id == id) > 0;
    }
}

Step 3. To create an Angular Project

Create a new service in our Angular application using syntax & create a company service.
ng g service our_service_name

Now we will write code to get the data from our API in the service i.e. company.service.ts file contains the below code.
Note. Do not use a direct URL link in the typescript file anyone can easily hack it. For demo purposes, I have used it.

The below code contains the file company.service.ts.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Company } from '../Model/company';

@Injectable({
  providedIn: 'root'
})
export class CompanyService {

  constructor(private http: HttpClient) { }

  getData() {
    return this.http.get("http://localhost:8012/api/Employees");
  }
}

In the above code, CompanyService is a class that contains our getData method that returns a result from API from where we are getting a record using a GET request, API/Employees (which is written in the API project). We can also host our API project & add that URL as well.

Step 4. Create a new component in our angular project
Now create a new component in our angular project using syntax & create the my-company component.
ng g c componentName


The below code contains the file my-company.component.html.
<p>Angular 8 using Web API !!!</p>

<div>
  <table class="gridList">
    <tr>
      <th>User Names</th>
      <th>Email</th>
    </tr>
    <tr *ngFor="let item of companyList">
      <td>{{ item.Name }}</td>
      <td>{{ item.Email }}</td>
    </tr>
  </table>
</div>


In the above code, we have used ngFor to iterate the loop. companyList is a variable in which we will get the data from our services refer to the below steps.

The below code contains the file my-company.component .ts
import { BrowserModule, Title } from '@angular/platform-browser';
import { Component, OnInit, ViewChild } from '@angular/core';
import { CompanyService } from '../../service/company.service';
@Component({
  selector: 'app-my-company',
  templateUrl: './my-company.component.html',
  styleUrls: ['./my-company.component.css']
})
export class MyCompanyComponent implements OnInit {
  companyList: any;
  constructor(private companyService: CompanyService) { }
  ngOnInit() {
    this.getData();
  }
  getData() {
    this.companyService.getData().subscribe(
      data => {
        this.companyList = data;
      }
    );
  }
}


In the above code, we have imported the company service. In the OnInit method, we will declare one variable company list & will assign the data that is returned by our method getData() from service.

Here, subscribe is used to send the list.

Step 5. Loading the company component in app.component.html

Now, to load our company component, we will add a selector in the app.component.html file.
<app-my-company></app-my-company>
<app-my-company></app-my-company>


Step 6. To run the Angular application

To run the Angular application, use the below syntax.
ng serve -o



AngularJS Hosting Europe - HostForLIFE :: Using Entity Framework to Begin With HTTP Client Get Request in Angular 8

clock June 6, 2024 08:53 by author Peter

In this post, I'll explain how to use the HttpClient module in Angular 8 to consume RESfFul API and how to use the entity framework to get requests. Requests for GET, POST, PUT, PATCH, and DELETE are handled by the HttpClient module. HTTP can be used by an Angular application to communicate with backend services.


RxJs observable-based API is available with Angular HTTP. When an HTTP request is unsuccessful, Observable generates an error.

Note: I won't go over the CRUD process in this post. This article aims to clarify things for newcomers.

Step 1. Create tables in the database
Consider the simple example of employees in a hotel. We will show the name & email ID of the employee in a hotel on the view in the last step of this article.

I am going to create one database & will add the table with some values. Use the below script for more information. Note that you can create a database structure as per your requirements.

GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Employee](
    [Id] [int] IDENTITY(1,1) NOT NULL,
      NULL,
      NULL,
      NULL,
    CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED
    (
        [Id] ASC
    ) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[Employee] ON
INSERT [dbo].[Employee] ([Id], [Name], [Email], [Password]) VALUES (1, N'Rupesh', N'[email protected]', N'123')
INSERT [dbo].[Employee] ([Id], [Name], [Email], [Password]) VALUES (2, N'Ashish', N'[email protected]', N'123')
INSERT [dbo].[Employee] ([Id], [Name], [Email], [Password]) VALUES (3, N'Sam', N'[email protected]', N'123')
INSERT [dbo].[Employee] ([Id], [Name], [Email], [Password]) VALUES (4, N'Ajit', N'[email protected]', N'123')
SET IDENTITY_INSERT [dbo].[Employee] OFF

Step 2: Establish a Web Application
First, we'll use Visual Studio to construct a WebAPI application. Navigate to File => New => Project after opening Visual Studio. Open a new project, choose an empty ASP.NET + WebAPI project from the template, and give it a name.

In our project, create the entity data model (.edmx) file by right-clicking on the solution, selecting Add, then New Item, and then choosing ADO.NET Entity Data Model from the Visual C# installed template in Data. Give it a name.

Create a web API controller by using the Entity framework. Use the Web API controller with REST actions to perform a CRUD operation from the entity framework context.

Give our controller a name. From the drop-down, choose the name of the context class.

We need to enable the CORS attribute on the above controller level as per the below syntax. CORS stands for Cross-Origin Resource Sharing. For more information refer to this article.
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class EmployeesController : ApiController
{
    // Our CRUD operation code here
}

The whole controller code is as shown below.
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class EmployeesController : ApiController
{
    private HotelEntities db = new HotelEntities();
    // GET: api/Employees
    public List<Employee> GetAllEmployees()
    {
        return db.Employees.ToList();
    }
    // GET: api/Employees/5
    [ResponseType(typeof(Employee))]
    public IHttpActionResult GetEmployee(int id)
    {
        Employee employee = db.Employees.Find(id);
        if (employee == null)
        {
            return NotFound();
        }
        return Ok(employee);
    }
    // PUT: api/Employees/5
    [ResponseType(typeof(void))]
    public IHttpActionResult PutEmployee(int id, Employee employee)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        if (id != employee.Id)
        {
            return BadRequest();
        }
        db.Entry(employee).State = EntityState.Modified;
        try
        {
            db.SaveChanges();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!EmployeeExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }
        return StatusCode(HttpStatusCode.NoContent);
    }
    // POST: api/Employees
    [ResponseType(typeof(Employee))]
    public IHttpActionResult PostEmployee(Employee employee)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }
        db.Employees.Add(employee);
        db.SaveChanges();
        return CreatedAtRoute("DefaultApi", new { id = employee.Id }, employee);
    }
    // DELETE: api/Employees/5
    [ResponseType(typeof(Employee))]
    public IHttpActionResult DeleteEmployee(int id)
    {
        Employee employee = db.Employees.Find(id);
        if (employee == null)
        {
            return NotFound();
        }
        db.Employees.Remove(employee);
        db.SaveChanges();

        return Ok(employee);
    }
    protected override void Dispose(bool disposing)
    {
        if (disposing)
        {
            db.Dispose();
        }
        base.Dispose(disposing);
    }
    private bool EmployeeExists(int id)
    {
        return db.Employees.Count(e => e.Id == id) > 0;
    }
}

Step 3. To create an Angular Project

Create a new service in our Angular application using syntax & create a company service.
ng g service our_service_name

Now we will write code to get the data from our API in the service i.e. company.service.ts file contains the below code.
Note. Do not use a direct URL link in the typescript file anyone can easily hack it. For demo purposes, I have used it.

The below code contains the file company.service.ts.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Company } from '../Model/company';

@Injectable({
  providedIn: 'root'
})
export class CompanyService {

  constructor(private http: HttpClient) { }

  getData() {
    return this.http.get("http://localhost:8012/api/Employees");
  }
}

In the above code, CompanyService is a class that contains our getData method that returns a result from API from where we are getting a record using a GET request, API/Employees (which is written in the API project). We can also host our API project & add that URL as well.

Step 4. Create a new component in our angular project
Now create a new component in our angular project using syntax & create the my-company component.
ng g c componentName


The below code contains the file my-company.component.html.
<p>Angular 8 using Web API !!!</p>

<div>
  <table class="gridList">
    <tr>
      <th>User Names</th>
      <th>Email</th>
    </tr>
    <tr *ngFor="let item of companyList">
      <td>{{ item.Name }}</td>
      <td>{{ item.Email }}</td>
    </tr>
  </table>
</div>


In the above code, we have used ngFor to iterate the loop. companyList is a variable in which we will get the data from our services refer to the below steps.

The below code contains the file my-company.component .ts
import { BrowserModule, Title } from '@angular/platform-browser';
import { Component, OnInit, ViewChild } from '@angular/core';
import { CompanyService } from '../../service/company.service';
@Component({
  selector: 'app-my-company',
  templateUrl: './my-company.component.html',
  styleUrls: ['./my-company.component.css']
})
export class MyCompanyComponent implements OnInit {
  companyList: any;
  constructor(private companyService: CompanyService) { }
  ngOnInit() {
    this.getData();
  }
  getData() {
    this.companyService.getData().subscribe(
      data => {
        this.companyList = data;
      }
    );
  }
}


In the above code, we have imported the company service. In the OnInit method, we will declare one variable company list & will assign the data that is returned by our method getData() from service.

Here, subscribe is used to send the list.

Step 5. Loading the company component in app.component.html

Now, to load our company component, we will add a selector in the app.component.html file.
<app-my-company></app-my-company>
<app-my-company></app-my-company>


Step 6. To run the Angular application

To run the Angular application, use the below syntax.
ng serve -o



Node.js Hosting - HostForLIFE :: How Can I Use MySQL To Create JWT Token Authentication In Node.js?

clock June 5, 2024 08:12 by author Peter

The JSON Web Token (JWT) authentication method is a popular security measure for Node.js applications. A token is created upon login and is used for subsequent request authentication. This tutorial shows you how to implement JWT authentication in a Node.js application using MySQL and Express. You'll learn how to set up the database, create authentication routes, and oversee token generation and validation. By securing your API endpoints and restricting access to protected resources to only authorized users, you may increase the security and scalability of your service.

Steps for Creating a project
Step 1. Initialize a new Node.js project ;(CMD Command)

mkdir Node_JWT_Project
cd Node_JWT_Project
npm init -y

Step 2. Install the required packages ;(CMD Command)
npm install express mysql2 jsonwebtoken bcryptjs body-parser

Step 3. Create the project structure

Step 4. Database Configuration (config/db.js)
const mysql = require('mysql2');
const connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'password',
    database: 'my_database'
});
connection.connect((err) => {
    if (err) {
        console.error('Error connecting to the database:', err.stack);
        return;
    }
    console.log('Connected to the database.');
});
module.exports = connection;


Step 5. Create a Model folder (models/userModel.js)
const db = require('../config/db');
const User = {};
User.create = (user, callback) => {
    const query = 'INSERT INTO users (username, email, password) VALUES (?, ?, ?)';
    db.query(query, [user.username, user.email, user.password], callback);
};
User.findById = (id, callback) => {
    const query = 'SELECT * FROM users WHERE id = ?';
    db.query(query, [id], callback);
};
User.findByEmail = (email, callback) => {
    const query = 'SELECT * FROM users WHERE email = ?';
    db.query(query, [email], callback);
};
User.update = (id, user, callback) => {
    const query = 'UPDATE users SET username = ?, email = ? WHERE id = ?';
    db.query(query, [user.username, user.email, id], callback);
};
User.delete = (id, callback) => {
    const query = 'DELETE FROM users WHERE id = ?';
    db.query(query, [id], callback);
};
module.exports = User;

Step 6. Controller (controllers/userController.js)
const User = require('../models/userModel');
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const userController = {};
userController.register = async (req, res) => {
    const { username, email, password } = req.body;
    const hashedPassword = await bcrypt.hash(password, 10);
    User.create({ username, email, password: hashedPassword }, (err, result) => {
        if (err) {
            return res.status(500).json({ error: err.message });
        }
        res.status(201).json({ message: 'User registered successfully!' });
    });
};
userController.login = (req, res) => {
    const { email, password } = req.body;
    User.findByEmail(email, async (err, results) => {
        if (err || results.length === 0) {
            return res.status(400).json({ error: 'Invalid email or password' });
        }
        const user = results[0];
        const isMatch = await bcrypt.compare(password, user.password);
        if (!isMatch) {
            return res.status(400).json({ error: 'Invalid email or password' });
        }
        const token = jwt.sign({ id: user.id }, 'your_jwt_secret', { expiresIn: '1h' });
        res.json({ token });
    });
};
userController.getUser = (req, res) => {
    const userId = req.user.id;
    User.findById(userId, (err, results) => {
        if (err) {
            return res.status(500).json({ error: err.message });
        }
        if (results.length === 0) {
            return res.status(404).json({ message: 'User not found' });
        }
        res.json(results[0]);
    });
};
userController.updateUser = (req, res) => {
    const userId = req.user.id;
    const { username, email } = req.body;
    User.update(userId, { username, email }, (err, results) => {
        if (err) {
            return res.status(500).json({ error: err.message });
        }
        res.json({ message: 'User updated successfully!' });
    });
};
userController.deleteUser = (req, res) => {
    const userId = req.user.id;
    User.delete(userId, (err, results) => {
        if (err) {
            return res.status(500).json({ error: err.message });
        }
        res.json({ message: 'User deleted successfully!' });
    });
};
module.exports = userController;


Step 7. Routes (routes/userRoutes.js)
const express = require('express');
const router = express.Router();
const userController = require('../controllers/userController');
const authMiddleware = require('../middlewares/authMiddleware');
router.post('/register', userController.register);
router.post('/login', userController.login);
router.get('/profile', authMiddleware, userController.getUser);
router.put('/profile', authMiddleware, userController.updateUser);
router.delete('/profile', authMiddleware, userController.deleteUser);
module.exports = router;

Step 8. Middleware (middlewares/authMiddleware.js)
const jwt = require('jsonwebtoken');
const authMiddleware = (req, res, next) => {
    const token = req.header('Authorization').replace('Bearer ', '');
    if (!token) {
        return res.status(401).json({ message: 'Access denied. No token provided.' });
    }
    try {
        const decoded = jwt.verify(token, 'your_jwt_secret');
        req.user = decoded;
        next();
    } catch (error) {
        res.status(400).json({ message: 'Invalid token.' });
    }
};
module.exports = authMiddleware;


Step 9. Main Application (app.js)
const express = require('express');
const bodyParser = require('body-parser');
const userRoutes = require('./routes/userRoutes');
const app = express();
app.use(bodyParser.json());
app.use('/api/users', userRoutes);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});


Step 10. Create a Database and Table
CREATE DATABASE my_database;
USE my_database;
CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(255) NOT NULL,
    email VARCHAR(255) NOT NULL,
    password VARCHAR(255) NOT NULL
);


Step 11. Running the project (CMD Command)
node app.js

Step 12. Check-in Postman

Similarly, we can use Endpoint Update, Insert, and Delete.

Conclusion

Only authenticated users can access protected resources, which improves security and scalability when JWT authentication is implemented in a Node.js application using MySQL. You may create a strong authentication system by following the procedures listed, which include setting up the database, making authentication routes, and creating and validating tokens. This method offers a scalable solution for user management in your application in addition to securing your API endpoints. You can make your application more dependable and user-friendly by maintaining a seamless and secure user experience with JWT authentication.

HostForLIFE.eu Node.js Hosting
HostForLIFE.eu 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 customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.


 



AngularJS Hosting Europe - HostForLIFE :: Opening Angular: Enhanced Functionalities, Safety, and ERP Integration

clock May 14, 2024 07:56 by author Peter

Enterprise resource planning (ERP) technologies are essential for optimizing business operations in the quickly changing digital landscape of today. Robust ERP solutions are becoming more and more necessary as businesses expand. With its cutting-edge functionality, improved security features, and speed gains, Angular is a formidable framework for creating cutting-edge ERP apps. This article will explore how Angular may boost ERP projects, emphasizing how it integrates with.NET Core online apps effortlessly and offers enhanced features, security advancements, and speed gains.

Advanced Functionalities
The extensive feature set of Angular enables developers to design complex ERP solutions that are suited to certain business requirements. Let's look at an actual instance of Angular integration in an inventory management ERP project.

// Angular component for inventory management
import { Component, OnInit } from '@angular/core';
import { InventoryService } from './inventory.service';
import { InventoryItem } from './inventory-item.model';

@Component({
  selector: 'app-inventory',
  templateUrl: './inventory.component.html',
  styleUrls: ['./inventory.component.css']
})
export class InventoryComponent implements OnInit {
  inventoryItems: InventoryItem[];

  constructor(private inventoryService: InventoryService) { }

  ngOnInit(): void {
    this.loadInventory();
  }

  loadInventory(): void {
    this.inventoryService.getInventoryItems()
      .subscribe(items => this.inventoryItems = items);
  }
}

Security Enhancements
Security is paramount in ERP systems handling sensitive business data. Angular provides robust security features such as built-in cross-site scripting (XSS) protection, strict contextual auto-escaping for templates, and a powerful HTTP client module for secure communication with backend services. Let's integrate authentication and authorization using Angular's router guards in our ERP project.

// Angular router guard for authentication
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router } from '@angular/router';
import { AuthService } from './auth.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {
  constructor(private authService: AuthService, private router: Router) { }

  canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    if (this.authService.isAuthenticated()) {
      return true;
    } else {
      this.router.navigate(['/login']);
      return false;
    }
  }
}

Performance Improvements
Angular's latest versions come with performance optimizations such as Ahead-of-Time (AOT) compilation, lazy loading modules, and tree-shaking for efficient bundle sizes. These optimizations ensure smooth user experiences, especially in large-scale ERP applications. Let's leverage Angular's performance improvements by lazy loading modules in our ERP project.

// Angular lazy loading module for improved performance
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

const routes: Routes = [
  {
    path: 'dashboard',
    loadChildren: () => import('./dashboard/dashboard.module').then(m => m.DashboardModule)
  },
  {
    path: 'inventory',
    loadChildren: () => import('./inventory/inventory.module').then(m => m.InventoryModule)
  },
  // Other lazy-loaded modules
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

Integration with .NET Core Web Application
Integrating Angular with a .NET Core web application is seamless, thanks to Angular's flexible architecture and .NET Core's robust backend capabilities. You can use ASP.NET Core Web API to provide data services to your Angular frontend. Here's a basic example of how you can set up a .NET Core Web API to serve data to our Angular ERP application.

// .NET Core Web API controller for inventory management
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;

namespace ERP.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class InventoryController : ControllerBase
    {
        private readonly InventoryContext _context;

        public InventoryController(InventoryContext context)
        {
            _context = context;
        }

        [HttpGet]
        public ActionResult<IEnumerable<InventoryItem>> Get()
        {
            return _context.InventoryItems.ToList();
        }

        // Other CRUD operations
    }
}

Conclusion

Because of its sophisticated ERP application development features, security upgrades, and speed advantages, Angular is a great option. Through the integration of Angular with.NET Core web apps, developers can fully utilize the capabilities of both platforms to provide safe and efficient ERP systems that are customized to fit the specific requirements of contemporary enterprises.



Node.js Hosting - HostForLIFE :: Combining Python and Node.js to Shorten URLs with PyShorteners

clock May 2, 2024 08:45 by author Peter

This blog post will explain how to use the pyshorteners module to integrate Node.js and Python to build a basic URL shortening application. We can take advantage of Node.js's robust features for controlling the entire application and Python's URL-shortening functionality by leveraging the strengths of both languages.

Node.js Script (nodeScript.js)
Let's begin by examining nodeScript.js, a Node.js script. This script is in charge of starting a Python process and sending a command-line argument with a URL to be abbreviated.

const { spawn } = require('child_process');
let urlToShorten = 'dynamitetechnology.in';
const pyProg = spawn('python', ['shortUrl.py', urlToShorten]);

pyProg.stdout.on('data', (data) => {
  console.log('Python script output:', data.toString());
});

pyProg.stderr.on('data', (data) => {
  console.error('Error from Python script:', data.toString());
});

pyProg.on('close', (code) => {
  console.log(`Python script exited with code ${code}`);
});


Explanation
The spawn function from the child_process module is used to execute the Python script (shortUrl.py).
The URL to be shortened ('dynamitetechnology.in' in this case) is passed as a command-line argument when spawning the Python process.
Event listeners are set up to capture the standard output and standard error streams from the Python process.

Python Script (shortUrl.py)
Now, let’s take a look at the Python script, shortUrl.py. This script utilizes the pyshorteners library to perform URL shortening.
import sys
import pyshorteners

# Check if a URL is provided as a command-line argument
if len(sys.argv) != 2:
    print("Usage: python shortUrl.py <url>")
    sys.exit(1)

url_to_shorten = sys.argv[1]

s = pyshorteners.Shortener()
print(s.tinyurl.short(url_to_shorten))


Explanation

The Python script checks whether a URL is provided as a command-line argument. If not, it prints a usage message and exits.
The provided URL is then passed to the pyshorteners library, and the shortened URL is printed to the console using the TinyURL service.

Conclusion
Python and Node.js were used to develop a straightforward but powerful URL-shortening tool. Python performs the URL shortening functionality, and Node.js provides the orchestration and communication with the Python script. This integration demonstrates the adaptability and compatibility of many programming languages, enabling programmers to take advantage of each language's advantages for particular tasks inside a single application.



Europe mySQL Hosting - HostForLIFEASP.NET :: MySQL Queries Cheat Sheet

clock April 19, 2024 08:28 by author Peter

One of the most widely used and adaptable database management system platforms is MySQL. Regardless of your position in the database industry or amount of development experience, it is imperative that you are familiar with MySQL and its querying features. The fundamentals of MySQL querying will be covered in this tutorial, along with easy to use techniques for connecting to your databases.

A few simple SQL queries
CHOOSE Information from one or more columns of a table can be obtained using this technique. You enter the desired columns, separated by commas, after the SELECT keyword.

SELECT column1, column2 FROM tablename;
SELECT * FROM tablename;


WHERE Records can be filtered using this clause depending on specific requirements. You can only obtain the rows that match the given criteria.
SELECT *FROM tablename
WHERE columnname = value;


INSERT To add new records (rows) to a table, use this statement. The values you wish to add to each column and the name of the table are also specified.

INSERT INTO tablename (column1, column2)
VALUES (value1, value2);


UPDATE A table's existing records can be changed using this statement. The table name, the columns you wish to change, and the new values are all specified.
UPDATE tablename
SET column1 = newvalue
WHERE condition;


DELETE  Depending on specific requirements, this statement is used to remove records from a table. You can use it to remove particular rows that fit the requirements.
DELETE FROM tablename
WHERE condition;


JOIN This joins rows from one or more tables together according to a shared column. With just one query, you can obtain data from several tables.
SELECT *
FROM table1
JOIN table2 ON table1.columnname = table2.columnname;


GROUP BY Rows with the same values are grouped together into summary rows using this clause. It is frequently used to calculate values on grouped data together with aggregate functions such as COUNT, SUM, AVG, etc.
SELECT columnname, COUNT(*)
FROM tablename
GROUP BY columnname;

ORDER BY Depending on one or more columns, this clause can be used to sort the result set either ascending (ASC) or descending (DESC).
SELECT *
FROM tablename
ORDER BY columnname ASC;


LIMIT This has the function of limiting how many rows are returned in a result set. It is frequently used to increase query efficiency by obtaining only a subset of rows, or for pagination.
SELECT *
FROM tablename
LIMIT 10;


DISTINCT This term pulls distinct rows out of a column. Duplicate rows are removed from the result set.
SELECT DISTINCT columnname
FROM tablename;


Data Manipulation Functions

COUNT This function counts the number of rows that satisfy a certain criteria or the total number of rows in a table.
SELECT COUNT(*)
FROM tablename;


MAX/MIN The maximum and minimum values from a column can be obtained, respectively, using these functions.
SELECT MAX(columnname), MIN(columnname)
FROM tablename;


AVG The average value of a numeric column can be determined with this function.
SELECT AVG(columnname)
FROM tablename;


SUM The total of the values in a numeric column can be determined using this function.
SELECT SUM(columnname)
FROM tablename;

Constraints
PRIMARY KEY The primary key constraint is responsible for uniquely identifying every record within a table. It guarantees that every table row has a distinct identity.
CREATE TABLE tablename (
    columnname INT PRIMARY KEY,
    ...
);


FOREIGN KEY  By referencing the primary key or unique key of another table, this constraint creates a relationship between tables.
CREATE TABLE tablename1 (
    columnname INT,
    FOREIGN KEY (columnname) REFERENCES table_name2(columnname)
);

INDEX  By based an index on one or more columns, this technique helps to speed up data retrieval operations on a table. Based on the indexed columns, it enables the database engine to find rows rapidly.
CREATE INDEX indexname
ON tablename (columnname);

Conclusion
The SQL cheat sheet offers a quick reference for effectively carrying out crucial database practices. It includes a wide range of operations, from simple commands like SELECT, INSERT, UPDATE, and DELETE for data retrieval, addition, and modification to more complex techniques like JOIN for merging data from various tables and GROUP BY for data summary. The cheat sheet also contains constraints like PRIMARY KEY, FOREIGN KEY, and INDEX, as well as data manipulation methods like COUNT, MAX, MIN, AVG, and SUM, which are essential for maintaining the accuracy of data and maximising database performance.



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