Full Trust European Hosting

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

AngularJS Hosting Europe - HostForLIFE :: A Comprehensive Guide to Angular Cheatsheets

clock August 15, 2025 08:27 by author Peter

Google created the well-known front-end web framework Angular. With HTML, CSS, and TypeScript, it facilitates the creation of quick, interactive, and organized single-page applications (SPAs). Components, services, routing, and dependency injection are some of the tools that Angular offers to facilitate and organize the development of large-scale online applications.

1. NgModule, or the Angular Module
A module is defined as a container for directives, pipes, services, and components. There is a root module named AppModule in every Angular application.
For instance

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

Key Point: Modules organize the app into functional sections.

2. Component

Definition: A component controls a part of the user interface. Each component has three parts: HTML template, TypeScript class, and CSS style.

Example
@Component({
  selector: 'app-hello',
  template: '<h1>Hello {{ name }}</h1>'
})
export class HelloComponent {
  name = 'World';
}


Key Point: Components are the basic building blocks of any Angular app.

3. Data Binding
Definition: Data binding connects the data between your class (TypeScript) and the template (HTML).
Types and Examples
      Interpolation: {{ value }}
    Property Binding: [src]="imageUrl"
    Event Binding: (click)="doSomething()"
    Two-way Binding: [(ngModel)]="name"


Key Point: Use FormsModule for two-way binding with ngModel.

4. Directives
Definition: Directives change the behavior or appearance of elements.

Types
Structural Directives: *ngIf, *ngFor
Attribute Directives: [ngClass], [ngStyle]

Example
<p *ngIf="isVisible">This is visible</p>

Key Point: Structural directives change the DOM layout.

5. Services and Dependency Injection

Definition: Services are used to share data or logic across components. Angular uses dependency injection to provide services.

Example
@Injectable()
export class DataService {
  getData() {
    return ['One', 'Two', 'Three'];
  }
}


Key Point: Use services to avoid repeating logic in multiple components.

6. Routing

Definition: Routing is used to navigate between different views or components.

Example
const routes: Routes = [
  { path: 'home', component: HomeComponent },
  { path: 'about', component: AboutComponent }
];


Key Point: Use <router-outlet> in HTML to display routed views.

7. Lifecycle Hooks
Definition: Hooks let you run code at specific times in a component’s life.
Common Hooks

  • ngOnInit(): Runs after component initializes.
  • ngOnDestroy(): Runs before component is removed.

Example
ngOnInit() {
  console.log('Component loaded');
}


Key Point: Use ngOnInit() to fetch data when the component loads.

8. Pipes
Definition: Pipes transform the data in the template.
Built-in Pipes: date, uppercase, lowercase, currency

Example
<p>{{ today | date }}</p>

Key Point: You can also create custom pipes using @Pipe.

9. Forms

Definition: Angular provides two types of forms:

  • Template-driven (simple, suitable for small apps)
  • Reactive forms (more control, suitable for large apps)


Template-driven Example
<input [(ngModel)]="user.name">

Reactive Example
this.form = new FormGroup({
  name: new FormControl('')
});


Key Point: Import ReactiveFormsModule or FormsModule based on the type of form.

10. HTTPClient
Definition: Angular’s HttpClient is used to make HTTP requests to a backend server.

Example
this.http.get('https://api.example.com/data').subscribe(result => {
  console.log(result);
});


Key Point: Import HttpClientModule and inject HttpClient in the constructor.

11. Event Handling
Definition: Event handling lets you respond to user actions like clicks or input changes.

Example
<button (click)="onClick()">Click Me</button>

onClick() {
  alert('Button clicked!');
}

Key Point: Use event binding syntax (event)="handler()".

12. Template Reference Variable

Definition: Template variables give you a reference to DOM elements in your HTML.

Example
<input #userInput>
<button (click)="log(userInput.value)">Log</button>


Key Point: Template variables start with #.

13. ngFor and ngIf

Definition: Used to display lists or conditionally show/hide elements.

Example
<li *ngFor="let item of items">{{ item }}</li>
<div *ngIf="isLoggedIn">Welcome</div>

Key Point: Use trackBy in ngFor for better performance.

14. @Input and @Output
Definition
    @Input passes data into a component.
    @Output sends data out using EventEmitter.

Example
@Input() title: string;
@Output() clicked = new EventEmitter<void>();


Key Point: Use these to communicate between parent and child components.

15. Angular CLI Commands

Definition: CLI helps you create and manage Angular apps.

Common Commands
    ng new app-name: Create a new app
    ng serve: Run the app locally
    ng generate component name: Create a component
    ng build: Build the app for production


Key Point: CLI automates repetitive tasks.
16. Interceptors
Definition: Interceptors are used to modify HTTP requests or responses globally (for example, adding auth tokens or handling errors).

Example:
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    const token = 'my-token';
    const authReq = req.clone({
      headers: req.headers.set('Authorization', `Bearer ${token}`)
    });
    return next.handle(authReq);
  }
}


Key Point: Register interceptors in providers using { provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }.

17. Guards (Route Protection)

Definition: Guards control access to routes based on logic like login status or user roles.

Types: CanActivate, CanDeactivate, CanLoad, Resolve

Example
@Injectable()
export class AuthGuard implements CanActivate {
  canActivate(): boolean {
    return isUserLoggedIn(); // your custom logic
  }
}


Key Point: Attach guards in the route configuration.

18. Lazy Loading

Definition: Lazy loading loads modules only when needed, reducing the initial load time.

Example
const routes: Routes = [
  { path: 'admin', loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule) }
];


Key Point: Use loadChildren in the routing module for lazy loading.
19. Standalone Components (Angular 14+)
Definition: Components that do not need to be declared inside a module. Useful for simpler architecture and micro frontends.

Example
@Component({
  standalone: true,
  selector: 'app-simple',
  template: '<p>Standalone works!</p>',
  imports: [CommonModule]
})
export class SimpleComponent {}


Key Point: Use them for lightweight or isolated features.

20. Environment Files

Definition: Store different settings (like API URLs) for development and production.

Example:
// environment.ts
export const environment = {
  production: false,
  apiUrl: 'http://localhost:3000'
};

Key Point: Use environment.apiUrl in services to avoid hardcoding URLs.

21. TrackBy with ngFor
Definition: Improves rendering performance by identifying items uniquely.

Example
<li *ngFor="let item of items; trackBy: trackById">{{ item.name }}</li>

trackById(index: number, item: any) {
  return item.id;
}


Key Point: Always use trackBy when rendering large lists.

22. Content Projection (ng-content)

Definition: Allows you to insert custom HTML content into a component.

Example
<!-- In reusable component -->
<div class="box">
  <ng-content></ng-content>
</div>

<!-- Usage -->
<app-box>
  <p>This content goes inside the box</p>
</app-box>

Key Point: Use for building reusable UI components like modals and cards.

23. ViewChild and ViewChildren

Definition: Access DOM elements or child components from the class.

Example
@ViewChild('myInput') inputRef: ElementRef;

ngAfterViewInit() {
  console.log(this.inputRef.nativeElement.value);
}


Key Point: Access is available only after ngAfterViewInit().

24. Custom Directive

Definition: Create your own directive to change element behavior.

Example
@Directive({
  selector: '[appHighlight]'
})
export class HighlightDirective {
  constructor(el: ElementRef) {
    el.nativeElement.style.backgroundColor = 'yellow';
  }
}


Key Point: Directives add custom behavior to HTML elements.

25. State Management (Basics)

Definition: Managing shared data across components.

Approaches

  • Service with RxJS
  • NgRx (Redux-style)
  • Component Input/Output


Example (RxJS)
private data = new BehaviorSubject<string>('initial');
data$ = this.data.asObservable();


Key Point: Use shared services and Observables to manage app state without tight coupling.

26. Animations

Definition: Angular provides animation support via @angular/animations.

Example
trigger('fadeIn', [
  transition(':enter', [
    style({ opacity: 0 }),
    animate('500ms', style({ opacity: 1 }))
  ])
])

Key Point: Import BrowserAnimationsModule in AppModule to enable animations.

27. Change Detection Strategy

Definition: Angular runs change detection to update the view when data changes. You can control this behavior using strategies.

Types

  • Default: Checks all components.
  • OnPush: Only checks when input changes or events occur.

Example
@Component({
  selector: 'app-sample',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `<p>{{ data }}</p>`
})
export class SampleComponent { }

Key Point: Use OnPush to boost performance in large apps.

28. Error Handling (Global and Local)

Local Example

this.http.get('/data').subscribe({
  next: data => console.log(data),
  error: err => console.error('Error:', err)
});


Global Error Handler


@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
  handleError(error: any) {
    console.error('Global Error:', error);
  }
}


Key Point: Always log and handle errors gracefully.
29. Async Pipe
Definition: Automatically subscribes to Observables in templates and unsubscribes when the component is destroyed.

Example
<p>{{ user$ | async }}</p>

Key Point: Avoid manual subscriptions when possible. Prevents memory leaks.

30. Unsubscribe from Observables
Problem: If you forget to unsubscribe, memory leaks can happen.

Solution
private destroy$ = new Subject<void>();

ngOnDestroy() {
  this.destroy$.next();
  this.destroy$.complete();
}


Key Point: Always unsubscribe from long-living Observables like interval() or HttpClient.

31. Structural Directive with ng-template

Definition: Define a template to render conditionally or repeatedly.

Example
<ng-template [ngIf]="show" [ngIfElse]="elseBlock">Visible</ng-template>
<ng-template #elseBlock>Hidden</ng-template>

Key Point: ng-template helps when you want full control over rendering.

32. Custom Pipe

Definition: Create your own pipe to format data.

Example
@Pipe({ name: 'capitalize' })
export class CapitalizePipe implements PipeTransform {
  transform(value: string): string {
    return value.charAt(0).toUpperCase() + value.slice(1);
  }
}


Key Point: Custom pipes are stateless functions used in templates.

33. Reusable Shared Module
Definition: A module that contains common components, directives, and pipes used across the app.

Example
@NgModule({
  declarations: [HeaderComponent, FooterComponent],
  exports: [HeaderComponent, FooterComponent]
})
export class SharedModule { }


Key Point: Import SharedModule wherever common elements are needed.

34. Feature Modules
Definition: Organize your app into multiple modules for better scalability.
Example: UserModule, AdminModule, AuthModule

Key Point: Each module should focus on a single area of the application.

35. Module Preloading

Definition: Load lazy-loaded modules in the background after the app starts.

Example
RouterModule.forRoot(routes, { preloadingStrategy: PreloadAllModules })

Key Point: Improves user experience by reducing wait time when navigating.

36. Angular Universal (SSR)
Definition: Server-side rendering for Angular apps. Helps with SEO and faster initial loading.

Key Point: Use @nguniversal/express-engine to set up SSR.

37. Web Workers

Definition: Run heavy tasks in a separate thread to keep UI responsive.
Key Point: Use Angular CLI to generate workers:
ng generate web-worker my-worker

38. ViewEncapsulation
Definition: Controls how styles are applied to components.

Types

  • Emulated (default)
  • ShadowDom
  • None


Example
@Component({
  encapsulation: ViewEncapsulation.None
})

Key Point: Choose based on your CSS scoping needs.

39. Testing with Jasmine and Karma

Definition: Angular uses Jasmine for writing tests and Karma for running them.

Example
it('should create the app', () => {
  const fixture = TestBed.createComponent(AppComponent);
  const app = fixture.componentInstance;
  expect(app).toBeTruthy();
});

Key Point: Always write unit tests for components and services.

40. Internationalization (i18n)

Definition: Supports multiple languages in Angular apps.
Key Point: Use Angular’s i18n module or third-party libraries like ngx-translate.

Conclusion

You now have a complete Angular cheatsheet that covers everything from beginner to intermediate and even advanced topics. Mastering Angular means understanding not only how components, services, and routing work but also how to manage performance, structure large projects, test effectively, and write clean, maintainable code.



AJAX Hosting Spain - HostForLIFE.eu :: Understanding AJAX (Asynchronous JavaScript and XML)

clock August 11, 2025 10:26 by author Peter

What is AJAX?
Programming is not what AJAX (Asynchronous JavaScript and XML) is. This web development technique enables a page to communicate with a server in the background, allowing us to change specific sections of the page without having to reload the entire page.

  • Asynchronous: It works in the background while we continue using the page.
  • JavaScript: Sends the request and updates the page.
  • XML: It was the original data format, but now JSON is used more often.

Like, we are on Amazon and type “wireless mouse” into the search box.

  • As we type, product suggestions appear instantly, and we don’t have to press Enter or reload the page.
  • This is AJAX: our browser sends small requests to Amazon’s servers in the background, gets suggestion data, and updates only that part of the page.

AJAX is ideal for scenarios where dynamic updates improve usability, such as form validation, live search suggestions, refreshing lists, or real-time notifications. It helps eliminate interruptions in user workflow by updating data seamlessly in the background, making applications feel more responsive and modern.

How AJAX Works?

AJAX is like having a messenger who runs to the server, gets only the data we need, and updates the exact part of our page without forcing the whole page to reload.

  • User triggers an event (e.g., clicks a button)
  • JavaScript creates an XMLHttpRequest
  • Request is sent to the server
  • Server processes and sends back data
  • JavaScript updates the page dynamically

Like, we are on Amazon and type “wireless mouse” into the search box.

  • We perform an action: This could be typing in a search box, clicking a “Load More” button, or selecting a filter.
  • JavaScript sends a background request: Using fetch(), XMLHttpRequest, or jQuery’s $.ajax(), our browser makes an HTTP request to the server (GET, POST, etc.) without interrupting the page.
  • The server processes the request: Our backend code (.NET, Node.js, PHP, Python, etc.) runs logic — maybe queries a database — and prepares the response.
  • The server sends back data: Usually in JSON, sometimes in HTML or plain text.
  • JavaScript receives the response: The browser doesn’t reload the data is received in memory.
  • We update only the needed part of the page: For example, we might insert new HTML into a <div> or refresh a product list section.

A simple example for fetching countries that we often use in forms.
<input type="text" id="search-input" placeholder="Start typing a country name...">
<div id="search-results"></div>

<script>
const searchInput = document.getElementById('search-input');
const searchResults = document.getElementById('search-results');


let debounceTimer;

searchInput.addEventListener('input', function () {
  clearTimeout(debounceTimer);
  const searchTerm = this.value.trim();

  if (searchTerm.length > 2) {
    debounceTimer = setTimeout(() => {
      searchResults.innerHTML = '<p>Loading...</p>';

      fetch(`https://restcountries.com/v3.1/name/${encodeURIComponent(searchTerm)}`)
        .then(response => {
          if (!response.ok) {
            throw new Error('HTTP error ' + response.status);
          }
          return response.json();
        })
        .then(data => {
          if (Array.isArray(data) && data.length > 0) {
            searchResults.innerHTML = data
              .map(country => {

                const regex = new RegExp(`(${searchTerm})`, 'gi');
                const highlighted = country.name.common.replace(regex, '<strong>$1</strong>');
                return `<p>${highlighted}</p>`;
              })
              .join('');
          } else {
            searchResults.innerHTML = '<p>No countries found.</p>';
          }
        })
        .catch(() => {
          searchResults.innerHTML = '<p>Error fetching results.</p>';
        });
    }, 300); // Wait 300ms after typing stops
  } else {
    searchResults.innerHTML = '';
  }
});
</script>


How does this work now?

  • We type at least 3 letters.
  • The script waits 300ms after we stop typing (debounce) before making a request.
  • It fetches matching countries from the REST Countries API without reloading page.
  • It displays them instantly and bolds the matching text.
  • If there’s an error or no match, it shows a message instead of breaking.

Why Use AJAX?

  • Faster User Experience Loads only needed data without refreshing the entire page, so pages respond quickly.
  • Reduced Server Load Transfers smaller amounts of data, saving bandwidth and server resources.
  • Smooth Interactions Lets users continue interacting while data loads in the background.
  • Partial Page Updates Updates only parts of a webpage (like search results or forms) without full reloads.
  • Better Responsiveness Enables dynamic features like live search, filters, and notifications that improve usability. 

Conclusion
AJAX is a cornerstone of modern web development, empowering developers to build responsive, user-friendly applications. By selectively updating content without full page reloads, it improves performance, reduces server strain, and keeps users engaged. While it’s not a one-size-fits-all solution especially for SEO-heavy pages or real-time communication it’s an essential tool for dynamic interfaces and smoother workflows.

HostForLIFE.eu AJAX 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.



Node.js Hosting Europe - HostForLIFE.eu :: When and How to Use Session vs. Token-Based Authentication in MERN?

clock July 30, 2025 07:37 by author Peter

The cornerstone of online application security is authentication. The authentication environment in MERN (MongoDB, Express.js, React, and Node.js) stack apps is dominated by two popular methods: two methods of authentication: session-based and token-based. Although they both accomplish the same objective—verifying a user's identity and safeguarding resources their implementation, application cases, and scalability are very different. This page describes each approach, how it functions in a MERN setting, and why it is better to use one over the other.

What is Authentication?
Before we dive in, let’s clarify.

  • Authentication: confirming the identity of the user (Are you who you say you are?)
  • Authorization: controlling access to resources (What can you do now that you're authenticated?)

Overview of Authentication Methods

Method Session-Based Authentication Token-Based Authentication
Storage Server-side (in memory or DB) Client-side (usually in localStorage or cookies)
Identity Proof Session ID (stored in cookie) JWT (JSON Web Token)
Stateless/Stateful Stateful Stateless
Scalability Less scalable unless using session store More scalable
Common Use Cases Traditional web apps SPAs, mobile apps, microservices

Session-Based Authentication (Cookie-Based)

How does it work?

  • User submits credentials via lthe ogin form.
  • Backend verifies and creates a session, saving it on the server (in memory, Redis, or DB).
  • Server returns a session ID in a secure HTTP-only cookie.
  • On each request, the browser sends the session ID via cookie.
  • Server looks up session data using the ID and verifies the user.

Where does it fit in MERN?

  • React: The frontend sends login requests and automatically includes cookies on future requests (if configured correctly).
  • Express/Node.js: Stores sessions using express-session or similar libraries.
  • MongoDB: Often used with a session store like connect-mongo.

Security Features

  • HttpOnly cookies protect against XSS.
  • Cookies can be set to SameSite, Secure, and have expiry times.

Drawbacks

  • Needs server-side storage (memory or DB).
  • Less ideal for horizontal scaling unless using a centralized session store (e.g., Redis).
  • Slightly more complex to manage in APIs for SPAs or mobile apps.

Token-Based Authentication (JWT)
How does it work?

  • User logs in with credentials.
  • Server verifies and returns a signed token (usually JWT).
  • Token is stored on the client (localStorage, sessionStorage, or cookie).
  • On each request, a token is sent in headers (commonly in Authorization: Bearer <token>).
  • Server validates token signature and grants access.

Where does it fit in MERN?

  • React: Stores token in localStorage or cookies, attaches it to API requests using Axios or Fetch.
  • Express/Node.js: Verifies token with jsonwebtoken or similar libraries.
  • MongoDB: Optionally stores refresh tokens for session control.

Security Features

  • Tokens can be signed with a secret or private key.
  • Supports token expiration (exp), issued at (iat), and more.

Drawbacks

  • If stored in localStorage, vulnerable to XSS attacks.
  • No built-in logout mechanism (tokens are self-contained).
  • Revocation is difficult without additional mechanisms (blacklists, short expiration with refresh tokens).

Comparison Table

Feature Session-Based Token-Based (JWT)
Storage Server-side (in-memory, Redis, DB) Client-side (localStorage, cookie)
Stateless No (unless using JWT in session) Yes
Suitable for SPAs With extra setup Best choice
Mobile Compatibility Harder (no cookie support) Very good
CSRF Protection (if using cookies) Requires manual implementation
XSS Risk Safer (HttpOnly cookies) Risky if using localStorage
Logout Server clears the session Token must expire or be blacklisted
Performance Lookup needed on each request No DB lookup if using stateless JWTs
Token Revocation Easy (delete session) Complex (blacklist, refresh tokens)

When to Use What?

Use Session-Based Authentication When

  • You’re building a server-rendered web app (e.g., admin dashboard).
  • You control both client and server and want automatic cookie handling.
  • You need simple session invalidation (e.g., logging users out remotely).
  • You can scale horizontally with a session store like Redis.

Use Token-Based Authentication (JWT) When?

  • You’re building a single-page application (SPA) with React.
  • You want to support mobile apps or third-party clients.
  • You prefer a stateless API that’s easy to scale.
  • You want users to remain authenticated across multiple domains/services (microservices).

Session + Token Hybrid Approach (Best of Both Worlds)
Many modern apps use a hybrid approach.

  • Store the JWT in an HttpOnly cookie (safer from XSS).
  • Use refresh tokens with short-lived access tokens.
  • Server can keep track of refresh tokens to allow logout.

This combines the statelessness of tokens with the security of sessions.

Final Thoughts

There’s no one-size-fits-all approach to authentication in the MERN stack. Your decision depends on.

  • Application type (SPA, mobile, or SSR).
  • Security requirements.
  • Scalability and infrastructure.
  • Developer experience and ease of maintenance.

Both session-based and token-based auth systems have matured. The best strategy in 2025 is to choose consciously based on your application’s architecture and implement it securely.

Conclusion
In the evolving world of full-stack development, especially in MERN applications, choosing the right authentication method is crucial for performance, security, and user experience. Session-based authentication remains reliable for traditional web apps where server-side session control is preferred. On the other hand, token-based authentication (JWT) is ideal for modern, stateless, API-driven applications like SPAs and mobile apps.

By understanding the trade-offs between these two approaches, developers can design authentication systems that are secure, scalable, and user-friendly. In many real-world scenarios, a hybrid approach combining short-lived tokens with secure cookies offers the best balance between security and flexibility.

Ultimately, the best choice is not about which method is superior - it's about which method aligns with your architecture, user experience goals, and scalability needs.

 



AngularJS Hosting Europe - HostForLIFE :: Angular Reactive Forms: Real-Time Problem Solving and Dynamic Validation

clock July 24, 2025 08:53 by author Peter

The handling of dynamic form validation in Angular Reactive Forms is described in this article. It illustrates a real-world situation in which validation rules must alter in response to user input, such as requiring a company name for corporations and a PAN number for individuals. According to the article, developers frequently make the error of forgetting to call updateValueAndValidity() after updating or clearing validators, which results in unexpected form behavior. It explains the problem, displays the code that was wrong and fixed, and offers a reusable custom validator for PAN format.


 Overall, with a useful example and real-time bug fixes, this article assists developers in understanding how to implement clear, dynamic validation logic in Angular forms.

Overview
Angular’s Reactive Forms module gives you fine-grained control over form data, structure, and validation. One of the most useful features is dynamically applying validators based on user input or context.

In real-world applications, dynamic validation is essential, for example, requiring a secondary email only if a checkbox is selected, or validating a PAN number only for Indian users.

Scenario

In one of our insurance applications, we had a registration form with the following fields:

  • User Type (Individual / Organization)
  • PAN Number (Mandatory for Individuals)
  • Company Name (Mandatory for Organizations)

The validation was supposed to change dynamically when the user toggles between "Individual" and "Organization".

Initial Implementation
Here’s the basic structure of the Reactive Form:
this.registrationForm = this.fb.group({
  userType: ['Individual'],
  panNumber: [''],
  companyName: ['']
});


In the onUserTypeChange() method, we tried to manually add/remove validators:
onUserTypeChange(userType: string) {
  if (userType === 'Individual') {
    this.registrationForm.get('panNumber')?.setValidators([
      Validators.required,
      this.panValidator
    ]);
    this.registrationForm.get('companyName')?.clearValidators();
  } else {
    this.registrationForm.get('companyName')?.setValidators([
      Validators.required
    ]);
    this.registrationForm.get('panNumber')?.clearValidators();
  }

  // Missing updateValueAndValidity
}

Real-Time Issue Faced
Despite switching user type, the form still showed both fields as invalid/valid incorrectly.

Root Cause
We forgot to call updateValueAndValidity() after changing the validators. As a result, the validation state wasn’t recalculated.

Fix Implemented
We modified the method to:
onUserTypeChange(userType: string) {
  const panControl = this.registrationForm.get('panNumber');
  const companyControl = this.registrationForm.get('companyName');

  if (userType === 'Individual') {
    panControl?.setValidators([Validators.required, this.panValidator]);
    companyControl?.clearValidators();
  } else {
    companyControl?.setValidators([Validators.required]);
    panControl?.clearValidators();
  }

  panControl?.updateValueAndValidity();
  companyControl?.updateValueAndValidity();
}


Also, we triggered onUserTypeChange() on form initialization to ensure it reflects the default selection.

Real-Time PAN Validator

Here’s how the PAN format validator looked:
panValidator(control: AbstractControl): ValidationErrors | null {
  const panRegex = /^[A-Z]{5}[0-9]{4}[A-Z]{1}$/;

  if (control.value && !panRegex.test(control.value)) {
    return { invalidPAN: true };
  }

  return null;
}

Outcome
The dynamic validation works perfectly now

Fields show real-time validation updates
This pattern is reusable across other forms with dynamic sections

Conclusion

Dynamic form validation is a common need in Angular apps. Always remember:

  • Use setValidators() and clearValidators() as needed
  • Call updateValueAndValidity() after updating validators
  • For complex logic, extract reusable custom validators

This simple oversight (not updating the validity) caused hours of confusion in a production bug. But the lesson helped in building better reactive forms in other modules too.



Visual Studio Hosting - HostForLIFE.eu :: Code cleanup in Visual Studio 2022

clock July 21, 2025 07:49 by author Peter

The Code Cleanup function in Visual Studio 2022 automatically formats and applies code style guidelines to your code. This keeps your codebase readable, maintainable, and clean.

What is Code Cleanup?
Code Cleanup applies refactoring and formatting rules to your code files. It includes:

  • Removing unnecessary usings/Imports
  • Sorting usings/Imports
  • Applying naming conventions
  • Formatting spacing and indentation
  • Converting var to explicit types (or vice versa)
  • Removing unused variables

How to Use Code Cleanup?
1. Using the Toolbar Button

  • Open a C#, VB.NET, or other supported code file.
  • Click the broom icon 🧹 on the bottom-right corner of the editor.
  • There may be two profiles (Profile 1, Profile 2). Click the dropdown arrow to choose or configure a profile.
  • Click the broom icon to run the cleanup.

2. Using a Keyboard Shortcut
Default shortcut: Ctrl + K, Ctrl + E
(You can customize it in Tools > Options > Keyboard).

3. Context Menu
Right-click anywhere in your code editor.
Select Run Code Cleanup

code clean up

Configure Code Cleanup Profiles
Go to: Tools > Options > Text Editor > [Your Language, e.g., C#] > Code Style > Code Cleanup
There are two profiles (Profile 1 & Profile 2). Each can be customized with:

  • Format document
  • Sort and remove usings
  • Apply file header
  • Apply naming rules
  • Remove unnecessary code

Click Configure Code Cleanup to choose what each profile should do.


Run Cleanup on Entire Solution or Project

  • Right-click on the Solution or Project in Solution Explorer.
  • Choose Analyze and Code Cleanup > Run Code Cleanup.

Note: By default, this only formats open documents. To apply it to all files, use a tool like Roslyn analyzers or the dotnet format CLI (for .NET Core/.NET 5+ projects).

Optional Tools for Deeper Cleanup

.editorconfig file: Store consistent code style settings in the repo.
Roslyn Analyzers: Enforce rules across the solution.
Refactoring Suggestions: Lightbulb actions (Ctrl + .)

Conclusion
In this article, I have tried to cover Code cleanup in Visual Studio 2022.



AngularJS Hosting Europe - HostForLIFE :: Communication Between Parent and Child Components: Resolving the Sync Problem

clock July 16, 2025 08:41 by author Peter

Component communication is essential for creating reusable and modular components in Angular. Data is often sent from a parent component to a child component using @Input() and returned using @Output() with an EventEmitter.

The Real Issue
One of our projects involved a parent component passing a selected item ID to a child component via @Input().  The child component used that ID to retrieve and show the details.  However, when the user quickly picked a different item, the kid did not always display the change.  Sometimes it displayed outdated info or didn't update at all.

What Went Wrong
Angular's @Input() only updates when the value changes, but in certain situations (such as when the same ID is passed again after a brief delay), lifecycle hooks like ngOnChanges() failed to detect it. Additionally, ngOnInit() wasn't retriggered on each input change because the child only made one HTTP call.

Solution


We moved the API fetch logic from ngOnInit() to ngOnChanges() and added a proper check for changes:
@Input() itemId!: string;

ngOnChanges(changes: SimpleChanges): void {
  if (changes['itemId'] && changes['itemId'].currentValue) {
    this.loadItemDetails(changes['itemId'].currentValue);
  }
}

loadItemDetails(id: string) {
  this.http.get(`/api/items/${id}`).subscribe(res => {
    this.itemDetails = res;
  });
}


We also added a condition to prevent redundant API calls if the ID hasn’t changed.

Additional Fix
For cases where the same value might be passed again, we manually reset the input before reassigning:
this.selectedItemId = null;
setTimeout(() => this.selectedItemId = item.id, 0);


This trick forces Angular to treat the new input as a different value.

Conclusion
Angular’s @Input() and @Output() work well for component communication, but they don’t always detect subtle changes unless lifecycle hooks are handled properly. Moving logic to ngOnChanges() ensures that child components respond to dynamic data accurately.



Node.js Hosting Europe - HostForLIFE.eu :: What is the architecture of Node.js?

clock July 14, 2025 08:04 by author Peter

It's likely that Node.js is responsible for any websites that load really quickly or change in real time, such as chat apps or live scores. However, what is Node.js and how does its architecture contribute to its power? Let's put it in plain language.

What is Node.js?
Node.js is not a programming language or a framework; it’s a runtime environment. It enables developers to run JavaScript on the server side, outside of the browser. It’s built on Google Chrome’s V8 JavaScript engine, which makes it super fast.

e.g: "Hello World" in Node.js.
// Import the built-in 'http' module
const http = require('http');

// Create a simple server
const server = http.createServer((req, res) => {
  res.end('Hello World from Node.js!');
});

// Server listens on port 3000
server.listen(3000, () => {
  console.log('Server is running on http://localhost:3000');
});

This simple server handles HTTP requests using a single thread and responds with "Hello World". Even if 100 users open it at once, Node.js can manage that efficiently, thanks to its architecture.

Let’s break it down.

1. Single-Threaded Event Loop

Node.js uses a single thread to handle all client requests. That means it doesn’t create a new thread for every request like traditional web servers (such as Apache). Here the question comes.

Then, how does it handle multiple users simultaneously?

It supports multiple users simultaneously through its Event-Driven Architecture. Let's explore it.

2. Event-Driven Architecture

Imagine you are at a restaurant. Instead of the chef cooking only one dish at a time (waiting for it to finish before starting the next), he puts dishes in the oven and moves on to the next task. When the oven beeps, he knows the food is ready.

Our Node.js works in the same way.

  • When a request (like fetching data or reading a file) comes in, it’s added to the event queue.
  • Node.js doesn’t wait for the task to finish. Instead, it moves on to the next task.
  • Once the task is completed, Node.js receives notification (via a callback function) and processes the result.

This makes Node.js extremely fast and efficient, particularly for I/O-Intensive tasks.

  • Reading/writing files
  • Talking to databases
  • Calling APIs

3. Non-Blocking I/O

  • Most web servers use blocking I/O, which means they wait for one operation to finish before moving to the next.
  • Node.js uses non-blocking I/O, meaning it doesn’t wait for input. This allows Node.js to handle thousands of requests per second with a single thread.

Let's simulate a non-blocking operation, such as reading a file.
const fs = require('fs');

console.log('Start reading file...');

fs.readFile('example.txt', 'utf8', (err, data) => {
  if (err) {
    return console.error(err);
  }
  console.log('File content:', data);
});

console.log('Reading file initiated...');


Output

Key Components of Node.js Architecture
Here are the main parts that makeup Node.

Components Role

V8 Engine

Converts JavaScript code into machine code. It’s fast and powerful.

Libuv

A library that provides the event loop and handles asynchronous operations.

Event Loop

Keeps checking for completed tasks and runs their callback functions.

CallBacks

Functions that are executed when a task finishes.

APIs

Node.js provides APIs for file systems, networks, and more.

Advantages of Node.js Architecture
Fast: Thanks to V8 and the non-blocking model.

  • Scalable: Handles a large number of users without crashing or slowing down.
  • Efficient: Great for real-time apps like chat, games, or live data.
  • Lightweight: Uses fewer system resources compared to traditional servers.

When to Use Node.js?
Node.js is ideal for.

  • Real-time apps (chat apps, online games)
  • APIs for web/mobile apps
  • Data streaming apps
  • Single Page Applications (SPAs)

Conclusion
Node.js architecture is what makes it stand out. Its event-driven, non-blocking, and single-threaded design helps developers build fast, scalable, and efficient applications.

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 :: Lazy Loading in Angular: An Issue and Fix in Real Time

clock July 10, 2025 07:49 by author Peter

A common technique for improving performance in large Angular apps is lazy loading. The practice of loading a module only after the user has reached its route is known as lazy loading. This reduces the initial load time of the application. In one of our projects, we had a dashboard module that was loaded slowly. The module worked flawlessly when the app was being used. However, when the user reloaded the browser while on the dashboard route (http://localhost:4200/dashboard), a blank page or 404 error was shown.

Causes of the Issue
Client-side angular routing is used. When you hit refresh, the browser asks the server to fetch that route, but the server is not aware of this.

How Did We Fix It?
We fixed that by instructing the server to divert all requests to index.html so that Angular could handle the routing. In this case, we changed the.htaccess file with the following since we were using an Apache server:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /

  RewriteRule ^index\.html$ - [L]

  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d

  RewriteRule . /index.html [L]

</IfModule>


There is no issue if you use the built-in dev server in Angular CLI, as it takes care of this already. However, the hosting server needs to know for production.

Conclusion

App performance is enhanced by lazy loading, but if the server is not set up correctly, it may result in unforeseen problems. To allow Angular to handle routing, always ensure that your server reroutes unknown routes to index.html.



AngularJS Hosting Europe - HostForLIFE :: Angular Lifecycle Hooks: An Understanding

clock July 1, 2025 08:06 by author Peter

Google developed the open-source Angular frontend framework, which is based on TypeScript. It assists developers in creating scalable, contemporary online applications, particularly Single Page Applications (SPAs), in which content updates dynamically rather than requiring a page reload. By employing components and services to arrange our code, it facilitates efficient and maintainable development. We must first establish a clear understanding of Angular's definition, structure, and component placement before lifecycle hooks make any sense.

AngularJS vs Angular (Modern Angular)

Feature AngularJS Angular (2+)
Language JavaScript TypeScript
Architecture MVC Component-based
Mobile Support Poor Excellent
Performance Slower Faster (AOT, Tree Shaking)
Development Support Discontinued Actively maintained
Ecosystem Classic JS ecosystem RxJS, TypeScript, CLI

Here’s how the high-level angular structure looks.

Angular Element Purpose School App Example
Modules Organize the app into functional areas StudentModule, TeacherModule, AdminModule, and TimetableModule group features into manageable sections.
Components Handle UI and logic for individual features StudentListComponent, AttendanceFormComponent, and ExamResultsComponent power the core screens of the app.
Templates Define the view using Angular-enhanced HTML A dynamic report card template uses *ngFor to loop through subjects and display student scores.
Services Share business logic and data access across components StudentService centralizes logic to fetch, add, or update student records from the backend.
Routing Enable navigation between pages Angular Router handles navigation to /students, /teachers, /results, and /library.
Directives Add dynamic behavior to templates *ngIf="isAbsent" highlights students in red if they’re absent during the attendance check.
Pipes Format output in templates {{ dateOfBirth | date:'longDate' }} formats a birthday date

What is a Component in Angular?

The core of the user interface in Angular is a component. Usually, every screen, button, form, or card is implemented as a component, much like the Common Language Runtime (CLR) components in.NET. A component is the fundamental unit of the user interface (UI) in Angular. It holds the HTML template, CSS styling, and TypeScript logic for a view, which is a section of the screen that it controls.

Structure of a Component
1. Class contains the logic and data for the component using TypeScript. And File Extension: .ts
@Component({
  selector: 'app-product',         // We can use <app-product></app-product> in HTML
  templateUrl: './product.html',   // Uses product.html for UI
  styleUrls: ['./product.css']     // Uses product.css for styles
})
export class ProductComponent {    // This class holds logic like product name, price, etc.
  name = 'T-Shirt';
  price = 499;
}


2. Template defines the user interface (UI layout) using HTML. It displays data from the class using Angular's data binding.File Extension: .html
<!-- product.component.html -->
<h2>{{ productName }}</h2>
<p>Price: ₹{{ price }}</p>

3. Style adds styling (colors, fonts, spacing) specific to this component. File Extension: .css or .scss

/* product.component.css */
h2 {
  color: blue;
  font-weight: bold;
}

p {
  font-size: 16px;
}


Why are components important for Lifecycle Hooks?

Lifecycle hooks are embedded within components. So, unless you understand how components are created, rendered, and destroyed, lifecycle hooks won’t mean much. Here’s the flow.

  • Angular initializes a component.
  • Angular runs specific hooks at each stage of that component's life.
  • We use those hooks to run our own logic at the perfect moment (like fetching data, unsubscribing, or calculating total).

Angular Lifecycle Hooks
Lifecycle hooks in Angular are special methods that get called automatically at specific stages of a component’s life, from creation to destruction. Lifecycle hooks let Angular manage the creation, change detection, and destruction of components. This gives us fine control over how and when code runs.

Lifecycle hooks are built-in functions that Angular calls at different moments during a component’s lifetime, like when it's created, updated, or destroyed.
Why Use Lifecycle Hooks?

We use lifecycle hooks to,

  • Run initial setup code (like fetching data when the component loads)
  • Detect changes in inputs
  • Perform cleanup tasks (like clearing timers or unsubscribing from services)
  • Debug the flow of your component.


Hook Name When Called Purpose Usage Example
constructor() When a component instance is created Basic initialization of class members (no Angular bindings yet) console.log('Constructor')
ngOnChanges(changes: SimpleChanges) When @Input() property changes Respond to input property changes this.loadData(changes['userId'].currentValue);
ngOnInit() Once after the first ngOnChanges() Fetch data, initialize bindings this.getDataFromService();
ngDoCheck() Every change detection run Custom change tracking logic detectManualChange();
ngAfterContentInit() After content projected via <ng-content> is initialized Set up logic dependent on projected content console.log('ng-content loaded')
ngAfterContentChecked() After every check of the content projection Respond to changes in projected content validateProjectedTemplate();
ngAfterViewInit() After the component’s view (and child views) are initialized DOM access, @ViewChild operations this.chart.init(this.chartElement.nativeElement);
ngAfterViewChecked() After every check of the component and child views Update logic if template data changes adjustLayout();
ngOnDestroy() Just before Angular destroys the component Cleanup (unsubscribe, clear interval) subscription.unsubscribe();

Conclusion
Understanding Angular’s architecture is essential for building modern, scalable, and maintainable web applications. This article walked through the foundational blocks of Angular, Components, Component Lifecycle Hooks, which provide precise control over how Angular creates, updates, and destroys components.

 



AngularJS Hosting Europe - HostForLIFE :: Custom Deferred Grid Using MVC Web API And AngularJS

clock June 26, 2025 10:09 by author Peter

This post will demonstrate how you use AngularJS and Web API to create a custom deferred grid in MVC. Using web API and AngularJS $http services, we will retrieve the data from the database and create a unique user interface for the grid. When working with a Web API, we typically utilize the ADO.NET Entity data model as the model class, correct?

Here, we will retrieve the data from our database using our standard SQLDataAdapter, SQLConnection, and stored procedure in place of an entity data model. We use Virtual Repeat in AngularJS for loading the data in UI, so that the data will be loaded whenever there is a user action that is scrolling (Virtual Scrolling). So that in the view port we will load only few items first. Now shall we go and see this in detail? I hope you will like this.

Background
We have so many plugins available to show the data in a grid format, don't we? if you want to know few of them, you can find them here. Now what if you need to show the data in a grid format without using any additional plugins? What if you need to load the data to that grid dynamically, that is whenever user scrolls the grid? If you could not find the answer for these questions, here in this post I am going to share an option. I hope you will enjoy reading.

Create a MVC application
Click File, New, Project and then select MVC application. Before going to start the coding part, make sure that AngularJS is installed. You can see all the items mentioned above from NuGet. Right click on your project name and select Manage NuGet packages. 

AngularJS NuGet Package Visual Studio
Once you have installed, please make sure that all the items are loaded in your scripts folder.

Using the code
I hope everything is set now, then it is time to start our coding. First we will create a controller action and a view. Below is the code snippet of our controller.
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web;  
    using System.Web.Mvc;  
    namespace Custom_Deffered_Grid_Using_MVC_Web_API_And_Angular_JS.Controllers  
    {  
        public class DefaultController: Controller  
        {  
            // GET: Default  
            public ActionResult Index()  
            {  
                return View();  
            }  
        }  
    }  


Here Default/em> is my controller name. Now create a view for this action, and load the needed references.
    @{  
    ViewBag.Title = "Index";  
    }  
    <h2>Index</h2>  
    <link href="~/Content/angular-material.css" rel="stylesheet" />  
    <script src="~/scripts/angular.min.js"></script>  
    <script src="~/scripts/angular-route.min.js"></script>  
    <script src="~/scripts/angular-aria.min.js"></script>  
    <script src="~/scripts/angular-animate.min.js"></script>  
    <script src="~/scripts/angular-messages.min.js"></script>  
    <script src="~/scripts/angular-material.js"></script>  
    <script src="~/scripts/svg-assets-cache.js"></script>  
    <script src="~/scripts/Default/Default.js"></script>  


You can get these files from the source code attached with this article. And the file Default.js is the additional file where we are requested to do our additional scripts. So far the basic implementation of our view is done. Now we will create a Web API and additional model class to fetch the data from the database. Are you ready? 

Below is my Web API controller.
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Net;  
    using System.Net.Http;  
    using System.Web.Http;  
    using Custom_Deffered_Grid_Using_MVC_Web_API_And_Angular_JS.Models;  
    namespace Custom_Deffered_Grid_Using_MVC_Web_API_And_Angular_JS.Controllers  
    {  
        public class DataAPIController : ApiController  
        {  
          DataModel dm = new DataModel();  
          public string getData(int id)  
            {  
              var d = dm.fetchData(id);  
              return d;  
            }  
        }  
    }  


Have you noticed that I have included using Custom_Deffered_Grid_Using_MVC_Web_API_And_Angular_JS.Models; in the section? This is to ensure that we can use the model classes whatever we have created so far. In this case DataModel is our model class and we are creating an instance for the same.
    DataModel dm = new DataModel();  

The controller action getData accepting the parameter id, right? This is actually the page offset value which we are passing from the client side. Now we will create our model class, you can find the code snippets below for that.
    using System;  
    using System.Collections.Generic;  
    using System.Linq;  
    using System.Web;  
    using System.Data;  
    using System.Data.Sql;  
    using System.Data.SqlClient;  
    using System.Configuration;  
    namespace Custom_Deffered_Grid_Using_MVC_Web_API_And_Angular_JS.Models  
    {  
        public class DataModel  
        {  
        public string fetchData(int pageOffset)  
        {  
            string connection = ConfigurationManager.ConnectionStrings["TrialsDBEntities"].ConnectionString;  
            using (SqlConnection cn = new SqlConnection(connection))  
            {  
            SqlCommand cmd = new SqlCommand("usp_Get_SalesOrderDetailPage", cn);  
            cmd.Parameters.Add("@pageoffset", SqlDbType.Int).Value = pageOffset;  
            cmd.CommandType = CommandType.StoredProcedure;  
            try  
                {  
                DataTable dt = new DataTable();  
                SqlDataAdapter da = new SqlDataAdapter(cmd);  
                cn.Open();  
                da.Fill(dt);  
                return GetJson(dt);  
                }  
            catch (Exception)  
            {  
            throw;  
            }  
          }  
        }  
     }  
    }


As I said before, instead of using an entity model we use our normal sql connections and sql data adapter to load the data. Before going to use this function, please make sure that you have added the below references.
    using System.Data;  
    using System.Data.Sql;  
    using System.Data.SqlClient;  
    using System.Configuration;


Now coming back to the fetchData function, we use the connection string TrialsDBEntities from the web config file. So it is mandatory that you must have a connection string with that name in your web config file. Once that is done, we call the stored procedure usp_Get_SalesOrderDetailPage and fill the data using SqlDataAdapter. 

Another thing to be notified here is we are passing that DataTable to a function called GetJson. So you must have the definition for that too.
    public string GetJson(DataTable dt)  
    {  
     try  
     {  
       if (dt == null)  
        {  
          throw new ArgumentNullException("dt");  
        }  
       System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();  
       List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();  
       Dictionary<string, object> row = null;  
       foreach (DataRow dr in dt.Rows)  
       {  
        row = new Dictionary<string, object>();  
        foreach (DataColumn col in dt.Columns)  
         {  
           row.Add(col.ColumnName.Trim(), dr[col]);  
         }  
         rows.Add(row);  
       }  
    return serializer.Serialize(rows);  
    }  
    catch (Exception)  
    {  
    throw;  
    }  
    } 


What this function does is, it converts the data table to a JSON format. So far, the coding related to Web API is done, now it is time to create a database, table, and a stored procedure. 

Create a database
The following query can be used to create a database in your SQL Server.
    USE [master]  
    GO  
    /****** Object: Database [TrialsDB] Script Date: 25-Feb-16 12:34:32 PM ******/  
    CREATE DATABASE [TrialsDB]  
    CONTAINMENT = NONE  
    ON PRIMARY  
    ( NAME = N'TrialsDB', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB.mdf' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )  
    LOG ON  
    ( NAME = N'TrialsDB_log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\TrialsDB_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)  
    GO  
    ALTER DATABASE [TrialsDB] SET COMPATIBILITY_LEVEL = 110  
    GO  
    IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))  
    begin  
    EXEC [TrialsDB].[dbo].[sp_fulltext_database] @action = 'enable'  
    end  
    GO  
    ALTER DATABASE [TrialsDB] SET ANSI_NULL_DEFAULT OFF  
    GO  
    ALTER DATABASE [TrialsDB] SET ANSI_NULLS OFF  
    GO  
    ALTER DATABASE [TrialsDB] SET ANSI_PADDING OFF  
    GO  
    ALTER DATABASE [TrialsDB] SET ANSI_WARNINGS OFF  
    GO  
    ALTER DATABASE [TrialsDB] SET ARITHABORT OFF  
    GO  
    ALTER DATABASE [TrialsDB] SET AUTO_CLOSE OFF  
    GO  
    ALTER DATABASE [TrialsDB] SET AUTO_CREATE_STATISTICS ON  
    GO  
    ALTER DATABASE [TrialsDB] SET AUTO_SHRINK OFF  
    GO  
    ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS ON  
    GO  
    ALTER DATABASE [TrialsDB] SET CURSOR_CLOSE_ON_COMMIT OFF  
    GO  
    ALTER DATABASE [TrialsDB] SET CURSOR_DEFAULT GLOBAL  
    GO  
    ALTER DATABASE [TrialsDB] SET CONCAT_NULL_YIELDS_NULL OFF  
    GO  
    ALTER DATABASE [TrialsDB] SET NUMERIC_ROUNDABORT OFF  
    GO  
    ALTER DATABASE [TrialsDB] SET QUOTED_IDENTIFIER OFF  
    GO  
    ALTER DATABASE [TrialsDB] SET RECURSIVE_TRIGGERS OFF  
    GO  
    ALTER DATABASE [TrialsDB] SET DISABLE_BROKER  
    GO  
    ALTER DATABASE [TrialsDB] SET AUTO_UPDATE_STATISTICS_ASYNC OFF  
    GO  
    ALTER DATABASE [TrialsDB] SET DATE_CORRELATION_OPTIMIZATION OFF  
    GO  
    ALTER DATABASE [TrialsDB] SET TRUSTWORTHY OFF  
    GO  
    ALTER DATABASE [TrialsDB] SET ALLOW_SNAPSHOT_ISOLATION OFF  
    GO  
    ALTER DATABASE [TrialsDB] SET PARAMETERIZATION SIMPLE  
    GO  
    ALTER DATABASE [TrialsDB] SET READ_COMMITTED_SNAPSHOT OFF  
    GO  
    ALTER DATABASE [TrialsDB] SET HONOR_BROKER_PRIORITY OFF  
    GO  
    ALTER DATABASE [TrialsDB] SET RECOVERY FULL  
    GO  
    ALTER DATABASE [TrialsDB] SET MULTI_USER  
    GO  
    ALTER DATABASE [TrialsDB] SET PAGE_VERIFY CHECKSUM  
    GO  
    ALTER DATABASE [TrialsDB] SET DB_CHAINING OFF  
    GO  
    ALTER DATABASE [TrialsDB] SET FILESTREAM( NON_TRANSACTED_ACCESS = OFF )  
    GO  
    ALTER DATABASE [TrialsDB] SET TARGET_RECOVERY_TIME = 0 SECONDS  
    GO  
    ALTER DATABASE [TrialsDB] SET READ_WRITE  
    GO 


Now we will create a table. 

Create table in database
Below is the query to create table in database.
    USE [TrialsDB]  
    GO  
    /****** Object: Table [dbo].[SalesOrderDetail] Script Date: 25-Feb-16 12:35:45 PM ******/  
    SET ANSI_NULLS ON  
    GO  
    SET QUOTED_IDENTIFIER ON  
    GO  
    CREATE TABLE [dbo].[SalesOrderDetail](  
    [SalesOrderID] [int] NOT NULL,  
    [SalesOrderDetailID] [int] IDENTITY(1,1) NOT NULL,  
    [CarrierTrackingNumber] [nvarchar](25) NULL,  
    [OrderQty] [smallint] NOT NULL,  
    [ProductID] [int] NOT NULL,  
    [SpecialOfferID] [int] NOT NULL,  
    [UnitPrice] [money] NOT NULL,  
    [UnitPriceDiscount] [money] NOT NULL,  
    [LineTotal] AS (isnull(([UnitPrice]*((1.0)-[UnitPriceDiscount]))*[OrderQty],(0.0))),  
    [rowguid] [uniqueidentifier] ROWGUIDCOL NOT NULL,  
    [ModifiedDate] [datetime] NOT NULL,  
    CONSTRAINT [PK_SalesOrderDetail_SalesOrderID_SalesOrderDetailID] PRIMARY KEY CLUSTERED  
    (  
    [SalesOrderID] ASC,  
    [SalesOrderDetailID] 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  


Can we insert some data to the table now?

Insert data to table
To insert the data, I will attach a database script file along with the download file, you can either run that or insert some data using the following query. By the way if you would like to know how to generate scripts with data in SQL Server, you can check here.
    USE [TrialsDB]  
    GO  
    INSERT INTO [dbo].[SalesOrderDetail]  
    ([SalesOrderID]  
    ,[CarrierTrackingNumber]  
    ,[OrderQty]  
    ,[ProductID]  
    ,[SpecialOfferID]  
    ,[UnitPrice]  
    ,[UnitPriceDiscount]  
    ,[rowguid]  
    ,[ModifiedDate])  
    VALUES  
    (<SalesOrderID, int,>  
    ,<CarrierTrackingNumber, nvarchar(25),>  
    ,<OrderQty, smallint,>  
    ,<ProductID, int,>  
    ,<SpecialOfferID, int,>  
    ,<UnitPrice, money,>  
    ,<UnitPriceDiscount, money,>  
    ,<rowguid, uniqueidentifier,>  
    ,<ModifiedDate, datetime,>)  
    GO

Along with this, we can create a new stored procedure which will fetch the data. The following is the query to create the stored procedure.
    USE [TrialsDB]  
    GO  
    /****** Object: StoredProcedure [dbo].[usp_Get_SalesOrderDetailPage] Script Date: 25-Feb-16 12:53:07 PM ******/  
    SET ANSI_NULLS ON  
    GO  
    SET QUOTED_IDENTIFIER ON  
    GO  
    -- =============================================  
    -- Author: <Author,Sibeesh Venu>  
    -- Create date: <Create Date, 18-Feb-2016>  
    -- Description: <Description,To fetch SalesOrderDetail Page Wise>  
    -- =============================================  
    ALTER PROCEDURE [dbo].[usp_Get_SalesOrderDetailPage] @pageOffset int=0 AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from  
    -- interfering with SELECT statements.  
    SET NOCOUNT ON;  
    WITH CTE_Sales(SlNo, SalesOrderID,SalesOrderDetailID,CarrierTrackingNumber,OrderQty,ProductID,UnitPrice,ModifiedDate) AS  
    ( SELECT ROW_NUMBER() over (  
    ORDER BY ModifiedDate DESC) AS SlNo,  
    SalesOrderID,  
    SalesOrderDetailID,  
    CarrierTrackingNumber,  
    OrderQty,  
    ProductID,  
    UnitPrice,  
    ModifiedDate  
    FROM dbo.SalesOrderDetail)  
    SELECT *  
    FROM CTE_Sales  
    WHERE SlNo>=@pageOffset  
    AND SlNo<@pageOffset+10 END  
    --[usp_Get_SalesOrderDetailPage] 4  


Here we are using Common Table Expressions in SQL Server. If you are new to CTE, you can always visit"Common Table Expression Example" for some more information regarding that. It seems the database is ready with the data now. Then we can go back to our view. We will change our view as follows with the custom styles.
    @{  
    ViewBag.Title = "Index";  
    }  
    <h2>Index</h2>  
    <link href="~/Content/angular-material.css" rel="stylesheet" />  
    <style>  
    .virtualRepeatdemoDeferredLoading #vertical-container {  
    padding: 10px;  
    border: 1px solid #ccc;  
    border-radius: 5px;  
    box-shadow: 1px 10px 10px 1px #ccc;  
    background-color: #fff;  
    width: 40%;  
    height: 390px;  
    margin: 20px;  
    }  
    .virtualRepeatdemoDeferredLoading .repeated-item {  
    border-bottom: 1px solid #ddd;  
    box-sizing: border-box;  
    height: 40px;  
    padding: 10px;  
    border: 1px solid #ccc;  
    border-radius: 5px;  
    box-shadow: 1px 10px 10px 1px #ccc;  
    background-color: #fff;  
    width: 90%;  
    height: 120px;  
    margin: 20px;  
    color: #aaa;  
    font-size: 12px;  
    line-height: 20px;  
    }  
    .virtualRepeatdemoDeferredLoading md-content {  
    margin: 16px;  
    }  
    .virtualRepeatdemoDeferredLoading md-virtual-repeat-container {  
    border: solid 1px grey;  
    }  
    .virtualRepeatdemoDeferredLoading .md-virtual-repeat-container .md-virtual-repeat-offsetter div {  
    padding-left: 16px;  
    }  
    #introduction {  
    border-bottom: 1px solid #ddd;  
    box-sizing: border-box;  
    height: 40px;  
    padding: 10px;  
    border: 1px solid #ccc;  
    border-radius: 5px;  
    box-shadow: 1px 10px 10px 1px #ccc;  
    background-color: #fff;  
    width: 98%;  
    height: 70px;  
    color: #aaa;  
    font-size: 12px;  
    line-height: 25px;  
    }  
    </style>  
    <div ng-controller="AppCtrl as ctrl" ng-cloak="" class="virtualRepeatdemoDeferredLoading" ng-app="MyApp">  
    <md-content layout="column">  
    <div id="introduction">  
    <p>  
    Please scroll the Grid to load the data from database. This is a simple demo of deffered or virtual data loading in Angular JS.  
    We created this application MVC with Web API to fetch the data. I hope you enjoyed the demo. Please visit again <img src="http://sibeeshpassion.com/wp-includes/images/smilies/simple-smile.png" alt=":)" class="wp-smiley" style="height: 1em; max-height: 1em;">  
    </p>  
    </div>  
    <md-virtual-repeat-container id="vertical-container">  
    <div md-virtual-repeat="item in ctrl.dynamicItems" md-on-demand="" class="repeated-item" flex="">  
    <div> <b>SlNo:</b> {{item.SlNo}}, <b>SalesOrderID:</b> {{item.SalesOrderID}}</div>  
    <div> <b>SalesOrderDetailID:</b> {{item.SalesOrderDetailID}}, <b>CarrierTrackingNumber:</b> {{item.CarrierTrackingNumber}}</div>  
    <div> <b>OrderQty:</b> {{item.OrderQty}}, <b>ProductID:</b> {{item.ProductID}}</div>  
    <div> <b>UnitPrice:</b> {{item.UnitPrice}}</div>  
    </div>  
    </md-virtual-repeat-container>  
    </md-content>  
    </div>  
    <script src="~/scripts/angular.min.js"></script>  
    <script src="~/scripts/angular-route.min.js"></script>  
    <script src="~/scripts/angular-aria.min.js"></script>  
    <script src="~/scripts/angular-animate.min.js"></script>  
    <script src="~/scripts/angular-messages.min.js"></script>  
    <script src="~/scripts/angular-material.js"></script>  
    <script src="~/scripts/svg-assets-cache.js"></script>  
    <script src="~/scripts/Default/Default.js"></script>   


As you can see from the above code, our AngularJS controller is ng-controller=”AppCtrl as ctrl” and the AngularJS app is ng-app=”MyApp”. We use md-virtual-repeat as a repeater control, so that it can be used to loop through the object item in ctrl.dynamicItems. Now it is time to create our AngularJS scripts. Shall we?

We can create our Angular App and Controller as follows.
    (function () {  
    'use strict';  
    angular  
    .module('MyApp', ['ngMaterial', 'ngMessages', 'material.svgAssetsCache'])  
    .controller('AppCtrl', function ($http, $timeout) {  
    });  
    })();


Now in the controller we will add a function with some predefined items as follows.
    var DynamicItems = function () {  
    this.loadedPages = {};  
    this.numItems = 0;  
    this.PAGE_SIZE = 10;  
    this.fetchNumItems_();  
    };  


Here loadedPages is the data collection which is keyed by the page number (Our parameter id in the controller). And numItems is the total number of items. PAGE_SIZE is the number of items to be fetched from each requests.

Now we will create a function to calculate the length of the records.
    DynamicItems.prototype.getLength = function () {  
    return this.numItems;  
    };  


This numItems can be set in the below function.
    DynamicItems.prototype.fetchNumItems_ = function () {  
    $timeout(angular.noop, 300).then(angular.bind(this, function () {  
    this.numItems = 1000;  
    }));  
    };  


Here we are setting the numItems as 1000 for demo purposes, you can always get the count from database and assign it here with a $http request as we load the data from database here, you are yet to see that, no worries.

Below is the function to get the item by index.
    DynamicItems.prototype.getItemAtIndex = function (index) {  
    var pageNumber = Math.floor(index / this.PAGE_SIZE);  
    var page = this.loadedPages[pageNumber];  
    if (page)  
     {  
       return page[index % this.PAGE_SIZE];  
     } else if (page !== null)  
     {  
       this.fetchPage_(pageNumber);  
     }  
    };  

Here is the main part to load the data from database using a $http service in AngularJS.
    DynamicItems.prototype.fetchPage_ = function (pageNumber) {  
    this.loadedPages[pageNumber] = null;  
    $timeout(angular.noop, 300).then(angular.bind(this, function () {  
    var thisObj = this;  
    this.loadedPages[pageNumber] = [];  
    var pageOffset = pageNumber * this.PAGE_SIZE;  
    var myData;  
    var url = '';  
    url = 'api/DataAPI/' + pageOffset;  
    $http({  
    method: 'GET',  
    url: url,  
    }).then(function successCallback(response) {  
    // this callback will be called asynchronously  
    // when the response is available  
    myData = JSON.parse(response.data);  
    pushLoadPages(thisObj, myData)  
    }, function errorCallback(response) {  
    console.log('Oops! Something went wrong while fetching the data. Status Code: ' + response.status + ' Status statusText: ' + response.statusText);  
    // called asynchronously if an error occurs  
    // or server returns response with an error status.  
    });  
    }));  
    };   

As you can see call to our Web API ( url = ‘api/DataAPI/’ + pageOffset;) from $http service, the callback functionSuccessCallback will get the data from database as a response. Once we get the response, we will pass the data to a function pushLoadPages to push the data items to the loadedPages. Cool right? Below is the code snippets for that function.
    function pushLoadPages(thisObj, servData)   
    {  
    if (servData != undefined)  
    {  
        for (var i = 0; i < servData.length; i++)  
        {  
            thisObj.loadedPages[pageNumber].push(servData[i]);  
        }  
    }  
    }  


Here is the complete code for our AngularJS. 

AngularJS Complete Code
    (function () {  
    'use strict';  
    angular  
    .module('MyApp', ['ngMaterial', 'ngMessages', 'material.svgAssetsCache'])  
    .controller('AppCtrl', function ($http, $timeout) {  
    var DynamicItems = function () {  
    this.loadedPages = {};  
    this.numItems = 0;  
    this.PAGE_SIZE = 10;  
    this.fetchNumItems_();  
    };  
    DynamicItems.prototype.getItemAtIndex = function (index) {  
    var pageNumber = Math.floor(index / this.PAGE_SIZE);  
    var page = this.loadedPages[pageNumber];  
    if (page) {  
    return page[index % this.PAGE_SIZE];  
    } else if (page !== null) {  
    this.fetchPage_(pageNumber);  
    }  
    };  
    DynamicItems.prototype.getLength = function () {  
    return this.numItems;  
    };  
    DynamicItems.prototype.fetchPage_ = function (pageNumber) {  
    this.loadedPages[pageNumber] = null;  
    $timeout(angular.noop, 300).then(angular.bind(this, function () {  
    var thisObj = this;  
    this.loadedPages[pageNumber] = [];  
    var pageOffset = pageNumber * this.PAGE_SIZE;  
    var myData;  
    var url = '';  
    url = 'api/DataAPI/' + pageOffset;  
    $http({  
    method: 'GET',  
    url: url,  
    }).then(function successCallback(response) {  
    // this callback will be called asynchronously  
    // when the response is available  
    myData = JSON.parse(response.data);  
    pushLoadPages(thisObj, myData)  
    }, function errorCallback(response) {  
    console.log('Oops! Something went wrong while fetching the data. Status Code: ' + response.status + ' Status statusText: ' + response.statusText);  
    // called asynchronously if an error occurs  
    // or server returns response with an error status.  
    });  
    function pushLoadPages(thisObj, servData) {  
    if (servData != undefined) {  
    for (var i = 0; i < servData.length; i++) {  
    thisObj.loadedPages[pageNumber].push(servData[i]);  
    }  
    }  
    }  
    }));  
    };  
    DynamicItems.prototype.fetchNumItems_ = function () {  
    $timeout(angular.noop, 300).then(angular.bind(this, function () {  
    this.numItems = 1000;  
    }));  
    };  
    this.dynamicItems = new DynamicItems();  
    });  
    })();    



About HostForLIFE.eu

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 offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in