Wednesday, August 29, 2018

Rolta

1. Why we use interface?
2. Difference between Abstract class and interface.
3.
class A
{
public virtual print()
{
}
}

class B:A
{
public override print()
{
}
}

class C:B
{
public new print()
{
}
}

main()
{

A objA = new A();
C objC= new C();
objA = objC;

objA.print();// -- override method of B
objC.print() // C method

}

4. How to show user counter in Website (MVC)
5. Session.Abandon() what will be impact.

If on Logout button we have called Session.Abandon what will happen
New session will be made or some sesssion will be there.

6. What is providers in angular 5
Ans Providers are a set of entities that are entitled to be injected as a parameter of the constructor, and they automatically generate a singleton instance.
7. How can we make service as static?
8. What is observable?
Ans : https://interview-preparation-for-you.blogspot.com/2018/03/observable-in-angular.html
9. How to send value from child to Parent ?
Ans using Output driective

10. We have following fields in table employe|id|saalry|department
.How to get highest paid employee in the department?
Ans Select min(employeeName),min(departmentName), max(salary) from employee group by  department.

11. How to load module dynamically?
Ans : import("..common/commonModule").next(x=>{/*Some Code*/})

Sunday, August 19, 2018

MyDesq

1. dependency Injection in angular JS
2. How to format the string in angular
3. How to Send value from one component to other component without services
4. Then in services
5. how to inherit the class in typescript
6. if I want to change the index.html to home.html then where i have to change.

Ans : Angular-cli.json inside app

"apps": [
{
"root": "src",
"outDir": "dist",
"assets": [
"assets",
"favicon.ico"
],
"index": "index.html",
"main": "main.ts",

],

7. how to use Interface in typescript
8. what are the configuration files in angular2
  1. tsconfig.json - This file is used to give the options about TypeScript used for the Angular JS project.
  2. package.json  - contains the dependency and development dependencies name and version/
  3. systemjs.config.json - This file contains the system files required for Angular JS application. This loads all the necessary script files without the need to add a script tag to the html pages.
  
9. Observable and subject
Ans : https://interview-preparation-for-you.blogspot.com/2018/02/difference-between-subject-and.html
10. calling the http service(Code)
11. parameter of http get service

get take two parameteres url and parameter const opts = { params: new HttpParams({fromString: "_page=1&_limit=10"}) }; return this.httpClient.get("http://server.com/api/products", opts);
12. View Child
https://interview-preparation-for-you.blogspot.com/2018/02/passing-data-from-child-to-parent-using.html
13. Shared Module in angular

Ans : You can put commonly used directives, pipes, and components into one module and then import just that module wherever you need it in other parts of your app.
14. How to send the Json object as parameter to http services that can be recieved as query string.
  1. Take the JSON object and convert it to string (JSON.stringify)
  2. Take the string and encode it in Base64 (you can find some useful info on this here
  3. Append it to the URL and make the GET call
  4. Reverse the process. decode and parse it into an object
15. how to format the response in angular
Ans: using interface you can format the response if it is customized than you can use map function.
16. how to send the query string parameter to http services

A set of parameters attached to the end of the URL is called Query Parameters. They are appended to the URL by adding ‘?’ at the end of the URL. In addition to that, they are followed immediately with a key-value pair(Query Parameter).
  HttpParams()
We add the URL parameters using the helper class HttpParams.  The HttpParams is passed as one of the arguments to HttpClient.get method.

To use HttpParams, you need to import it first as shown below.
 
import { HttpClient,HttpParams } from '@angular/common/http';
 
Then create an instance of the HttpParams class.

const params = new HttpParams()
  .set('page', PageNo)
  .set('sort', SortOn);
 
And then call the httpClient.get method passing the params as the argument.
 
return this.httpClient.get(this.baseURL + 'users/' + userName + '/repos',{params})
 

17. what is tuple

Ans : https://interview-preparation-for-you.blogspot.com/2017/11/how-to-use-two-object-in-single-view.html
18. angular 2 vs angular 4 vs angular 5 vs angular 6.
19. Change detection strategy

Ans : https://medium.com/@bencabanes/angular-change-detection-strategy-an-introduction-819aaa7204e7
20. Difference between ng-for and ng-for-of
1.     The [ngFor] is not a type safe
2.     The [NgForOf] is a type Safe
3.     The [NgFor] directive instantiates a template once per item from iterate
4.     The [ngFor] and [ngForOf] are actually the selectors of the [NgForOf] directive and it is not two distinct things
5.     The [ngFor] will be works like as collections
6.     The [ngForOf] will be works like as generics

Example - ngFor

{{i}} - {{user.name}}
OR Example - ngForOf
{{i}} - {{user.name}}

Thursday, August 16, 2018

MVC Security

1) Security Misconfiguration (Error Handling Must Setup Custom Error Page)

In this kind of attack the attacker intercepts form data which is submitted by end User and changes values and sends the modified data to the server.

So for such kind of scenarios developers do put proper validations in place but when these validations display error lot of information of the server is revealed.

So is data annotation validations more than enough to secure the page. No, that’s not enough for securing page I will show you a small demo of how these validations get bypassed.

With the help of Burp software you can modify request in middle.

Solution: -
So the solution here is we need to set some kind of error page which does not show the internal technical error but rather shows a custom error message.

We have two approaches for it :-

Create a custom Error handling Attribute.
Setting Custom Error page from Web.config file

2) Cross-Site Request Forgery (CSRF)

A CSRF vulnerability allows an attacker to force a validated and logged in user to perform actions without their consent or unknowingly.

Take this simple example.

User logs in to the bank server.
Bank authorizes and a secure session is established between user and the bank server.
The attacker sends an email with a malicious link saying “Earn 100000$ now” to the user.
User clicks on the malicious link and the site tries transfer money from your account to the attackers account. Because the secure session is established the malicious code can execute successfully.


Microsoft has recognized this threat and for preventing the same we have something called as AntiForgeryToken.

Solution:-

We need to add @Html.AntiForgeryToken()helper in your form inside form tag . And on the Action Method which handles your post ([HttpPost])Request we need to put[ValidateAntiForgeryToken] attribute which will check if the token is valid.

When we add AntiForgeryToken helper on View it creates a hidden field and assigns a unique token value to it and meanwhile a session Cookie is added to the browser.

When we post formHTML itschecksfor __RequestVerificationToken Hidden field and whether __RequestVerificationToken Cookie are present or not. If either the cookie or the form __RequestVerificationToken Hidden field values are missing, or the values don't match, ASP.NET MVC does not process the action. This is how we can prevent cross-site request forgery attack in asp.net MVC.

Cross-Site Scripting (XSS) attacks

Cross-site Scripting (XSS) is an attack in which malicious scripts is injected via input fields this attack is most common and allows an attacker to steal credentials and valuable data that can lead to a big security breach.


In this attack attacker visits a website and tries to execute a malicious scripts in form comment box. Now if website has not checked for Malicious code then the code can get executed on the server causing damage.

Lets try to understand the same using a example.Below is simple Employee form which we are trying to save data. Now in the text box I am trying to execute some malicious code using javascript using the SCRIPT tag. But if we try to submit the same MVC throws an error that something bad is happening.

Solution: -

[ValidateInput(false)]
[AllowHtml]
[RegularExpressionAttribute]
AntiXSS Library

Malicious File Upload.

Till now we have learned how to protect all your input fields from attack but still, we are missing one main field it is File upload control we need to protect from taking invalid input most attackers try to upload a malicious file which may cause a security issue. The attacker can change file extension [tuto.exe to tuto.jpeg] and the malicious script can be uploaded as an image file. The Most of the developer just look on the file extension of the file and save in folder or database but file extension is valid not file it may have a malicious script.


Solution:-

First thing we need to do is validate file uploads
Allow only access to files extension which are required
Check the file header.

Version Discloser

Version information can be used by anattacker to target specific attack on that Version which is disclosed.

Whenever browsersendsHTTP torequest to theserverin response we get response header which contains information of [Server, X-AspNet-Version,X-AspNetMvc-Version, X-Powered-By].

The server shows information of which web server is begin used.

X-AspNet-Versionshows information of which specific Asp.Net VersionUsed.

X-AspNetMvc-Versionshows information of which ASP.NET MVC version Used.

X-Powered-By shows information of which framework your website is running on.

Solution:-

For removingX-AspNetMvc-Version header
To remove response X-AspNetMvc-Versionwhich shows information of which ASP.NET MVC version used we have built in property in MVC.

Just set [MvcHandler.DisableMvcResponseHeader = true;] in Global.asaxApplication start event [Application_Start()] this will remove header it won’t be displayed any more.

6) SQL Injection Attack.

SQL Injection attack is one of the most dangerousattacks it is ranked 1 in top 10 Vulnerabilitiesby OWASP2013 [Open Web Application Security Project] . SQL injection attack can give valuable data to theattacker that can lead to abig security breach and can also take full access to thedatabase server.

In SQL Injection attacker always try to enter malicious SQL statement which will get executed in thedatabase and return unwanted data to the attacker.


Solution:-

Validate inputs
Use of low-privileged database logins
Use Parameterized queries
Use ORM (e.g. Dapper , Entity framework )
5) Use Stored Procedures

https://www.codeproject.com/Articles/1116318/Points-to-Secure-Your-ASP-NET-MVC-Applications

Monday, August 13, 2018

Choosing Between Class and Struct

One of the basic design decisions every framework designer faces is whether to design a type as a class (a reference type) or as a struct (a value type). Good understanding of the differences in the behavior of reference types and value types is crucial in making this choice.
The first difference between reference types and value types we will consider is that reference types are allocated on the heap and garbage-collected, whereas value types are allocated either on the stack or inline in containing types and deallocated when the stack unwinds or when their containing type gets deallocated. Therefore, allocations and deallocations of value types are in general cheaper than allocations and deallocations of reference types.
Next, arrays of reference types are allocated out-of-line, meaning the array elements are just references to instances of the reference type residing on the heap. Value type arrays are allocated inline, meaning that the array elements are the actual instances of the value type. Therefore, allocations and deallocations of value type arrays are much cheaper than allocations and deallocations of reference type arrays. In addition, in a majority of cases value type arrays exhibit much better locality of reference.
The next difference is related to memory usage. Value types get boxed when cast to a reference type or one of the interfaces they implement. They get unboxed when cast back to the value type. Because boxes are objects that are allocated on the heap and are garbage-collected, too much boxing and unboxing can have a negative impact on the heap, the garbage collector, and ultimately the performance of the application. In contrast, no such boxing occurs as reference types are cast.
Next, reference type assignments copy the reference, whereas value type assignments copy the entire value. Therefore, assignments of large reference types are cheaper than assignments of large value types.
Finally, reference types are passed by reference, whereas value types are passed by value. Changes to an instance of a reference type affect all references pointing to the instance. Value type instances are copied when they are passed by value. When an instance of a value type is changed, it of course does not affect any of its copies. Because the copies are not created explicitly by the user but are implicitly created when arguments are passed or return values are returned, value types that can be changed can be confusing to many users. Therefore, value types should be immutable.
As a rule of thumb, the majority of types in a framework should be classes. There are, however, some situations in which the characteristics of a value type make it more appropriate to use structs.
✓ CONSIDER defining a struct instead of a class if instances of the type are small and commonly short-lived or are commonly embedded in other objects.
X AVOID defining a struct unless the type has all of the following characteristics:
  • It logically represents a single value, similar to primitive types (intdouble, etc.).
  • It has an instance size under 16 bytes.
  • It is immutable.
  • It will not have to be boxed frequently.
In all other cases, you should define your types as classes.

Friday, August 10, 2018

Difference Between var and let



let gives you the privilege to declare variables that are limited in scope to the block, statement of expression unlike var.


var is rather a keyword which defines a variable globally regardless of block scope.


Global window object

Even if the let variable is defined as same as var variable globally, the let variable will not be added to the global window object.


See the example below -


var varVariable = “this is a var variable”;

let letVariable = “this is a let variable”;

Say, here we have two variables declared. let us see what output it actually gives you.


console.log(window.varVariable); //this is a var variable

console.log(window.letVariable); //undefined

Thus let variables cannot be accessed in the window object because they cannot be globally accessed.


Block

let variables are usually used when there is a limited use of those variables. Say, in for loops, while loops or inside the scope of if conditions etc. Basically, where ever the scope of the variable has to be limited.


For example: -


For loop using let variable: -


for(let i=0;i

console.log(i); //i is visible thus is logged in the console as 0,1,2,....,9

}

console.log(i); //throws an error as "i is not defined" because i is not visible

For loop using var variable: -


for(var i=0; i

console.log(i); //i is visible thus is logged in the console as 0,1,2,....,9

}

console.log(i); //i is visible here too. thus is logged as 10.

Thus, as you can see the var variable is logged as 10 outside of the for loop too.


Note: It logged it as 10 because the for loop terminates after checking the incremented value of i.

Redeclaration

let variables cannot be re-declared while var variable can be re-declared in the same scope.


Assume we are using strict mode


'use strict';

var temp = "this is a temp variable";

var temp = "this is a second temp variable"; //replaced easily

We cannot do the same thing with let-


'use strict';

let temp = "this is a temp variable";

let temp = "this is a second temp variable" //SyntaxError: temp is already declared

Function

let and var variables work the same way when used in a function block.


function aSampleFunction(){

let letVariable = "Hey! What's up? I am let variable.";

var varVariable = "Hey! How are you? I am var variable.";

console.log(letVariable); //Hey! What's up? I am let variable.

console.log(varVariable); //Hey! How are you? I am var variable.

}

With the above explanation, I can surely tell that now you have total idea about the difference about let and var variables.


Source : https://codeburst.io/difference-between-let-and-var-in-javascript-537410b2d707

Thursday, August 9, 2018

What is Polyfills

A polyfill is a piece of JavaScript that can “implant” missing APIs into an older browser. For example, shims and polyfills enable older ECMA5 browsers to run ECMA6 code.

Lazy Loading

Lazy loading is a technique in Angular that allows you to load JavaScript components asynchronously when a specific route is activated. This can add some initial performance during the initial load, especially if you have many components with complex routing. There are some good posts about lazy loading in angular, but I wanted to simplify it further. This lesson will show you how to enable lazy loading in 3 easy steps with a brand new app.

Why singleton should be sealed?

public class NotReallySingleton
{
    private NotReallySingleton() {}

    public class CursesFoiledAgain : NotReallySingleton
    {
    }
}

...
 NotReallySingleton x = new NotReallySingleton.CursesFoiledAgain();
 NotReallySingleton y = new NotReallySingleton.CursesFoiledAgain();

This works because private access is limited to the program text of the type, including nested types. So CursesFoiledAgain has access to the private constructor of NotReallySingleton.

But even leaving this aside, if your intention is that no-one can derive from the class, why would you not want to signal that intention as clearly as possible, via sealed?

Wednesday, August 8, 2018

Angular Performance Checklist

1. Remove console.log()
2. Logic should not be in template.
3. Never initialize a member object variable until it is use.
4. Monitor changeDetection Strategy closely if it should be OnPush or default.
5. Enable JLint and TSLint in VS Code
6. Use trackBy in ngFor if items are adding in array dynamically.
7. preserveWhiteSpace should not be true. By default it is false.

Difference Between Bootstrap 3 and 4


Bootstrap 3 Source CSS Files is LESS.
Bootstrap 4 Source CSS files Converted in SCSS.

Bootstrap 3 has 4 grid system (col-xs-3, col-sm-3, col-md-3, col-lg-3).
Bootstrap 4 has 5 grid system (.col-, .col-sm-3, .col-md-3, .col-lg-3, .col-xl-3). Bootstrap 4 has removed the xs from the lowest break point. Therefore, (col-) covers all devices.

Bootstrap 3 Offset class is like this (col-md-offset-4).
Bootstrap 4 has changed the offset class (offset-md-4).

In Bootstrap 3 we are used this (.img-responsive) class for responsive image.
Bootstrap 4 has changes the class for responsive image (.img-fluid).

In Bootstrap 3 we are used (.input-lg) and (.input-sm) to increase and decrease the input size.
Bootstrap 4 has changed to (.form-control-lg) and (.form-control-sm) to increase and decrease the input size.

Generator in JavaScript

A generator is a special type of function that can be entered and exited a number of times. You might hear people describe it as, “a function that can be paused.

Example

function * generatorForLoop(num) {
  for (let i = 0; i < num; i += 1) {
    yield console.log(i);
  }
}

const genForLoop = generatorForLoop(5);

genForLoop.next(); // first console.log - 0
genForLoop.next(); // 1
genForLoop.next(); // 2
genForLoop.next(); // 3
genForLoop.next(); // 4

Yield delegator
Yield with asterisk can delegate it’s work to another generator. This way you can chain as many generators as you want.

function * anotherGenerator(i) {
  yield i + 1;
  yield i + 2;
  yield i + 3;
}

function * generator(i) {
  yield* anotherGenerator(i);
}

var gen = generator(1);

gen.next().value; // 2
gen.next().value; // 3
gen.next().value; // 4

Yield returns a value only once, and the next time you call the same function it will move on to the next yield statement.

Also in generators we always get the object as output. It always has two properties value and done. And as you can expect, value - returned value, and done shows us whether the generator has finished its job or not.


function * generator() {
  yield 5;
}

const gen = generator();

gen.next(); // {value: 5, done: false}
gen.next(); // {value: undefined, done: true}
gen.next(); // {value: undefined, done: true} - all other calls will produce the same result

Not only can yield be used in generators, return will also return the same object to you, but after you reach the first return statement the generator will finish it’s job.

function * generator() {
  yield 1;
  return 2;
  yield 3; // we will never reach this yield
}

const gen = generator();

gen.next(); // {value: 1, done: false}
gen.next(); // {value: 2, done: true}
gen.next(); // {value: undefined, done: true}

Methods and initialization
Generators are reusable, but to be so — you need to initialize them, fortunately it is quite simple.

function * generator(arg = 'Nothing') {
  yield arg;
}

const gen0 = generator(); // OK
const gen1 = generator('Hello'); // OK
const gen2 = new generator(); // Not OK

generator().next(); // It will work, but every time from the beginning.

Method return():
function * generator() {
  yield 1;
  yield 2;
  yield 3;
}

const gen = generator();

gen.return(); // {value: undefined, done: true}
gen.return('Heeyyaa'); // {value: "Heeyyaa", done: true}

gen.next(); // {value: undefined, done: true} - all next() calls after return() will return the same output.

Return() will ignore any code in the generator function that you have. But will set the value based on a passed argument and set done to be true. Any calls next() after return() will return done-object.

Method throw():

function * generator() {
  yield 1;
  yield 2;
  yield 3;
}

const gen = generator();

gen.throw('Something bad'); // Error Uncaught Something bad
gen.next(); // {value: undefined, done: true}

It’s easy one all is throw() do — just throws the error. We can handle it using try — catch.

Not only next() we can use to iterate generator. But using for-of loop we get all the values (not the object) of our generator.

function * generator(arr) {
  for (const el in arr)
    yield el;
}

const gen = generator([0, 1, 2]);

for (const g of gen) {
  console.log(g); // 0 -> 1 -> 2
}

gen.next(); // {value: undefined, done: true}

This will not work with for-in loop and you can’t get access to properties by just typing number — generator[0] = undefined.

Monday, August 6, 2018

HCL Angular

1. Closure?
2. What is the benefit of closure?
  The first benefit of ClosureClosure is to preserve local variables within the scope. Since javaScript is a first-class function, developers often encounter name clashing, that will cause some unexpected output. Using ClosureClosure can help preserve the namespace in that scope, private variable. You can see this a lot in the past of jQuery code, where one defines a click method.

$(function() {
  var selections = []
  $(".something").click(function() { // this closure has access to the outer variable selections
    selections.push("something") // this are able to get the outer function selections
  })
})
While this is indeed one of the use-cases of ClosureClosure, it might leave you thinking, “Is this really what the real purpose of closure?” You might still question the statement as to what is the general use case of ClosureClosure might be.

The second benefit, which is more of a general use case, is that it is useful in an asynchronous environment.

Imagine if you need to loop through a value in an array:

for(var i = 0 ; i< 3; i++) {
  setTimeout(() => console.log(i), 3000)
}

What will the output of this program?

It prints 3 three times. Since, setTimeout is asynchronous, by the time the loop finishes, the outer scope i has also changed to 3, and the subsequent call to setTimeout during the loop triggers the callback and print 3.

How would you solve this problem?

There are many ways, including using an ES6 syntax let instead of var to define its scope at the block level and solve the issue. However, if they want you to solve this issue without using any ES6 feature, ClosureClosure is your answer.

function printSomething(i) {
  setTimeout(() => console.log(i), 3000)
}

for(var i = 0; i<3; i++) {
  printSomething(i)
}
By just creating another outer function outside of setTimeout, you are defining a closure. The i value is preserved even after printSomething is terminated. The callback then prints 0 1 2 to the console.

That is the reason why ClosureClosure is powerful javaScript feature. You can use ClosureClosure to preserve the scope of the outer variable in an asynchronous environment.

Another Example One
Let’s imagine another example where you need to create a function that needs to call 3rd party API and aggregate the result and return it to the caller.

function getAPI(cb) {
    setTimeout(() => cb("a"), 3000)
}

function getAPIB(cb) {
    setTimeout(() => cb("b"), 2000)
}

function getAPIC(cb) {
    setTimeout(() => cb("c"), 1000)
}

function aggregateValue() {
  var aggregateData = []
  
  // your implementation here
}
Before you continue reading, about the solution, pause for a second and think about how you can solve this without promises, async/await.

We can leverage the power of ClosureClosure to preserve the scope of the function and to stop aggregateValue to return early by using callbacks.

Since getAPI, getAPIB, getAPIC all uses a callback function, you can create a callback function that increments the number of count of API called so far. Once the number of API called so far counter exceed 2, call the return callback value.

function aggregateValue(cb) {
  var aggregateData = []
  var numberAPICalledSoFar = 0
  
  function callback(value) {
    aggregateData = [...aggregateData, value]
    if(numberAPICalledSoFar < 2) {
      numberAPICalledSoFar++;
    }else {
      cb(aggregateData)
    }
  }
  getAPI(callback)
  getAPIB(callback)
  getAPIC(callback)
}
The above code leverages, again, the power of ClosureClosure, to preserve the local variable of the enclosing function when it is triggered. As getAPI finishes its called and evoke the callback function, the callback function access the outer scope aggregateValue to increment the number of counts that the API finishes executing. The aggregateData then return with a callback from the outer aggregateValue function that needs all the aggregate data from all the 3rd party API.

Run this function:

aggregateValue((ans) => ans.foreach(console.log))

3. this keyword based scenario?
4. Generator?
5. Generator is synchronous  or asynchronous?
And: Generator is synchronous, We can make it asynchronous using Promise or co library.

6 How to convert asynchronous generator to synchronous generator
Ans using yield.
7. If you have multiple objects and you want to right a function that is accesbile to all objects?
Ans
var a = {}; or a = new Object();
Object.prototype.print=(){
console.log('Hello World');
}

8. If we change something in prototype function will it change in all objects?

9. What are different type of decorator in angular?
Ans : There are four type of decorator in angular 
1. class Decorator ( @Component())
2. Function Decorator (@HostListener())
3. Property Decorator (@Input()..)
4. Constructor Decorator (@Inject())

10.What is @function (function decorator)?
Ans example is HostListener

11.If you have home page and in the home page multiple tab then how will you maintain the tab to displayed according to the role in angular way?
12. How will you manage state in redux?
13. Write a code , we receive user list from api. And need to display the list?
14. How the components communicate?
15. What is benefit of SPA?
16.

What will be return

return
0;

17. How will you implement inheritance in javascript?
Ans using prototype?
18. What is eval in javascript?
Ans : https://interview-preparation-for-you.blogspot.com/2011/04/eval-in-javascript.html
19. And why it is bad practice to use eval ?
Ans :  

1. It requires a compile and is therefore slow
2. Improper use of eval opens up your code for injection attacks

20. What will be print

var x=8;
var x = function  ()
{
console.log("fgf");
}


console.log(x);


Ans : 8;

21. What will be print

var x=8;
function x ()
{
console.log("fgf");
}


console.log(x);

Ans : 8;

22. What will be print

var x=8;
function x ()
{
console.log("fgf");
}


console.log(x());

Ans: Error 

Uncaught TypeError: x is not a function


Followers

Link