Saturday, 28 September 2019

Performance comparison of Generic and non Generic List after JIT compilation


Performance of generic and non-generic list is well known. But there is a catch. We should always consider results which comes after JIT compilation. The difference between the test run of the code snippet and running the code after JIT does its job may surprise you.
  1. Now what happens when you run the test application for performance comparison.
  2. When you run the application, JIT runs i.e. Just in Time compiler.
  3. JIT compiles the application, optimize the code and finds the best approach to executes the code.
  4. All these JIT steps are time consuming which are included in first execution, so the execution time is always way more than actual run time
  5. So how you can calculate the actual run time? Simple, to check the performance of your test application with test data, call code snippet in a loop.

Example
private static void GenericListPerformance()
{
     var genList = new List<int>() { 10, 100, 13, 19, 14, 100, 99 };
     var nonGenList = new ArrayList() { 10, 100, 13, 19, 14, 100, 99 };

     var stWatch = Stopwatch.StartNew();
     genList.Sort();
     stWatch.Stop();
     Console.WriteLine("Generic List sorting "+ stWatch.Elapsed.TotalMilliseconds.ToString());

     stWatch = Stopwatch.StartNew();
     nonGenList.Sort();
     stWatch.Stop();
Console.WriteLine("Non Generic List sorting "+ stWatch.Elapsed.TotalMilliseconds.ToString());
}

Here I have created a simple method to compare the two list ArrayList and List<T>. I have used Stopwatch which is present in System.Diagnostics namespace of .net framework and then printed the messages with time.

static void Main(string[] args)
{
         for (int i = 0; i < 5; i++)
            {
                Console.WriteLine(string.Format("<--------Call Number {0} -------->",i));
                GenericListPerformance();
                Console.WriteLine();
            }
}

Now this is where I have used the actual concept. I have called the same method in main inside a loop which runs 5 times. So, when it run for first time JIT can optimize the code and find the best approach to run this code. Later, JIT will use the native code and give us the best results.

Result

See the results.
For first run the execution time is-
For Generic - 0.0263
For Non-Generic – 0.233
And later it came to be line
Generic – 0.0012, 0.0013, 0.0011, 0.0013
Non-Generic – 0.0032, 0.0026, 0.0026, 0.0029



Therefor, we should always consider the JIT time

Subscribe to my blog if you want to get notified about more detailed analysis of topics. Comment if you have any question or want me to do some analysis on the topic you want.
Thanks

Friday, 20 September 2019

Default implementation of method in interface(New feature of interface)


The latest version of c# allows you to define body of interface method.



For example :-
Consider you have a project of Asset Management which has an interface IAsset and which has properties AssetName, AssetAge, Id and so on

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Stucts.New_Features.Interface
{
    interface IAsset
    {
        string AssetName { get; set; }
        string AssetAge { get; set; }
        string Id { get; set; }

    }
}

Now consider you have this interface inherited in multiple classes like FixedAssets, TemporaryAssets and so on

using System;
using Stucts.New_Features.Interface;

namespace Stucts.New_Features
{
    class FixedAsset : IAsset
    {
        public string AssetName { get; set ; }
        public string AssetAge { get; set; }
        public string Id { get; set; }
    }
}

Consider you want to add new feature to you application which moves asset to archive after certain years as per customer needs. It may be possible that you need to implement this logic for all kind of asset or just for few or some different logic based on other calculation.
In older version you need to define a non body method in interface and implement that method in all the other classes and. In some cases this might not seem a very big issue but I know when you are working on an ultra large scale software then this is a headache no one wants.



In C# 8.0 you can define default implementation of a method in interface and classes can use that method or if you can give different definition to same method in child classes

        public void MoveAssetToArchive(int age)
        {
              //Your log here
        }

You can start using this method in all the child classes without implementing it

FixedAsset  _fixAsset = new FixedAsset () {
AssetAge="4",
       AssetName="HTC Explorer Mobile phone",
              Id = "1001"
       };
       IAsset _IAsset = _fixAsset;
       _IAsset.MoveAssetToArchive(4);

Notice the following section of the test:

IAsset _IAsset = _fixAsset;
       _IAsset.MoveAssetToArchive(4);


Well that saved lot of time and effort :)

Similarly you can also declare variable as well as static members in interface
I would love if you guys create a demo project with scenario where we might need to declare static members and behaviors in an interface. Please do try to create a Demo. I will create a demo and with a scenario and write it in the blog soon so that we can discuss it. Comment if you have any question or want to discuss something. Reach out to me at ishooagarwal@gmail.com. Please add [Blog] in subject so that I can differentiate regular mail.
Meanwhile follow and subscribe the blog to get notifications of the blog
Thanks.

Tuesday, 17 September 2019

Passing data form one component to another (Sibling component) in angular 8





This blog shows you how to pass data from one component to another using EventEmitter
First create a service that could be injected in both the component (ANGULAR CLI COMMANDng g s customer-forms’) this will create a service with the name customerForms.service.ts
Now create a method in service that will be called from component on click, Let’s call is PassData
PassData(DataSource)
    {
        console.log(DataSource);
    }

Create a EventEmitter object which will emit the data
$dataSource = new EventEmitter();

Use this $dataSource variable in PassData method
PassData(DataSource)
    {
        console.log(DataSource);
        this.$dataSource.emit(DataSource);
    }

Now let’s create a method on component which will call PassData of service
Edit(CustomerRequest)
  {
    console.log(CustomerRequest);
    this.customerRequestService.PassData(CustomerRequest);
  }

Call this method on click of any html component.
<section class="col-md-3 border cursor-action" (click)="Edit(customerRequest)" 
    *ngFor="let customerRequest of customerRequests">

After running This you will see logs in console


Now we need to handle this emit in other component
For this we need subscribe to the variable $dataSource of service in receiving component in ngInit()
this.customerRequestService.$dataSource
      .subscribe((data=> {console.log('DataSource received'data);
      this.Edit(data);
    });

And finally
  Edit(CustomerRequest)
  {
    console.log(CustomerRequest);
    this.form.setValue({
      CompanyName:CustomerRequest.CompanyName,
      Name: CustomerRequest.Name,
      SoftwareId:CustomerRequest.SoftwareId,
      RelationshipDuration:CustomerRequest.RelationshipDuration,
      RequestMessage:CustomerRequest.RequestMessage
    });
  }

After doing all this you can see that the code is working in the console of browser


Thanks
Do not forget to subcribe to my blog i.e. codeinout.blogspot.com

Saturday, 7 September 2019

Creating Angular app


Building Angular App

Agenda

What we are going to cover in this blog
1.     Generate our own component using ng generate component ‘name’ in Angular CLI
2.     Generating service using it to manipulate data
3.     How to include bootstrap in Angular app

Let’s get started –

Angular uses typescript as its default scripting language
First using npm generate component named ‘customer-forms’. If you don’t know what is npm or how to work with npm I recommend you click here
It will generate 4 files



One is page specific ‘customer-forms.component.css’ file other is ‘customer-forms.component.html’ next is ‘customer-forms.component.spec.ts’ which is a test file to test your code and last is ‘customer-forms.component.ts’ which is typescript file
Add this component to your ‘app.module.ts’ file
import { BrowserModule } from '@angular/platform-browser';
import { CommonModule } from '@angular/common';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule} from '@angular/forms'
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CustomerFormsComponent } from './customer-forms/customer-forms.component';
import { CustomerViewComponent } from './customer-view/customer-view.component';

@NgModule({
  imports: [
    BrowserModule,
    CommonModule,
    AppRoutingModule,
    FormsModule,
    ReactiveFormsModule
  ],
  declarations: [
    // AppComponent,
    CustomerFormsComponent,
    CustomerViewComponent
  ],
  bootstrap: [
    // AppComponent,
    CustomerFormsComponent,
    CustomerViewComponent
  ]
})
export class AppModule { }


Now let’s create service.ts file for future use
Type ng generate service ‘name
export class CustomerFormsService{
    softwareData = [
        {Label:'None',Option:[{softwareId:0,SoftwareName:'None'}]},

        {Label:'ECommerce',Option:[
            {softwareId:1,SoftwareName:'Flipkart'},
            {softwareId:2,SoftwareName:'Amazon'}]
        },
   
        {Label:'Asset Manager',Option:[
            {softwareId:3,SoftwareName:'Asset Management'},
            {softwareId:4,SoftwareName:'Barcode Printer'},
            {softwareId:5,SoftwareName:'Asset Locator'}]
        },
   
        {Label:'School Management',Option:[
            {softwareId:6,SoftwareName:'Attendance Management'},
            {softwareId:7,SoftwareName:'Exam Management'},
            {softwareId:8,SoftwareName:'Faculty Management'},
            {softwareId:9,SoftwareName:'Schooling'}]
        },
   
        {Label:'Business',Option:[
            {softwareId:10,SoftwareName:'Warehouse'},
            {softwareId:11,SoftwareName:'Billing'},
            {softwareId:12,SoftwareName:'GST filing'}]
        }
    ];

    customerRequests = [
        {
        id: 1,
        CompanyName: 'Rohan IT',
        Name: 'Rohan Sharma',
        SoftwareId: 5,
        RelationshipDuration: 10
    },
    {
        id: 2,
        CompanyName: 'Infogain IT',
        Name: 'Lokesh Sharma',
        SoftwareId: 0,
        RelationshipDuration: 0
    },
    {
        id: 3,
        CompanyName: 'Infozech',
        Name: 'Rahul Kumar',
        SoftwareId: 9,
        RelationshipDuration: 11
    }];

    getAllSoftware()
    {
        return this.softwareData;
    }

    getSoftwareName(id:number)
    {
        return this.softwareData.find(x=> x.Option.find(y=> y.softwareId==id))
        .Option.find(z=> z.softwareId == id).SoftwareName;
    }

    get()
    {
        return this.customerRequests;
    }

    getOne(id: number)
    {
        return this.customerRequests.find( x=> x.id == id );
    }

    add(customerRequest)
    {
        console.log('In for add');
        this.customerRequests.push(customerRequest)
        console.log('Added sucessfully');
        console.log(this.customerRequests);
    }
   
    delete(customerRequest)
    {
        const index = this.customerRequests.indexOf(customerRequest);
        if(index == 0)
        {
            this.customerRequests.splice(index,1);
        }
    }
}

I have create ‘customer-forms.service.ts’ with data and some useful methods
We need to add this service to out ‘app.module.ts file as well. For that we shall add Providers properties in @NgModule directive and pass the service name there
import { CustomerFormsComponent } from './customer-forms/customer-forms.component';
import { CustomerFormsService } from '../Services/customer-forms.service';
import { CustomerViewComponent } from './customer-view/customer-view.component';

@NgModule({
  imports: [
    BrowserModule,
    CommonModule,
    AppRoutingModule,
    FormsModule,
    ReactiveFormsModule
  ],
  declarations: [
    // AppComponent,
    CustomerFormsComponent,
    CustomerViewComponent
  ],
  providers: [
    CustomerFormsService
  ],
  bootstrap: [
    // AppComponent,
    CustomerFormsComponent,
    CustomerViewComponent
  ]
})
export class AppModule { }

By doing this angular knows that this file will be injected in other classes or components.
Now lets make our component
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { Validations } from '../Validations';
import { CustomerFormsService } from '../../Services/customer-forms.service';
import { CustomerViewComponent } from '../customer-view/customer-view.component';

@Component({
  selector: 'app-customer-forms',
  templateUrl: './customer-forms.component.html',
  styleUrls: ['./customer-forms.component.css']
})
export class CustomerFormsComponent implements OnInit {
  form: FormGroup;
  customerRequests;
  SoftwareData;
  constructor(private customerRequestService : CustomerFormsService) {
   
  }

  ngOnInit() {
    this.form = new FormGroup({
      CompanyName: new FormControl('', Validators.required),
      Name: new FormControl('', Validators.required),
      SoftwareId: new FormControl(''),
      RelationshipDuration: new FormControl('', Validators.compose([
        Validators.required
      ])),
    });
    this.SoftwareData = this.customerRequestService.getAllSoftware();
  }

  OnSubmit(CustomerRequest){
    console.log(CustomerRequest);
    this.customerRequestService.add(CustomerRequest);
    console.log('Added successfully');
  }

  SelectId(id)
  {
    debugger;
    this.form.value["SoftwareId"] = id.target.selectedOptions[0].value;
    console.log(this.form.value["SoftwareId"]);
    console.log(this.SoftwareData);
  }
}

Here passing values in constructor is dependency injection ‘private customerRequestService : CustomerFormsService
Angular is built upon very powerful dependency injection framework
i.e. ‘you can pass the dependency to the class itself’. Here the ‘customer-forms.component.ts’ needs the ‘customer-forms.service.ts’ which was injected to the component through constructor.
Use command npm install bootstrap to install bootstrap in your project and add the bootstrap to angular.json file
"styles": [
              "node_modules/bootstrap/dist/css/bootstrap.min.css",
              "src/styles.css"
            ],

In the ‘customer-forms.component.html’ write your html code
<header role="banner">
    <h1>Customer Request</h1>
    <nav role="navigation">
        <h2>Site navigation</h2>
    </nav>
</header>
<main role="main" class="container">
<section>
    <h3>Request</h3>
    <p>Existing customer should register their request like need of new deature in a software,
        fix to a bug in s/w, need special permission in a s/w or want a new s/w from scratch.
        We'll get in touch within 2 hours</p>
</section>
<section class="row">
    <form
    [formGroup]="form"
    (ngSubmit)="OnSubmit(form.value)" class="col-md-12">
    <p class="row">
        <label for="CompanyName" class="col-md-3 lable">Company Name</label>
        <input type="text" id="CompanyName" name="CompanyName" formControlName="CompanyName"
        class="col-md-8 form-control"/>
    </p>
    <p class="row">
        <label for="Name" class="col-md-3">Name</label>
        <input type="text" id="Name" name="Name" formControlName="Name"  class="col-md-8"/>
    </p>
    <p class="row">
        <label for="Softwares" class="col-md-3">Software Purchased</label>
        <select id="Softwares" name="Softwares" formControlName="SoftwareId" class="col-md-4"
        (change)="SelectId($event)">
            <optgroup *ngFor="let softwareGroup of SoftwareData" label="{{softwareGroup.Label}}">
                <option *ngFor="let softwareOption of softwareGroup.Option"
                [value]="softwareOption.softwareId">{{softwareOption.SoftwareName}}</option>
            </optgroup>
        </select>
    </p>
    <p class="row">
        <label for="RelationshipDuration" class="col-md-3"> Relationship with us</label>
        <input type="text " id="RelationshipDuration" maxlength="3" Min="18"
        name="RelationshipDuration" formControlName="RelationshipDuration" class="col-md-2"/>
        <span *ngIf="form.get('RelationshipDuration').hasError('required')" class="error col-md-6">
            Age must be  greater than 18 and cannot be blank!
        </span>
    </p>
    <p class="row">
        <input type="submit" value="Save" [disabled]="!form.valid" class="col-md-2 btn btn-success"/>
    </p>
    </form>
</section>
</main>
<footer></footer>


Now when you click on Save button you should see console window of your browser and see if the object is logged or not.

Thanks

Send All Azure App Insights Or Logs Data To Tool Like Datadog

  Introduction Microsoft Azure provides a variety of insights and monitoring logs that you can monitor to check the state of a resource and ...