Professional Documents
Culture Documents
Net Framework
1. SOILD Principle
SOLID are five basic principles which help to create good software architecture. SOLID is an acronym
where:-
Single Responsibility Principle-it says that every class should have single responsibility. A class
should not have more than one reason to change.
Example
1. Asp.net MVC HomeController class should be responsible related to Home Page functionality of
software system.
Suppose, you have created a class XmlValidator for XML validation, which has the responsibility to
validate XML.
If there is a need to update XML, then a separate class should be created for the same. XmlValidator
class should not be used for updating XML.
Open Close Principle- A class should be open for an extension and closed for the modification.
1. In detail, We can extend any class via Interface, Inheritance or Composition whenever it's
required instead of opening a class and modifying it's code.
For example, suppose you have implemented a functionality to calculate area of Rectangle and after
some time you need to calculate the area of Square, then In this case you should not modify your
original class code to add extra code for square. Instead you should create one base class initially
and now you should extend this base class by your square class.
2. Example
Suppose, we have a class name Customer, which has a property InvoiceNumber, which has an
integer type
get;
set; }
In the future, if the requirement changes now, InvoiceNumber should be alphanumeric rather than
only an integer. Hence, in this case, you should create a subclass CustomerNew with a same
property but different datatype rather than modifying the previous one.
}
}
A parent object should be able to replace its child during runtime polymorphism.
In other words, if A is subtype of B then instances of B may be replaced by the instances of A without
altering the program correctness.
Interface Segregation Principle (ISP)
Client specific interfaces are better than general purpose interfaces.
In other words No client should be forced to implement other methods which it does not require. It
means it's better to create a separate interface and allow your classes to implement multiple
interfaces.
Suppose, we have one interface for clicking.
public interface IClick{
void onClick(Object obj);
}
As time passes, new requirement comes for adding one more function onLongClick. You need to add
this method in already created interface.
After some time, one new requirement comes for adding function for touch also and you need to
add the method in the same interface
At this point, you need to decide to change the name of interface too because touch is different than
click.
In this way, this interface becomes a problem—generic and polluted. At this stage, ISP comes into
play.
Suppose, some clients need only onClick function and some need only onTouch function, then one
will be useless for both. Hence ISP gives the solution, which splits the interface into two interfaces.
ITouch and IClick. The client which has required onClick can implement IClick, which needs onTouch.
It can implement ITouch and when it needs both, it can implement both.
class Student
{
// Handle to EventLog writer to write to the logs
LogWriter writer = null;
Public Student(LogWriter writer)
{
This.writer = writer;
}
// This function will be called when the student has problem
public void Notify(string message)
{
writer.Write(message);
}
}
The written classes given above are bad designs because in the case of a change in LogWrite, you
have to disturb Student class. We should use an interface inside Student instead of a class.
class Student
{
// Handle to EventLog writer to write to the logs
ILogWriter writer = null;
Public Student(ILogWriter writer)
{
This.writer = writer;
}
// This function will be called when the student has problem
public void Notify(string message)
{
writer.Write(message);
}
}
Design Principles are the core principles which we are supposed to follow while designing
any software system on any platform using any programming language. Examples of Design
Principles:
o Dependency on abstraction not concrete classes
o Encapsulate that varies
o Program to interfaces not implementations
Design Patterns are the solutions to common occurring general problems, they are not exact
program that can be fit to solve your problem rather you need to customize according to
your problem. Design Patterns are already invented solutions which are well tested and safe
to use. Examples of Design Patterns:
o Single Design Pattern: When you want only one instance of a class.
o Repository Design Pattern: To separate different layers of application (Business
Repository, Data Repository)
OCP – Can you name some techniques using which we can expose new functionality to client
without touching existing code?
There are various ways achieving it. Some are,
2. Garbage collector
Garbage collector is a feature of CLR which cleans unused managed (it does not clean
unmanaged objects) objects and reclaims memory. It’s a back ground thread which runs
continuously and at specific intervals it checks if there are any unused objects whose memory
can be claimed
When program start system allocated some memory for program to get executed.
There are 2 places in memory where the CLR stored items
1. Stack -Keep track what executing in your code(like your local variable)
Value types can be stored on both the stack and the heap.
For an object on the heap, there is always a reference on the stack that points to it.
The garbage collector starts cleaning up only when there is not enough room on the heap to
construct a new object
The stack is automatically cleared at the end of a method. The CLR takes care of this and you don’t
have to worry about it.
The heap is managed by the garbage collector.
Gen 0:- When application creates fresh objects they are marked as Gen 0.it stored short lived
object like temp variable.Grabage collector occurs must frequently in this generation
Gen 1:- When GC is not able to clear the objects from Gen 0 in first round it moves them to Gen
1 bucket.
Gen 2:- When GC visits Gen 1 objects and he is not able to clear them he moves them gen 2.
This generation contains long-lived objects. An example of a long-lived object is an object in a
server application that contains static data that is live for the duration of the process.
Generations are created to improve GC performance. Garbage collector will spend more time on
Gen 0 objects rather than Gen 1 and Gen 2 thus improving performance.
Garbage collector cleans managed code then how do we clean unmanaged code?
Garbage collector only claims managed code memory. For unmanaged code you need to put clean
up in destructor / finalize.
“System.GC.Collect ()” forces garbage collector to run. This is not a recommended practice but can
be used if situations arise.
and using statement
when we create a destructor the performance falls down?
Yes, when we define a destructor, garbage collector does not collect these objects in the first round.
It moves them to Gen 1 and then reclaims these objects in the next cycle.
As more objects are created in Gen 1 the performance of the application falls down because more
memory is consumed.
1. GC.GetGenteration -This method returns the generation number of the target object. It required
single parameter i.e the target object of which generation number is required.
using System;
using System;
3. GC.Collect method –
Garbage collection can be forced in the system using the GC.Collect() method. This method
requires a single parameter i.e. number of the oldest generation for which garbage collection
occurs
using System;
Garbage collector (GC) plays the main and important role in .NET for memory management so
programmer can focus on the application functionality. Garbage collector is responsible for releasing
the memory (objects) that is not being used by the application. But GC has limitation that, it can
reclaim or release only memory which is used by managed resources. There are a couple of
resources which GC is not able to release as it doesn't have information that, how to claim memory
from those resources like File handlers, window handlers, network sockets, database connections
etc. If your application these resources than it's programs responsibility to release unmanaged
resources. For example, if we open a file in our program and not closed it after processing than that
file will not be available for other operation or it is being used by other application than they cannot
open or modify that file.
So Dispose and Finalize will be used to release unmanage object that is not in used.
Dispose() Method
- This dispose method will be used to free unmanaged resources like files, database connection
etc.
- To clear unmanaged resources we need to write code manually to raise dispose() method.
This Dispose() method belongs to IDisposable interface.
- If we need to implement this method for any custom classes we need to inherit the class from
IDisposable interface.
- It will not show any effect on performance of website and we can use this method whenever we
want to free objects immediately.
//Implement IDisposable.
public void Dispose()
{
Dispose(true);
}
disposed = true;
}
}
}
Finalize() Method
- This method also free unmanaged resources like database connections, files etc…
- It is automatically raised by garbage collection mechanism whenever the object goes out of
scope.
- This method belongs to object class.
- We need to implement this method whenever we have unmanaged resources in our code and
make sure these resources will be freed when garbage collection process done.
- It will show effect on performance of website and it will not suitable to free objects
immediately.
- Finalize method can not be called explicitly in the code. Only Garbage collector can call the the
Finalize when object become inaccessible. Finalize method cannot be implemented directly it can
only be implement via declaring destructor
Example
So CLR will contains its own data type which is common to all programming language.
At the time of compilation, all language specific data types are convert into CLR data types. This
data type system of CLR which is common to all programming language of .net is call CTS.
C#
String is immutable, Immutable means if you create string object you cannot modified it. and It
always create new object of string type in memory.
Stringbuilder
StringBuilder is mutable, means if create string builder object then you can perform any
operation like insert, replace or append without creating new instance for every time.it will
update string at one place in memory doesn’t create new space in memory.
We create stringBuilder class using new keyword and passing in initials string.
Output:
Hello World!
Hello C#.
https://www.tutorialsteacher.com/csharp/csharp-stringbuilder
Constructor in c#
It is the special type of method of class that automatically executed whenever we create
instance of the class.
Types of constructor in C#
Note: The point that you need to keep in mind is that the System will only provide the default
constructor if as a programmer you are not defined any constructor explicitly.
Parameter constructor
Copy Constructor
The constructor which take parameter of the class type is called a copy constructor. This constructor
is used to copy one object’s data into another object. The main purpose of the copy constructor is to
initialize a new object (instance) with the values of an existing object (instance).
namespace ConstructorDemo
{
class Employee
{
int eid, age;
string address, name;
public Employee()
{
Console.WriteLine("ENTER EMPLOYEE DETAILS");
Console.WriteLine("Enter the employee id");
this.eid = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the employee age");
this.age = int.Parse(Console.ReadLine());
Console.WriteLine("Enter the employee name");
this.name = Console.ReadLine();
Console.WriteLine("Enter the employee address:");
this.address = Console.ReadLine();
}
public Employee(Employee tempobj)
{
this.eid = tempobj.eid;
this.age = tempobj.age;
this.name = tempobj.name;
this.address = tempobj.address;
}
public void Display()
{
Console.WriteLine();
Console.WriteLine("Employee id is: " + this.eid);
Console.WriteLine("Employee name is: " + this.name);
Console.WriteLine("Employee age is: " + this.age);
Console.WriteLine("Employee address is: " + this.address);
}
}
class Test
{
static void Main(string[] args)
{
Employee e1 = new Employee();
Employee e2 = new Employee(e1);
e1.Display();
e2.Display();
Console.ReadKey();
}
}
}
Static Constructor
We can create a constructor as static and when a constructor is created as static, it will be invoked
only once. There is no matter how many numbers of instances (objects) of the class are created but
it is going too invoked only once and that is during the creation of the first instance (object) of the
class.
The static constructor is used to initialize static fields of the class and we can also write some code
inside the static constructor that needs to be executed only once.
Private constructor
The constructor whose accessibility is private is known as a private constructor. When a class
contains a private constructor then we cannot create an object for the class outside of the class. So,
private constructors are used to creating an object for the class within the same class.
private constructors are used in class that contains only static members.
Another way of accessing a private constructor is by creating a public static method within
this class and have its return type as its object. Yes, we can access the private constructor or
instantiate a class with private constructor.
IMP- https://www.geeksforgeeks.org/private-constructors-in-c-sharp/
In C#, a structure is a value type data type. It helps you to make a single variable hold related data of
various data types. The struct keyword is used for creating a structure. It can contain a
parameterized constructor, static constructor, constants, fields, methods, properties, indexers,
operators, events, and nested types.struct can be used to hold small data values that do not require
inheritance, e.g. coordinate points, key-value pairs, and complex data structure.
In C#, a structure is a value type data type. It helps you to make a single variable hold related data of
various data types. The struct keyword is used for creating a structure.
Allocation of large reference type is cheaper Allocation and de-allocation is cheaper in value type as
than allocation of large value type. compare to reference type.
Class is generally used in large programs. Struct are used in small programs.
Structure does not contain parameter less constructor or
destructor, but can contain Parameterized constructor or
Classes can contain constructor or destructor. static constructor.
Classes used new keyword for creating Struct can create an instance, with or without new
instances. keyword.
The data member of a class can be protected. The data member of struct can’t be protected.
Function member of the class can be virtual or Function member of the struct cannot be virtual or
abstract. abstract.
Two variable of class can contain the reference Each variable in struct contains its own copy of
of the same object and any operation on one data(except in ref and out parameter variable) and any
variable can affect another variable. operation on one variable can not effect another variable.
Sealed Class
A class from which it is not possible to create/derive a new class is known as sealed class. In simple
words, we can also define the class that is declared using the sealed modifier is known as the
sealed class and a sealed class cannot be inherited by any other class.
Sealed Method-
The method that is defined in a parent class, if that method cannot be overridden under a child class,
we call it a sealed method. By default, every method is a sealed method because overriding is not
possible unless the method is not declared as virtual in the parent class.
When should a method be declared as sealed in C#?
If we don’t want to allow subclasses to override the superclass method and to ensure that all sub-
classes use the same superclass method logic then that method should be declared as sealed.
What is the difference between the private and sealed method in C#?
The private method is not inherited whereas the sealed method is inherited but cannot be
overridden in C#. So, a private method cannot be called from sub-classes whereas sealed method
can be called from sub-classes. The same private method can be defined in sub-class and it does not
lead to error.
How the sealed class method constructor access?
Creating object of the class.
using System;
public class Animal{
public virtual void eat() { Console.WriteLine("eating..."); }
public virtual void run() { Console.WriteLine("running..."); }
}
public class Dog: Animal
{
public override void eat() { Console.WriteLine("eating bread..."); }
public sealed override void run() {
Console.WriteLine("running very fast...");
}
}
public class BabyDog : Dog
{
public override void eat() { Console.WriteLine("eating biscuits..."); }
public override void run() { Console.WriteLine("running slowly..."); }
}
public class TestSealed
{
public static void Main()
{
BabyDog d = new BabyDog();
d.eat();
d.run();
}
}
Partial Classes
A class in which code can be written in two or more files is known as a partial class. To make
any class partial we need to use the keyword partial. even physically they are divided but
logically it is one single unit only.
namespace PartialDemo
{
public partial class PartialEmployee
{
public void DisplayFullName()
{
Console.WriteLine(@"Full Name is : {0} {1}", _firstName, _lastName);
}
}
}
All the parts spread across different class files, must use the partial keyword. Otherwise, a compiler
error is raised. Missing partial modifier. Another partial declaration of this type exists.
All the parts spread across different files, must have the same access modifiers. Otherwise, a
compiler error is raised. Partial declarations have conflicting accessibility modifiers.
Partial Method
Partial method is private by default and it is giving complier error if include access modifiers.
Rules
I have a class that is split into two partial classes. These two partial classes have the same
methods. What happens when we compile
At compile time all partial classes will be combined together to form a single final class. In the
same class, we cannot have multiple methods with the same name. But of course method
overloading possible.
If you do not specify an access modifier for a method, what is the default access modifier?
private
Classes and structs support inheritance. Is this statement true or false?
False, only classes support inheritance. structs do not support inheritance.
If a class derives from another class, will the derived class automatically contain all the public,
protected, and internal members of the base class?
Yes, the derived class will automatically contain all the public, protected, and internal members of
the base class except its constructors and destructors.
Yes, you can access static methods in partial classes. Partial classes are just a way of representing a
regular class in multiple source files, often with some of those source files controlled (or generated)
by tools.
4. Static class,Method,Constractor
Static class
Static means something which cannot be instantiated. You cannot create an object of static class and
cannot access static member using object
C# classes, variables, methods, properties, operators, events, and constructors can be defined as
static using the static modifier keyword.
Static Class
Apply the static modifier before the class name and after the access modifier to make a class static.
Below is the example of Static Class:
class Program
{
static void Main(string[] args)
{
var result = Calculator.Sum(10, 25); // calling static method
Calculator.Store(result);
Calculator class is static class. All the member of its also static. We cannot the create object of static
class therefore member of the static class can be accessed directly using class name like
ClassName.MemberName.
The non static class contain one or more static member,properties,methods fields.
Static fields in non static class can be define using the static keyword.
Static fields of non-static class is shared access all the instance. So, changes done by one instance
would reflect to other.
Below is the example of Static member in Non-Static class
using System;
We can define one or more static method in non static class. static method can be called without
creating an object. You cannot call static methods using an object of the non static class. You cannot
access non-static members of the class in the static methods.
class Program
{
static int counter = 0;
string name = "Demo Program";
Static Constructors
Static Constructors is only once whenever the static method is used or creating instance for the first
time. The following example shows that the static constructor gets called when the static method
called for the first time. Calling the static method second time onwards won't call a static
constructor.
using System;
//StopWatch sw1 = new StopWatch(); // First static constructor and then instance constructor
called
//StopWatch sw2 = new StopWatch();// only instance constructor called
//StopWatch.DisplayInfo();
}
}
public class StopWatch
{
// static constructor
static StopWatch()
{
Console.WriteLine("Static constructor called");
}
// instance constructor
public StopWatch()
{
Console.WriteLine("Instance constructor called");
}
// static method
public static void DisplayInfo()
{
Console.WriteLine("DisplayInfo called");
}
// instance method
public void Start() { }
// instance method
public void Stop() { }
}
Output:
DisplayInfo called
DisplayInfo calle
In the above example static constructor called only once when the Static method is called.
Static constructor will be executed only once in the lifetime. So, you cannot determine when
it will get called in an application if a class is being used at multiple places.
A static constructor can only access static members. It cannot contain or access instance
members.
A Static constructor is called automatically to initialize the class before the first instance is
created or any static members are referenced. A static constructor will run before an
instance constructor. A type's static constructor is called when a static method assigned to
an event or a delegate is invoked and not when it is assigned.
A static constructor cannot be called directly and is only meant to be called by the common
language runtime (CLR). It is invoked automatically.
It is not possible to create a static constructor with parameters. This is because the static
constructor is the first block of code which is going to execute under a class. And this static
constructor called implicitly, even if parameterized there is no chance of sending the
parameter values.
Usage
A typical use of static constructors is when the class is using a log file and the constructor is
used to write entries to this file.
Static constructors are also useful when creating wrapper classes for unmanaged code, when
the constructor can call the LoadLibrary method.
Static constructors are also a convenient place to enforce run-time checks on the type
parameter that cannot be checked at compile time via constraints (Type parameter
constraints).
What is the difference between static class and class with static methods? In which case I should
use either of them?
If your class has only static members you never need an instance of that class so you should make
the class itself static but if your class has instance members (non-static) then you have to make your
class an instance class to access its instance members via instances of your class.
Extension methods, as the name suggest are the additional methods. Extension methods allow
developers to extend functionality on an existing method without creating a new derived type,
recompiling, or otherwise modifying the original type.
Extension methods can be used as an approach of extending the functionality of a class in the future
if the source code of the class is not available or we don’t have any permission in making changes to
the class
using System;
using System.Text;namespace ClassLibExtMethod
{
public class Class1 {
public string Display()
{
return ("I m in Display");
}
Now create a new project using "File" -> "New" -> "Project...".
Add the reference of the previously created class library to this project.
Use the following code and use the ClassLibExtMEthod.dll in your namespace:using System;
using System.Text;
using ClassLibExtMethod;
namespace ExtensionMethod1
{
public static class XX
{
public static void NewMethod(this Class1 ob)
{
Console.WriteLine("Hello I m extended method");
}
}
class Program
{
static void Main(string[] args)
{
Class1 ob = new Class1();
ob.Display();
ob.Print();
ob.NewMethod();
Console.ReadKey();
}
}
}
How to extent the inbuild string method ?
namespace CustomExtensions
{
// Extension methods must be defined in a static class.
public static class StringExtension
{
// This is the extension method.
// The first parameter takes the "this" modifier
// and specifies the type for which the method is defined.
public static int WordCount(this String str)
{
return str.Split(new char[] {' ', '.','?'}, StringSplitOptions.RemoveEmptyEntries).Length;
}
}
}
https://dotnettutorials.net/lesson/extension-methods-csharp/
Important point
3. An extension method can have only one binding parameter and that should be
defined in the first place of the parameter list.
4. If required, an extension method can be defined with normal parameter also
starting from the second place of the parameter list.
Inheritance
IMP- If parent class has overloaded constructor (one is with parameter and without parameter) then
parameter less constructer will be executing first.
If parent class has multiple constructor, then we can use the base keywork in child class to define
which constructor will be executed.
Example-Father and Son Relationship. Here son inherits Father physical properties, but father can't
get son physical properties.
Method hiding in C#
Use the new keyword to hide a base class member. You get the compile warning if you miss
the new keyword.
Different ways to invoke a hidden base class member from derived class.
o Use base keyword
o Cast child type to parent type and invoke the hidden member
o ParentClass PC=new ChildCalss()
PC.HiddenMethod();
IMP-Parent class reference variable can point to the child class object, but child class reference
variable cannot point to the parent class object. Because child class is specialization of base
class=means child class has all the capability of base class and additional features child class has
Point to remember: -
A reserve keyword name “base ” can be used in derived class to call the base class method.
Inheritance does not backwards.
o Derived class can be accessing all the base class method. But base class cannot
access derived class methods.
Expect constructer and destructors, a class inherits everything from base class.
In inheritance in C#, custom classes cannot derive from special built in C# classes like
System.ValueType, System.Enu etc…
Circular dependency is not allowed in inheritance in C#. ClassA is derived from class ClassC
which was derived from ClassB and ClassB again derived from ClassA, Which clause circular
dependency in three classes, that is logically impossible.
1. Class- Internal
2. Class method- private
3. Interface -internal
4. Interface methods- public
The difference is Convert.ToString() method handles null whereas the ToString() doesn’t handle null
in C#.
Enum in C#
In C#, an enum (or enumeration type) is used to assign constant names to a group of numeric integer
values. It makes constant values more readable, for example, WeekDays.Monday is more readable
then number 0 when referring to the day in a week.
enum WeekDays
{
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Sunday
}
Interface in c#.
Interface is a fully un-implemented class used for declaring a set of operations of an object. So we
can define an interface is a pure abstract class which allow us to define only abstract method.
.net doesn’t support multiple inheritance with classes. So we use the interface as superclass to
develop abstraction for supporting multiple inheritance.
Both abstract class and interface are similarity both is incomplete and cannot created instance of
abstract class and interface.
Abstract classes can have implementation for some of its member(method),but the interrace
can’t have implementations for any of its member.
Abstract example:
Interface Example
Interface cannot have fields, but abstract class can have fields
Abstract class have constructor. Interface cannot have constructor.
A class can inherit from multiple interfaces at the same time, where as a class cannot inherit
from multiple classes at the same time.
Abstract class member can have access modifiers whereas interface members cannot have
access modifiers.
Abstract class mehtotds is by default private and interface methods is by default public
The Basis of C# Interface C# Abstract Class
comparison
Access Specifier In C#, Interface cannot have access In C#, an abstract class can have
specifier for functions. It is public by access specifier for functions.
default.
Implementation In C#, an interface can only have a An abstract class can provide
signature, not the implementation. complete implementation.
Fields Interface cannot have fields. An abstract class can have defined
fields and constants.
Methods Interface has only abstract methods. An abstract class can have non-
abstract methods.
So, in short, we would create an abstract class when want to move the common functionality of 2 or
more related classes into a base class and when, we don’t want that base class to be instantiated.
When we have the requirement of a class that contains some common properties or methods with
some common properties whose implementation is different for different classes, in that situation,
it's better to use Abstract Class then Interface.
We have Hyundai and Toyota car which have same common functionality but different
implementation and have same common property
1. Price
2. GetTotalSeat
3. Color
Common Property
1. Wheel
2. Check AC()
3. CallFacitlty()
using System;
using System.Collections;
using System.Collections.Generic;
namespace oops1
{
public abstract class Cars
{
//put all the common functions but diffrent implementation in abstract method.
public abstract double price();
public abstract int getTotalSeat();
public abstract string colors();
}
public string CheckAC()
{
return "AC is available";
}
public string CallFacility()
{
return "Call Facility supported";
}
}
}
Now, here is my Toyota class which is derived from Cars abstract class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace oops1
{
public class Toyota : Cars
{
public string DiscountPrice()
{
return "20% discount on buying Toyoya Cars";
}
public override double price()
{
return 1000000.00;
}
public override int getTotalSeat()
{
return 5;
}
public override string colors()
{
return "Red";
}
Console.WriteLine(Toy.CallFacility());
Console.WriteLine(Toy.Wheel());
Console.WriteLine(Toy.CheckAC());
Console.WriteLine("-------Own property defined in Toyota class------------");
Console.WriteLine(Toy.DiscountPrice());
Console.WriteLine("-------Common method but implementation is diffrent defined in IExtra Int
erface------------");
Console.WriteLine("Total ONRoad Price:"+ Toy.price());
Console.WriteLine(Toy.getTotalSeat());
Console.WriteLine(Toy.colors());
Console.ReadLine();
}
}
1.
2. }
Interface example
Like we have car Hundai and Toyato calss which inharitace from the CAR class
using System;
using System.Collections;
using System.Collections.Generic;
namespace oops1
{
public class Cars
{
}
public string CheckAC()
{
return "AC is available";
}
public string CallFacility()
{
return "Call Facility supported";
}
}
Now, here is my Toyota class which is derived from Cars.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace oops1
{
public class Toyota : Cars
{
Console.WriteLine(Toy.CallFacility());
Console.WriteLine(Toy.Wheel());
Console.WriteLine(Toy.CheckAC());
Console.ReadLine();
}
}
}
Here is my Hyundai class which is derived from Cars.
using oops1;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace oops1
{
public class Hyundai:Cars
{
Console.WriteLine(dust.CallFacility());
Console.WriteLine(dust.Wheel());
Console.WriteLine(dust.CheckAC());
Console.ReadLine();
}
}
1. }
A new feature for the Hyundai car is Introduced called GPS which is not supported in Toyota cars.
Here if we define the abstract class and define GPS method and inherit it on Hyundai class and
implement the GPS method this approach give error because multiple class inheritance not possible
because Hundai already inherit from the CAR class
1. interface INewFeatures
2. {
3. void GPS();
4.
5. }
6. using oops1;
7. using System;
8. using System.Collections.Generic;
9. using System.Linq;
10. using System.Text;
11. using System.Threading.Tasks;
12.
13. namespace oops1
14. {
15. public class Hyundai:Cars,INewFeatures
16. {
17. public void GPS()
18. {
19. Console.WriteLine("GPS supported.");
20.
21. }
22.
23.
24. static void Main(string[] args)
25. {
26. Hyundai hun = new Hyundai();
27.
28. Console.WriteLine(hun.CallFacility());
29. Console.WriteLine(hun.Wheel());
30. Console.WriteLine(hun.CheckAC());
31. hun.GPS();
32.
33.
34. Console.ReadLine();
35.
36.
37. }
38. }
39.
40.
41. }
For example refer https://www.c-sharpcorner.com/article/when-to-use-abstract-class-and-
interface-in-real-time-projects/
Interface use like we have some common method and some unique methods that we use
interface
If a class inherits an interface, what are the 2 options available for that class?
Option1: Provide Implementation for all the members, inherited from the interface.
Option2: If the class does not wish to provide Implementation for all the members inherited from
the interface, then the class has to be marked as abstract.
interface Car
void Drive();
}
class Demo : Car
void Car.Drive()
Console.WriteLine("Drive Car");
//DemoObject.Drive();
((Car)DemoObject).Drive();
An abstract method in an abstract class does not have any implementation, so what is the use of
calling it from the abstract class constructor?
If we want the abstract method to be invoked automatically whenever an instance of the class that is
derived from the abstract class is created, then we would call it in the constructor of the abstract
class.
Why can the abstract class not be instantiated?
Because it is not fully implemented in the class as its abstract methods cannot be executed. If the
compiler allows us to create the object for the abstract class, then we can invoke the abstract
method using that object which cannot be execute
Explain the differences between overriding methods and abstract methods in C#?
The concept of the abstract method is similar to the concept of method overriding because in
method overriding if a Parent class contains any virtual methods in it, then those methods can be re-
implemented under the child class by using the override modifier.
In a similar way, if a parent class contains any abstract methods in it, those abstract methods must
be implemented under the child class by using the same override modifier.
The main difference between method overriding and abstract method is in the case of method
overriding the child class re-implementing the method is optional but in the case of the abstract
method, the child class implementing the method is mandatory.
Abstraction
In Abstraction, by using access modifiers we can hide the required details of object and
expose only necessary methods and properties through the reference of object.
In real time, laptop is the perfect example for abstraction in c#. A laptop which consists of
many things such as processor, RAM, motherboard, LCD screen, camera, USB ports, battery,
speakers, etc. To use it, we just need to know how to operate the laptop by switching it on,
we don’t need to know how internally all the parts are working. Here, the laptop is an object
which is designed to expose only required features by hiding its implementation details.
Abstraction is a process of hiding work style of an object and showing only those information
which are required to understand the object. Abstraction means putting all the variables and
methods in a class which are necessary.
The process of defining a class by providing the necessary and essential details of an object
to the outside world and hiding the unnecessary things is called abstraction in C#. It means
we need to display what is necessary and compulsory and need to hide the unnecessary
things to the outside world. In C# we can hide the member of a class by using private access
modifiers.
Encapsulation
The process of binding the data and functions together into a single unit (i.e class) is called
encapsulations. Or we can say that the process of defining a class by hiding its internal data
member direct access from outside the class and providing its access only through public
expose methods or properties with proper validations and authentications Is called
encapsulation.
The Data encapsulation is also called data hiding because by using this principle we can hide
the internal data from outside the class.
https://dotnettutorials.net/lesson/encapsulation-csharp/
1. By declaring the variables as private(to restrict its direct access from outside the class)
2. By defining one pair of public setter and getter methods or properties to access private
variables.
Abstraction is used to hide the implementation details and display only essential features of the
object. Abstraction is a process of hiding work style of an object and showing only those information
which are required to understand the object. Abstraction means putting all the variables and
methods in a class which are necessary.
Encapsulation is a process of hiding all the internal details of an object from outside the word.It
restrict client from seeing its internal view where behavior of the abstraction is implemented
Abstraction Example
TV or Car remote is the also example of Abstraction.TV or Car remote is assembled from the
collection of circuits but they don't show to the user all circuits behind the remote, They only
provide remote to the user to use it. When the user presses the key on remote the channel gets
changed. They provide only necessary information to the user. This concept is called Data
Abstraction.
A Laptop consists of many things such as processor, motherboard, RAM, keyboard, LCD screen,
wireless antenna, web camera, usb ports, battery, speakers etc. To use it, you don't need to know
how internally LCD screens, keyboard, web camera, battery, wireless antenna, speaker's works. You
just need to know how to operate the laptop by switching it on.
Non-Technical Example:
A capsule is the be st
example of encapsulation. A capsule is inside the wrapper and wrapper provide the security to the
capsule and wrapper is work as a container like class.
https://www.codeproject.com/Articles/1037139/Difference-between-Encapsulation-and-
Abstraction-i
Polymorphism
Technically we can say that when a function shows different behaviors when we passed different
types and number values, then it is called polymorphism. So behaving in different ways depending
on the input received is known as polymorphism i.e. whenever the input changes, automatically the
output or the behavior also changes.
Types of Polymorphism in C#
There are two types of polymorphism in C#
1. Static polymorphism / compile-time polymorphism / Early binding
2. Dynamic polymorphism / Run-time polymorphism / Late binding
The following diagram shows different types of polymorphisms in C# with their examples.
What is Compile-Time Polymorphism?
In the case of compile-time polymorphism, the object of class recognizes which method to be
executed for a particular method call at the time of program compilation and binds the method call
with method definition.
This happens in case of overloading because in case of overloading each method will have a different
signature and based on the method call we can easily recognize the method which matches the
method signature.
Overloading
It is process of creating multiple methods in a callses with same name but with a different signature.
In C# it is also possible to overload method in a derived classes which means, it allows us to create a
method in the derived class with the same name as the method name defined in the base class
So in C# functions or methods can be overloaded based on the number, type (int, float, etc), order,
and kind (Value, Ref or Out) of parameters.
The point that you need to keep in mind is the signature of a method does not include the return
type and the params modifiers. So it is not possible to overload a method just based on the return
type and params modifier.
namespace PolymorphismDemo
{
class Program
{
public void add(int a, int b)
{
Console.WriteLine(a + b);
}
public void add(float x, float y)
{
Console.WriteLine(x + y);
}
public void add(string s1, string s2)
{
Console.WriteLine(s1 + s2);
}
static void Main(string[] args)
{
Program obj = new Program();
obj.add(10, 20);
obj.add(10.5f, 20.5f);
obj.add("pranaya", "kumar");
Console.WriteLine("Press any key to exist.");
Console.ReadKey();
}
}
}
You can not define more than one method with the same name, Order and the type of the
arguments. It would be compiler error.
What happens when method signature is same and the return type is different?
The compiler will give error as the return value alone is not sufficient for the compiler to figure
out which function it has to call. Only if both methods have different parameter types (so, they
have the different signature), then Method overloading is possible.
If you want to execute the same logic but with different types of argument i.e. different types of
values, then you need to overload the methods.
What are the advantages of using method overloading in C#? Or what are the disadvantages if we
define methods with a different name?
If we overload the methods, then the user of our application gets comfort feeling in using the
method with an impression that he/she calling one method bypassing different types of values. The
best example for us is the system-defined “WriteLine()” method. It is an overloaded method, not a
single method taking different types of values.
When is a method considered as an overloaded method in C#?
If two methods have the same method name those methods are considered overloaded methods.
Then the rule we should check is both methods must have different parameter
types/number/order.
What is inheritance-based overloading?
A method that is defined in a class can also be overloaded under its child class. It is called
inheritance-based overloading.
7. Method Overriding
The process of re-implementing of parent class method in the child class with the same
prototype(same signature ) is called as Function/Method Overriding.
Overriding method always execute using the current class object (Child class).
If super class logic did not fulfil the sub classes business requirement then sub class need to override
method with the required business logic.
namespace PolymorphismDemo
{
class Class1
{
public virtual void show()
{
Console.WriteLine("Super class show method");
}
}
class Class2 : Class1
{
public override void show()
{
base.show();
Console.WriteLine("Sub class override show method");
}
}
class Program
{
static void Main(string[] args)
{
Class2 obj = new Class2();
obj.show();
Console.ReadKey();
}
}
}
A parent class method can be redefined under its child class using two different approaches.
1. Method Overriding.
2. Method Hiding.
In Method overriding, the parent class gives permission for its child class to override the method by
declaring it as virtual. Now the child class can override the method using the Override keyword as it
got permission from the parent. The parent class methods can be redefined under child classes even
if they were not declared as Virtual by using the ‘new’ keyword.
In method overriding a base class reference variable pointing to a child class object will invoke the
overridden method in the child class. In method hiding a base class reference variable pointing to a
child class object will invoke the hidden method in the base class.
For hiding the base class method from the derived class simply declare the derived class method
with the new keyword. Whereas in C#, for overriding the base class method in a derived class, we
need to declare the base class method as virtual and the derived class method as the override.
If a method is simply hidden then the implementation to call is based on the compile-time type of
the argument “this”. Whereas if a method is overridden then the implementation to be called is
based on the run-time type of the argument “this”. New is reference-type specific, overriding is
object-type specific.
Can you access a hidden base class method in the derived class?
Yes, Hidden base class methods can be accessed from the derived class by casting the instance of the
derived class to an instance of the base class as shown in the example below.
public class BaseClass
((BaseClass)DC).Method();
In BMW project We have one functionality Cash posting which do the cash posting against the deal
to settle the deal or partial paid.
First we have Upload function which first upload the cash posting with confirm status and the sent
this request to the LCC roles to approve the request.
Some time requierent was change now client need to auto approval means at the time of uploading
function cash posting also approve.
String is immutable.
String Immutability(Why)
String is reference data type in c#. A String is a sequential collections of character that is used to
represent a text.
Creation of string
Now, we will try to understand what happens when CLR reads the below statement which is written
to create a string.
1. First, CLR checks the type of the data type. It is a reference type which will be stored into
heap memory.
2. Now, CLR need to reserve some amount of memory to store the string value. So it checks the
number of characters that exist in the string to; it is 4 (4x2 bytes = 8 bytes) characters.
3. A character array will be created into a heap with the size of 8 bytes and “Siva” will be stored
into memory. Let’s assume that the memory location of this is 101.
When you create a string, it is immutable. That means it is read-only. When something is immutable
or read-only, it means it cannot be changed at a later time
An immutable object is defined as an object that cannot be changed after it has been created.
In C#, the CLR (Common Language Runtime) is responsible for determining where to store strings. a
string is an array of characters. The CLR implements an array to store strings. Arrays are a fixed size
data structure, meaning that they cannot be dynamically increased or decreased in size. Once an
array is assigned a size, the size cannot be changed. To make an array larger, the data must be
copied and cloned into a new array, which is put into a new block of memory by the CLR. If you edit
a string, you are really not modifying that string; rather, the CLR is creating a new memory reference
for the modified string, and the original string will get removed from memory via garbage collection.
9. Reflection
Reflection object are used for obtaining type information at runtime. The class that give access to
the metadata of a running program are in the System.Refelcation namespace.
Reflection provide object (of type Type ) that describe assemblies, modules and type.
The System.Reflection namespace contains classes that allow you to obtain information about the
application and to dynamically add types, values, and objects to the application.
Applications of Reflection
Reflection has the following applications −
It allows view attribute information at runtime.
It allows examining various types in an assembly and instantiate these types.
It allows late binding to methods and properties
It allows creating new types at runtime and then performs some tasks using those types.
Example of reflection using the GetType() method- inherited by all types from object base class.
int i = 42;
Type type = i.GetType();
Console.WriteLine(type);
Output
Console.WriteLine(info);
Generic Class
Generic means the general form, not specific. In C#, generic means not specific to a particular data
type.
C# allows you to define generic classes, interfaces, abstract classes, fields, methods, static methods,
properties, events, delegates, and operators using the type parameter and without the specific data
type.
class DataStore<T>
{
public T Data { get; set; }
}
In project we have one ManageComman abstract generic class. In this class we have method like
LogErrorMessage,ValidateDateFormat.
In this Generic class is use in different classes to log the error message or validate
the request.
1. Inherit and pass the T type parameter as data object classes
2. Access the method using this modifier.
Var keyword
Variables declared with var are statically typed. Here type of variable is decided at the compile time.
Var should be initialized at the time of declaration. By looking at the assigned value, the compiler will
decide the variable type. As compiler knows the data type of the variable at compile time, errors will
be caught at that time only.
Example
1. obj = 10;
In the above line, the compiler will throw an error, as compiler already decided the type of obj as
String and assigned an integer value to string variable violating safety rule type.
Dynamic Keyword
Variables declared with dynamic were dynamically typed. Here, the type of variable declared is
decided at runtime. Variables which are declared as dynamic don't need to initialize the time of
declaration. The compiler won't know the variable type at the time of compiling, hence errors can't
be caught by the compiler while compiling. IntelliSense is not available since the type of variable will
be decided at runtime.
Example
1. obj = 10;
The comipler will not throw any error, though obj is assigned to the integer value. The compiler will
create the type of obj as String and then it recreates the type of obj as an integer when we assign
an integer value to obj.
We cannot use var as parameter for any function but the dynamic type can be used as parameter for
any function. We cant create method with var return type but we can create a method whose return
type is dynamic.
A static constructor is used to initialize any static data, or to perform a particular action that needs to
be performed once only. It is called automatically before the first instance is created or
any static members are referenced.
1. both singleton and static class can have only one instance of a copy of that variable in
memory throughout the whole application.
2. Both static class and singleton class implemented as thread safe.
The most important point that you need to keep in mind is that Static is a language feature whereas
Singleton is a design pattern. So both belong to two different areas.
1. We cannot create an instance of a static class in C#. But we can create a single instance of a
singleton class and then can reuse that singleton instance.
2. When the compiler compiles the static class then internally it treats the static class as an
abstract and sealed class. This is the reason why neither we create an instance nor extend a
static class in C#.
3. The Singleton class constructor is always marked as private. This is the reason why we
cannot create an instance from outside the singleton class. It provides either public static
property or a public static method whose job is to create the singleton instance only once
and then return that singleton instance each and every time when we called that public
static property/method from outside the singleton class.
4. A Singleton class can be initialized lazily or can be loaded automatically by CLR (Common
Language Runtime) when the program or namespace containing the Singleton class is
loaded. whereas a static class is generally initialized when it is first loaded for the first time
and it may lead to potential classl oader issues.
5. It is not possible to pass the static class as a method parameter whereas we can pass the
singleton instance as a method parameter in C#.
6. In C#, it is possible to implement interfaces, inherit from other classes and allow inheritance
with Singleton class. These are not possible with a static class. So the Singleton class is more
flexible as compared to static classes.
7. We can clone the Singleton class object whereas it is not possible to clone a static class. It is
possible to dispose of the objects of a singleton class whereas it is not possible to dispose of
a static class.
8. We cannot implement the Dependency Injection design pattern using Static class because
the static class is not interface driven.
9. Singleton means a single object across the application lifecycle, so the scope is at the
application level. As we know the static class does not have any Object pointer, so the scope
is at the App Domain level.
https://dotnettutorials.net/lesson/singleton-vs-static-class/
Static Class: Declared with Static keyword, methods in Static Class are also static along with
variables of the class.
This class cannot be instantiated, i.e we cannot have objects of this class. To access methods
of this class, you can directly use classname.method. Also this class cannot be inherited.
Sealed Class: Declared with Sealed keyword, which enables this class to seal all its variables,
methods and properties. No other class can inherit anything from this class or in other
words, this class cannot be inherited. But we can instantiate this class, i.e we can have any
number of objects of a sealed class.
Abstract Class: Declared with abstract keyword, this class is primarily created as a
Inheritable class. An abstract class enables other classes to inherit from this class, but forbids
to instantiate. One can inherit from an abstract class but we cannot create objects of an
abstract class. Abstract class can have abstract as well as non abstract methods. Abstract
methods are those which are not having method definition.
11. Same name/Signature method in 2 interface which are implemented in same class
We can create same name/signature method in 2 different interface and we can implemented
these method in same class to mentioned interface explicitly.
namespace Practice
{
interface IFirstInterface
{
void FirstName(String Name);
}
interface ISecondInterface
{
void FirstName(String Name);
}
class MyClass :IFirstInterface,ISecondInterface
{
public void FirstName(String Name)
{
Console.WriteLine("First Interface Name is "+Name+" ");
}
void ISecondInterface.FirstName(String strname)
{
Console.WriteLine("Second Interface Name is " + strname + "");
}
}
class Program
{
Console.ReadLine();
}
}
Object on demand is also called Lazy Loading. Lazy loading delay the initialization on object.
Lazy loading is a concept where we delay the loading of the object until the point where we need it.
Putting in simple words, on demand object loading rather than loading objects unnecessarily.
https://www.codeproject.com/Articles/652556/Can-you-explain-Lazy-Loading
throw : If we use "throw" statement, it preserve original error stack information. In exception
handling "throw" with empty parameter is also called re-throwing the last exception.
throw ex : If we use "throw ex" statement, stack trace of exception will be replaced with a stack
trace starting at the re-throw point. It is used to intentionally hide stack trace information.
Below example
If we use throw in Method 2, we have a full hierarchy, in other words FaultyMethod2, then Method2
and then Method1 along with the line numbers at which an exception occurred or was thrown. Also,
the target site is given as "FaultyMethod2".
Thus, after looking at the output of the "throw" and "throw ex" we can say "throw" maintains the
full hierarchy in the stack trace and gives complete information about the exception occurred in the
code. Whereas "throw ex" pretends that exceptions occurred on the line where "throw ex" was
written and removes all the hierarchy above the method containing the "throw ex" expression
Using statements is used to work with an object in C# that inherit IDisposable interface.
IDisposable interface has one public method called Dispose that is used to dispose of the object.
When we use the using statement ,we don’t need to explicitly dispose the object in the code,
These days, a web service call is often used in our applications. We can also use the using
statement when calling a web service. Once we call the web service if we forgot to dispose
of the object then the using statement helps in closing and disposing of the object
because web service objects are heavy.
In C# constructor is a special method which is invoke automatically at the time of object creation.It is
used to initialize the data member of new object generally.
//Base class
class Base
{
public Base() { Console.WriteLine("Constructor: Base"); }
~Base() { Console.WriteLine("Destructor: Base"); }
}
//Derived class
class DerivedOne : Base
{
public DerivedOne() { Console.WriteLine("Constructor: DerivedOne"); }
~DerivedOne() { Console.WriteLine("Destructor: DerivedOne"); }
}
//Derived class
class DerivedTwo : DerivedOne
{
public DerivedTwo() { Console.WriteLine("Constructor: DerivedTwo"); }
~DerivedTwo() { Console.WriteLine("Destructor: DerivedTwo"); }
}
class Program
{
static void Main(string[] args)
{
Base o = new DerivedTwo();
}
}
Output:
Constructor: Base
Constructor: DerivedOne
Constructor: DerivedTwo
Destructor: DerivedTwo
Destructor: DerivedOne
Destructor: Base
Both ref and out keyword is used to pass argument within method or function. Both indicate that an
argument\parameter is passed by reference.
Ref keyword is used to pass an argument as a reference. This means that value of the parameter is
change in the method, it gets reflected in the calling method. An argument that is passed using ref
keyword must be initialized in the calling method before is passed to the called method.
Out keyword is used to pass an argument as a reference, but argument can be passed without
assigned any value to it. An argument that is passed using an out keyword must be initialized in the
called method before it returns back to calling method. it is generally used when a method returns
multiple values
So, let’s simplify that. If we want to change an existing value of a variable inside a method, we are
going to use the ref keyword. But, if we want to assign a completely new value to the variable inside
a method, then we use the out keyword.
Example 1 for the Value Type
In this one, we are going to see the behavior of value type variables when we use those keywords:
class Program
numberRef = 25;
numberOut = 60;
ChangeRef(ref numberRef);
Console.WriteLine();
int numberOut;
ChangeOut(out numberOut);
This all is pretty clear. If we use the ref or the out keyword on the value type variable, its original
value will change. But the difference is that with the out keyword we can use unassigned variables
1. Do not be confused with the concept of passing by reference and the concept of reference type.
These two concepts are not the same.
2. A value type or a reference type can be passed to method parameter by using ref keyword. There is
no boxing of a value type when it is passed by reference.
3. Properties cannot be passed to ref or out parameters since internally they are functions and not
members/variables.
Both ref and out cannot be used in method overloading simultaneously. However, ref and out are
treated differently at run-time but they are treated same at compile time (CLR doesn't differentiates
between the two while it created IL for ref and out). Hence methods cannot be overloaded when
one method takes a ref parameter and other method takes an out parameter. The following two
methods are identical in terms of compilation.
class MyClass
{
public void Method(out int a) // compiler error “cannot define overloaded”
{
// method that differ only on ref and out"
}
public void Method(ref int a)
{
// method that differ only on ref and out"
}
}
However, method overloading can be done, if one method takes a ref or out argument and the other
method takes simple argument. The following example is perfectly valid to be overloaded.
class MyClass
{
public void Method(int a)
{
}
public void Method(out int a)
{
// method differ in signature.
}
}
Sr. Key ref keyword out keyword
No.
Purpose ref keyword is used when a called method out keyword is used when a called
1
has to update the passed parameter. method has to update multiple
parameter passed.
2 Direction ref keyword is used to pass data in bi- out keyword is used to get data in uni-
directional way. directional way.
18. Delegate
Delegate is a type safe function pointer. It means they hold the reference of a method or function
and the calls method for execution.
A function can have one or more parameters of different data types, but if we want to pass a
function as method parameter? How does C# handle the callback functions or event handler?
1. Declare a delegate
2. Instantiating a delegate
3. Invoke a delegate
del.Invoke("Hello World!");
// or
del("Hello World!");
class Program
{
static void Main(string[] args)
{
MyDelegate del = ClassA.MethodA;
InvokeDelegate(del);
del = ClassB.MethodB;
InvokeDelegate(del);
class ClassA
{
static void MethodA(string message)
{
Console.WriteLine("Called ClassA.MethodA() with parameter: " + message);
}
}
class ClassB
{
static void MethodB(string message)
{
Console.WriteLine("Called ClassB.MethodB() with parameter: " + message);
}
}
Multicast Delegate
The delegate can points to multiple methods. A delegate that points multiple methods is called a
multicast delegate. The "+" operator adds a function to the delegate object and the "-" operator
removes an existing function from a delegate object.
Example
printDel(1000);
printDel -=PrintHexadecimal;
printDel(2000);
}
Multicast delegate invoked the methods in the invocation list, in the same order in which they are
added.
If the delegate has a return type other than void and if the delegate is a multicast delegate. then
only the value of the last invoked method will be returned. Along the same lines, if the delegate has
an out parameter, the value of the output parameter will be the value assigned by the last method.
https://dotnettutorials.net/lesson/delegates-csharp/
Reduced Dependencies.
Reduced Dependency Carrying.
More Reusable Code.
More Testable Code.
More Readable Code
It also reduces the risk that you have to change a class just because one of
its dependencies changed.
In C#, a const keyword is used to declare constant fields and constant local. The value of the
constant field is the same throughout the program or in other words, once the consent field is
assigned the value of this field is not be changed. In C#, constant fields and locals are not variables, a
constant is a number, string, null reference, boolean values.
In C#, Readony keyword is used to declare a read only variable. This keyword shows that you can
assign the variable only when you declare a variable or in a constructor of the same class in which it
is declared.
In C#, readonly fields can be created using readonly In C#, constant fields are created using
keyword const keyword.
It cannot be declared inside the method. It can be declared inside the method.
In readonly fields, we can assign values in declaration In const fields, we can only assign values
and in the constructor part. in declaration part.
It can be used with static modifiers. It cannot be used with static modifiers.
Mocking
Mocking is very useful concept when the project is distributed among many team members. The
fundamental idea behind mocking is to inject dependency and perform a unit test.
Mocking helps to improve unit tests by removing the outside dependencies which results in better,
faster, independent unit tests.
https://www.c-sharpcorner.com/UploadFile/dacca2/fundamental-of-unit-testing-understand-mock-
object-in-unit/
https://www.codeproject.com/Articles/30381/Introduction-to-Mocking
Lambdas Expression
Lambda expressions are anonymous function that contain expressions or sequence of operators. All
lambda expression uses the lambda operator =>, that can be led as “goes to” or becomes.
The left side of lambda operator specifies the input parameter and right side hold the expression or
a code block that work with the entry framework. Usually lambda expressions are used as predicates
or instead of delegates (a type that references a method).
Expression Lambdas
The lambda operator => divides a lambda expression into two parts. The left side is the input
parameter and the right side is the lambda body.
Output
246
S
Array ArrayList
r
Array is strongly typed. This means that an array can store ArrayList can store any type of
1
only specific type of items\elements items\elements.
In arrays we can store only one datatype either int, string, In arraylist we can store all
2
char etc… the datatype values
Arraylist belongs to
Arrays belong to System.Array namespace System.Collection
4
using System; namespaces
using System.Collections;
Example -
Example - ArrayList Arrlst = new
int[] intArray=new int[]{2}; ArrayList();
5
intArray[0] = 1; Arrlst.Add("Sagar");
intArray[2] = 2; Arrlst.Add(1);
Arrlst.Add(null);
Stack
Stack Allow null and duplicate value.
Push method is used to insert object in stack.
Pop method is used to removed object form stack.
If object is not present in stack and we are trying to remove it will throw an
exception i.e. System.InvalidOperationException
Peek() method is used to return object from stack without removing it.
Queue
Peek(): The peek() method of the Queue class is used to return the oldest object i.e.
the object present at the start of the Queue without removing it.
Enqueue used to insert the object in queue.
Dequeue delete object form queue.
ArrayList also contain null and duplicate value . We can add null value in array list using
below syntax:
var arlist1 = new ArrayList();
arlist1.Add(1);
arlist1.Add("Bill");
arlist1.Add(" ");
arlist1.Add(true);
arlist1.Add(4.5);
arlist1.Add(null);
HashTable
Hashtable will allow us to store duplicate values, but keys must be unique to identify the hashtable
values. In hashtable, the key cannot be null, but the value can be null. You
can access hashtable elements either by using keys or with a foreach loop.
Collection classes are specialized classes for data storage and retrieval
1. ArraryList
2. HashTable
3. SortedList
4. Stack
5. Queue
A generic collection is strongly typed (you can store one type of objects into it) so that we can
eliminate runtime type mismatches, it improves the performance by avoiding boxing and
unboxing.
Stack Generics
Value type can not accept the null value. For example int i=null give a compiler time error.
So to stored the null value in C# introduce Nullable type which is use to assign null value to
value type variable.
Nullable<int> i = null;
[Serializable]
public struct Nullable<T> where T : struct
{
int? i = null;
double? D = null;
?? Operator
int? i = null;
int j = i ?? 0;
Console.WriteLine(j);
Output is 0.
In stacks we maintain only one In queues we maintain two pointers to access the list.
pointer to access the list, called the The front pointer always points to the first element
top, which always points to the last inserted in the list and is still present, and the rear
element present in the list. pointer always points to the last inserted element.
Stack is used in solving problems Queue is used in solving problems having sequential
works on recursion. processing.
If we have overloaded method which have 3 add methods with different parameter. Please refer
below example
class Test
{
float myNum = 5.7F;
So if we have call add method and pass parameter like 1,1 then integer method will called.
If we passed parameters like 1.1, 1.1 then which method call add with float parameter or add with
double parameter.
Answer is double because float data type store fractional numbers. We should ent the folat vaue
with an “F”.
For example
Console.WriteLine(myNum);
Single ton class example or which scenario we can use singleton pattern?
LINQ IN C#
LINQ or Language Integrated Query allows us to write queries for local as well as remote data
sources such as XML, SQL etc. LINQ will work on any collection class that gears the IEnumerable
interface. The GroupBy operator.
LINQ provides a uniform programming model (i.e. common query syntax) which allows us to work
with different data sources but using a standard or you can say unified coding style. As a result, we
don’t require to learn different syntaxes to query different data sources.
tor returns a group of elements from the given collection based on some key value.
If multiple employees may have equal salary and you wish to return an IEnumerable of all the
employees with the second-highest salary you could do:
c.Name,
TotalOrders = c.Orders.
});
The main difference between LINQ and SQL is that LINQ is a Microsoft .net framework component,
which adds native data querying capability to .NET language Which SQL is standard language to store
and manage data in RDBMS.
LINQ provide syntax in language such as C# ,VN.NET etc.. to perform operations on the data
available in various data source and formats.It also reduces the mismatch and complexity between
the usual programming languages and databases. In short, LINQ is a structured query syntax built-
in .NET languages. On the other hand, DBMS is a software that makes it easier to manage data.
Additionally, RDBMS is a DBMS that is designed according to the relational model, and SQL is the
language that helps to perform operations such as insert, update, delete, select in the RDBMS.
IQuerable vs IEnumerable
Both IQuerable and IEnumerable used to hold the collection data and also use to perform
manipulation operations such as filtering, ordering, grouping etc.
IEnumerable:
1. IEnumerable is an interface that is available in the System.Collections namespace.
2. While querying the data from the database, the IEnumerable executes the “select
statement” on the server-side (i.e. on the database), loads data into memory on the client-
side, and then only applied the filters on the retrieved data.
3. So you need to use the IEnumerable when you need to query the data from in-memory
collections like List, Array, and so on.
4. The IEnumerable is mostly used for LINQ to Object and LINQ to XML queries.
5. The IEnumerable collection is of type forward only. That means it can only move in forward,
it can’t move backward and between the items.
6. IEnumerable supports deferred execution.
7. It doesn’t support custom queries.
8. The IEnumerable doesn’t support lazy loading. Hence, it is not suitable for paging like
scenarios.
IQueryable:
1. The IQueryable is an interface that exists in the System.Linq Namespace.
2. While querying the data from a database, the IQueryable executes the “select query” with
the applied filter on the server-side i.e. on the database, and then retrieves data.
3. So you need to use the IQueryable when you want to query the data from out-memory such
as remote database, service, etc.
4. IQueryable is mostly used for LINQ to SQL and LINQ to Entities queries.
5. The collection of type IQueryable can move only forward, it can’t move backward and
between the items.
6. IQueryable supports deferred execution.
7. It also supports custom queries using CreateQuery and Executes methods.
8. IQueryable supports lazy loading and hence it is suitable for paging like scenarios.
Single() - There is exactly 1 result, an exception First() - There is at least one result, an
is thrown if no result is returned or more than exception is thrown if no result is returned.
one result.
FirstOrDefault() - Same as First(), but not
SingleOrDefault() – Same as Single(), but it can thrown any exception or return null when there
handle the null value. is no result.
Single() asserts that one and only one element First() simply gives you the first one.
exists in the sequence.
Use Single / SingleOrDefault() when you sure Developer may use First () / FirstOrDefault()
there is only one record present in database or anywhere, when they required single value
you can say if you querying on database with from collection or database.
help of primary key of table.
LINQ Providers.
1. LINQ to object- query an in memory object such as array, collection and generic collection.
2. LINQ to SQL- work with SQL server database.
3. LINQ to Dataset-
4. LINQ to Entities: The LINQ to Entities provider looks like LINQ to SQL. It means it is also an
object-relational mapping (ORM) framework that allows one to one, one to many, and many
to many mapping between the database tables and .NET Classes. The point that you need to
remember is, it is used to query any database such as SQL Server, Oracle, MySQL, DB2, etc.
Now, it is called ADO.NET Entity Framework.
5. LINQ to XML- work with the xml document.
1. Query Syntax
2. Method Syntax
3. Mixed Syntax (Query + Method)
1. Data Source
2. Query
3. Exceution
1. Initialization
2. Coding
3. Selection
MVC
ViewBag
The ViewBag in MVC is one of the mechanisms to pass data form controller to view.
ViewBag uses that dynamic property of the controller base class.
As we already discussed in our previous articles, we can use ViewData, ViewBag, and strongly typed
model to pass the data from a controller action method to a view. Now, we will see another
approach to send the data from the controller action method to a view using the TempData.
The limitation of both ViewData and ViewBag is they are limited to one HTTP request only. So,
if redirection occurs then their values become null means they will lose the data they hold. In many
real-time scenarios, we may need to pass the data from one HTTP Request to the next subsequent
HTTP Request. For example, we may need to pass the data from one controller to another controller
or one action method to another action method within the same controller. Then in such situations
like this, we need to use TempData.
As you can see the TempDataDictionary class implements the IDictionary interface. So we can say
that the TempData in ASP.NET MVC is a dictionary object. As it is a dictionary object, so it is going to
store the data in the form of key-value pairs where each key must be a string and the value that we
are passing to the dictionary is going to be stored in the form of an object type.
in strongly type view we pass model object as parameter to View() extension method.
In order to create a strongly typed view in ASP.NET MVC, we need to specify the model type within
the view by using the @model directive. As here, the Employee class is going to be the model so we
need to specify the model directive as shown below.
@model FirstMVCDemo.Models.Employee
ViewModel in MVC
In MVC single model object may can not contain all necessary data required . For example, a view
may require different model data. Then in such situations like this, we need to use the concept
ViewModel.
A ViewModel in ASP.NET MVC application is a model which contains more than one model data
required for a particular view. As this model is specific for a particular view, we call this as
ViewModel in MVC.
https://dotnettutorials.net/lesson/view-model-asp-net-mvc/
Filter in MVC
What are Filters in ASP.NET MVC Application?
As of now, we discussed when a client makes a request, then that request comes to the Routing
Engine and then the Routing Engine navigates that Request to the Controller. The controller then
selects the appropriate action method to execute. So, it is the Controller action method which is
going to handle the incoming request and send the response back to the client who initially made
the request as shown in the below image.
But what will you do, if you want to execute some code or logic either before or after the action
method executed as shown in the below image?
If that is what you want to achieve then you need to use Filters in ASP.NET MVC application.
1. Global Level
[Authorize(Roles = "Admin")]
public class AdminController : Controller
{
//Code
}
3. Action level
Authorization filter
By default all the action methods of all controllers can be accessed by both authenticated and
anonymous users. But If you want the action methods to be available only for the authenticated and
authorized users, then you need to use the Authorization Filter in MVC.
The Authorization Filter provides two built-in attributes such as Authorize and AllowAnonymous
which we can use as per our business requirement
2. Action Filter
Action filter executed before and after an action method executes. Action filter attribute can be
applied to an individual action method or controller .When an action filter is applied to a controller,
it will be applied to all the controller's action methods.
There are some action filder provided by MVC
[HandleError(view=”Error.cshtml”)]
public ActionResult Index()
{
3. Authorize -authorized user to access the resource.
The OutputCache is a built-in action filter attribute that can be applied to an action method for
which we want to cache the output
[OutputCache(Duration=100)]
public ActionResult Index()
{
return View();
}
You can create a custom action filter in two ways, first, by implementing the IActionFilter interface
and the FilterAttribute class. Second, by deriving the ActionFilterAttribute abstract class.
Traditional Approach
In this approach, we can use the request object of the HttpRequestBase class. This object contains
the input field name and values as name-value pairs in case of the form submit. So we can easily get
the values of the controls by their names using as indexer from the request object in the controller.
For example: Let's say you are having an input in the form with name 'txtName', then its values can
be retrieved in controller from request object like below:
Copy Code
string strName = Request["txtName"].ToString();
FromCollection
Through FormCollection: We can also get post requested data by the FormCollection object. This
object also has requested data as the name/value collection as the Request object.
For example:
Copy Code
[HttpPost]
public ActionResult Calculate(FormCollection form)
{
string strName = form["txtName"].ToString();
....................
}
Through Parameters:
We can also pass the input field names as parameters to the post action method by keeping the
names same as the input field names. These parameters will have the values for those fields and the
parameter types should be string. Also, there is no need to define the parameters in any specific
sequence.
For example:
Copy Code
[HttpPost]
public ActionResult Calculate(string txtName)
{
string strName = Convert.ToString(txtName);
.....................................
}
Strongly Type
Strongly typed model binding to view: Here, we need to create a strongly typed view which will bind
directly the model data to the various fields of the page.
For example:
Create a model with the required member variables.
Let's say we have a model named 'Person' with member variable named as 'Name'
Now pass the empty model to the view as parameter in the controller action.
For example:
Copy Code
public ActionResult GetName()
{
Person person = new Person();
return View(person);
}
i. Prepare the strongly typed view to display the model property values through html elements as
below:
For example:
Copy Code
<div><%= Html.Encode(person.Name) %></div>
ii. Create the action method that handles the POST request & processes the data.
For example:
[HttpPost]
public ActionResult GetPersonName(Person person)
{
return Content(person.Name.ToString());
}
2. Action Result
All the public method inside a controller which respond to the URL is know is Action method.
Action result is the result of action method or return type of action method. The action result is the
abstract class. It is the base class of all types of result.
There are different types of action results in ASP.NET MVC. Each result has a different type of result
format to view page. ActionResult is the base class of all the result type action method. The
following are the Result types that an action method can return in MVC.
1. ViewResult – Represents HTML and markup.
2. EmptyResult – Represents no result.
3. RedirectResult – Represents a redirection to a new URL.
4. JsonResult – Represents a JavaScript Object Notation result that can be used in an AJAX
application.
5. JavaScriptResult – Represents a JavaScript script.
6. ContentResult – Represents a text result.
7. FileContentResult – Represents a downloadable file (with the binary content).
8. FilePathResult – Represents a downloadable file (with a path).
9. FileStreamResult – Represents a downloadable file (with a file stream).
There are different type of result. These result are categorized into three sections:
These results are categorized into three sections:
1. Content-returning
2. Redirection
3. Status.
Content-returning:
These ActionResults are responsible for returning content to the browser or calling script. The
examples are as follows
1. ViewResult
2. PartialViewResult
3. FileResult
4. ContentResult
5. EmptyResult
6. JsonResult
7. JavaScriptResult
Redirection:
These ActionResults are responsible for redirecting to other URLs or actions. The examples are as
follows
1. RedirectResult
2. RedirectToRouteResult
3. RedirectToActionResultV
Status:
These ActionResults are responsible for returning status codes to the browser for it to use. The
examples are as follows
1. HttpStatusCodeResult
2. HttpUnauthorizedResult
3. HttpNotFoundResult
View Result
View result returns basic results to the view page. The View Result can return data to the View Page
through the model class. The view page is a simple HTML page. Here view page has a “.cshtml”
extension.
File Result
The File Result returns different type of file format view when we implement the file download
concept in MVC using file result. Let us understand File Result with an example. Please modify the
HomeController as shown below.
public class HomeController : Controller
{
public FileResult Index()
{
return File("Web.Config", "text");
}
}
If you want to return a file from your action method then you need to use this File Result as the
return type of your action method. Moreover, depending on the overload version of the File you
use, you can specify what action the browser is going to take with the downloaded file.
Content Result
The Content Result in ASP.NET MVC returns different content format to the view like HTML format,
JavaScript format, and any other format.
Let us modify the HomeController as shown below to use Content Result in MVC.
public class HomeController : Controller
{
public ContentResult Index()
{
return Content("<h3>Here's a custom content header</h3>", "text/html");
}
}
Calling this action will display the h3 tag in the browser.
Redirect Result
f you wanted to redirect to a URL, then you can use RedirectResult, like this:
public class HomeController : Controller
{
public RedirectResult Index()
{
return Redirect("https://dotnettutorials.net");
}
}
That works great for redirecting to outside sites from the current application, but not so much for
redirecting to other pages within the same application. For that, we can use RedirectToRouteResult.
Redirect result is returning the result to a specific URL. It is rendered to the page by URL. If we
give the wrong URL, it will show 404-page errors.
}
RedirectToAction Result in MVC
The RedirectToAction Result is returning the result to a specified controller and action method.
Controller name is optional in RedirectToAction method. If not mentioned, Controller name redirects
to a mentioned action method in the current Controller. Suppose action name is not available but
mentioned in the current controller, then it will show a 404 error page.
public class HomeController : Controller
6. Routing in MVC
The ASP.NET Routing module is responsible for mapping the incoming browser requests (i.e. the
incoming URL) to a particular MVC controller action method. This mapping is done by the routing
rules defined for your application.
In the asp.net application each and every URL should be match with sapcific .aspx file. example, a
URL http://dotnettutorials/employeeinfo.aspx must match with a physical file i.e.
employeeinfo.aspx that contains necessary code and HTML for rendering the response to the
browser. So in case of ASP.NET Web Forms, the URL pointing to the file must have its physical
existence.
Then ASP.NET Framework introduced the concept of Routing to eliminate the needs of mapping
each and every URL to a physical file. The Routing enables us to define the URL pattern that maps to
the request handler. This request handler can be a class or file.
In case of ASP.NET Webform application, the request handler is a file (i.e. aspx file) and in case of
ASP.NET MVC Framework, the request handler is the Controller Actions. For
example, http://dotnettutorials/employees can be mapped to
http://dotnettutorials/employeeinfo.aspx in ASP.NET Webforms application and the same URL can
be mapped to Employee Controller and Index action method in ASP.NET MVC application.
Route is handle the incoming requests to map the appropriate controller action method. In simple
word routing is pattern maching machnisum that handle the incoming request and figure out what
to do with that incoming request. All the configured routes of an ASP.NET MVC application stored in
the RouteTable and this Route table will be used by the Routing engine to determine the appropriate
handler class or file for an incoming request. We can register one or more URL patterns to the Route
table at Application_Start event.
Route is configured in the RouteConfig class which is in RourteConfig.cs file under the App_Start
folder. By Default MVC framework provide one default route.
namespace FirstMVCDemo
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default", //Route Name
url: "{controller}/{action}/{id}", //Route Pattern
defaults: new
{
controller = "Home", //Controller Name
action = "Index", //Action method Name
id = UrlParameter.Optional //Defaut value for above defined parameter
}
);
}
}
}
MVC framework evaluates each route in sequence. It starts with the first configured route and if
incoming URL doesn’t satisfy with the First URL pattern of the route then it will evaluate the second
route and so on.
Route Constraints
The Route Constraint in ASP.NET MVC Routing allows us to apply a regular expression to a URL
segment to restrict whether the route will match the request. In simple words, we say that Route
constraint is a way to put some validation around the defined route.
Suppose we have route and we want to restrict the incoming request URL with numirec id only.
routes.MapRoute(
name: "Default", //Route Name
url: "{controller}/{action}/{id}", //Route Pattern
defaults: new
{
controller = "Home", //Controller Name
action = "Index", //Action method Name
id = UrlParameter.Optional //Defaut value for above defined parameter
},
constraints :new { id = @"\d+" } //Restriction for id
);
URL rewriting is focused on mapping one URL (new URL) to another URL (old URL) while routing is
focused on mapping a URL to a resource.
URL rewriting rewrites your old URL to a new one while routing never rewrites your old URL to a new
one but it maps to the original route.
Attribute Routing
Using the [Route] attribute to define routes is called Attribute Routing. It provides you more control
over the URIs by defining routes directly on actions and controllers in your ASP.NET MVC application.
The first thing that you need to do is Enabling Attribute Routing in RouteConfig.cs class.
And then add the Route attribute in the controller action mehtod
[HttpGet] [
Route("students/{studentID}/courses")]
public ActionResult GetStudentCourses(int studentID) {
}
RoutePrefix attribute is used to specify the common route prefix at the controller level to eliminate
the need to repeat that common route prefix on each and every controller action method
Example
namespace AttributeRoutingDemoInMVC.Controllers
{
[RoutePrefix("students")]
public class StudentsController : Controller
{
static List<Student> students = new List<Student>()
{
new Student() { Id = 1, Name = "Pranaya" },
new Student() { Id = 2, Name = "Priyanka" },
new Student() { Id = 3, Name = "Anurag" },
new Student() { Id = 4, Name = "Sambit" }
};
[HttpGet]
[Route]
//This will be translated to /students
public ActionResult GetAllStudents()
{
return View(students);
}
[HttpGet]
[Route("{studentID}")]
//This will be translated to /students/2
public ActionResult GetStudentByID(int studentID)
{
Student studentDetails = students.FirstOrDefault(s => s.Id == studentID);
return View(studentDetails);
}
}
Controller in MVC
A controller in ASP.NET MVC is a class having a set of public methods. These public methods of the
controller are called action methods or simple actions. It is these action methods in MVC application
which is going to handle the incoming HTTP Requests.
View in MVC
In the MVC pattern, the view component contains the logic to represent the model data as a user
interface with which the end user can interact. Typically, it creates the user interface with the data
from the model which provided to it by the controller in an MVC application. So you can consider the
Views in ASP.NET MVC as HTML templates embedded with Razor syntax which generate HTML
content that sends to the client. the views are having “.cshtml” extension
Model in MVC
The Models in ASP.NET MVC application are the component which contains a set of classes that are
used to represent the business data as well as it also contains logic to manage the business data. So
in the simple word we can say that the model in ASP.NET MVC is used to manage the domain data
i.e. the state of the application in memory.
7. Authentication in MVC
Authentication is nothing but a process that ensures and confirms a user’s identity. In other words,
we can say that it is a process to validate someone against some data source.
What is Authorization?
Authorization is a security mechanism which is used to determine whether the user has access to a
particular resource or not. The most point that you need to remember is, authentication happens
first, then only authorization
Type of authentication
1. Forms Authentication: In this type of authentication the user needs to provide his
credentials through a form.
2. Windows Authentication: Windows Authentication is used in conjunction with IIS
authentication. The Authentication is performed by IIS in one of three ways such as basic,
digest, or Integrated Windows Authentication. When IIS authentication is completed, then
ASP.NET uses the authenticated identity to authorize access
3. Passport Authentication: It is a centralized authentication service (paid service) provided by
Microsoft which offers a single logon and core profile services for member sites.
4. None: No Authentication provided. This is default Authentication mode
Form Authenticatin
In web.config file of your application, you can specify the Authentication mode as shown below.
Form authentication
SignOut
The SignOut method removes the forms-authentication ticket information from the cookie or the
URL if CookiesSupported is false . You can use the SignOut method in conjunction with the
RedirectToLoginPage method to log one user out and allow a different user to log in.
1. The user enters his credentials (i.e. the username and password) into the client (here client
means the browser or mobile devices, etc).
2. The client then sends these credentials (i.e. username and password) to the Authorization
Server.
3. Then the Authorization Server authenticates the client credentials (i.e. username and
password) and generates and returns an access token. This Access Token contains enough
information to identify a user and also contains the token expiry time.
4. The client application then includes the Access Token in the Authorization header of the
HTTP request to access the restricted resources from the Resource Server until the token is
expired.
1. Create required database table like user details user name and password
2. Create the Empty application.
3. Add the required references from NuGet packages into your application.
1. Microsoft.Owin.Host.SystemWeb
2. Microsoft.Owin.Security.OAuth
3. Microsoft.Owin.Cors
4. Newtonsoft.json
For adding the above references from NuGet, Go to Solution Explorer > Right Click on the
References > Click on Manage NuGet Packages > Search for
the Microsoft.Owin.Host.SystemWeb,
Microsoft.Owin.Security.OAuth, Microsoft.Owin.Cors and Newtonsoft.json and install.
4. Add the ADO.NET entity model with userMaster table and the Validate method that
take the username and password as input parameter and validate its.
5. Add a class for validating the user credentials asking for tokens- here add to class in
our application and need to write logic to validate the user credential and generate
the token. We need to inherit class from OAuthAuthorizationServerProvider and
then need to override
ValidateClientAuthentication and GrantResourceOwnerCredentials method.
Now we need to add the OWINStartup class where we will configure the OAuth
Authorization Server. This is going to be our authorization server.
To do so, go to the Solution Explorer > Right Click on Project Name form the Solution
Explorer > Add > New Item > Select OWIN Startup class > Enter the class name
as Startup.cs > and then click on the Add button as shown in the below image.
Here we created a new instance of the OAuthAuthorizationServerOptions class and then set
its options as follows:
9. Model Binding
The ASP.NET MVC Model Binding allows us to map HTTP request data with a model. It is the
process of creating .NET objects using the data sent by the browser in an HTTP request.
Model binding is a well-designed bridge between the HTTP request and the C# action
methods. It makes it easy to work with data on forms (views) because POST and GET are
automatically transferred into a data model we specify. ASP.NET MVC uses default binders
to complete this behind the scene.
UpdateModel
TryUpdateModel
UpdateModel -function capture the posted form data.In order to do this, please modify the
Create (HttpPost) action method as shown below.
[HttpPost]
public ActionResult Create()
{
if (ModelState.IsValid)
{
EmployeeBusinessLayer employeeBusinessLayer = new EmployeeBusinessLayer();
Employee employee = new Employee();
UpdateModel<Employee>(employee);
employeeBusinessLayer.AddEmmployee(employee);
return RedirectToAction("Index");
}
return View();
TryUpdateModel
This is also use for capture the posted from data.
Now let’s understand how to use the TryUpdateModel function in ASP.NET MVC. Modify the create
(HttpPost) action method as shown below. Here we use TryUpdateModel() instead of
UpdateModel().
[HttpPost]
[ActionName("Create")]
public ActionResult Create_Post()
{
EmployeeBusinessLayer employeeBusinessLayer = new EmployeeBusinessLayer();
Employee employee = new Employee();
TryUpdateModel(employee);
if (ModelState.IsValid)
{
employeeBusinessLayer.AddEmmployee(employee);
return RedirectToAction("Index");
}
else
{
return View();
}
}
https://stackoverflow.com/questions/102558/biggest-advantage-to-using-asp-net-mvc-vs-web-
forms
You can apply filters at a global level in the Application_Start event of the global.asax.cs file by using
default FilterConfig.RegisterGlobalFilters() method. The global filters will be applied to all the
controller and action methods of an application.
When the client makes a request, and if it is the first request to the application then
the Application_Start event is going to be fired. the Application_Start event calls
the RegisterRoutes Method of the RouteConfig class which will fill the RouteTable with the routes
defined for your application. Then the Request comes to the Routine module.
1. Routing module
The aim of the Routing Module in ASP.NET MVC Application is very simple. It just maps the
incoming request i.e. URL to a Route and then selects the HttpHandler which is associated with the
Route to handle that Request.
As shown in the above image, we can say that the Routing Module is the first module in the
ASP.NET MVC Request Processing Pipeline which receives the incoming request made by the client.
Once it receives the incoming request, then it tries to find a matching URL pattern defined in the
Route Table. If it does not find any matching URL pattern in the Route table then it simply returns
a 404 HTTP Status code to the client.
On the other hand, if it found a matching URL Pattern in the Route table, then it selects the HTTP
Handler (a handler that implements the IHttpHandler interface) which is associated with
that Route and then forward that request to the corresponding handler.
2. MvcHandler
The purpose of the MVC Handler in the ASP.NET MVC application is to create the Controller
Instance which is going to process the current request. MVCHandler take the RequestContext object
as its parameter From URL it get controller name and pass request to the controller.
3. Controller
The purpose of the Controller in ASP.NET MVC Request Processing Pipeline is to call
the ActionInvoker method of the Controller class to deal with the current request.
In the ASP.NET MVC application, the Controller class implements the IController interface as well as
it also inherits from the ControllerBase class. The ControllerBase class exposes the Execute method
which is called by the MvcHandler by providing the RequestContext object as a parameter.
Once the Execute method is called, then it calls the ExecuteCore method of the ControllerBase class.
It gets action method name from RequestContext and pass to Action invoker
4. Action Invoker
The Role of Action Invoker in ASP.NET MVC Request Life Cycle is to execute the Action Method
passed to it by the controller.
The ActionInvoker class implements the IActionInvoker interface. The IActionInvoker interface has
a single method i.e. InvokeAction
The ControllerActionInvoker calls the FindAction method to find the information about the Action
method which is going to be executed.
The ActionInvoker then calls the Authentication filters to verify if the user is authenticated or not. If
the user is an authenticated user then it calls the authorization filters to check whether the user is
authorized to this action method or not.
If the user is an authorized user then the ActionInvoker calls the Model Binder object to map the
request parameters to the Action Method parameters. This process is called Model Binding in the
ASP.NET MVC application.
Then it calls the Action Filters to add the pre and post-processing logic. Finally,
the ControllerActionInvoker calls the InvokeAction method to execute the action method and
returns the ActionResult.
4. Result Exection
The Role of Result Execution in ASP.NET MVC application is to render the view as a web page to the
client who initially made the request.
Once the Result is generated, then the Result Filters are going to be applied before sending the Final
Response to the browser.
The ASP.NET MVC is an open-source web application development framework from Microsoft that
is based on the MVC (Model-View-Controller) architectural design pattern which provides a clean
separation of code. This is the most customizable and extensible platform or framework provided by
Microsoft.
{
// Method logic
}
Can you change the action method name?
We can also change the action method name by using the ActionName attribute. Now action
method will be called by the name defined by the ActionName attribute.
[ActionName("DoAction")]
How to restrict an action method to be invoked only by HTTP GET, POST, PUT or DELETE?
By default, each and every action method can be invoked by an HTTP request (i.e. GET, PUT, POST,
and DELETE). But you can restrict an action to be invoked only by a specific HTTP request by applying
HttpGet or HttpPost or HttpPut or HttpDelete attribute.
<html>
<head>
<title>@ViewBag.Title</title>
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")
</head>
<body>
@RenderBody() @Scripts.Render("~/bundles/jquery")
</html>
View Engine is responsible for rendering the view into Html form to the browser. ASP.NET MVC
supports web form(.aspx) and Razor View (.cshtml).
View Engine is used to convert HTML + programming language to pure HTML. View can contain C#
and HTML code. Once the view renders on the browser, the C# code written on the view is
converted into pure html format. To Convert C# code pure HTML is the job of ViewEngine.
1. AddEmployee
2. UpdateEmployee
3. GetAllEmployee
JavaScript/jQuery
What is Promise?
In JavaScript promise is the same as a promise we make in real life. When we make a
promise in real life, it is assured that we are going to do keep in the future. As promises can
only be made for the future.
https://dotnettutorials.net/lesson/javascript-promise/
2. What is Colures
A Closures is nothing but a function inside the function.
In other words, a closure gives you access to an outer function’s scope from an inner
function.
Closures are nothing but Stateful Function
what is the use of such isolated stateful functions (i.e. closures). The simplest answer to this
question is, closures help us to implement object-oriented programming concepts in
JavaScript.
3. Namespaces in Javascript
Namespace like the container which contain classes. In javascript you can achieve the same
functionality as namespace by creating nested object.
In any modern day application, Namespace is a must to have because at the end, we need
third party libraries and components.
Unfortunately JavaScript doesn’t provide namespace by default. So anything
(function, method, object, variable) we create in JavaScript is global and we continue
polluting that global namespace by adding more to that.
But the good news is that we can create namespace in JavaScript and that too very easily.
As we know, in JavaScript everything is an object and creating an object is very simple. We
can achieve namespace very easily with some minor tweaks.
this.cost = cost;
this.getCost = function(){
return this.cost;
};
};
function doTaxCalculations() {
In the above code, the two functions and the class, all three are settled down in the global space.
It's a simple code base but it contains 3 global items (calculateTax, product, doTaxCalculations).
These three will really put us in trouble if we are using 3rd party libraries and they also contain the
same name.
Like if it is used before other library, it will be overridden by Library and vice versa.
In JavaScript, it is nothing but a single global object which will contain all our functions, methods,
variables and all that. Here ‘MYAPPLICATION‘ is acted as a JavaScript namespace and the only global
object which contains all other items.
var MYAPPLICATION = {
calculateTax: function (item) {
return item * 1.40;
},
product: function (cost) {
this.cost = cost;
this.getCost = function(){
return this.cost;
};
},
doTaxCalculations: function () {
var p = new MYAPPLICATION.product(100);
alert(this.calculateTax(p.getCost()));
}
}
To access any of the methods or variables, you need to fetch it through the MYAPPLICATION.
Not only single namespace like the above one, but we can create nested JavaScript Namespace as
well.
Let's look at a sample of nested JavaScript Namespace.
4. Design Pattern
Design patterns are generally sets of standardized practices used in the software development
industry. Design Patterns represent the solutions given by the community to general problems faced
in every-day tasks regarding software development.
Creational patterns
o Factory method/Template
o Abstract Factory
o Builder
o Prototype
o Singleton
Structural patterns
o Adapter
o Bridge
o Filter
o Composite
o Decorator
o Facade
o Flyweight
o Proxy
Behavioral patterns
o Interpreter
o Template method/ pattern
o Chain of responsibility
o Command pattern
o Iterator pattern
o Strategy pattern
o Visitor pattern
J2EE patterns
o MVC Pattern
o Data Access Object pattern
o Front controller pattern
o Intercepting filter pattern
o Transfer object pattern
5. JQuery Selector
jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes, types,
attributes, values of attributes and much more. It's based on the existing CSS Selectors, and in
addition, it has some own custom selectors.
$("p")
The # Selector
The jQuery #id selector uses the id attribute of an HTML tag to find the specific element.
An id should be unique within a page, so you should use the #id selector when you want to find a
single, unique element.
$("#test")
Example
When a user clicks on a button, the element with id="test" will be hidden:
Example
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});
$(".test")
https://www.w3schools.com/jquery/jquery_selectors.asp
6. JavaScript Scoping
JavaScript has function scope: Each function creates a new scope.Scope determines the accessibility
(visibility) of these variables.
Variables defined inside a function are not accessible (visible) from outside the function.
Undefined
It means a variable declared, but no value has been assigned a value.
For example,
var demo;
alert(demo); //shows undefined
alert(typeof demo); //shows undefined
null
Whereas, null in JavaScript is an assignment value. You can assign it to a variable.
For example,
SQL Server
The MERGE statement selects the rows from one or more tables (called Source table),
and based on conditions specified, INSERT or UPDATE data to another table (called
Target table).
Atomicity - The atomicity acid property in SQL. It means either all the operations (insert,
update, delete) inside a transaction take place or none. Or you can say, all the statements
(insert, update, delete) inside a transaction are either completed or rolled back.
Consistency: This SQL ACID property ensures database consistency. It means, whatever
happens in the middle of the transaction, this acid property will never leave your database in
a half-completed state.
o If the transaction completed successfully, then it will apply all the changes to the
database.
oIf there is an error in a transaction, then all the changes that already made will be
rolled back automatically. It means the database will restore to its state that it had
before the transaction started.
o If there is a system failure in the middle of the transaction, then also, all the changes
made already will automatically rollback.
Isolation: Every transaction is individual, and One transaction can’t access the result of other
transactions until the transaction completed. Or, you can’t perform the same operation using
multiple transactions at the same time.
Durability: Once the transaction completed, then the changes it has made to the database
will be permanent. Even if there is a system failure, or any abnormal changes also, this SQL
acid property will safeguard the committed data.
Joins in SQL server are used to retrieve data from 2 more related table. In general, tables are
related to each other using foreign key constraints. An SQL JOIN is used to combine rows from
two or more tables based on a common field between them.
Inner Join
Inner join returns only the matching rows between both the tables. Non-matching rows
are eliminated. The inner join is used to retrieve matching data from both the tables.
Outer Join
The OUTER JOIN is an extension of INNER JOIN or EQUI JOIN. In an inner join, the user
will get matching data only from the tables i.e. the user will lose un-matching data from
the tables. So to overcome the above problem we use the outer join mechanism
If two or more tables are combined with each other without any condition we call it a
Cartesian or cross join. When we join the records without any condition is known as
CROSS JOIN. In cross join, each record of a table is joins with each record of another
table. Cross Join should not have an ON clause
Non Equi join
When we retrieve the information from the tables with any condition except equality
condition then it is known as NON-EQUI JOIN. We may use <, >, <=,>=, <!,>!, AND, OR,
NOT, etc except “=” operator.
Self Join
Joining a table by itself is called a self-join. When we have some relation between the
columns within the same table then we use the self-join mechanism. When we
implement a self-join mechanism we should create the alias for the table. We can create
any number of aliases for a single table. Self-join is not a different kind of join.
https://dotnettutorials.net/lesson/sql-server-joins-interview-questions-answers/
3. Stored Procedure
When we create a stored procedure, the syntaxes are checked while creating the procedure or we
can say at the design pattern. When we execute the procedure for the first time, the best plan is
selected and is cached in memory. And after that whenever we execute the stored procedure, the
query execution plan is taken from the cache rather than creating again and again and executed.
Index in SQL
1. It is a database object which is used to speed up the querying process by providing query
access to rows in the data table.
2. When we create an index on any column SQL Server internally maintains a separate table
called index table so that when any user trying to retrieve the data from the existing table
depends on index table SQL Server directly go to the table and retrieve required data very
quickly.
3. In a table, we can use a maximum of 250 indexes. The index type refers to the way the index
is stored internally by SQL Server.
4. Index are created on tables and views.
Clustered Index
Non-Clustered Index
Clustered Index
1. In the case of a clustered index, the arrangement of the data in the index table will be the
same as the arrangement of the data of the actual table.
2. Example: The index we find the start of a book.
3. When a table has a clustered index then the table is called a clustered table.
4. If a table has no clustered index its data rows are stored in an unordered structure.’
5. A table can have only one clustered index in it which will be created when the primary key
constraint used in a table.
6. A clustered index determines the physical order of data in a table. For this reason, a table
can have only one clustered index.
Non-Clustered Index
1. In the case of a non-clustered index, the arrangement of data in the index table will be
different from the arrangement of the actual table.
2. A non-clustered index is analogous to an index in a textbook. The data is stored in one place,
the index is another place. The index will have pointers to the storage location of the data.
3. Since, the non-clustered index is stored separately from the actual data a table can have
more than one non clustered index, just like how a book can have an index by chapters at
the beginning and another index by common terms at the end.
4. In the index itself, the data is stored in an ascending or descending order of the index key
which does not in any way influence the storage of data in the table.
5. In a table, we can create a maximum of 249 non clustered indexes.
In SQL Server we can create a maximum of 249 non clustered indexes for a table
Check if there is an Index created on the UntiPrice column used in the ORDER BY clause. An
index on the UnitPrice column can help the above query to find data very quickly. When we ask
for sorted data, the database will try to find an index and avoid sorting the results during the
execution of the query. We control sorting of data by specifying a field, or fields, in an ORDER BY
clause, with the sort order as ASC (ascending) or DESC (descending).
5. Triggers in SQL
Triggers are nothing but they are logic’s like stored procedures that can be executed automatically
before the Insert, Update or Delete happens in a table or after the Insert, Update, or Delete happens
in a table. In simple words, we can say that, if you want to execute some pre-processing or post-
processing logic before or after the Insert, Update, or Delete isn a table then you need to use
Triggers.
However, the difference between a trigger and a stored procedure is that the trigger is attached to a
table and is only fired when an INSERT, UPDATE or DELETE operation occurred whereas stored
procedures are not attached to a specific table and can be executed explicitly by making a call to the
stored procedure. In addition to that, triggers can also execute stored procedures.
When we copy the data from one table to another table we use insert and select query. Tables
always independent objects that mean a table does not depend on other tables.
diagram, the injector class creates an object of the service class and injects that object to a client
class. In this way, the Dependency Injection pattern separates the responsibility of creating an object
of the service class out of the client class.
How to create a new table from an existing table or in how many ways we can create a new table
from an existing table?
If required we can create a new table from an existing table as below.
Syntax1: (with all column from an existing table)
SELECT * INTO <NEW TABLE NAME> FROM <OLD TABLE NAME>
Example: SELECT * INTO NEWEMPLOYEE FROM EMPLOYEE
When we execute the above query it will create a new table with all records from an existing table.
Syntax2: (with specific columns from an existing table)
SELECT <REQUIREDCOLUMN> INTO <NEW TABLE NAME> FROM <OLD TABLE NAME>
Example: SELECT EID, SALARY INTO SPECEMP FROM EMPLOYEE
When we execute the above query it will create a new table with the specific column data from an
existing table.
Syntax3: (creating a new table without data)
SELECT * INTO <NEW TABLE NAME> FROM <OLD TABLE NAME> WHERE 1 = 0
Example: SELECT * INTO DUMMYEMP FROM EMPLOYEE WHERE 1 = 0
OR
SELECT <REQUIRED COLUMNS> INTO <NEW TABLE NAME> FROM <OLD TABLE NAME>
SELECT EID, SALARY INTO TAB1 FROM EMPLOYEE WHERE 1 = 0
How to create a new table from an existing table or in how many ways we can create a new table
from an existing table?
If required we can create a new table from an existing table as below.
Syntax1: (with all column from an existing table)
SELECT * INTO <NEW TABLE NAME> FROM <OLD TABLE NAME>
Example: SELECT * INTO NEWEMPLOYEE FROM EMPLOYEE
When we execute the above query it will create a new table with all records from an existing table.
Syntax2: (with specific columns from an existing table)
SELECT <REQUIREDCOLUMN> INTO <NEW TABLE NAME> FROM <OLD TABLE NAME>
Example: SELECT EID, SALARY INTO SPECEMP FROM EMPLOYEE
When we execute the above query it will create a new table with the specific column data from an
existing table.
Syntax3: (creating a new table without data)
SELECT * INTO <NEW TABLE NAME> FROM <OLD TABLE NAME> WHERE 1 = 0
Example: SELECT * INTO DUMMYEMP FROM EMPLOYEE WHERE 1 = 0
OR
SELECT <REQUIRED COLUMNS> INTO <NEW TABLE NAME> FROM <OLD TABLE NAME>
SELECT EID, SALARY INTO TAB1 FROM EMPLOYEE WHERE 1 = 0
A cursor in SQL is a temporary work area created in system memory when a SQL statement is
executed. A SQL cursor is a set of rows together with a pointer that identifies a current row. It is a
database object to retrieve data from a result set one row at a time. It is useful when we want to
manipulate the record of a table in a singleton method, in other words, one row at a time. In other
words, a cursor can hold more than one row but can process only one row at a time. The set of rows
the cursor holds is called the active set.
In order to work with a cursor we need to perform some steps in the following order:
1. Declare cursor
2. Open cursor
3. Fetch row from the cursor Process fetched row Close cursor
4. Deallocate cursor
What is a NOLOCK?
This is one of the most frequently asked SQL Interview Questions. Using the NOLOCK query
optimizer hint is generally considered good practice in order to improve concurrency on a busy
system. When the NOLOCK hint is included in a SELECT statement, no locks are taken when data is
read. The result is a Dirty Read, which means that another process could be updating the data at the
exact time you are reading it. There are no guarantees that your query will retrieve the most recent
data.
2. Global Temporary Tables- Global Temporary tables name starts with a double hash (“##”).
Once this table has been created by a connection, like a permanent table it is then available
to any user by any connection. It can only be deleted once all connections have been
closed.The Global Temporary Tables are visible to all the connections of the SQL Server and
are only destroyed when the last connection referencing the table is closed.
Multiple users across multiple connections can have Local temporary tables with the same
name but Global Temporary Table Names should be unique and if we inspect the name of
the Global Temporary Table in the object explorer there will be no random numbers suffixed
at the end of the table name.
Can you please explain when to use a temp table in SQL Server?
When we want to perform many operations on the data in a specific table in the database, we can
load the data into a temporary table and then we can perform operations on the temporary table.
Loading data into a temporary table speeds up the process because all the operations are performed
locally on the client. Use of the Temporary Tables reduces the load on both the network and server
as all the interaction with temporary tables occurs on the Client.
1. When we are doing a large number of row manipulation in stored procedures.
2. This is useful to replace the cursor. We can store the result set data into a temp table, then
we can manipulate the data from there.
3. When we are having a complex join operation.
4. A Temporary Table variable can be very useful when used with stored procedures to pass
input/output parameters or to store the result of a table-valued function.
Q:-2. What are some tips to improve the performance of SQL queries?
Ans. Optimizing SQL queries can bring substantial positive impact on the performance. It also
depends on the level of RDBMS knowledge you have. Let’s now go over some of the tips for tuning
SQL queries.
1. Prefer to use views and stored procedures in spite of writing long queries. It’ll also help in
minimizing network load.
2. It’s better to introduce constraints instead of triggers. They are more efficient than triggers and
can increase performance.
4. The UNION ALL clause responds faster than UNION. It doesn’t look for duplicate rows whereas the
UNION statement does that regardless of whether they exist or not.
7. Make use of SET NOCOUNT ON clause while building stored procedures. It represents the rows
affected by a T-SQL statement. It would lead to reduced network traffic.
8. It’s a good practice to return the required column instead of all the columns of a table.
9. Prefer not to use complex joins and avoid disproportionate use of triggers.
We can apply Culster ,non cluster index Primary key constraint or Unique Keon temp tab
DELETE
SQL DELETE query deletes all records from a database table. To execute a DELETE query, delete
permissions are required on the target table. If you need to use a WHERE clause in a DELETE, select
permissions are required as well.
DROP
DROP table query removes one or more table definitions and all data, indexes, triggers, constraints,
and permission specifications for those tables. DROP command requires to ALTER permission on the
schema to which the table belongs, CONTROL permission on the table, or membership in the
db_ddladmin fixed database role.
What is normalization?
Database normalization is a data design and organization process applied to data structures based
on rules that help build relational databases. In relational database design the process of organizing
data to minimize redundancy. Normalization usually involves dividing a database into two or more
tables and defining relationships between the tables. The objective is to isolate data so that
additions, deletions, and modifications of a field can be made in just one table and then propagated
through the rest of the database via the defined relationships.
WITH T AS
(
SELECT *,
DENSE_RANK() OVER (ORDER BY Salary Desc) AS Rnk
FROM Employee
)
SELECT Name
FROM T
WHERE Rnk=2;
USE [TDFERU]
GO
GO
AND
CTE in SQL
CTE stands for Common Table Expressions. It was introduced with SQL Server 2005. It is a temporary
result set and typically it may be a result of complex sub-query. Unlike the temporary table, its life is
limited to the current query. It is defined by using WITH statement. CTE improves readability and
ease in maintenance of complex queries and sub-queries.
The CTE query start with a “With” and is followed by the expression name. e will be using this
expression name in our select query to display the result of our CTE Query and be writing our CTE
query definition.
AS ( CTE_query_definition )
To view the CTE result we use a Select query with the CTE expression name.
Or
1. Temp Tables are physically created in the tempdb database. These tables act as the normal table
and also can have constraints, an index like normal tables.
2. CTE is a named temporary result set which is used to manipulate the complex sub-queries data. This
exists for the scope of a statement. This is created in memory rather than the Tempdb database.
You cannot create an index on CTE.
3. Table Variable acts like a variable and exists for a particular batch of query execution. It gets
dropped once it comes out of a batch. This is also created in the tempdb database but not the
memory.
we can use CTE in CREATE, UPDATE, DELETE and create View but within that scope. If we create the
CTE in a Stored Procedure, I can’t use it in another Stored Procedure. So what we can say is that CTE
is a derived table; it’s a temporary result set.
ADO.NET
Ado.Net Classes
In Connected architecture, the connection must be open to access the data retrieve from the
database. It was built on the classes connection,command,Data reader and transaction.
In Disconnect architecture, the data retrieve from database can be accessed even when connection
to be database was closed It was built on classes connection, dataadapter, commandbuilder and
dataset and dataview.
DataSet
To achieve this you need to use DataAdapter which work as a mediator between Database
and DataSet.
Example
DataReader
It is a connected architecture, which means when you require data from the database you
need to connect with database and fetch the data from there. You can use if you need
updated data from the database in a faster manner. DataReader is Read/Forward only that
means we can only get the data using this but we cannot update or insert the data into the
database. It fetches the record one by one.
Example
Yesterday I was stuck with some logic to maintain a single transaction in a multi DML operation in SQL
Server and Oracle Database. I mean to say that I had to set a transaction on a single click where an
insert or update was to be done in a SQL database and an insert or update was to be done in a Oracle
Database. After extensive research I finally got the solution from the MSDN. I want to explain my
experience with a small example.
You can easily maintain one transaction for multiple databases or a single database with multiple
connectionstrings, using TransactionScope.
When you use TransactionScope there is no need to close any Database connections in the middle.
Just make an object of the TransactionScope class with using. Write all your code in this block and
after completion of all your operations call "objTransactionscope.complete()". Ensure one thing; you
should write a try/catch block in the TransactionScope block.
Now if an exception occurrs in method1(), method2() or method3() then it will catch the exception in
the catch block and all the operations will be rolled back automatically. There is no option to call a
rollback manually in TransactionScope.
ADO.NET code to perform CRUD operations with the underlying database. For this, we need to
create a connection with the database, open the connection, create a DataSet to fetch or submit the
data to the database, and convert the data from the DataSet to .NET objects or vice-versa to apply
our business rules. Actually, this was a time-consuming, cumbersome, and error-prone process.
Microsoft has provided a framework called “Entity Framework” to automate all these database
related activities for our application if we provided the necessary details to the Entity Framework.
It is the framework automatically created classes based on database tables and vise versa is also true
that is, it can also generate necessary SQL to create database tables based on classes.
This is the primary class that is responsible for interacting with data as object
is System.Data.Entity.DbContext. The context class in Entity Framework is a class that derives
from DBContext in EF 6 and EF Core. It is an important class in Entity Framework, which represents a
session with the underlying database.
The context class is used to query or save data to the database. It is also used to configure domain
classes database-related mappings, change tracking settings, caching, transactions, etc
These POCO entities support most of the same query, insert, update, and delete behaviors as entity
types that are generated by the Entity Data Model. The following is an example of an Employee
POCO entity.
public class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string Gender { get; set; }
public Nullable <int> Salary { get; set; }
public Nullable <int> DepartmentId { get; set; }
public virtual Department Department { get; set; }
}
2. Dynamic proxy entities
The Dynamic Proxy is a runtime proxy class that wraps the POCO entity.
1. Database first
2. Code-First
3. Model – First
We can use the Database First Approach if the database schema already existing. In this approach,
we generate the context and entities for the existing database using the EDM(Entity data model
wizard ) wizard. This approach is best suited for applications that use an already existing database.
we can say that the entity framework will create the model classes based on tables and
columns from the relational database.
Code first approach is used when we do not have existing database for application. In the code-
first approach, you start writing your entities (domain classes) and context class first and then create
the database from these classes using migration commands.
This approach is very much similar to the Code First approach, but in this case, we use a visual EDMX
designer to design our models. So in this approach, we create the entities, relationships, and
inheritance hierarchies directly on the visual designer and then generate entities, the context class,
and the database script from your visual model.
the domain object defines the business object and it's properties and methods. It's used to
manipulate and move the data within the processing system. The Entity object exists to take
those domain properties and map them to a persistent storage object, such as a database table.
And in BMW
using (System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(handler))
{
Logger.AddToLog("Call WIT Start ResOne
User_Name:Pass :" + strWIT_USER_NAME + " : " + strWIT_USER_PASS, Severity.Information,
LogGroup.LA);
client.BaseAddress = new Uri(WitVehicleBasic);
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new
System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/xml"));
client.DefaultRequestHeaders.Authorization = new
AuthenticationHeaderValue(
"Basic",
Convert.ToBase64String(
System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}",
strWIT_USER_NAME, strWIT_USER_PASS))));
var response =
client.GetAsync(WitVehicleBasic).Result;
Logger.AddToLog("Call WIT Hitted",
Severity.Information, LogGroup.LA);
if (response.IsSuccessStatusCode)
{
}
Post
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new
MediaTypeWithQualityHeaderValue("application/jason"));
var responseUpload =
client.PostAsync(String.Format(CallValidateDealerURL), content).Result;
Logger.AddToLog(
"INT190 Response IsSuccessStatusCode: " +
Convert.ToString(responseUpload.IsSuccessStatusCode),
Severity.Information, LogGroup.LA);
if (responseUpload.IsSuccessStatusCode)
{
returnData =
responseUpload.Content.ReadAsStringAsync().Result;
//MS Logger.AddToLog("INT100 response Return Data: " +
Convert.ToString(returnData), Severity.Information, LogGroup.LA);
objApiResponseModel =
JsonConvert.DeserializeObject<ValidateDealerResponse>(returnData);
}
Synchronous basically means that you can only execute one thing at a
time. Asynchronous means that you can execute multiple things at a time and you don't have to
finish executing the current thing in order to move on to next one.
AJAX communicates with the server using XMLHttpRequest object. ... User sends a request
from the UI and a javascript call goes to XMLHttpRequest object. HTTP Request is sent to
the server by XMLHttpRequest object. Server interacts with the database using JSP, PHP,
Servlet, ASP.net etc.
Call server side method from javascript function via asp button?
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<script type="text/javascript">
function funTest() {
alert('in the javascript function...');
document.getElementById('btnTestHidden').click();
}
</script>
</head>
<body>
<form id="form1" runat="server">
<input id="btnTest"
runat="server"
type="submit"
value="Test"
onclick="funTest()" />
<asp:Button ID="btnTestHidden"
runat="server"
Text="this is btnTestHidden - later it will be display:none"
style="display:block"
onclick="btnTestHidden_Click" />
</form>
</body>
</html>
Patch request says that we would only send the data that we need to modify without modifying or
effecting other parts of the data. Ex: if we need to update only the first name, we pass only the first
name. PUT is for complete entity replacement whereas PATCH is to partially update the entity.
The tow most common Http methods are Get and Post
GET method is used to appends form data to the URL in name or value pair. If you use GET, the
length of URL will remain limited. It helps users to submit the bookmark the result. GET is better for
the data which does not require any security or having images or word documents.
depicts that a web server accepts the data included in the body of the message. POST is often used
by World Wide Web to send user generated data to the web server or when you upload file.