Asp.net And HTML Css And Web Development: How to Connect Aspl.net MVC Signalr Hub To Angular...

Asp.net And HTML Css And Web Development: How to Connect Aspl.net MVC Signalr Hub To Angular...: How to Connect Aspl.net MVC Signalr Hub To Angular 6 web site  Firstly you need to install nuget package for Create Hub in asp.net w...

How to Connect Aspl.net MVC Signalr Hub To Angular 6 web site

How to Connect Aspl.net MVC Signalr Hub To Angular 6 web site 


Firstly you need to install nuget package for Create Hub in asp.net web api
for install package 
1). open nuget package manage :- (first Create Project )
    1)  Open Visual Studio go to > File >New Project Choose ASP.Net MVC application.
    2). Used MVC. Check Web API reference then hit ok button
    3). Right click the project > Manage NuGet package > Browse to install
                                  or
          write command nuget package manager console
                "Install-Package Microsoft.AspNet.SignalR."

2). now you need to create hub class 

using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;

namespace Tritex.Api
{
    [HubName("SendNotificationHub")]
    public class NotificationHub : Hub
    { 
        public void NotificationService(string message)
        { 
            Clients.All.messageReceived(message);
        }
    }

3). Create Owin startup.cs class if not avaible 


using Microsoft.Owin;  
using Owin;  
  
[assembly: OwinStartupAttribute(typeof(NotifSystem.Web.Startup))]  
namespace NotifSystem.Web  
{  
    public partial class Startup  
    {  
        public void Configuration(IAppBuilder app)  
        {  
            app.MapSignalR();  
        }  
    }  
}  


4). Now You Need to Create Controller for api

public class StudentController : ApiController
{
     public  IHttpActionResult  Get(int id, string name) 
    {
     var context = Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.
                          GetHubContext<NotificationHub>();
     context.Clients.All.messageReceived("Get Student Called");
 return Ok("Done");
    }

5). Now You Need to Impliment Your Agnular 6 code in Create New Service 
   
I Have Created Angular 6 service name "Signalr" 

import { Injectable } from '@angular/core';
declare var $: any;
@Injectable()
export class SignalrService {
    private connection: any;
    private proxy: any;
    constructor() { }
    public initializeSignalRConnection(): void {

      // Host address with port (url) of domain where hub is published  
        const signalRServerEndPoint = 'http://localhost:57311/';

     // Initialize Connection to hubConnection by assign end url 
        this.connection = $.hubConnection(signalRServerEndPoint);

     // Create Hub Proxy By assign name of Hub in CreateHubProxy Methord
        this.proxy = this.connection.createHubProxy('SendNotificationHub');

    // After Proxy Create "messageRecive" method of Hub(server) Get Response of other Client Notificaiton and "serverMessage" is variable hold message and assign to other method  Name is "onMessageRecived" method
        this.proxy.on('messageReceived', (serverMessage) =>                   this.onMessageReceived(serverMessage));

// Now Here Connect stablish and if application is  Connected to Hub 
You Can Send Notification To Other User by This Method "broadcastMessage"
        this.connection.start().done((data: any) => {
            console.log('Connected to Notification Hub');
            this.broadcastMessage();
        }).catch((error: any) => {
            console.log('Notification Hub error -> ' + error);
        });
    }


// this method send message to Hub For Other Client
    public broadcastMessage(): void {
        this.proxy.invoke('notificationService', 'Welcome to Dashboard')
            .catch((error: any) => {
                console.log('broadcastMessage error -> ' + error);
            });
    }

// This method Recived Message from Hub send by other client
    private onMessageReceived(serverMessage: string) {
        console.log('New message received from Server: ' + serverMessage);
    }
}

Asp.net And HTML Css And Web Development: How To Use Mat Table /Data Table in angular 6

Asp.net And HTML Css And Web Development: How To Use Mat Table /Data Table in angular 6: How To Use Mat Table /Data Table in angular 6 Here We Are Highlight Code in red line for Toggle Button of plus and minus for Extend Ro...

How To Use Mat Table /Data Table in angular 6

How To Use Mat Table /Data Table in angular 6

Here We Are Highlight Code in red line for Toggle Button of plus and minus for Extend Row in dataTable in Mat or Mat-table

1). From " View-Users.Component.ts" File

import { join } from 'path';
import { map } from 'rxjs/operators';
import { Component, OnInit, ViewChild } from '@angular/core';
import { SearchUser } from '../../../../../models/SearchUser.model';
import { animate, state, style, transition, trigger } from '@angular/animations';
import { UserService } from '../../../../../services/user/user.service';
import { LoggerService } from '../../../../../services/log4ts/logger.service';
import { Router } from '@angular/router';
import swal from 'sweetalert2';
import { MatTableDataSource, MatPaginator, MatSort } from '@angular/material';
import { BrowserStorageService } from '../../../../../utility/browser-storage.service';
import { AuthenticationService } from '@alfresco/adf-core';
import * as moment from 'moment';
import { ApiService } from '../../../../../services/api.service';
import { SpinnerService } from '../../../../../services/spinner.service';
import { Constants } from '../../../../../constants/app.constants';

@Component({
  selector: 'app-view-users',
  templateUrl: './view-users.component.html',
  styleUrls: ['./view-users.component.scss'],
  animations: [
    trigger('detailExpand', [
      state('collapsed', style({ height: '0px', minHeight: '0' })),
      state('expanded', style({ height: '*' })),
      transition('expanded <=> collapsed', animate('225ms cubic-bezier(0.4, 0.0, 0.2, 1)')),
    ])],
})
export class ViewUsersComponent implements OnInit {
  dataSource = new MatTableDataSource();
  rowCount = 0;
  isExpansionDetailRow = null;

  error: any;
  public data: SearchUser[];
  public filterQuery = '';
  userId: string;
  responseStatus = null;
  @ViewChild('successContractSwal') successContractSwal: any;
  constructor(public userService: UserService,
    private authService: AuthenticationService,
    private apiService: ApiService,
    private spinner: SpinnerService,
    private browserStorageService: BrowserStorageService, private loggerService: LoggerService, private router: Router) {
  }
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild('MatPaginator') paginator: MatPaginator;
  displayedColumns = [
    'IsExtended', 'EmailID', 'Name', 'RoleName', 'UserBelong', 'CreatedBy', 'CreatedDate', 'Action'];
  ngOnInit() {
    this.apiService.isSpinner = false;
    this.spinner.displaySpinner(true);
    this.userId = this.browserStorageService.getLocalStorageItem('userId');
    this.getUserData();
  }

  applyFilter(filterValue: string) {
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }
  public toInt(num: string) {
    return +num;
  }
  private showPopup(type: string, title: string, text: string) {
    this.successContractSwal.type = type;
    this.successContractSwal.title = title;
    this.successContractSwal.text = text;
    this.successContractSwal.show();

  }

  getUserdetail(UserID: any) {
    this.browserStorageService.setSessionStorageItem('TritexUuid', UserID);
    this.setRedirectAddUserUrl();
  }

  setRedirectAddUserUrl() {
    this.router.navigate(['/mastersetup/users/add-users/' + new Date().getTime() + '/' + new Date().getDate()]);
  }

  public sortByWordLength = (a: any) => {
    return a.name.length;
  }

  public getDate(regDate: string) {
    const date = new Date(regDate);
    return date.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: '2-digit' });
  }

  getUserData() {
    this.responseStatus = null;
    const UserRoleList = this.browserStorageService.getSessionStorageItem('UserRoleNames').split(',');
    this.userService.searchUser(UserRoleList.indexOf('SUPER_ADMIN') > -1 ?
      null : this.browserStorageService.getLocalStorageItem('userId'),
      localStorage.getItem('ticket-ECM')).then((res: any) => {
        this.responseStatus = res.status;
        this.data = res.result;
        this.data.forEach((element: any) => {
          element.CreatedDate = moment(element.CreatedDate, 'DD/MM/YYYY HH:mm:ss');
          element.IsExtendedRow = false;
        });

        this.dataSource = new MatTableDataSource(this.data);
        // inner object filter
        this.dataSource.filterPredicate = (data: any, filter: string) => {
          const accumulator = (currentTerm, key) => {
            return key === 'UserGroupOperator' ? currentTerm + data.UserGroupOperator.map(x => x.Code).join('')
              + data.UserGroupOperator.map(x => x.Name).join('') : currentTerm + data[key];
          };
          const dataStr = Object.keys(data).reduce(accumulator, '').toLowerCase();
          const transformedFilter = filter.trim().toLowerCase();
          return dataStr.indexOf(transformedFilter) !== -1;
        };
        this.rowCount = this.data.length;
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
        this.apiService.isSpinner = true;
        this.spinner.displaySpinner(false);
      }).catch((error) => {
        this.apiService.isSpinner = true;
        this.spinner.displaySpinner(false);
        this.error = error;
        this.showPopup('error', 'Error!', error.message);
      });

  }

  isExpandedRow(element) {

    this.dataSource.data.forEach((data: any) => {
      if (element === data) {
        element.IsExtendedRow = !element.IsExtendedRow;
      } else {
        data.IsExtendedRow = false;
      }

    });

  }
  
}


2). From " View-Users.Component.html" File

<div class="tab-container">
  <div class="box-section">
    <swal #successContractSwal title="Success!" type="success" text="" (confirm)="getUserData()"
      [options]="{ showConfirmButton: true, confirmButtonText: 'OK', confirmButtonColor: '#DD6B55' }"></swal>
    <div class="box-view box-blue" #respMessage>
      <div class="box-header bottom-border">
        <h3 class="box-header-title">User List</h3>
      </div>
      <div class="form-section">
        <div class="box-body">
          <div class="row">
            <div class="col-md-1">
            </div>
            <div *ngIf="data" class="col-md-11">
              <div class="col-md-3 offset-md-9 d-flex justify-content-end filter-row" style="padding-left: 10px;">
                <div class="input-group" style="margin-top: 10px;margin-bottom: 15px;">
                  <div class="input-group-prepend">
                    <span class="input-group-text">
                      <i class="fa fa-search"></i>
                    </span>
                  </div>
                  <input type="text" class="form-control" (keyup)="applyFilter($event.target.value)"
                    placeholder="Search">
                </div>
              </div>
            </div>
          </div>
          <div class="row" style="margin-bottom: 15px;">
            <div class="col-md-12">
              <div class="workflow-table custom-table-responsive">
                <div class="example-container mat-elevation-z8">

                  <mat-table #table mat-table matSort [dataSource]="dataSource" multiTemplateDataRows
                    class="table-responsive">
                    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>

                    <ng-container matColumnDef="IsExtended">
                      <mat-header-cell *matHeaderCellDef mat-sort-header></mat-header-cell>
                      <mat-cell *matCellDef="let element" style="justify-content: center;">
                        <!-- <i [ngClass]="{'fa fa-plus': !element.IsExtendedRow, 'fa fa-minus': element.IsExtendedRow}"></i> -->
                        <i class="{{!element.IsExtendedRow ? 'fa fa-plus' : 'fa fa-minus'}}"></i>
                      </mat-cell>
                    </ng-container>

                    <ng-container matColumnDef="EmailID">
                      <mat-header-cell *matHeaderCellDef mat-sort-header> EmailID </mat-header-cell>
                      <mat-cell *matCellDef="let element">
                        <a href="JavaScript:void(0);" (click)="getUserdetail(element.UserID)">
                          {{element.EmailID}}
                        </a>
                      </mat-cell>
                    </ng-container>

                    <ng-container matColumnDef="Name">
                      <mat-header-cell *matHeaderCellDef mat-sort-header> Name </mat-header-cell>
                      <mat-cell *matCellDef="let element">{{ element.Name }}</mat-cell>
                    </ng-container>
                    <ng-container matColumnDef="RoleName">
                      <mat-header-cell *matHeaderCellDef mat-sort-header> Role's </mat-header-cell>
                      <mat-cell *matCellDef="let element">{{ element.RoleName | permissionPipe}}</mat-cell>
                    </ng-container>

                    <ng-container matColumnDef="UserBelong">
                      <mat-header-cell *matHeaderCellDef mat-sort-header>User Belong </mat-header-cell>
                      <mat-cell *matCellDef="let element">{{ element.UserBelong }}</mat-cell>
                    </ng-container>

                    <ng-container matColumnDef="CreatedBy">
                      <mat-header-cell *matHeaderCellDef mat-sort-header> Created By</mat-header-cell>
                      <mat-cell *matCellDef="let element">{{ element.CreatedBy }}</mat-cell>
                    </ng-container>

                    <ng-container matColumnDef="CreatedDate">
                      <mat-header-cell *matHeaderCellDef mat-sort-header> Created Date</mat-header-cell>
                      <mat-cell *matCellDef="let element">{{ element.CreatedDate | date : 'dd/MM/yyyy HH:mm:ss'}}
                      </mat-cell>
                    </ng-container>

                    <ng-container matColumnDef="Action">
                      <mat-header-cell *matHeaderCellDef> Action </mat-header-cell>
                      <mat-cell *matCellDef="let element">
                        <a href="JavaScript:void(0);" tooltip="Click to release lock" placement="bottom"
                          (click)="LockUser(element)" *ngIf="element.isAccountLocked">
                          <i class="fa fa-lock" aria-hidden="true"></i>
                        </a>
                      </mat-cell>
                    </ng-container>

                    <ng-container matColumnDef="noData">
                      <mat-footer-cell *matFooterCellDef colspan="8">
                        Whoa! No User Data Found !
                      </mat-footer-cell>
                    </ng-container>

                    <ng-container matColumnDef="expandedDetail">
                      <mat-cell *matCellDef="let detail" class="period-bg-ligt-blue">
                        <ng-container *ngIf="detail.UserGroupOperator.length==0">
                          no record found
                        </ng-container>
                        <ng-container class="row" *ngIf="detail.UserGroupOperator.length>0">
                          <div class="col-md-6 col-sm-12">
                            <table class="table table-responsive-sm table-bordered table-sm">
                              <thead>
                                <tr>
                                  <th>Name</th>
                                  <th>Code</th>
                                  <th>IsTritex</th>
                                  <th>#</th>
                                </tr>
                              </thead>
                              <tbody>
                                <ng-container *ngFor="let item of detail.UserGroupOperator">
                                  <tr>
                                    <td>
                                      {{item.Name}}
                                    </td>
                                    <td>
                                      {{item.Code}}
                                    </td>
                                    <td style="text-align: center;"> <i *ngIf="item.IsTritex"
                                        class="fa fa fa-check"></i>
                                    </td>
                                    <td>{{item.isGroup===1?'Group':'Operator'}}</td>
                                  </tr>
                                </ng-container>
                              </tbody>
                            </table>
                          </div>
                        </ng-container>
                      </mat-cell>
                    </ng-container>

                    <mat-row *matRowDef="let row; columns: displayedColumns;" matRipple class="element-row"
                      [class.expanded]="expandedElement == row"
                      (click)="(expandedElement !== row)? expandedElement = row:expandedElement=[]; isExpandedRow(row)">
                    </mat-row>

                    <mat-row *matRowDef="let row; columns: ['expandedDetail'];when: isExpansionDetailRow"
                      [@detailExpand]="(row == expandedElement && row.UserGroupOperator.length>0) ? 'expanded' : 'collapsed'"
                      style="overflow: hidden">
                    </mat-row>

                    <mat-footer-row *matFooterRowDef="['noData']"
                      [ngClass]="{'hide':!(rowCount=== 0 && responseStatus)}">
                    </mat-footer-row>

                  </mat-table>
                  <mat-paginator #MatPaginator [pageSize]="50" [pageSizeOptions]="[5, 10, 20,50,100]"
                    showFirstLastButtons>
                  </mat-paginator>

                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>


3).users.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { NgMultiSelectDropDownModule } from 'ng-multiselect-dropdown';

import {
  MatInputModule,
  MatSelectModule,
  MatButtonModule,
  MatCheckboxModule,
  MatRadioModule,
  MatDatepickerModule, MatTableModule,
  MatPaginatorModule,
  MatSortModule
} from '@angular/material';
import { SweetAlert2Module } from '@toverux/ngx-sweetalert2';
import { NgSelectModule } from '@ng-select/ng-select';
// import { DataTableModule } from 'angular2-datatable';
import { DataFilterPipeModule } from '../../../../pipes/data-filter-pipe.module';
import { BsDropdownModule } from 'ngx-bootstrap';
import { CustomModalModule } from '../../../../modal/custom-modal.module';
import { ViewUsersComponent } from './view-users/view-users.component';
import { TooltipModule } from 'ngx-bootstrap';
import { ProfileModule } from '../../profile/profile.module';
const routes: Routes = [
  {
    path: '',
    component: ViewUsersComponent,
    data: {
      title: 'Search'
    }
  },
  {
    path: 'add-users/:refresh1',
    component: AddUsersComponent,
    data: {
      title: 'Add'
    }
  },
  {
    path: 'add-users/:refresh1/:refresh2',
    component: AddUsersComponent,
    data: {
      title: 'Edit'
    }
  },
  {
    path: 'view-users/:refresh',
    component: ViewUsersComponent,
    data: {
      title: 'Search'
    }
  }
];
@NgModule({
  imports: [
    RouterModule.forChild(routes),
    CommonModule,
    ReactiveFormsModule,
    FormsModule,
    MatInputModule,
    MatSelectModule,
    SweetAlert2Module.forRoot(),
    NgSelectModule,
    DataFilterPipeModule,
    MatButtonModule,
    MatCheckboxModule,
    MatRadioModule,
    MatDatepickerModule,
    CustomModalModule,
    NgMultiSelectDropDownModule,
    BsDropdownModule.forRoot(),
    MatTableModule,
    MatPaginatorModule,
    TooltipModule.forRoot(),
    ProfileModule,
    MatSortModule
  ],
  declarations: [ ViewUsersComponent]
})
export class UsersModule { }

Featured Post

How To Dynamic Upload multiple files with extra detail of model in asp.net core

 How To Dynamic Upload multiple files with extra detail of model in asp.net core  1). firstly create Model File  namespace MyModel {     pub...

Popular Posts