Saturday, December 16, 2017

Saxo Bank

What is shallow copy and deep copy?
2. How can we make deep copy?
3. If there are two threads one filling the queue and other one is consuming the queue. First one wait if queue is full second wait if queue is empty. Write the sudo code.
4. Write a program so that every user get updated value on their screen when some one update.
5. Which is fast 'in' and 'not in'?
6. How can we replace 'not in' something which is fast?
7. If there is a grid which is fetch data from database is there any mechanism to push data into grid from database.
8. Design an application where every user screen changed when any user add some value.
9. What other methods need to override while overriding Equal method?
10. What is the benefit of xml serialization?
11. What is advantage of implementing IDisposable interface other than dispose method called while using in using statement.

Thursday, December 14, 2017

Exl Services

Singleton Pattern?
How will you use singleton pattern in multithreading environment?
What is Mutex?
Explain SOLID principle?
Any Implementat of SOLID principle in your project?
Difference between factory method and abstract factory? give some real example?
What are the process of NUnit test?
What is the role of technical architect?
What is Async and Await?
How to pass results in multiple tasks?
WCF Vs WebApi?
What are the contracts in WCF?
Any performance monitoring tool that you have used for your application?
What steps you will take if Stored procedure is fast in development environment and slow in production environment?
What is .NET CORE?

Angular 2

1. What is Angular 2

Angular 2 is a JavaScript framework which allows to create reactive Single Page Application.

2. What is Angular CLI

Ans : A command line interface for Angular

Command to install Angular CLI :-npm install -g @angular/cli

* CLI uses Webpack  a tool which bundles all css and JS and include them in index.html file.

If you face any error installing any component from npm than run below command

npm set strict-ssl false


Angular 2

General Questions:
 What did you learn about Angular yesterday/this week?
 What are some of the reasons you would choose to use Angular in
your project?
 What did you like about working with Angular?
 How do you keep your Angular code more readable and maintainable?

 Animations Questions:
 How do you define transition between two states in Angular?
 How do you define a wildcard state?

 Architecture Questions:
 What is a good use case for ngrx/store?
 Can you talk about a bug related to a race condition, how to solve it
and how to test it?

 API Questions:
 What does this code do:
 @HostBinding('class.valid') isValid;
 <div *ngIf='someObservableData | async as data; else
loading'>{{data}}</div>
 <ng-template #loading>
 Loading Data...
 </ng-template>
 Why would you use renderer methods instead of using native element
methods?
 What is the point of calling renderer.invokeElementMethod(rendererEl,
methodName)?
 How would you control size of an element on resize of the window in a
component?
 What would be a good use for NgZone service?
 How would you protect a component being activated through the
router?
 How would you insert an embedded view from a prepared
TemplateRef?

 Template Syntax Questions:
 How can you add an active class to a selected element in a list
component?
 What is a template variable. How would you use it?

 Component Questions:
 What is the minimum definition of a component?
 What is the difference between a component and a directive?
 How do components communicate with each other?
 How do you create two way data binding in Angular?
 How would you create a component to display error messages
throughout your application?
 What does a lean component mean to you?

 Component Interaction & State Management Questions:
 How would you pass data from a parent component to a child
component?
 How would you pass data from a child component to a parent
component?
 Which components will be notified when an event is emitted?
 Tell me about the different ways how you would get data to your
components from a service and talk about why would you use one way
vs the other?
 How would you use cached data?

 Forms Questions:
 When do you use template driven vs model driven forms? Why?
 How do you submit a form?
 What's the difference between NgForm, FormGroup, and FormControl?
How do they work together?
 What's the advantage of using FormBuilder?
 How do you add form validation to a form built with FormBuilder?
 What's the difference between dirty, touched, and pristine on a form
element?
 How can you access validation errors in the template to display error
messages?
 What is async validation and how is it done?

 NgModules Questions:
 What is the purpose of NgModule?
 How do you decide to create a new NgModule?
 What are the attributes that you can define in an NgModule
annotation?
 What is the difference between a module's forRoot() and forChild()
methods and why do you need it?
 What would you have in a shared module?
 What would you not put shared module?
 What module would you put a singleton service whose instance will be
shared throughout the application (e.g. ExceptionService
andLoggerService)?
 What is the purpose of exports in a NgModule?
 Why is it bad if SharedModule provides a service to a lazy loaded
module?

 Services Questions:
 What is the use case of services?
 How are the services injected to your application?
 How do you unit test a service with a dependency?
 Why is it a bad idea to create a new service in a component like the
one below?
 let service = new DataService();

 Structural Directives Questions:
 What is a structural directive?
 How do you identify a structural directive in html?
 When creating your own structural directives, how would you decide on
hiding or removing an element? What would be the advantages or
disadvantages of choosing one method rather than the other?

 Style Guide Questions:
 What are some of the Angular Style Guide suggestions you follow on
your code? Why?
 Is it important to have a style guide? Why/not?

 Styling Questions:
 How would you select a custom component to style it.
 What pseudo-class selector targets styles in the element that hosts the
component?
 How would you select all the child components' elements?
 How would you select a css class in any ancestor of the component
host element, all the way up to the document root?
 What selector force a style down through the child component tree into
all the child component views?
 What does :host-context() pseudo-class selector targets?
 What does the following css do?
 :host-context(.theme-light) h2 {
 background-color: red;
 }

 Testing Questions:
 How do you mock a service to inject in a unit test?
 How do you mock a module in a unit test?

 Performance Questions:
 What tools would you use to find a performance issue in your code?
 What tools have you used to improve the performance of your
application?
 What are some ways you may improve your website's scrolling
performance?
 Explain the difference between layout, painting and compositing.
 Have you seen Jeff Cross's NgCruise talk on performance?

 Lifecycle Hooks Questions:
 What is the possible order of lifecycle hooks.
 When will ngOnInit be called?
 How would you make use of ngOnInit()?
 What would you consider a thing you should be careful doing on
ngOnInit()?
 What is the difference between ngOnInit() and constructor() of a
component?

 Pipes Questions:
 What is a pure pipe?
 What is an async pipe?
 What kind of data can be used with async pipe?
 How do you create a custom pipe?

 Routing Questions:
 What is the difference between RouterModule.forRoot() vs
RouterModule.forChild()? Why is it important?
 How does loadChildren property work?
 Do you need a Routing Module? Why/not?
 When does a lazy loaded module is loaded?
 Below link doesn't work. Why? How do I fix it?
 <div routerLink='product.id'></div>
 Can you explain the difference between ActivatedRoute and
RouterState?

 Observables/RxJS Questions:
 What is the difference between an observable and a promise?
 What is the difference between an observable and a subject?
 What are some of the angular apis that are using observables?
 How would you cache an observable data?
 How would you implement a multiple api calls that needs to happen in
order using rxjs?
 How would you make sure an api call that needs to be called only once
but with multiple conditions. Example: if you need to get some data in
multiple routes but, once you get it, you can reuse it in the routes that
needs it, therefor no need to make another call to your backend apis.
 How would you implement a brush behavior using rxjs?
 How would you implement a color picker with rxjs?
 If you need to respond to two different Observable/Subject with one
callback function, how would you do it?(ex: if you need to change the
url through route parameters and with prev/next buttons).

 TypeScript Questions:
 Why do you need type definitions?

 How would you define a custom type?
 What is the difference between an Interface and a Class?
 First line below gives compile error, second line doesn't. Why?
 someService.someMethod(x);
 someService['someMethod'](x);
 What are Discriminated union types?
 How do you define Object of Objects type in typescript?

 Security Questions:
 ...

 JavaScript Questions:
 Explain the difference between var, let and const key words.
 Could you make sure a const value is garbage collected?
 Explain Object.assign and possible use cases.
 Explain Object.freeze and possible use cases.
 Explain the code below. How many times the createVal function is
called?
 function createVal(){
 return Math.random();
 };

 function fun( val = createVal()){
 // Do something with val...
 }

 fun();
 fun(5);

 Coding Questions:
 What would these components render?
 import { Component, ContentChildren, Directive, Input,
QueryList } from '@angular/core';
 @Directive({selector: 'pane'})
 export class Pane {
 @Input() id: string;
 }

 @Component({
 selector: 'tab',
 template: `
 <div>panes: {{serializedPanes}}</div>
 `
 })
 export class Tab {
 @ContentChildren(Pane) panes: QueryList<Pane>;
 get serializedPanes(): string { return this.panes ?
this.panes.map(p => p.id).join(', ') : ''; }
 }

 @Component({
 selector: 'example-app',
 template: `
 <tab>
 <pane id="1"></pane>
 <pane id="2"></pane>
 <pane id="3" *ngIf="shouldShow"></pane>
 </tab>
 <button (click)="show()">Show 3</button>
 `,
 })
 export class ContentChildrenComp {
 shouldShow = false;
 show() { this.shouldShow = true; }
 }

 how to declare a component
 what type of directives are there
 how does rxjs differ from promises
 What is ChangeDetection.OnPush and what other
ChangeDetection strategies exist
 What is NgZone and what is it used for
 How do you declare an event binding
 How to declare a property binding
 What is ngModel and why is it considered a shorthand?
 Explain @Input @Output
 Explain NgModule and how a root module differs from a
feature module

 Explain where you would put shared components and where
you would put shared services
 Explain how you can use lay loading and what the benefit is
and also what impact this has on where you place
components and services
 What is AOT
 What is tree shaking
 What is “@Inject” and why is it needed
 What directive would you use to loop data?
 How would you import only the operators you need in Rxjs
and how would you import the whole lib and it what cases
would you use each strategy?
 • What is ngModule
 Difference between component and directives
 Why to use Module and diff between module and
component
 Default pipes
 Built in directives and their syntax's
 What is lazzy loading.
 Routing configuration
 Work flow of basic project structure
 “In Angular 2 how do you determine the active route”
 “Angular 2 data attributes”
 “Can't bind to 'formGroup' since it isn't a known property of
'form”
 “How do I create a singleton service in Angular 2?”
 “Angular2 exception: Can't bind to 'ngForIn' since it isn't a
known native property”
 “NativeScript/Angular - How to import global styles?”
 “Angular2 - What is the meanings of module.id in
component?”
 “Angular 2: How to use/import the http module?”
 “Angular2 material dialog has issues - Did you add it to

@NgModule.entryComponents?”
 “The pipe ' ' could not be found angular2 custom pipe”
 • “How do I call an Angular 2 pipe with multiple
arguments?”
 “Huge number of files generated for every Angular project”
 “Angular - Promise vs Observable”
 “Huge number of files generated for every Angular project”
 “Difference between Constructor and ngOnInit”
 “Angular 2 html binding”
 “Angular 2 HTTP GET with TypeScript error http.get(…).map
is not a function in [null]”
 “How to bundle an Angular 2, 4 & … app for production”
 “@Directive v/s @Component in angular2”
 “Angular 2 pipes details”
 “Angular 2 Forms Update”
 “Angular 2 Routing (3.0.0+) ”
 “Angular 2 RXJS Subjects and Observables with API
requests”
 “Angular Routing”
 “Directives”
 “How to Use ngif”

C# 7.0 & 7.1 , 7.2

1. Discards (C# 7.0)

a. Use with Out Param

private void DiiscardTest()
        {
            //Before  C# 7.0

            string s = "4";
            if (int.TryParse(s,out int x))
            {
                Console.WriteLine("This is an intger");
            }
            int y;            
            if (int.TryParse(s, out y))
            {
                Console.WriteLine("This is an integer");
            }

            //After C# 7.0
            if (int.TryParse(s, out int _))
            {
                Console.WriteLine("This is an intger");
            }

            if (int.TryParse(s, out _))
            {
                Console.WriteLine("This is an intger");
            }
//It is applicable on multiparameter

        }

b. Discard With Tuple

private void DiscardWithTuple()
        {
            Program p = new Program();

            //Before C# 7.0
            (int id, String name) = p.GetDetail();

            //After C$ 7.0
            (int ID, _) = p.GetDetail();

        }

        private (int id, String name) GetDetail() => (1, "red");

c. Use Discard alone

 private void DiscardAlone()
        {
            //Before C# 7.0
            int x = 90;
            bool y = x > 90 ? UpdateID() : UpdateName();

            //After C# 7.0
            _ = x > 90 ? UpdateID() : UpdateName();
        }

        private bool UpdateID()
        {
            //Updated...
            //............
            return true;
        }

        private bool UpdateName()
        {
            //Updated...
            //............
            return true;
        }

d. Use Discard in Pattern Matching

private void DoWork(dynamic c)
        {
            if (c is int)
            {
                Console.WriteLine("c is an intger");
            }
            else if (c is string)
            {
                Console.WriteLine("c is a String");
            }
            else if(c is var _)
            {
                Console.WriteLine("Unknow Type");
            }
        }

e. Discard with Tasks

Before C# 7.0

static void Main(string[] args) => PrintOddNumbers(20);  
  
private static void PrintOddNumbers(int maxNumber)  
{  
  Task task = Run(() => {   
    for (int i = 1; i < maxNumber; i += 2)  
    {  
        Write($"{i}\t");  
        Sleep(500);  
    }  
    });              
   Delay(300*maxNumber).Wait();  

In above example there is no use of task, so using discard we can avoid task

After C# 7.0

private static void PrintOddNumbers(int maxNumber)  
{  
  _= Run(() => {   
    for (int i = 1; i < maxNumber; i += 2)  
    {  
        Write($"{i}\t");  
        Sleep(500);  
    }  
    });              
   Delay(300*maxNumber).Wait();  

2. 'is' type Pattern Matching


Before C# 7.0 
        private static void PrintObject(dynamic x)
        {
            if (x is Seller)
            {
                var c = x as Seller;
                WriteLine($"Seller Id : {c.Id} Seller Name {c.Name}");
            }
            if (x is Manager)
            {
                var p = x as Manager;
                WriteLine($"Manager Id : {p.ManagertId} Manager Name {p.Name}");
            }
            else
                WriteLine("Unknown type");
        }

After C# 7.0 

private static void PrintObject(dynamic x)
        {
            if (x is Seller s)
            {
                WriteLine($"Seller Id : {s.Id} Seller Name {s.Name}");
            }
            if (x is Manager m)
            {
                WriteLine($"Manager Id : {m.ManagertId} Manager Name {m.Name}");
            }
            else
                WriteLine("Unknown type");
        }

3. Pattern matching with switch

private static void PrintObject(dynamic x)  
        {  
            switch (x)  
            {  
                case Customer c:  
                    WriteLine($"Customer Id : {c.Id} Customer Name {c.Name}");  
                    break;  
                case Product p:  
                    WriteLine($"Product Id : {p.ProductId} Product Name {p.Name}");  
                    break;  
                default:  
                    WriteLine("Unknown type");  
                    break;  
            }              
        } 


4. switch statement with when condition

private void PrintShapeType(object shape)  
        {  
            switch (shape)  
            {  
                case Triangle t when t.SideA == t.SideB && t.SideB == t.SideC:  
                    WriteLine($"Equilateral Triangle");  
                    break;  
  
                case Triangle t:  
                    WriteLine($"Not a Equilateral Triangle");  
                    break;  
  
                case Rectangle r when r.Height == r.Width:  
                    WriteLine($"Square");  
                    break;  
  
                case Rectangle r:  
                    WriteLine($"Rectangle");  
                    break;  
  
                default:  
                    WriteLine($"Unknow shape");  
                    break;  
            }  
        }  


5. Does Sequence matter for switch


Yes sequence matter first matching case will excute first.


using static System.Console;  
namespace CaseExpressionSequence  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            PrintData(0);  
            PrintData(2);  
            PrintData(5);  
            PrintData(false);  
            PrintData(true);  
            PrintData(55.5);  
        }  
  
        private static void PrintData(object obj)  
        {  
            switch (obj)  
            {  
                case 0:  
                case 5:  
                case true:  
                    WriteLine($"you passed {obj}");  
                    break;  
                case int number:  
                    WriteLine($"you passed a numeric value");  
                    break;  
                case bool b:  
                    WriteLine($"you passed a boolean value");  
                    break;  
                default:  
                    WriteLine($"Invalid data");  
                    break;  
            }  
        }  
    }  
}  


6. Async method returning Task


class Program1
        {
            static void Main(string[] args)
            {                
                PrintPrimeNumbers(100);
                ReadKey();
            }

            private static async Task PrintPrimeNumbers(int maxNumber)
            {
                await Run(() =>
                {
                    WriteLine($"printing prime numbers between 0 and {maxNumber}");
                    List primes = new List();
                    bool isPrime;

                    for (int number = 2; number <= maxNumber; number++)
                    {
                        isPrime = true;
                        foreach (var prime in primes.Where(x => x <= Sqrt(number)))
                        {
                            if (number % prime == 0)
                            {
                                isPrime = false;
                                break;
                            }
                        }
                        if (isPrime)
                        {
                            WriteLine(number);
                            primes.Add(number);
                        }
                    }
                });
            }
        }

7. Same way you can reurn Task

8. Acynch method can return void

9. Async method returning ValueTask

In above example we cna return ValueTask instead of Task because task is frreqence type and we need

10. To use ValueTask, you must need to install NuGet package “System.Threading.Tasks.Extensions”.

11. Async Main (Main Method returning Task)

Main function can return now Task, Task, it may be async also.

12. Can we have more than one Main method in a Project?

Yes  , it is possible in C# 7.0, Main method where you want to start executaion set it in property window strtup project

13. Infer Tuple Element Names

// Tuple created without Tuple keyword
class Program  
    {  
        static void Main(string[] args)  
        {  
            var activity = ActivityTracker.GetActivity();  
            WriteLine($"Activity Data: \n Steps: {activity.Item1}\n Distance: {activity.Item2} Km.\n Calories Burned: 

{activity.Item2}\n Sleep Time: {activity.Item4}\n Heart Rate: {activity.Item5}\n Weight: {activity.Item6}");  
        }  
    }  
  
    public class ActivityTracker  
    {  
        public static (int, double, double, TimeSpan, double, double) GetActivity()  
        {  
            int steps = 7000;  
            double distance = 5.2;  
            double caloriesBurned = 30.02;  
            TimeSpan sleepTime = new TimeSpan(6, 20, 00);  
            double heartRate = 72;  
            double weight = 75.5;  
            var activity = (steps, distance, caloriesBurned, sleepTime, heartRate, weight);  
            return activity;  
        }  
    }  

13. Assign a name to every member of tuple

class Program  
    {  
        static void Main(string[] args)  
        {  
            var activity = GetActivity();  
            WriteLine($"Activity Data: \n Steps: {activity.steps}\n Distance: {activity.distance} Km.\n Calories Burned: 

{activity.caloriesBurned}\n Sleep Time: {activity.sleepTime}\n Heart Rate: {activity.heartRate}\n Weight: 

{activity.weight}");  
        }  
    }  
  
    public class ActivityTracker  
    {  
        public static (int steps, double distance, double caloriesBurned, TimeSpan sleepTime, double heartRate, double 

weight) GetActivity() => (steps: 7000, distance: 5.2, caloriesBurned: 30.02, sleepTime: new TimeSpan(6, 20, 00), heartRate: 

72, weight: 75.5);  
    }  


14. Deconstructing Tuple


class Program  
    {  
        static void Main(string[] args)  
        {  
            (int steps, double distance, double caloriesBurned, TimeSpan sleepTime, double heartRate, double weight) = 

GetActivity();  
            WriteLine($"Activity Data: \n Steps: {steps}\n Distance: {distance} Km.\n Calories Burned: {caloriesBurned}\n 

Sleep Time: {sleepTime}\n Heart Rate: {heartRate}\n Weight: {weight}");  
        }  
  
        public static (int steps, double distance, double caloriesBurned, TimeSpan sleepTime, double heartRate, double 

weight) GetActivity() => (steps: 7000, distance: 5.2, caloriesBurned: 30.02, sleepTime: new TimeSpan(6, 20, 00), heartRate: 

72, weight: 75.5);  
    }  

15 Inferring element name of a Tuple


public static void GetActivity()  
 {  
     int steps = 7000;  
     double distance = 5.2;  
     double caloriesBurned = 30.02;  
     TimeSpan sleepTime = new TimeSpan(6, 20, 00);  
     double heartRate = 72;  
     double weight = 75.5;  
     var activity = (steps, distance, caloriesBurned, sleepTime, heartRate, weight);  
  
     WriteLine($"Activity Data: \n Steps: {activity.steps}\n Distance: {activity.distance} Km.");  
 }  



16. Default keyword before C# 7.0

Before C# 7.1
int a = default(int);  
        bool b = default(bool);  
        string c = default(string);  
        int? d = defailt(int?);  

After C# 7.1
int a = default;  
bool b = default;  
string c = default;  
int? d = default;  
Action action = default;  
Predicate predicate = default;  
List list = default;  
Dictionary dictionary = default;  
public int Add(int x, int y = default, int z = default)  
 {  
     return x + y + z;  
 } 



17.Pattern Matching with Generics 


public void PrintProduct(T product) where T:Product  
{  
    switch (product)  
    {  
        case ConvenienceProduct p:  
            WriteLine("Convenience Product");  
            // ---- print other information  
            break;  
        case ShoppingProduct p:  
            WriteLine("Shopping Product");  
            // ---- print other information  
            break;  
  
        case SpecialtyProduct p:  
            WriteLine("Specialty Product");  
            // ---- print other information  
            break;  
        default:  
            WriteLine("General Product");  
            break;  
    }  

public void Print(T type) where T : class  
{  
    switch (type)  
    {  
        case Customer customer:  
            WriteLine($"{customer.Id} {customer.Name} {customer.CustomerType} {customer.MonthlyPurchase}");  
            break;  
        case Product product:  
            WriteLine($"{product.ProductId} {product.ProductName} {product.ProductDescription}");  
            break;  
        default:  
            break;  
    }  


18. in Visual studio 2017 support for inline variable declaration has been added and it also provides intellisence for inline variable declaration with information id “IDE0018”.


19. In C# 7 we can use ‘ref’ for return a variable from a method i.e. a method can return variable with reference.


20. Use ref kyword as a local and return variable

class Program  
    {  
        public ref int GetFirstOddNumber(int[] numbers)  
        {  
            for (int i = 0; i < numbers.Length; i++)  
            {  
                if (numbers[i] % 2 == 1)  
                {  
                    return ref numbers[i]; //returning as reference  
                }  
            }  
            throw new Exception("odd number not found");  
        }  
        static void Main(string[] args)  
        {  
            Program p = new Program();  
            int[] x = { 2, 4, 62, 54, 33, 55, 66, 71, 92 };  
            ref int oddNum = ref p.GetFirstOddNumber(x); //storing as reference  
            WriteLine($"\t\t\t\t{oddNum}");  
            oddNum = 35;  
            for (int i = 0; i < x.Length; i++)  
            {  
                Write($"{x[i]}\t");                  
            }  
            ReadKey();  
        }  
    }  

Output 2 4 62 35 55 66 71 92

So if will update oddNum variable than it will updated in array as well

21. Use ref as a return type

class Program  
    {  
        static void Main(string[] args)  
        {  
            GetEmployee() = new Employee { Id = 2, Name = "Banketeshvar", Age = 28 };  
        }  
    }  
  
    class Employee  
    {  
        public int Id { get; set; }  
        public string Name { get; set; }  
        public int Age { get; set; }  
    }  
  
    class DummyEmployees  
    {  
        public static Employee employee = null;  
        public static ref Employee GetEmployee()  
        {  
            if (employee == null)  
            {  
                employee = new Employee { Id = 1, Name = "Manish Sharma", Age = 27 };  
            }  
            return ref employee;  
        }  
    }  
}   

22. Local functions or nested functions

using static System.Console;  
namespace UseLocalFunctions {  
    class Program {  
        static void Main(string[] args) {  
            void Add(int x, int y) {  
                WriteLine($ "Sum of {x} and {y} is : {x + y}");  
            }  
            void Multiply(int x, int y) {  
                WriteLine($ "Multiply of {x} and {y} is : {x * y}");  
                Add(30, 10);  
            }  
            Add(20, 50);  
            Multiply(20, 50);  
        }  
    }  
}  

It can also return value.
Factoril wihtout recursive function

private static long GetFactorialUsingLocal(int number) {  
    if (number < 0) throw new ArgumentException("negative number", nameof(number));  
    if (number == 0) return 1;  
    long result = number;  
    while (number > 1) {  
        Multiply(number - 1);  
        number--;  
    }  
    void Multiply(int x) => result *= x;  
    return result;  
}  

23. Binary Literals


You can use “0B” or “0b” for binary literal. So, in C# 7, you can represent integer in 3 ways - decimal literal, hexadecimal literal, and binary literal. Before C# 7 there were only two literal allowed decimal and hexa

 int a = 50; // decimal representation of 50  
            int b = 0X32; // hexadecimal representation of 50  
            int c = 0B110010; //binary representation of 50  
            //Represent 100 in decimal, hexadecimal & binary  
            int d = 50 * 2; // decimal represenation of 100   
            int e = 0x32 * 2; // hexadecimal represenation of 100  
            int f = 0b110010 * 2; //binary represenation of 100  

24. Digit Separators

We can use one or more than one Underscore( _ ) character for digit separators. Sometimes, it is required when we are going to represent a big number.

region Using Digit Separators  
            int binaryData = 0B0010 _0111_0001_0000; // binary value of 10000   
            int hexaDecimalData = 0X2B _67; //HexaDecimal Value of 11,111   
            int decimalData = 104 _567_789;  
            int myCustomData = 1 ___________2__________3___4____5_____6;  
            double realdata = 1 _000 .111 _1e1_00;  
            WriteLine($ " binaryData :{binaryData} \n hexaDecimalData: {hexaDecimalData} \n decimalData: {decimalData} \n myCustomData: {myCustomData} \n realdata: {realdata}");#  
            endregion  

25. Pattern matching


var myData = "Custom Data";  
            var myData2 = myData is string ? "String" : "Not a string";  
            var myData3 = myData is string a ? a : "Not a String";  
            WriteLine(myData2);  
            WriteLine(myData3);  
            //Example 2   
            var x = 10;  
            dynamic y = 0b1001;  
            var sum = y is int ? $ "{y * x}" : "Invalid data";  
            WriteLine(sum);  

26. Deconstruction

“deconstruction” is a concept which allows us to access a tuple member directly with its name without using any tuple variable name.


37. Throw Expressions


In C# 7, we can throw an exception directly through expression.
class Program {  
    static void Main(string[] args) {  
        var a = Divide(10, 0);  
    }  
    public static double Divide(int x, int y) {  
        return y != 0 ? x % y : throw new DivideByZeroException();  
    }  
} // This is just a sample script. Paste your real code (javascript or HTML) here.  
if ('this_is' == /an_example/) {  
    of_beautifier();  
} else {  
    var a = b ? (c % d) : e[f];  
}  

Thursday, November 30, 2017

Type of Entities

Fluent API

Fluent API is used to configure model class. While using Data Annotation we need to configure each property while using Fluent API we can configure multiple properties in a single line code.

https://www.tutorialspoint.com/entity_framework/entity_framework_fluent_api.htm

DbModelBuilder

DbModelBuilder is used to map CLR classes to a database schema. This code centric approach to building an Entity Data Model (EDM) model is known as 'Code First'.

DbContext.OnModelCreating Method (DbModelBuilder)

This method is called when the model for a derived context has been initialized, but before the model has been locked down and used to initialize the context. The default implementation of this method does nothing, but it can be overridden in a derived class such that the model can be further configured before it is locked down.

We use it to use EF's fluent API to refine our model.

Wednesday, November 29, 2017

How to use two object in a single view

There are multiple way to do is

1. Using ExpandoObject

ExpandoObject (the System.Dynamic namespace) is a class that was added to the .Net Framework 4.0 that allows us to dynamically add and remove properties onto an object at runtime.

 public ActionResult Index()  
    {  
        ViewBag.Message = "Welcome to my demo!";  
        dynamic mymodel = new ExpandoObject();  
        mymodel.Teachers = GetTeachers();  
        mymodel.Students = GetStudents();  
        return View(mymodel);  
    }  

In View

@using MultipleModelInOneView;  
@model dynamic  
@{  
    ViewBag.Title = "Home Page";  
}


2. Using View Model


ViewModel is nothing but a single class that may have multiple models. It contains multiple models as a property. It should not contain any method.

public class ViewModel  
{  
    public IEnumerable Teachers { get; set; }  
    public IEnumerable Students { get; set; }  




Controller code

public ActionResult IndexViewModel()  
{  
    ViewBag.Message = "Welcome to my demo!";  
    ViewModel mymodel = new ViewModel();  
    mymodel.Teachers = GetTeachers();  
    mymodel.Students = GetStudents();  
    return View(mymodel);  
}  

In View

@using MultipleModelInOneView;  
@model ViewModel   
@{  
    ViewBag.Title = "Home Page";  
}  

3. Using ViewData 


Controller Code

public ActionResult IndexViewData()  
{  
    ViewBag.Message = "Welcome to my demo!";  
    ViewData["Teachers"] = GetTeachers();  
    ViewData["Students"] = GetStudents();  
    return View();  
}  

View Code

@using MultipleModelInOneView;  
@{  
    ViewBag.Title = "Home Page";  


4. Using ViewBag


public ActionResult IndexViewBag()  
{  
    ViewBag.Message = "Welcome to my demo!";  
    ViewBag.Teachers = GetTeachers();  
    ViewBag.Students = GetStudents();  
    return View();  
}  

5. Using Tuple


A Tuple object is an immutable, fixed-size and ordered sequence object. It is a data structure that has a specific number and sequence of elements. The .NET framework supports tuples up to seven elements.

Using this tuple object we can pass multiple models from the controller to the view.

Controller Code

public ActionResult IndexTuple()  
{  
    ViewBag.Message = "Welcome to my demo!";  
    var tupleModel = new Tuple, List>(GetTeachers(), GetStudents());  
    return View(tupleModel);  
}  

View Code

@using MultipleModelInOneView;  
@model Tuple , List >  
@{  
    ViewBag.Title = "Home Page";  
}  

6. Using Render Action Method


A Partial View defines or renders a partial view within a view. We can render some part of a view by calling a controller action method using the Html.RenderAction method. The RenderAction method is very useful when we want to display data in the partial view. The disadvantages of this method is that there are only multiple calls of the controller.

Controller Code

///   
/// Render Teacher List  
///
  ///   
public PartialViewResult RenderTeacher()  
{  
    return PartialView(GetTeachers());  
}  
   
///   
/// Render Student List  
///
  ///   
public PartialViewResult RenderStudent()  
{  
    return PartialView(GetStudents());  
}  

View Code

@{  
   ViewBag.Title = "PartialView";  

@ViewBag.Message

  

  

    @{  
        Html.RenderAction("RenderTeacher");  
        Html.RenderAction("RenderStudent");  
    }  


RenderTeacher.cshtml
RenderStudent.cshtml

http://www.c-sharpcorner.com/UploadFile/ff2f08/multiple-models-in-single-view-in-mvc/

Data Annotation

The Data annotations attribute classes are used to decorate the classes or properties. These attributes help Entity Framework Code First to apply pre-defined rules on entity models

We can devide data annotations into the following categories

1. Database Schema related
2. Validation attributes.


1. Database Schema related

1. Table Attribute : 

Provides the alternate table name and specify the schema.

2. Column Attribute : 

Provide alternate column name, order amd database type for column.

3. Key Attribute :

 By default a property with name Id or Class Name + Id is primary key in a class, but if you want to make another property as a primary key, you can use key attribute.

4. Composite Keys :

 Add keyy attribute to more than one column will behave as composite key.


The Timestamp attribute specifies the byte array (byte []) property / column that has a concurrency mode of "Fixed" in the model and it should be a Timestamp column in the stored model (database). It is not nullable.

5. ConcurrencyCheck Attribute : 

If you want to prevent conflict while updating data by two user than we use concurrency check for each filed , whose value we  want to compare with old one before updating.

https://docs.microsoft.com/en-us/aspnet/mvc/overview/getting-started/getting-started-with-ef-using-mvc/handling-concurrency-with-the-entity-framework-in-an-asp-net-mvc-application


6. Timestamp Attribute : 

A timestamp value compare while updating the data to prevent conflict. Instead of marking each field concurrency check.

7. ForeignKey Attribute : 

This attribute specifies the foreign key for the Navigation property.

8. InverseProperty Attribute : 

Used when the same type takes part in multiple relationships. 


Using an InverseProperty attribute, we can specify which navigation property should be returned.



public class Contact
{
    public int ContactId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public User CreatedBy { get; set; }
    public User UpdatedBy { get; set; }
}

public class User
{
    public int UserId { get; set; }
    public string UserName { get; set; }
    public List ContactsCreated { get; set; }
    public List ContactsUpdated { get; set; }
}

This model appears to fit the inverse navigation property convention for Entity Framework Core, but EF Core will raise an error when asked to map these relationships:

Unable to determine the relationship represented by navigation property 'Contact.CreatedBy' of type 'User'. Either manually configure the relationship, or ignore this property from the model.
The InverseProperty attribute is applied to the navigation properties in the User class to specify their corresponding inverse navigation properties in the Contact class:

public class Contact
{
    public int ContactId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Email { get; set; }
    public User CreatedBy { get; set; }
    public User UpdatedBy { get; set; }
}

public class User
{
    public int UserId { get; set; }
    public string UserName { get; set; }
    [InverseProperty("CreatedBy")]
    public List ContactsCreated { get; set; }
    [InverseProperty("UpdatedBy")]
    public List ContactsUpdated { get; set; }
}

https://www.tektutorialshub.com/data-annotations-inverseproperty-attribute-in-entity-framework/

9. Index Attribute : 

The property of the model can be marked with an attribute and it should participate in a store index. The Index attribute allows us to create an index on one or more columns and we can specify the name of the index.

[Index("IX_Name_DepartmentMaster", IsClustered = false)]
public string Name { get; set; }

DatabaseGenerated Attribute : 

There are three type of DatabaseGenerated Attributes


Identity

The database generates the identity value when a row is inserted.

Computed

The database generates a value for the property when a row is inserted or updated.

None

The database does not generate a value for the property when the row is inserted or updated

10. ComplexType Attribute : 

If you are declaring a field whose data type is a class than you need to mark that field complex type.

11. NotMapped Attribute : 

If you want  your column should not be created in database than use NotMapped attribute.

2. Validation Attributes

StringLength: 

StringLength is user to define the length of string allowed in table

MinLength: 

MinLength define the minimum required length of string.

MaxLength: 

MaxLength define the minimum required length of string.

Required: 

The Required annotation will ensure that property has data in

Followers

Link