Full Trust European Hosting

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

European Visual Studio 2022 Hosting - HostForLIFE :: Create Your First Visual Studio Extension

clock April 19, 2023 08:09 by author Peter

In this article, we will look into the basics of visual studio extension. Also, create one application and understand file structure and implementation.


How to Create a New VSIX Project?
Step 1
Install Visual Studio extension development from Tools-> Get Tools and Features.

Step 2
Next, install Extensibility Essentials 2022, which helps us write different extensions.

Step 4
Configure a new project.


Step 3
Create a new VSIX Project

  • Many VSIX project templates are available, each with its purpose and usage.
  • VSIX Project w/Command (Community) template comes with a command hooked up, which helps us start a new extension easily after creating commands and configuring the same with Visual Studio.
  • VSIX Project w/Tool Window (Community) template with tool window command.
  • Empty VSIX Project (Community) and VSIX Project (Community) templates for MEF-only extensions or use in advanced customized scenarios.

But, here in this article, we will use VSIX Project w/Command (Community) template.

Step 5
Default Project Structure

As you can see, it will create different files inside the VSIX project solution, each with its purpose. So, we looked into them one by one and understood their purpose of it.

MyCommand.cs
The command handler file executes logic when the user triggers the command.
namespace VSIXProject
{
    [Command(PackageIds.MyCommand)]
    internal sealed class MyCommand : BaseCommand<MyCommand>
    {
        protected override async Task ExecuteAsync(OleMenuCmdEventArgs e)
        {
            await VS.MessageBox.ShowWarningAsync("VSIXProject", "Button clicked");
        }
    }
}

Resources/icon.png
This file is used to set icons for our extension. We can also set our custom icons for the same.

source.extension.vsixmanifest
It contains metadata of our extensions project like name, description, version, tags, author, etc.
// ------------------------------------------------------------------------------
// <auto-generated>
//     This file was generated by the extension VSIX Synchronizer
// </auto-generated>
// ------------------------------------------------------------------------------
namespace VSIXProject
{
    internal sealed partial class Vsix
    {
        public const string Id = "VSIXProject.34901e8a-0458-4252-9662-9ca734552faf";
        public const string Name = "VSIXProject";
        public const string Description = @"Empty VSIX Project.";
        public const string Language = "en-US";
        public const string Version = "1.0";
        public const string Author = "jaydeepvpatil225";
        public const string Tags = "";
    }
}

VSCommandTable.vsct
This XML file contains the binding of different commands with ids, button text for our command, parent menu, and many more.
<?xml version="1.0" encoding="utf-8"?>
<CommandTable xmlns="http://schemas.microsoft.com/VisualStudio/2005-10-18/CommandTable" xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <Extern href="stdidcmd.h"/>
  <Extern href="vsshlids.h"/>
  <Include href="KnownImageIds.vsct"/>
  <Include href="VSGlobals.vsct"/>

  <Commands package="VSIXProject">
    <Groups>
      <Group guid="VSIXProject" id="MyMenuGroup" priority="0x0600">
        <Parent guid="VSMainMenu" id="Tools"/>
      </Group>
    </Groups>

    <!--This section defines the elements the user can interact with, like a menu command or a button
        or combo box in a toolbar. -->
    <Buttons>
      <Button guid="VSIXProject" id="MyCommand" priority="0x0100" type="Button">
        <Parent guid="VSIXProject" id="MyMenuGroup" />
        <Icon guid="ImageCatalogGuid" id="StatusInformation" />
        <CommandFlag>IconIsMoniker</CommandFlag>
        <Strings>
          <ButtonText>My Command</ButtonText>
          <LocCanonicalName>.VSIXProject.MyCommand</LocCanonicalName>
        </Strings>
      </Button>
    </Buttons>
  </Commands>

  <Symbols>
    <GuidSymbol name="VSIXProject" value="{bb2edf02-da6e-4673-b2a4-b3b7449b2ce7}">
      <IDSymbol name="MyMenuGroup" value="0x0001" />
      <IDSymbol name="MyCommand" value="0x0100" />
    </GuidSymbol>
  </Symbols>
</CommandTable>

VSIXProjectPackage
This file has one Initialize method that registers commands asynchronously when we run our extension project.
global using Community.VisualStudio.Toolkit;
global using Microsoft.VisualStudio.Shell;
global using System;
global using Task = System.Threading.Tasks.Task;
using System.Runtime.InteropServices;
using System.Threading;

namespace VSIXProject
{
    [PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)]
    [InstalledProductRegistration(Vsix.Name, Vsix.Description, Vsix.Version)]
    [ProvideMenuResource("Menus.ctmenu", 1)]
    [Guid(PackageGuids.VSIXProjectString)]
    public sealed class VSIXProjectPackage : ToolkitPackage
    {
        protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
        {
            await this.RegisterCommandsAsync();
        }
    }
}


Step 6

Run Project
When we run the project, it will open one experimental visual studio and keep its own things separately related to settings.

As we can see, our command comes up under the Tool menu “MyCommand”, and when you click on it, a message popup with details that we put inside the MyCommand file. Here we just looked into the basics, but you can customize it as required and perform different operations.

This is all about VSIX Sample Project. Here we discussed the basics of VSIX Extension with a demo application implementation and its file structure details.
Happy Coding!!!



AngularJS Hosting Europe - HostForLIFE :: How To Set And Get Cookies In Angular With Example?

clock April 14, 2023 10:22 by author Peter

You can use the next-cookie-service package to set and get cookies in Angular. Here's an example,


1. First, install the ngx-cookie-service package using the following command.
npm install ngx-cookie-service --save

2. Import the CookieService from the ngx-cookie-service package in your component.
import { CookieService } from 'ngx-cookie-service';

3. Create an instance of the CookieService in your constructor.
constructor(private cookieService: CookieService) { }

4. To set a cookie, use the set method of the CookieService.
this.cookieService.set('cookieName', 'cookieValue');

5. To get a cookie, use the get method of the CookieService.
const cookieValue = this.cookieService.get('cookieName');

Here's the complete code for setting and getting a cookie:
import { Component } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  constructor(private cookieService: CookieService) {
    // Set cookie
    this.cookieService.set('cookieName', 'cookieValue');

    // Get cookie
    const cookieValue = this.cookieService.get('cookieName');
    console.log('Cookie value:', cookieValue);
  }
}


Note. Remember to import the CookieModule in your app.module.ts file after installing the package.
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { CookieModule } from 'ngx-cookie';
import { AppComponent } from './app.component';

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


I hope this helps. If this helps you, then share it with others.
Sharing is caring! :)



AngularJS Hosting Europe - HostForLIFE :: Interceptors In Angular Along With Benefits

clock April 10, 2023 08:33 by author Peter

In Angular, an interceptor is a middleware that intercepts HTTP requests and responses. Interceptors are used to manipulate or transform HTTP requests and responses globally. This means you can modify HTTP requests and responses in one place and affect all the requests and responses that go through that place.

 

Ininterceptors In Angular
Interceptors are a powerful tool in Angular as they can be used for a wide variety of tasks, such as,
    Adding authorization headers to requests
    Logging requests and responses
    Adding or removing parameters from requests
    Transforming response data

How to implement an interceptor in Angular?
To implement an interceptor in Angular, you need to create a class that implements the HttpInterceptor interface. The HttpInterceptor interface has two methods to implement: intercept() and, optionally, handleError().

So let's start. Here's an example of an interceptor that adds an authorization header to every HTTP request,
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
    intercept(request: HttpRequest < any > , next: HttpHandler): Observable < HttpEvent < any >> {
        // Get the access token from your authentication service
        const accessToken = this.authService.getAccessToken();
        // Clone the request and add the authorization header
        const authRequest = request.clone({
            headers: request.headers.set('Authorization', `Bearer ${accessToken}`)
        });
        // Pass the cloned request to the next handler in the chain
        return next.handle(authRequest);
    }
}


In this example, the AuthInterceptor class implements the HttpInterceptor interface and overrides the intercept() method. In the intercept() method, we get the access token from our authentication service and clone the incoming request, adding an authorization header. We then pass the cloned request to the next handler in the chain using the next.handle() method.

To use this interceptor, register it with the Angular HTTP client. You can do this by providing it in the provider's array of your AppModule,
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';

import { AuthInterceptor } from './auth.interceptor';

@NgModule({
    imports: [BrowserModule, HttpClientModule],
    providers: [{
        provide: HTTP_INTERCEPTORS,
        useClass: AuthInterceptor,
        multi: true
    }]
})
export class AppModule {}


In this example, we import the HttpClientModule and our AuthInterceptor class. We then provide our interceptor in the provider's array using the HTTP_INTERCEPTORS token. The multi-option is set to true, which means that this interceptor is added to the existing array of HTTP interceptors rather than replacing it.
Benefits of using interceptors in Angular

    Interceptors allow the manipulation of HTTP requests and responses globally, making it easy to implement cross-cutting concerns such as authentication and error handling.
    Interceptors can reduce code duplication by providing a centralized place to modify requests and responses.
    Interceptors can be easily added or removed, making it easy to change the behavior of your application without having to modify every HTTP request and response.

Summary
Interceptors are a powerful Angular tool that allows you to manipulate HTTP requests and responses globally. They can be used for various tasks and provide a centralized place to modify requests and responses. By using interceptors, you can reduce code duplication and easily add or remove functionality from your application.



AngularJS Hosting Europe - HostForLIFE :: Build Multi-Repo Micro-Frontend Using Angular And Webpack 5 Module Federation

clock April 3, 2023 07:47 by author Peter

Angular is one of the popular Single Page Application framework. It is commonly used to build monolithic front-end applications. It supports the lazy loading of modules, allowing the browser to load the feature modules on demand. Angular internally uses Webpack as the bundling tool. Micro-frontend is a pattern that allows you to build the frontend applications as individual applications(remote) that can be integrated within a shell(host) application. Module federation plugin of the Webpack allows you to load these micro-frontend applications into a shell application.


This tutorial helps you to build Micro-frontends using Angular and Webpack Module Federation.
Prerequisites
    Angular CLI: Version 14.0.0 (use exact version)
    Module Federation library for Angular (@angular-architects/module-federation): 14.3.0 (compatible to Angular 14.0.0)
    Node 16.x or later
    Visual Studio Code

Build first remote(Micro-frontend) application (Auth-MFE)

1) Open the command terminal and create an Angular workspace for the first micro-frontend application. Run the following command to create a workspace for auth-app-remote.
ng new auth-app-remote --create-application false --skip-tests

2) Switch to the workspace folder and create a project inside the auth-app-remote.
cd auth-app-remote
ng g app auth-mfe --skip-tests --routing

3) Add a home component to the application.
ng g c components/home --project auth-mfe

4) Create a feature module for the auth-mfe project.
ng g module --project auth-mfe --routing auth

5) Add a component login to the auth feature module.
ng g c --project auth-mfe --module auth auth/components/login

6) Updates the auth-routing.module.ts file with the following route configuration.
const routes: Routes = [{
    path: 'login',
    component: LoginComponent
}];
@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class AuthRoutingModule {}


7) Update the app-routing.module.ts file with the following routing configuration.
const routes: Routes = [{
    path: '',
    component: HomeComponent,
    pathMatch: 'full'
}, {
    path: 'auth',
    loadChildren: () => import('./auth/auth.module').then(m => m.AuthModule)
}];
@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule {}

8) Install the bootstrap and jquery libraries to the project.
npm install [email protected] jquery --save

9) Open the app.component.html file and replace the existing code with the following code.
<nav class="navbar navbar-expand-lg bg-primary bg-body-tertiary" data-bs-theme="dark">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">Auth MFE</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNav">
      <ul class="navbar-nav">
        <li class="nav-item">
          <a class="nav-link active" aria-current="page" href="#">Home</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" routerLink="auth/login">Login</a>
        </li>
      </ul>
    </div>
  </div>
</nav>
<div class="container">
  <router-outlet></router-outlet>
</div>


10) Run and test the application.
ng serve --port 4200 -o

Configure the application with module federation
11) Install the Module federation plugin to the application. Install the supported version of the @angular-architects/module-federation based on the Angular CLI. In this demo, we are using Angular 14.0.0, so the supported version of the module federation plugin is 14.3.0.
ng add @angular-architects/[email protected] --type remote --project auth-mfe --port 4200

12) Open the webpack.config.js file, and update the name and exposes properties.
const {
    shareAll,
    withModuleFederationPlugin
} = require('@angular-architects/module-federation/webpack');
module.exports = withModuleFederationPlugin({
    name: 'auth-mfe',
    exposes: {
        './Module': './projects/auth-mfe/src/app/auth/auth.module.ts',
    },
    shared: {
        ...shareAll({
            singleton: true,
            strictVersion: true,
            requiredVersion: 'auto'
        }),
    },
});


13) Run and test the application.
ng serve --port 4200 -o

Build second remote(Micro-frontend) application (Book-MFE)

1) Open the command terminal and create an Angular workspace for another micro-frontend application. Run the following command to create a workspace for book-app-remote
ng new book-app-remote --create-application false --skip-tests

2) Switch to the workspace folder and create a project inside the book-app-remote.
cd book-app-remote
ng g app book-mfe --skip-tests --routing


3) Add a home component to the application.
ng g c components/home --project book-mfe

4) Create a feature module for the book-mfe project.
ng g module --project book-mfe --routing book

5) Add a component book-list to the book feature module.
ng g c --project book-mfe --module book book/components/book-list

6) Updates the book-routing.module.ts file with the following route configuration.
const routes: Routes = [{
    path: 'list',
    component: BookListComponent
}];
@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
})
export class BookRoutingModule {}

7) Update the app-routing.module.ts file with the following routing configuration.
const routes: Routes = [{
    path: '',
    component: HomeComponent,
    pathMatch: 'full'
}, {
    path: 'books',
    loadChildren: () => import('./book/book.module').then(m => m.BookModule)
}];
@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule {}

8) Install the bootstrap and jquery libraries to the project.
npm install [email protected] jquery --save

9) Open the app.component.html file and replace the existing code with the following code.
<nav class="navbar navbar-expand-lg bg-primary bg-body-tertiary" data-bs-theme="dark">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">Book MFE</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNav">
      <ul class="navbar-nav">
        <li class="nav-item">
          <a class="nav-link active" aria-current="page" href="#">Home</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" routerLink="books/list">Books</a>
        </li>
      </ul>
    </div>
  </div>
</nav>
<div class="container">
  <router-outlet></router-outlet>
</div>


10) Run and test the application.
ng serve --port 4200 -o

Configure the application with module federation
11) Install the Module federation plugin to the application.
ng add @angular-architects/[email protected] --type remote --project book-mfe --port 4300

12) Open the webpack.config.js file, and update the name and exposes properties.
const {
    shareAll,
    withModuleFederationPlugin
} = require('@angular-architects/module-federation/webpack');
module.exports = withModuleFederationPlugin({
    name: 'book-mfe',
    exposes: {
        './Module': './projects/book-mfe/src/app/book/book.module.ts',
    },
    shared: {
        ...shareAll({
            singleton: true,
            strictVersion: true,
            requiredVersion: 'auto'
        }),
    },
});


13) Run and test the application.
ng serve --port 4300 -o

Create a Shell(Host) Application (BookStore-Host)
1) Open the command terminal and create an Angular workspace for a shell application. Run the following command to create a workspace for bookstore-host .
ng new bookstore-host --create-application false --skip-tests

2) Switch to the workspace folder and create a project inside the bookstore-host.
cd bookstore-host
ng g app bookstore-shell --skip-tests --routing


3) Add a home component to the application.
ng g c components/home --project bookstore-shell

4) Update the app-routing.module.ts file with the following routing configuration.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './components/home/home.component';

const routes: Routes = [{
    path: '',
    component: HomeComponent,
    pathMatch: 'full'
}];
@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule {}


5) Install the bootstrap and jquery libraries to the project.
npm install [email protected] jquery --save

6) Open the app.component.html file and replace the existing code with the following code.
<nav class="navbar navbar-expand-lg bg-primary bg-body-tertiary" data-bs-theme="dark">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">Bookstore</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNav">
      <ul class="navbar-nav">
        <li class="nav-item">
          <a class="nav-link active" aria-current="page" routerLink="">Home</a>
        </li>
      </ul>
    </div>
  </div>
</nav>
<div class="container">
  <router-outlet></router-outlet>
</div>

7) Run and test the application.
ng serve --port 5000 -o

Configure the shell application with module federation

8) Install the Module federation plugin to the application.
ng add @angular-architects/[email protected] --type host --project bookstore-shell --port 5000

9) Open the webpack.config.js file, and update the remote property.
const {
    shareAll,
    withModuleFederationPlugin
} = require('@angular-architects/module-federation/webpack');
module.exports = withModuleFederationPlugin({
    remotes: {
        "auth-mfe": "http://localhost:4200/remoteEntry.js",
        "book-mfe": "http://localhost:4300/remoteEntry.js"
    },
    shared: {
        ...shareAll({
            singleton: true,
            strictVersion: true,
            requiredVersion: 'auto'
        }),
    },
});


10) Open the app-routing.module.ts file and update the routes for loading the auth and book micro-frontends.
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomeComponent } from './components/home/home.component';

const routes: Routes = [{
    path: '',
    component: HomeComponent,
    pathMatch: 'full'
}, {
    path: 'auth',
    loadChildren: () => import('auth-mfe/Module').then(m => m.AuthModule)
}, {
    path: 'books',
    loadChildren: () => import('book-mfe/Module').then(m => m.BookModule)
}];
@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule {}


11) Update the app.component.html to add the hyperlinks for invoking book list and login components from the micro-frontends.
<nav class="navbar navbar-expand-lg bg-primary bg-body-tertiary" data-bs-theme="dark">
  <div class="container-fluid">
    <a class="navbar-brand" href="#">Bookstore</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <div class="collapse navbar-collapse" id="navbarNav">
      <ul class="navbar-nav">
        <li class="nav-item">
          <a class="nav-link active" aria-current="page" routerLink="">Home</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" routerLink="books/list">Books</a>
        </li>
        <li class="nav-item">
          <a class="nav-link" routerLink="auth/login">Login</a>
        </li>
      </ul>
    </div>
  </div>
</nav>
<div class="container">
  <router-outlet></router-outlet>
</div>

12) Run and test the application.
ng serve --port 5000 -o



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