Angular 5 interceptor for loading message

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { UserDetailsComponent } from './user-details/user-details.component';

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { CommentsComponent } from './comments/comments.component';
import { loadingInterceptor } from './Services/loadingInterceptor';

@NgModule({
  declarations: [
    AppComponent,
    UserDetailsComponent,
    CommentsComponent
  ],
  imports: [
    BrowserModule,HttpClientModule
  ],
  providers: [{
    provide: HTTP_INTERCEPTORS,
    useClass: loadingInterceptor,
    multi: true
}],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html

<div class="row">
<div class="col-md-6">
    <app-user-details></app-user-details></div>
<div class="col-md-6">
    <app-comments></app-comments></div>
</div>
<div class="loading" style="display: none">
  <span>Loading.....</span></div>

app.component.css


.loading {
    background: rgba(0,0,0,0.4);
    position: fixed;
    display: block;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
}

.loading span {
    position: fixed;
    left: 50%;
    top: 50%;
    border: solid 1px #ccc;
    display: block;
    padding: 20px 40px;
    margin-left: -40px;
    background: rgba(255,255,255,0.8);
}

comments/comments.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { AppComponent } from '../app.component';

@Component({
  selector: 'app-comments',
  templateUrl: './comments.component.html',
  styleUrls: ['./comments.component.css']
})
export class CommentsComponent implements OnInit {
  commentList: Array<Comment>;
  constructor(private httpClient: HttpClient) { }

  ngOnInit() {
  }
  getComments() {
    this.commentList = [];
    this.httpClient.get('https://jsonplaceholder.typicode.com/comments').subscribe((data: Array<Comment>) => {
      this.commentList = data;
    })
  }
}

export class Comment {
  public body: string;
  public email: string;
  public id: number;
  public name: string;
  public postId: number;
}

comments/comments.component.html

<div class="row">
<div class="col-md-12">
    <button (click)="getComments()" class="btn btn-primary">Get Comments</button></div>
<div class="col-md-12" *ngFor="let item of commentList" style="max-height:500px;">
    <b style="display:block">{{item.name}}</b>
    <small>{{item.email}}</small>

{{item.body}}</div>
</div>

user-details/user-details.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-user-details',
  templateUrl: './user-details.component.html',
  styleUrls: ['./user-details.component.css']
})
export class UserDetailsComponent implements OnInit {

  private user: User;
  constructor(private httpClient: HttpClient) { }

  ngOnInit() {
  }
  getUserInfo() {
    this.httpClient.get('https://jsonplaceholder.typicode.com/users/3').subscribe(
      success => {
        this.user = (success as User);
      }
    )

  }
}

export class User {

  public id: number;
  public name: string;
  public username: string;
  public email: string;
  public phone: string;

}

user-details/user-details.component.html

<div class="row col-md-12">
  <button (click)="getUserInfo()" class="btn">Get User Info</button></div>
<div class="row col-md-12" *ngIf="user">
<table class="table">
<tr>
<td>Name</td>
<td>{{user.name}}</td>
</tr>
<tr>
<td>User Name</td>
<td>{{user.username}}</td>
</tr>
<tr>
<td>Email</td>
<td>{{user.email}}</td>
</tr>
<tr>
<td>Phone</td>
<td>{{user.phone}}</td>
</tr>
</table>
</div>

services/loadingInterceptor.ts

import { Injectable, Injector } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/observable/throw'
import 'rxjs/add/operator/catch';

@Injectable()
export class loadingInterceptor implements HttpInterceptor {
    constructor() { }

    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        let loadingContainer: HTMLElement = document.getElementsByClassName('loading').item(0) as HTMLElement;
        loadingContainer.style.display = 'block';
        //send the request
        next.handle(req).subscribe((observer: any) => {
            if (observer.status == 200) {
                loadingContainer.style.display = 'none';
            }
        })
        return next.handle(req);
    }
}
Advertisements

Getting error on add new “Table ‘conjero.tmpidentity_project_consultant_order’ doesn’t exist” on MySql CodeFirst with EF

In my project I am handling two type auto generated keys. Long and Guid. Previously long only i used in this project. Now added Guid also. I previously used this with out any with out any problem in MSSQL. I created one table via migration. It works fine. In the case of second table, I created model and table separately for a reason.  At this time I getting an error while am try to add something.

Table ‘conjero.tmpidentity_project_consultant_order’ doesn’t exist

I don’t have any idea about tmpidentity_. What it is ?

Search in google about tmpidentity and got one link, https://github.com/pdonald/mysql-connector-net/blob/master/Source/MySql.Data.Entity/MySqlMigrationSqlGenerator.cs

Here talking about some TRIGGER. So I checked previously created table and its trigger. there is trigger for handling auto generated guid. I Just copy paste that trigger and rename as per second table name.

My issue fixed!!

Following is the trigger:

CREATE DEFINER=`root`@`%` TRIGGER `conjero`.`project_consultant_order_BEFORE_INSERT` BEFORE INSERT ON `project_consultant_order` FOR EACH ROW
BEGIN
DROP TEMPORARY TABLE IF EXISTS tmpIdentity_project_consultant_order;
		CREATE TEMPORARY TABLE tmpIdentity_project_consultant_order (guid CHAR(36))ENGINE=MEMORY;
		SET @var_Id = UUID();
		INSERT INTO tmpIdentity_project_consultant_order VALUES(@var_Id);
		SET new.Id = @var_Id;
END

Showing angular expression at page load

angularIn my application I want to show a table data. I am showing a loading icon at first. At that time table will hidden. after data load that table will display. its working good. But some times some browsers showing angular expressions in table at page. After a 1/4 sec it will gone. But it shown 1/4 sec!!. I tried ng-show, ng-if, add a class,etc. everything failed. It is not fixed permanently. After that I tried with ng-cloak. It works!

I added the below code in my css file, and add a class to my table element.

CSS

[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
display: none !important;
}

Html

<table  class="ng-cloak">
....</table>

CSV To JSON Conversion


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>CSV to JSON</title>
	<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery.js"></script>
</head>
<body>
CSV to JSON Converter
<hr />

Paste Your CSV Here:

    <textarea id="csv" class="text" > </textarea>
    
    <button id="convert">Convert to JSON</button>
      
    <button id="download">Download JSON</button>
    <textarea id="json" class="text"></textarea>
    
	

<style>	.text{width: 100%;height: 250px;} button{margin:10px 0}	</style>

	<script>
	
	

function CSVToArray(strData, strDelimiter) {
    // Check to see if the delimiter is defined. If not,
    // then default to comma.
    strDelimiter = (strDelimiter || ",");
    // Create a regular expression to parse the CSV values.
    var objPattern = new RegExp((
    // Delimiters.
    "(\\" + strDelimiter + "|\\r?\\n|\\r|^)" +
    // Quoted fields.
    "(?:\"([^\"]*(?:\"\"[^\"]*)*)\"|" +
    // Standard fields.
    "([^\"\\" + strDelimiter + "\\r\\n]*))"), "gi");
    // Create an array to hold our data. Give the array
    // a default empty first row.
    var arrData = [[]];
    // Create an array to hold our individual pattern
    // matching groups.
    var arrMatches = null;
    // Keep looping over the regular expression matches
    // until we can no longer find a match.
    while (arrMatches = objPattern.exec(strData)) {
        // Get the delimiter that was found.
        var strMatchedDelimiter = arrMatches[1];
        // Check to see if the given delimiter has a length
        // (is not the start of string) and if it matches
        // field delimiter. If id does not, then we know
        // that this delimiter is a row delimiter.
        if (strMatchedDelimiter.length && (strMatchedDelimiter != strDelimiter)) {
            // Since we have reached a new row of data,
            // add an empty row to our data array.
            arrData.push([]);
        }
        // Now that we have our delimiter out of the way,
        // let's check to see which kind of value we
        // captured (quoted or unquoted).
        if (arrMatches[2]) {
            // We found a quoted value. When we capture
            // this value, unescape any double quotes.
            var strMatchedValue = arrMatches[2].replace(
            new RegExp("\"\"", "g"), "\"");
        } else {
            // We found a non-quoted value.
            var strMatchedValue = arrMatches[3];
        }
        // Now that we have our value string, let's add
        // it to the data array.
        arrData[arrData.length - 1].push(strMatchedValue);
    }
    // Return the parsed data.
    return (arrData);
}

function CSV2JSON(csv) {
    var array = CSVToArray(csv);
    var objArray = [];
    for (var i = 1; i < array.length; i++) {
        objArray[i - 1] = {};
        for (var k = 0; k < array[0].length && k < array[i].length; k++) {
            var key = array[0][k];
            objArray[i - 1][key] = array[i][k]
        }
    }

    var json = JSON.stringify(objArray);
    var str = json.replace(/},/g, "},\r\n");

    return str;
}

$("#convert").click(function() {
    var csv = $("#csv").val();
    var json = CSV2JSON(csv);
    $("#json").val(json);
});

$("#download").click(function() {
    var csv = $("#csv").val();
    var json = CSV2JSON(csv);
    window.open("data:text/json;charset=utf-8," + escape(json))
});

</script>
</body>
</html>

Entity Framework – AutoDetectChangesEnabled

From MSDN

When using most POCO entities the determination of how an entity has changed (and therefore which updates need to be sent to the database) is handled by the Detect Changes algorithm. Detect Changes works by detecting the differences between the current property values of the entity and the original property values that are stored in a snapshot when the entity was queried or attached. The techniques shown in this topic apply equally to models created with Code First and the EF Designer.

But some times we need to turn off this feature. for example, I need to upload a excel file it contains a bulk data. At this time AutoDetectChangesEnabled is true then it take a lot time for insert all rows. I can do the data validations at db side.

Just check the difference of AutoDetectChangesEnabled ON and OFF while inserting a bulk data.

Normal way:

namespace TestAutoDetectChangesEnabled
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Title = &amp;quot;Time Test - AutoDetectChangesEnabled&amp;quot;;
            string[] names = { &amp;quot;Arun&amp;quot;, &amp;quot;Raj&amp;quot;, &amp;quot;Musthaan&amp;quot;, &amp;quot;Majeed&amp;quot;, &amp;quot;Muzafir&amp;quot;,
                                 &amp;quot;Hari&amp;quot;, &amp;quot;Dharma&amp;quot;, &amp;quot;Kannan&amp;quot;, &amp;quot;Imran&amp;quot;, &amp;quot;Santo&amp;quot;,
                                 &amp;quot;Rahmath&amp;quot;, &amp;quot;Jayesh&amp;quot; };
            Stopwatch sw = new Stopwatch();
            sw.Start();
            var db = new AppContext();
            foreach (var i in Enumerable.Range(1, 20000))
            {
                var student = new Student()
                {
                    Name = names[(new Random().Next(0, 10))],
                    ContactNo = &amp;quot;9870002735&amp;quot;,
                    RegNo = i.ToString().PadLeft(7, '0')
                };
                db.Students.Add(student);
                Console.Clear();
                Console.WriteLine(&amp;quot;{0} records added&amp;quot;, i);
            }
            db.SaveChanges();
            sw.Stop();
            Console.WriteLine(&amp;quot;Taked time - {0}&amp;quot;, sw.ElapsedMilliseconds);
            Console.ReadKey();
        }
    }

    public class AppContext : DbContext
    {
        public AppContext()
            : base(&amp;quot;AppConnection&amp;quot;)
        {

        }
        public DbSet&amp;lt;Student&amp;gt; Students { get; set; }
    }
    public class Student
    {
        public long Id { get; set; }
        public string Name { get; set; }
        public string RegNo { get; set; }
        public string ContactNo { get; set; }

    }
}

AutoDetectChangesEnabled-before

After disable AutoDetectChanges

 class Program
    {
        static void Main(string[] args)
        {
            Console.Title = &amp;quot;Time Test - AutoDetectChangesEnabled&amp;quot;;
            string[] names = { &amp;quot;Arun&amp;quot;, &amp;quot;Raj&amp;quot;, &amp;quot;Musthaan&amp;quot;, &amp;quot;Majeed&amp;quot;, &amp;quot;Muzafir&amp;quot;,
                                 &amp;quot;Hari&amp;quot;, &amp;quot;Dharma&amp;quot;, &amp;quot;Kannan&amp;quot;, &amp;quot;Imran&amp;quot;, &amp;quot;Santo&amp;quot;,
                                 &amp;quot;Rahmath&amp;quot;, &amp;quot;Jayesh&amp;quot; };
            Stopwatch sw = new Stopwatch();
            sw.Start();
            var db = new AppContext();
            try
            {
                db.Configuration.AutoDetectChangesEnabled = false;

                foreach (var i in Enumerable.Range(1, 20000))
                {
                    var student = new Student()
                    {
                        Name = names[(new Random().Next(0, 10))],
                        ContactNo = &amp;quot;9870002735&amp;quot;,
                        RegNo = i.ToString().PadLeft(7, '0')
                    };
                    db.Students.Add(student);
                    Console.Clear();
                    Console.WriteLine(&amp;quot;{0} records added&amp;quot;, i);
                }
                db.SaveChanges();
            }
            finally
            {
                db.Configuration.AutoDetectChangesEnabled = true;
            }
            sw.Stop();
            Console.WriteLine(&amp;quot;Taked time - {0}&amp;quot;, sw.ElapsedMilliseconds);
            Console.ReadKey();
        }
    }

AutoDetectChangesEnabled-after

See the difference, it almost 10x faster. But use it with care. Don’t forget to re-enable detection of changes after the loop — used a try/finally to ensure it is always re-enabled even if code in the loop throws an exception.

See System.Data.Entity.Validation.DbEntityValidationException Details

Today i got an error on saving data to db using EF.

An exception of type ‘System.Data.Entity.Validation.DbEntityValidationException’ occurred in EntityFramework.dll but was not handled in user code

Additional information: Validation failed for one or more entities. See ‘EntityValidationErrors’ property for more details.

System.Data.Entity.Validation.DbEntityValidationException

but I can’t find out what are the failed validations.

System.Data.Entity.Validation.DbEntityValidationException2

No more details in quick watch. I stucked a little. At this time i find out the use of $exception.That is a special debugger variable. You cannot access it via code.

https://msdn.microsoft.com/en-us/library/ms164891.aspx

https://blogs.msdn.microsoft.com/shaykatc/2004/02/20/vs-2003-tip-3-view-exception-information-with-exception/

look  $exception in quickwatch.

System.Data.Entity.Validation.DbEntityValidationException3

 

The JSON request was too large to be deserialized.

I am working on a list and it has a bulk update through api. I am tested with upto 30 records and its working fine on my dev system. whilie update to QA they added a lot of records to update at that time I got an error The JSON request was too large to be deserialized

JSON request was too large
Problem is I am sending data as JSON as MVC’s default maximum Json deserializer members count is 1000. So I changed it in web.config.

<appSettings>
    <add key="aspnet:MaxJsonDeserializerMembers" value="150000" />
</appSettings>

List of all default Excel NumberFormatId’s

If you’d like to format your date another way, here is a list of all default Excel NumberFormatId’s

 

ID FORMAT CODE
0 General
1 0
2 0.00
3 #,##0
4 #,##0.00
9 0%
10 0.00%
11 0.00E+00
12 # ?/?
13 # ??/??
14 d/m/yyyy
15 d-mmm-yy
16 d-mmm
17 mmm-yy
18 h:mm tt
19 h:mm:ss tt
20 H:mm
21 H:mm:ss
22 m/d/yyyy H:mm
37 #,##0 ;(#,##0)
38 #,##0 ;[Red](#,##0)
39 #,##0.00;(#,##0.00)
40 #,##0.00;[Red](#,##0.00)
45 mm:ss
46 [h]:mm:ss
47 mmss.0
48 ##0.0E+0
49 @

Kendo Grid – add custom class to a column

logo kendoui

In many situation I was required a class for some specific columns. This is a simple solution for that.

$("#grid").kendoGrid({
 dataSource: GridSource,
 columns: [{
                title: "",
                template: actionTemplate,
                filterable: false,
                width: 105
            },
            {
                field: "Title",
                title: "Title",
                width: 350,
                attributes: {
                    "class": "table-cell"
                    }
             }]
   });

We can add in-line styles in the same way.

$("#grid").kendoGrid({
 dataSource: GridSource,
 columns: [{
                title: "",
                template: actionTemplate,
                filterable: false,
                width: 105
            },
            {
                field: "Title",
                title: "Title",
                width: 350,
                attributes: {
                    style: "text-align: right"
                    }
             }]
   });

The types of all properties in the Dependent Role of a referential constraint must be the same as the corresponding property types in the Principal Role

web_services[1]Some days before I got an error while try to update migration like :

UploadedData_GrpCategory_Target_UploadedData_GrpCategory_Source: : The types of all properties in the Dependent Role of a referential constraint must be the same as the corresponding property types in the Principal Role. The type of property ‘Category’ on entity ‘UploadedData’ does not match the type of property ‘Id’ on entity ‘GrpCategory’ in the referential constraint ‘UploadedData_GrpCategory’.

 

 

I didn’t understand what it is in first look.  Then I understood , I created Primary key and foreign key in different datatypes in Entities.