All QA 2.O
All QA 2.O
All QA 2.O
Modified By - SHUBHAM_LAMBAT
INDEX PAGE
TA B L E O F C O N T E N T S
03 SQL 15 C#
32 LINQ 38 JAVASCRIPT
55 MVC 67 ADO.NET
89 COMPANY QA 94 PROGRAMS
SQL
1. What are Different Types of SQL Commands? Or Explain DDL, DML, TCL Commands.
- There are different commands which we use to communicate with the database to perform specific
tasks.
- Data Definition Language (DDL) –
o Commands which affects on schema or structure.
o These SQL commands are used for creating, modifying, and dropping the structure of database
objects. (i.e. affects on schema or structure).
o These commands are CREATE, ALTER, DROP, RENAME, and TRUNCATE.
Truncate
- TRUCATE is a DDL command and it is faster.
- TRUNCATE removes all rows from a table.
- The operation cannot be rolled back and no triggers will be fired.
- Truncate command also reset identity.
Drop
- Drop is a DDL command.
- The DROP command Removes a Table from the database.
- All the tables' rows, indexes and privileges will also be removed.
- No DML triggers will be fired.
- The Drop operation cannot be rolled back.
[Reason why Truncate is faster? :- When you type DELETE, all the data get copied into the Rollback
Tablespace first then delete operation get performed. Thats why when you type ROLLBACK after
deleting a data, you can get back the data and this process take time. But when you type TRUNCATE,
it removes data directly without copying it into the Rollback Tablespace. Thats why TRUNCATE is
faster. Once you Truncate you can't get back the data.]
MODIFIED BY SHUBHAM LAMBAT
4
- We have the following options when setting up Cascading referential integrity constraint
a. No Action:
This is the default behavior.
It will not allow to delete or update record from primary key table.
b. Set NULL:
It will delete or update records from primary key table and set null value in foreign key
table.
c. Set Default:
It will delete or update records from primary key table and set default value in foreign key
table.
d. Cascade:
It will delete or update records from primary key table as well as from foreign key table.
8. What Will be the Value of Identity Column Value if All Rows Deleted from the Table? Will it
Reset to Default Values Automatically? If No Then, How to Reset Identity Column Seed and
Increment Value to Default Values?
- If all rows get deleted from table but still, we able to see last generated identity value.
- We can reset this identity column value to default value by using DBCC CHECKIDENT command.
DBCC CHECKIDENT (tblName, RESEED, 0)
MODIFIED BY SHUBHAM LAMBAT
5
9. What is Normalization in SQL? Why do we Need of Normalization? What are Different Forms
of Normalization? Explain 1st, 2nd and 3rd Normal Form.
- Database normalization is the step-by-step process to design a better database.
- Remove duplication (redundancy)
1NF
The data in each column should be atomic. (There should not be comma separated values).
The table does not contain any column repeating groups.
Every record should identify uniquely (i.e., every record should have primary key).
2NF
The table satisfy all the conditions of 1NF.
Identify groups and split into multiple tables.
Create relationship between these tables using foreign keys
3NF
The table satisfy all the conditions of 1NF and 2NF.
Remove all columns (attributes) that are not fully dependent upon the primary key.
12. What is Join? What are the Different Types of Joins Available in SQL? Explain them.
- JOINS are used to retrieve data from two or more tables based on logical relationships between these
tables.
- Basically, there are 3 types of joins available in SQL.
a. Inner Join
b. Outer Join which again classified to 3 subtypes
o Left Outer Join
o Right Outer Join
o Full Outer Join
c. Cross Join
Inner Join –
- Inner joins return only the common records from both the tables.
Left Outer Join –
- Left join returns common records from both tables as well as uncommon records from left table.
Right Outer Join –
- Right join returns common records from both tables as well as uncommon records from right table.
Full Outer Join –
- Full outer join returns common and uncommon records from both tables.
Cross Join –
- Cross join returns Cartesian product of the tables involved in the join.
16. What is a Sub Query? What are its Various Types? Explain Correlated and Non-Correlated
Sub query?
- A subquery is nothing but the simple select query that returns a single value and can be nested inside
a SELECT, UPDATE, INSERT, or DELETE statement.
- Subqueries are always enclosed in parenthesis called inner queries and the query containing the
subquery called outer query.
- There are two types of subqueries :
Correlated Sub Query :
- Inner query depends on outer query.
- Outer query runs first.
- Inner query runs multiple times till the records are there in outer query.
Non Correlated Sub Query :
- Outer query depends on inner query.
- Inner query runs first.
- Inner query executes once.
iv. Better Security - A database user can be granted access to an SP and prevent them from executing
direct "select" statements against a table. This is fine grain access control which will help control
what data a user has access to.
v. Avoids SQL Injection Attack - SP's prevent SQL injection attack.
18. What is Difference Between Return values and Output Parameter in Stored Procedures?
- Using return values, we can return only one value of type integer whereas output parameters can
return multiple values of any type.
- We always prefer, using output parameters over return values.
- Nondeterministic functions may return different results each time they are called with a specific set of
input values.
Examples: GetDate() and RAND()
21. What is RAND () Function? What if you Pass it a Parameter e.g., RAND (1)?
- Rand () function is a non-deterministic function i.e., every time called gives new value between 0
and 1.
- But if we provide the seed value, the function becomes deterministic, as the same value gets returned
for the same seed value.
22. What are functions in SQL? What are Different Types of Functions? Explain.
- Functions are block of SQL statement which are used to perform some computational logic.
- There are 3 different types of functions are available in SQL:
1) Scalar Function:
o Scalar functions always return a single scalar value.
o The returned value can be of any data type except text, ntext, image, cursor, and timestamp.
26. What is CTE in SQL? Can you write a syntax to create a CTE?
- CTE means common table expression.
- A CTE is a temporary result set, that can be referenced within a SELECT, INSERT, UPDATE, or
DELETE statement that immediately follows the CTE.
- CTE Should Be use With Next Immediate Statement
- Syntax :
WITH CTE_name (Column1, Column2, ..)
AS
( CTE_query )
Select * from CTE_Name
27. What are Differences Between Temporary Tables & Table Variables?
- Temporary tables can be stored in TempDB Whereas Table variables can be stored in memory but
if there is a memory pressure table variables can be stored in TempDB.
- Temporary tables participate in transaction Whereas Table variables does not participate in
transaction this makes table variable faster than a temporary table.
- You cannot pass Temporary table as parameter Whereas you can pass Table variable as parameter
to store procedure and function.
28. What is Difference Between INSERT INTO and SELECT INTO statements?
- Both the statements are used to copy data from one table to another table.
- For INSERT INTO statement it is mandatory to create the table and then fire insert into query whereas
for SELECT INTO statement table creation is not needed this query automatic generates the table and
copy the data.
- Syntax for INSERT INTO :
Insert into tblName values col Value, col Value,…
Or
INSERT INTO @targetTblName
- Disadvantages of Indexes:
Additional Disk Space: Clustered Index does not, require any additional storage. Every Non-
Clustered index requires additional space as it is stored separately from the table. The amount of
space required will depend on the size of the table, and the number and types of columns used in the
index.
Insert Update and Delete Statements can Become Slow: When DML (Data Manipulation
Language) statements (INSERT, UPDATE, DELETE) modifies data in a table, the data in all the
indexes also needs to be updated. Indexes can help, to search and locate the rows, that we want to
delete, but too many indexes to update can actually hurt the performance of data modifications.
31. Scenario: Interviewer may give you a table and a query and ask you for on which column
should I create a Clustered Index and Why? Let’s say there is a Employee table with Id Column
as a Primary Key :
32.
What are Views? Indexed View? Advantages of Views?
-A view is nothing more than a saved SQL query.
-A view can also be considered as a virtual table.
-When we try to retrieve data from the view, the data is actually retrieved from the underlying base
tables. So, a view is just a virtual table it does not store any data, by default.
- However, when we create an index, on a view, the view gets materialized. This means, the view is
now, capable of storing data. In SQL server, we call them Indexed views.
MODIFIED BY SHUBHAM LAMBAT
11
33. Can we Update Underlying Base Tables through View? [Tricky question] Depending on
your answer he can ask you Single/Multiple base tables?
- Yes. We can update the base tables through a view if there is single underlying base table.
- For a view based on multiple base tables we can use instead of trigger to correctly update the base
table values.
DML Triggers :
- DML triggers are fired whenever data is modified using INSERT, UPDATE and DELETE events.
- DML triggers can be again classified into 2 types.
a) After or For triggers
- After trigger will be fired and executed after performing the Insert, Update and Delete
actions successfully.
b) Instead of triggers
- Instead Of trigger allow you to skip an Insert, Update and Delete actions on table and
execute other statements defined in the trigger instead.
DDL Triggers :
- DDL triggers fire in response to DDL events i.e. for CREATE, ALTER and DROP (Table,
Function, Index, Stored Procedure etc...).
Logon Triggers :
- As the name implies Logon triggers fire in response to a LOGON event.
- Logon triggers fire after the authentication phase of logging in finishes, but before the user session is
actually established.
37. Can we Limit Connections for a Particular user? If Yes then How?
- Yes. We can limit the connections for a particular user.
- We can use Logon Triggers to achieve this.
38. How Error Handling done in SQL? Have you done Error Handling in your Project?
- We use Try Catch block just like C# language to catch and handle the exceptions in SQL.
- We cannot use try catch blocks in functions.
- If we have to through error to calling application then we use RAISERROR function in catch block.
- Also, we specify ROLLBACK command in catch block when we are dealing with transactions.
- RAISEERROR Function is use to throw exception directly to the calling application.
Syntax of RAISEERROR Function is
RAISERROR('Error Message', ErrorSeverity, ErrorState)
- Severity and State are integers. In most cases, when you are returning custom errors, the severity level
is 16, which indicates general errors that can be corrected by the user.
- ErrorState is also an integer between 1 and 255. RAISERROR only generates errors with state from 1
through 127.
39. What are Transactions in SQL? What all Commands used in Transaction?
- A transaction is a group of commands that change the data stored in a database.
- A transaction is treated as a single unit.
- A transaction ensures that, either all of the commands succeed, or none of them. If one of the commands
in the transaction fails, all of the commands fail, and any data that was modified in the database is rolled
back. In this way, transactions maintain the integrity of data in a database.
- Transaction processing follows these steps:
1. Begin a transaction.
2. Process database commands.
3. Check for errors.
If errors occurred,
rollback the transaction,
else,
commit the transaction
- We use Commit command to commit the changes permanently to database and Rollback
command to Rollback the changes on any error while working with transactions.
Rank function
- Rank function skips rankings if there is a tie.
- In Rank function ORDER BY clause is required.
- In Rank function PARTITION BY clause is optional.
- Syntax : Rank() OVER (ORDER BY Col1, Col2)
Dense_Rank function
- Dense_Rank function does not skip rankings if there is a tie.
- In Dense_Rank function ORDER BY clause is required.
- In Dense_Rank function PARTITION BY clause is optional.
- Syntax : Dense_Rank() OVER (ORDER BY Col1, Col2)
49. What are Cursors in SQL? Can you tell me What all Steps are Followed while using Cursors?
- If there is ever a need to process the rows, on a row-by-row basis, then cursors are your choice.
- Cursors are very bad for performance, and should be avoided always.
- Most of the time, cursors can be very easily replaced using Joins.
- There are different types of cursors in SQL server as listed below.
1. Forward-Only
2. Static
3. Keyset
4. Dynamic
[Note: If interviewer ask where did u use cursors in your project? Ans: I have never come across situation
where I can implement cursors in my project. Again, they are bad over performance.]
C#
1. Purpose of Main () Method? Scenario with Writing one more Main () Method?
• Every program needs an entry point to execute.
• This Main() method is an entry point where program starts its execution.
• Main() method is by default private and static.
• As C# is a case sensitive language it means Main(), main(), MAIN() these method names are
treated as different.
• Using as Keyword.
object a = "some string";
string b = a asstring;
We can use Parse and TryParse methods when we need to convert a string to other types like
int, bool, float etc.
6. What are Value Types and Reference Types in C#? Give Some Examples?
Value Type
In value type actual value get stored on stack.
When value type goes out of scope it will remove actual value from stack.
Value type does not hold null values but it can achieve using nullable type.
Ex. Integer, Boolean, Struct, etc..
Reference Type
In reference type references get stored on stack and actual value(object) get stored on heap.
When references goes out of scope it will just removes references from stack and actual
value (object) is there in heap.
Ex. String, Object, Class, etc..
Interviewer might extend his question further asking What are Anonymous Types?
• Anonymous types allow to create a new type without defining them.
• Type Without Name. Ex :-new{};
• They are extensively used in LINQ expressions whenever you want to return only a few
properties from its properties.
Ex. var person = new {Id = 101, Name = "ABC"};
MODIFIED BY SHUBHAM LAMBAT
17
10. What is Difference Between Var and Object Type and Dynamic Keyword?
Var
• It is compile time variable and does not require boxing and unboxing.
• Since Var is a compile time feature, all type checking is done at compile time only.
• Once var has been initialized we can’t change type stored in it.
• It is implicit Type Local variable
• We can use Var when we don’t know the type of value.
• Using var keyword less readability.
var test = 10; // after this line test has become of integer type
test == test + 10; // No error
test == "hello"; // Compile time error as test is an integer type
Object
• Each object in C# is derived from object type, either directly or indirectly.
• It is compile time variable and require boxing and unboxing for conversion and it makes it slow.
• You can change value type to reference type and vice versa.
object test = 10;
test = test + 10; // Compile time error
test = "hello"; // No error, Boxing happens here
Dynamic
• It is run time variable and not require boxing and unboxing.
• You can assign value to dynamic and also can change value type stored in same.
• All errors on dynamic can be discovered at run time only.
• We can also say that dynamic is a run time object which can hold any type of data.
dynamic test = 10;
test = test + 10; // No error
test = "hello"; // No error, neither compile time nor run time
11.
What is Array?
Array is a collection of similar datatypes.
Array elements are accessed by Index.
Index starts from 0.
Array size is fixed and its size cannot grow automatically.
If you try to access index which is not there it throws exception like “Index Out of Range
Exception”.
Types Of Array:
Single-Dimensional Array
Multi-Dimensional Array
Reference Parameters
• Any parameter value changes in called method will reflect in calling method.
• It is mandatory to initialize value in calling method before passing to method.
• It is not mandatory to assign value in called method before leaving a method.
Output Parameters
• Any parameter value changes in called method will reflect in calling method.
• Internally ref and out keyword works same.
• It is mandatory to assign value in called method before leaving a method.
• It is not mandatory to initialize value in calling method before passing to method.
• By default, method can return only a single value. If we want to return more than one value
from a method then we can use output parameters.
Parameter Arrays
• If a method has array as input parameter, then we can use params keyword with that parameter.
• Advantages of using parameter arrays are we can pass comma separated values instead of creating
and passing array as argument.
• Also, we can call that method without passing any parameter i.e. We can achieve optional
method parameter using parameter arrays.
18. What are all Ways Available in C# to Make Method Parameters as Optional?
There are different ways we can make a parameter as optional parameter:
Parameter Arrays
• We can use parameter arrays to make optional parameter as it allows us to call method without
passing value for params parameter.
Default Value
• We can specify default values to parameters to make them optional.
• If we are specifying default values then it should be from right to left.
Optional Attribute
• We can use [OptionalAttribute] with parameter to make it optional.
Data Members
Any field writing inside a class can referred as a data member.
We can write n number of class field in class.
Member Function
Any method or function inside a class is nothing but the member function.
21. What is Purpose of Constructor? How it Differs from Normal Member Function?
• The purpose of constructor is to initialize class fields.
• Constructors are automatically called when we create object of a class.
• There are Different Types of constructors we can write inside a class like
1) Parameter less Constructor (Default)
2) Parameterized Constructor
3) Copy Constructor
4) Static Constructor
27.
What is Method Overloading? On what basis a Method can be Overloaded?
• Method overloading is a compile time polymorphism means it checks at compile time.
• Same method name having different forms called method overloading.
• Method can be overloaded on the basis of
1) Number of Parameter
2) Types of Parameters
3) Order of Parameter
4) Kinds of Parameter
Method cannot be overloaded on the basis of
1) Return Type
2) Ref and Out Keyword
3) Using Params
MODIFIED BY SHUBHAM LAMBAT
21
28. Can Method Overloaded on Basis of Just Return Type? if no, then why?
• No. Method cannot be overloaded just on basis of return type.
• Return type is not considered in method signature while method overloading.
• This behavior is by design and it is because to avoid confusion of a developer that what will be
the output of the method if the method is same and just changed with the return type.
33. What is Method Hiding? Scenario of object Creation and Calling Methods.
• If base and derived class contain same method then a base class reference variable pointing to
a derived class object will call base class method is called method hiding.
• If we don’t provide new keyword in derived class method then compiler will give us a warning
that if hiding is intentional then use new keyword.
• We use new keyword in derived class method because method hiding is intentionally.
34. What are Properties? Why should we use Properties? What is Auto-Implemented
Properties?
• Properties are used to encapsulate and protect the private fields.
• We can write custom logic to validate the user data before it is actually assigned to or retrieved
from private fields.
• Using get and set access modifiers we can create Read Only, Write Only and Read Write
Properties depending on our requirement.
• Auto implemented properties, with this feature we do not need to declare a separate private
field for a property.
• Framework automatically creates a private field for the declared property.
Ex. Public string Name { get; set; }
• Ex :
string Name = i1[101];
Console.WriteLine (Name); o/p :- Shubham Lambat
37. What is Encapsulation and Abstraction? When Abstraction and Encapsulation comes
in Project Development?
- Abstraction is a concept of showing necessary information to outside world.
- Encapsulation is a concept of hiding unnecessary information from outside world.
- Encapsulation means Wrapping of Data and Methods/Properties into a Single Unit.
• Syntx :-
interface Print
{
void printA();
void printB();
}
MODIFIED BY SHUBHAM LAMBAT
23
39. What is Explicit Interface Implementation? When there will be need of Implementing
Interface Explicitly.
• When we are implementing 2 or more interfaces in a class and those interfaces are having
same method signature.
• Then we have to implement those interfaces explicitly in order to give implementation to all of
the interfaces.
• We have to prefix interface name with method name while implementing interface
explicitly.
• This implemented methods by default public. We cannot specify any other access modifier
even a public.
• To call particular method we have 2 approaches –
41. Can Abstract class have a Constructor? When it will get called?
• Yes. Abstract class can contain constructors.
• Abstract class constructors get called before derived class constructor call.
43. What is Difference between Interface and Abstract class? When to use Interface over
Abstract Class or Vice Versa.
• Interface cannot have definition for any of its member Whereas abstract class can have
definition for its members (non-abstract member).
• Interfaces cannot have fields Whereas abstract class can contain field.
• By default, access specifier for interface members is public and we cannot specify any other
even a public Whereas abstract class members access specifiers can be changed.
• If there is situation that all the derived classes have different implementation but we have to
provide same method signature then we can go with interfaces Whereas if there is a situation that
few of the derived classes sharing same implementation then we can think of using abstract class
instead of interface.
• In interface multiple inheritance is possible Whereas in abstract class multiple
inheritance not possible.
MODIFIED BY SHUBHAM LAMBAT
24
44. Why Multiple Class Inheritance is Not Possible in C#? How to Overcome it.
• Multiple class inheritance is not possible in C# it is also called as Diamond Problem.
• Let’s say we have one class A which is derived by two classes B and C. Class B and C has
overridden method which was marked virtual in class A.
• Now if we derive class B and C in a new class D and we are not providing any
implementation in class D.
• So, if we create an object of class D then which method implementation should get call here
from class B or class C. There will be an ambiguity in calling 2 different copies of overridden
method. This problem is called as Diamond Problem.
• We can achieve multiple class inheritance using interfaces.
46. What is Default Access Specifier for Type and Type Members?
• Default access modifier for a type is internal.
• Default access modifier for types member is private.
48. What are Partial Classes and Rules to Create Partial Classes?
• Partial classes allow us to split a class into 2 or more files.
• When the application is compiled, all these parts then combined into a single class.
Rules :
• All parts should have partial keyword.
• All parts should have same access modifiers.
• If one part is marked abstract then entire type is considered abstract.
• If one part is marked sealed then entire type is considered sealed.
• Multiple class inheritance is not possible in C# so different parts should not inherit different
base classes.
49. What are Partial Methods? Anything can be asked related to Rules followed during
creating Partial Methods?
• Partial class can contain partial methods.
• Partial method created using partial keyword and it has two parts – the declaration and the
implementation.
• Partial methods are by default private. We cannot specify any other modifier even private.
• Partial method implementation is optional.
• If we not provide implementation then complier removes its declaration as well as all the
calls.
• Partial method return type must be void. Giving any other type gives compile time error.
MODIFIED BY SHUBHAM LAMBAT
25
52. What is purpose of Finally Block? Scenario for Executing Return Statements.
• Finally Block is guaranteed to be executed in both the cases if there is error occurs or not.
• Also, it gets executed if there is any error occurs in catch block.
• So, we can use finally block to close the open connection or if we want to explicitly free the
resources.
55. Can we Customize Values in Enum? What is default Start Value to Enum?
• Yes, we can customize the values of Enum.
• The default start value of Enum is 0.
56. What is Default Underlying type to Enum? Can we change its Underlying type to some
other type?
• Default underlying type of enum is int.
• We can anytime change underlying type to any other integral datatypes like byte, short etc.
depending on the size we want to store.
MODIFIED BY SHUBHAM LAMBAT
26
58. What are all default methods Comes with every type in Dot Net? From where they are
Derived? Can we Override Them?
• All types in dot net directly or indirectly derived from Object class
• All these default methods are :
1) GetType()
2) ToString()
3) Equals()
4) GetHashCode()
We can override ToString(), Equals(), GetHashCode() methods because virtual keyword is in
there method signature.
62. Why to override Equals() method? Is there is any Warning/Error Associates with just
Overriding Equals Method? If yes, how to fix it?
• Equals() method works fine with built-in types but when it comes to complex types it checks
only reference equality and not value equality.
• So we can override this Equals() method to check value equality for complex types.
• There is one warning when we override Equals() method and that is we have to override
GetHashCode() method also. This method is helps to generate unique hash codes.
Constant
• Constant variables are used to create constant fields.
• It is mandatory to initialize the value at the time of declaration.
• Constant variables value cannot be changed throughout the program.
• They are by default static.
Read-Only –
• Read-Only fields are also similar to constant variables but we can change its value at runtime
through non static constructors.
• It is also not mandatory to initialize value at the time of declaration.
• We can also have static read-only fields in which we can assign value at runtime through static
constructor but only once.
67. What are types of Delegates? Predicate, Action and Func Delegate?
Basically, there are 2 types of delegates
Singlecast delegate – Delegate pointing to a single method.
Multicast delegate – Delegate Pointing to multiple methods.
- Apart from these types we have few generic delegates which extensively used in LINQ
methods.
Action Delegate – Delegate has type T as input parameter and void as return type. 16 overloads.
Predicate Delegate – Delegate has type T as input parameter and bool as return type.
Func Delegate – Delegate has type T as input parameters and T as output parameter. 17
overloads.
69. What is Generics? Name some Generic Collections and Non-Generic Collections?
• Generics allows us to design classes and methods decoupled from the data types.
• Which avoid boxing and unboxing operations and offers better performance.
• List<T>, Dictionary<T>, Stack<T>, Queue<T> are few examples of generic collections
classes.
• Array List and Hash Table are few examples of non-generic collections classes.
private Singleton()
{
}
publicstaticSingleton Instance()
{
if (_instance == null)
{
_instance = newSingleton();
}
return _instance;
}
}
• We can write below code to create instance of singleton class.
Singleton s1 = Singleton.Instance();
Singleton s2 = Singleton.Instance();
[Please note that here s1 == s2 will be true as both are referring to same object.]
• Inheritance scenarios - like multilevel inheritance with new and override keywords.
• Scenario based questions can be asked here –
• Let’s say there are 3 classes A, B and C. Class B is inheriting class A and class C is
inheriting class B.
• There will be a method which will be virtual in class A and it will be hidden by class B and C with
new keyword. Then which methods will get called with below set of objects.
• A a1 = newB();
• A a2 = newC();
• B b1 = newC();
• Same example can be replaced with override keyword or combination of new and override methods.
We have to think on the type of object and give the answers.
MODIFIED BY SHUBHAM LAMBAT
30
Aggregation
• Aggregation is a special type of association.
• It is a direct association among the objects.
• For example, departments and employees, a department has many employees but a single
employee is not associated with multiple departments. In this case both the objects have their
own life cycle. Employees may exist without a department. Here, department can be called an
owner object and the employee can be called a child object.
Composition
• Composition is special type of Aggregation.
• In this type of Aggregation, the child object does not have their own life cycle. The child object's
life depends on the parent's life cycle. Only the parent object has an independent life cycle. If we
delete the parent object then the child object(s) will also be deleted. We can define the
Composition as a "Part of" relationship.
• For example, the company and company location, a single company has multiple locations. If we
delete the company then all the company locations are automatically deleted. The company
location does not have their independent life cycle, it depends on the company object's life (parent
object).
LINQ
1) What are Lambda Expressions?
- A lambda expression is an anonymous function that can contain expressions and statements, and can
be used to create delegates or expression tree types.
- All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the
lambda operator specifies the input parameters (if any) and the right side holds the expression or
statement block.
- Ex: The => operator has the
- Lambdas are used in method-based LINQ queries e same precedence as assignment (=) and is right-
associative.
- as arguments to standard query operator methods such as Where and Where (IQueryable, String,
array []).
3) Can we write a Lambda Expression on the Left Side of the “is” or “as” Operator?
- Lambdas are not allowed on the left side of the is or as operator.
- The parentheses are optional only if the lambda has one input parameter; otherwise, they are required.
- Two or more input parameters are separated by commas enclosed in parentheses:
(x, y) => x == y
- Sometimes it is difficult or impossible for the compiler to infer the input types. When this occurs, you
can specify the types explicitly as shown in the following example:
(int x, string s) => s.Length > x
11) List out the Rules apply to Variable Scope in Lambda Expressions?
- A variable that is captured will not be garbage-collected until the delegate that references it goes
out of scope.
- Variables introduced within a lambda expression are not visible in the outer method.
- A lambda expression cannot directly capture a ref or out parameter from an enclosing method.
- A return statement in a lambda expression does not cause the enclosing method to return.
- A lambda expression cannot contain a goto statement, break statement, or continue statement whose
target is outside the body or in the body of a contained anonymous function.
- Normally you can use the SQL queries to run on the database to populate the Dataset, but you are not
able to use SQL query on a Dataset to retrieve a particular value.
- To get this you need to use ADO.NET functionalities. But, in case of LINQ, it provides more dignified
way of querying the Dataset and provides some new features as compared to ADO.NET
- N-tiers architecture usually have at least three separate logical parts, each located on separate physical
server. Each tier is responsible with specific functionality.
- Each tier is completely independent from all other tier, except for those immediately above and below
it. Communication between tiers is typically asynchronous in order to support better scalability.
- The main benefit of tier architecture styles are:
1. Maintainability. Because each tier is independent of the other tiers, updates or changes can be
carried out without affecting the application as a whole.
2. Scalability. Because tiers are based on the deployment of layers, scaling out an application is
reasonably straightforward.
3. Flexibility. Because each tier can be managed or scaled independently, flexibility is increased.
4. Availability. Applications can exploit the modular architecture of enabling systems using easily
scalable components, which increases availability.
- SingleOrDefault () :-
o It Return First Single Matching Item from Given Collection.
o It Handle Exception & Return Default Value.
o This Exception: throw Exception if no Matching item from given Collection
o It Does Not Handle Exception Of Multiple Matching Element
- Single () :-
o It Return First Single Matching Item from Given Collection
o It Throw Exception in two Scenario :
If there are multiple matching item
If no matching item from given collection
- IEnumerable: -
o It exists in System.Collection namespace.
o It can move forward only over collection.
o It is best to query data from in-memory collections like Array, List, etc.
o It is suitable for LINQ to Objects & LINQ To XML queries.
o It doesn't support lazy loading, hence not suitable for paging like scenario.
o We use IEnumerable for in memory collection like List, Dictionary
DataContextClasses db= new DataContextClasses();
IEnumerable<Employee>List = dc.Employees.Where(m=>m.Name.StartsWith("a"));
list=list.Take<Employee>(10):
- IQueryable: -
o It exists in System.Linq namespace.
o It can move forward only over collection.
o It is best to query data from out-memory like remote database.
o It is suitable for LINQ to SQL queries.
o It supports lazy loading, hence suitable for paging like scenario.
o we use IQuerable for remote servers like SQL server.
DataContextClasses db= new DataContextClasses();
IQueryable<Employee>List =dc.Employees.Where(m => m.Name.StartsWith("a")); list=list.
Take<Employee> (10);
JAVASCRIPT
1. What is JavaScript? or JavaScript is which type of Language?
It is object-based scripting language.
It is widely used for client-side validation.
It is Programming Language just like C#, Java, C++, etc.
We can use JavaScript as a client side as well as server-side language. (Using node.js)
Most of the time we use it as a client-side scripting language.
To manipulate HTML element.
To Validate User Input.
To Communicate with server-side code.
Faster Language
Disadvantages :-
JavaScript code is not secure.
Browser Combability Issue
8. What would be the difference if we declare Two Variables inside a JavaScript, one with
'var' keyword and another without 'var' keyword?
The variable with var keyword inside a function is treated as Local variable
Whereas the variable without var keyword inside a function is treated a global variable.
document.write(a + b);
})
(10,10);
2) slice ():
Same as substring () method but does not swap arguments.
3) substr ():
This method has 2 parameters Number start and Number length. {substr (index, count)}.
Start parameter is required and specifies the position where to start the extraction.
Length parameter is optional and specifies the length where the extraction end.
If value of start parameter is greater than end parameter then it does not swap the two
arguments.
2) setTimeout(func,delay) :
Executes a specified function after waiting a specified number of milliseconds.
3) clearInterval(intervalID):
Cancels the repeated execution of the method that was setup using setInterval()
method.
The JavaScript minification may reduce the size of the file by 30 to 90%.
The minification process will not change its original functionality.
Technique to compress JavaScript file.
Normal File – Home.js
Minified File – Home.min.js
Advantages:
o Reduce download time of JavaScript file on client machine before browser can execute
your JS code.
o Multiple JavaScript files can be compressed into one minified JS file.
Dis-Advantages:
o Readability is lost.
30. What are all the Types of Pop-up Boxes Available in JavaScript?
- Alert –
o Alert box displays only one button which is the OK button.
- Confirm –
o Confirmation box displays two buttons namely OK and Cancel.
- Prompt
3) Logical Errors:
These are the errors that occur due to the bad logic performed on a function which is having
different operation.
jQuery
1. What is jQuery?
jQuery is JavaScript library.
jQuery greatly simplifies JavaScript programming.
4. What is Chaining?
Chaining is used to run multiple jQuery methods (on the same element) within a single
statement.
Advantages :
It reduces the load from your server.
It saves bandwidth.
When any user visit on other website it saves in browser, as a result next time easily load.
SOLID Principle
What is SOLID Principle?
- We use to create a better application architecture.
- S SRP Single Responsibility Principle
- O OCP Open Close Principle
- L LSP Lisko Substitutions Principle
- I ISP Interface Segregation Principle
- D DIP Dependency Inversion Principle
SRP :-
o It says we should create class/interface/methods which are responsible for a single task concern.
o Or it means a class should have only one responsibility.
o Or a Class Should have only one reason to change.
o In My Project One Class is responsible for one Operation.
OCP :-
o Code Should be open for extension & closed for modification.
o To implement OCP we can use Extension Method.
LSP :-
o It Say child class object can replace parent class object always.
o Base class reference variable can point to any of its derived class object
o Object of child class must be able to replace & object of parent class without breaking
application.
o All base class method must be applicable for all the derived class. For that we can use Interface.
o Ex:-
I have 2 class in we can inherit that class.
In that base class have one method and that is virtual
In derived class can also contain same method and its override
Now if we create base class object then we can call base class method
And if we create a deriver class object then it will call derived class method.
Its work easily and we can also give output and our application is also work properly
its means we can fulfil the need of LSP.
ISP :-
o A class Should not be forced to implement Interface that does not use.
o It is better to have multiple smaller Interface than larger Interface.
o Ex.
o We crate FlyCar Class and in that we have two method drive and fly
o And if create a simple car class and inherit the FlyCar class then we have to
implement both drive and fly method and it is not good for performance.
o That’s why we create 2 different Interface 1st is Fly And 2nd is Drive.
o And now if we create simple car class then we only inherit drive interface.
o Or if we create FlyCar Class Then we Inherit both Fly & Drive Interface
DIP :-
o High level module should not directly depend on low level module instead they should
depend through abstract class or Interface.
o High Level Module or Low-level module means Concrete Class.
DESIGN Pattern
1. What is Design Pattern?
- Help to solve OOPs Problem.
- OOP - Class, Object, Inheritance, Polymorphism, Abstraction, Encapsulation, Association.
- Design Pattern talk about Code.
- Tyes Of Design Pattern :-
o Structural Design Pattern
o Creational Design Pattern
o Behavioral Design Pattern
D. IoC Container:
- Inversion of Control
- We use IoC container for
Registering Type (Dependency)
Resolving Type
- An IoC container is a framework or library that manages the dependencies between different
components in your application.
- It's responsible for instantiating objects, resolving their dependencies, and providing them to other
objects. This allows you to decouple the creation and management of objects from your application
logic.
- DI is a specific form of IoC where a component's dependencies are provided by an external entity
(often referred to as a container).
- This means that instead of a component creating its own dependencies, they are "injected" from the
outside, making components more modular, testable, and loosely coupled.
- AddScope –
o We create Object for Every Request.
o AddScope method create single instance per request.
o For every individual request there will be a single instance or object.
- AddTransient –
o AddTransient instance will not be shared at all even with in the same request.
o Every time a new instance will be Created.
ASP.NET
1. What is ASP.NET?
ASP.NET is Microsoft’s framework to build Web applications.
In ASP.NET we create aspx pages.
In ASP.Net Core, we create Razor Pages, means .cshtml.
In ASP.NET user request for physical file i.e., aspx page
A. Hidden Fields
Hidden field provides a way to store state information in the page.
Value property of the Hidden Filed is used to get or set the value.
Hidden fields value is stored as string i.e., plain text.
Scope on same Page.
C. Query strings
Query strings is a very common way to send data from one webform to
another.
Query strings are appended to the page URL.
?(Question Mark), indicates the beginning of a query string and its value.
It is possible to use more than one query string, the first query string is
specified using the ?(question mark). Subsequent query strings can be
appended to the URL using the &(ampersand) symbol.
Query strings are visible to the user, hence should not be used to send
sensitive information, unless encrypted.
To read the query string value, use Request.QueryString property.
D. Cookies
Cookies can be used to send data from one webform to another.
Cookies store at browser Side on user machine.
Response.Cookies command is used to create cookies.
Request.Cookies command is used to retrieve cookie value.
Cookies are browser specific.
Persistent Cookie:
Cookie has Expiration Time.
Non-Persistent Cookie:
These cookies expired when browser is closed.
Cookies are by default Non-Persistent.
E. ViewBag
ViewBag are used to pass data from controller to view.
ViewBag is a dynamic property collection
In ViewBag no need to type cast while reading value
Scope of ViewBag is only within single same request.
F. ViewData
ViewData are used to pass data from controller to view.
ViewData is key-value pair collection.
In ViewData Need type cast.
Scope of ViewData is only within single same request.
G. TempData
TempData is used to store the data and transfer to subsequent requests.
TempData value is cleared after subsequent requests completes.
There are Keep and Peek methods which we can use to retain value in TempData after
end of subsequent request also.
Keep() method preserves the value for next request.
Peek() method returns TempData value without clearing it from the memory.
A. Session
Session data stored in server memory.
Session state variables are available across all pages but only for a given single
session.
Session variables are like single-user global data.
Session state variables are stored on the web server.
The default session state mode is InProc.
Session State variables are cleared, when the user session times out.
The default timeout is 20 minutes. This is configurable in web.config
C. Cache
Caching is the technique of storing frequently used data/pages in memory.
D. Profile Properties
2) PostBackURL:
Add Button from Toolbox and use PostBackURL as tag.
We can’t redirect to another application page URL.
3) Server.Transfer:
Redirection done within same server.
Redirection done by the server.
URL does not change.
It skips current page and give target page content.
4) Response.Redirect:
Redirection done within same server.
Redirection done by the server.
URL does not change.
It does not skips current page and gives target page content as well as current page
content.
5) Server.Execute:
Redirection can be done across multiple servers.
Redirection done by the browser.URL get changed.
Skip current page.
6) Window.open():
To open a popup window use Window.open() method.
Window.open(URL, name, feature, replace)
<input type = “button” value = “Open Google”
onClick = “Window.open()”/>
6. .Net Invention
- WebForm (2002) .NET MVC (2009) .NET Core (Jun 2016).
8. What is Scaffolding
- It is code generation Framework for Asp.Net web application.
- It Give Code Automatically it is Known as Scaffolding.
- It gives auto Generated code.
- It reduces Developers Efforts & Time.
MVC
1. What is MVC? and its Architecture?
o MVC is an architectural pattern to design web applications.
o In MVC, M stands for Model, C stands for Controller and V stands for View.
o Every component has their own responsibilities.
o Model handles business logic and provides data to controller and view.
o View is used to render HTML.
o Controller handles user requests.
21. Can we create a View based on 2 different Models? or can we create a Strongly Typed View
based on 2 or more Models?
- Yes, we can create a view based on multiple models.
- There is various way to achieve this.
- We can use ViewBag, ViewData, PartialViews, TempData, ViewModel, Tuple to achieve this
scenario.
- Most preferred way is using ViewModel.
28. What is AJAX? can you write a Syntax for AJAX Call?
- AJAX is asynchronous JavaScript.
- Using AJAX, we can reload part of the page & it not reload full Page or Application.
- Using AJAX, we can call server code without reloading page.
- Syntax: $.ajax({
url:___, type:___, data:___,
success:function(){},
error:function(){}
});
30. Are there any other ways to Transfer more than one Models to a View?
- Yes. There is various way to achieve this.
- We can use ViewBag, ViewData, PartialViews, TempData, Tuple to achieve this scenario.
- Most preferred way is using ViewModel.
32. I have one View and that View have one Submit Button, if I click on that Submit Button how
Execution happens in MVC?
- This request will be a post request.
- This request reaches to Routing Engine and based on the parameters it selects an action method
of a controller.
- Controller takes help of model for any business logic or data.
- If action method is returning any view or any other result that will get returned to the client.
37. What are Security Threats in Application? What is Cross Site Scripting (CSS Attack)?
- Security threats means a way to access our application by any anonymous user to perform any
unauthorized activities which can harm to application data.
- There are lot of security threats and there are ways to prevent them.
- Cross Site Scripting attack is an attack where a user can inject any script through textbox or textarea
and he can execute those unwanted scripts.
- We can prevent CSS attack by giving proper validations against these input fields.
40. If I have one View which has a Button and a Div Tag. I have created a Partial View. Now on
click on that Button this Partial View should get rendered in Div Tag. Tell me Flow how will
you Write Code for This.
- I will write an AJAX call to implement this.
- I can achieve this in 2 ways writing an JQuery AJAX call or using MVC AJAX helper method.
- Firstly, I will write an action method which returns me partial view.
- Then on the main view I will call this action method using AJAX.ActionLink method
- and I will set UpdateTargetId parameter to div id.
41. How View Model Works? If I have to show 3 Models on single View, how will you Achieve that.
- Using ViewModels we can create a strongly typed view based on multiple models.
- I will create a view model and I will write all required models as properties inside this class.
- I will create a strongly typed view based on this ViewModel.
43. Suppose I have 2 Buttons on a View let’s say Add and Clear.
Then how will you write Events and Identify that which Button is Clicked?
- I will use jQuery selectors to write events for these two buttons.
- If required write action methods and I will call those action methods using AJAX call.
44. Let’s say I want to Display 1000 Records on my Site. How will you Show that?
- I will implement pagination to show 1000 of records on a page.
- In MVC we can use PagedList package to achieve pagination functionality.
47. Can one Partial View called from Another Partial View?
- Yes, one partial view can call another partial view.
53. Which Control you have used to Display Images in your Project?
- We have created custom helper class to display images in our application.
54. Can I call more than one Action Methods at Same Time in MVC?
- Yes, we can call more than one action methods at same time.
- We can write to action methods which are returning me a partial view.
- Then I can use RenderAction method on main view which will call all respective action methods.
60. What will happen if I have used HandleError Attribute and Try Catch block both in an
Action Method?
- It will not give me any compile time error
- But the error will be handled by Catch block in that case.
61. I have 2 Dropdown lists one is for State and other for City.
If I select State all Cities get shown in City dropdown list. How will write Code for this.
- I will create a ViewModel which will have List of State and City properties.
- I will add action method to controller and retrieve data for states from model.
- For this action method I will add a strongly typed view using ViewModel.
- On this View I will 2 dropdown list with the help of html helpers.
- Initially I will disable city dropdown list.
- I will add OnChange method to state dropdown list.
- If user change state, then I will write AJAX call to fetch and bind city data to city dropdown list.
62. I have a Textbox, Button and Label on a Page. If you Click on Button, entered text should
be Displayed on Label. Write a code for this.
- I will write an action method with parameter name same as textbox name.
- Then I will make a AJAX call to action method on click of button.
- OnSuccess event I will bind response to label.
- If we don’t have to hit to server then we can easily achieve this functionality using JavaScript code
writing a simple JavaScript function or jQuery selector and event.
63. How to Overload Action Methods? [This question can be asked with 2 Action Methods]
- I will use ActionName attribute where I will give same name which is used to make a request to that
action method and while writing actual method name, I will write different name there.
- So, both methods can be called with same request with different request type.
69. Can we have More than one Layouts in MVC? How will you Assign them to Views in case
of Multiple Layouts?
- Yes, we can have more than one layout in single application.
- We can assign them on view through ViewStart file or we can assign them on individual views also.
- We can give any condition to check for assigning layout to any view.
71. I have a Textbox, I want to Restrict its Character Limit to 10 Characters? How you achieve?
- We can use StringLength attribute on model property to do this type of validation.
72. I have a TextBox, I want to Allow a user to Enter their Valid Date? How can I Validate it?
- We can use DataType attribute on that field to do this validation.
- We can specify DataType.Date to this attribute as parameter.
ADO.NET
1. What is ADO.Net?
Ado.net stands Microsoft ActiveX Data Objects.
Ado.net is a set classes that can be used to interact with data sources like
database and XML.
ADO.Net, we use for database Communication.
Database can be anything like SQL, Oracle, MS Access, Excel, etc.
4. What is SqlCommand?
To Prepare & Execute Command.
SqlCommand class is used to prepare an SQL statement or Store Procedure that we
want to execute on SQL server database.
There are three methods of SqlCommand class which are commonly used:
a) ExecuteScalar – Used when query returns single value.
b) ExecuteReader – Used when query returns more than one value.
c) ExecuteNonQuery – Used when we want to perform an Insert, Update or
Delete operations.
5. What is SqlDataReader?
SqlDataReader reads data in the most efficient manner.
SqlDataReader is connection-oriented means it requires an active and open
connection to the data source while reading the data.
SqlDataAdapter :-
SqlDataAdapter provides us disconnected Oriented data access model.
It does not required connection Open or Close explicitly.
ENTITY Framework
1. Entity Framework and its Approaches?
Entity framework is used to communicate with the database.
Entity Framework approaches are
1) Database First
o Database first approach creates the entity framework from an existing
database.
2) Code First
o Code first approach create database that doesn’t exists.
o It can also be used if you have an empty database and then code first will add new tables.
3) Model First
2. Which Approach you have Used in your Project and Explain it?
We used Database first approaches as per requirement.
4. What is DbContext?
DbContext is an important class in entity framework.
DbContext is a bridge between entity classes and database.
DbContext is the primary class that is responsible for interacting with the database.
DbContextSaveChanges method executes Insert, Update and Delete commands to the
database.
5. What is Dbset?
The context class derived from DbContext must include the Dbset type properties for
the entities which maps the database table and views.
WEB API
1. What is Web API?
Web API is framework which used to develop http restful services.
Web API is service where we can write code once and consume it in any application.
In our Web API project, we wrote business logic and consume it in MVC application.
4. What is Protocol?
Protocol means guidelines or rules to communicate over internet.
A protocol refers to a set of rules and conventions that govern how data is transmitted over the
internet.
It defines the format and structure of messages exchanged between different software
components.
Ex. http - Internet
tcp - Intranet (Communicate with LAN)
namedpipe – Used when same server
msmq - To maintain que
There are several Commonly used Protocol in Web API.
o HTTP (Hypertext Transfer Protocol)
o HTTPS (Hypertext Transfer Protocol Secure)
o REST (Representational State Transfer)
o SOAP (Simple Object Access Protocol)
o WebSocket
o MQTT (Message Queuing Telemetry Transport)
10. Web API uses which of the following Open-Source Library for JSON Serialization?
Web API uses Json.NET library for JSON serialization.
HttpError
Exception Filters
HttpResponseException
Registering Exception Filters.
13. How can you Pass Multiple Complex Types in Web API?
Two methods to pass the complex types in Web API –
Using ArrayList and Newtonsoft array.
Await:
o The await keyword is used inside an async method to indicate a point at which the
method can pause its execution until a specific task is complete.
o The method will resume execution after the awaited task completes.
28. Suppose I Have Two Method with Same Name then How to call in Web API.
We can use as same name with different Parameter (it’s called Method Overloading)
Or we can use Action Name Attribute.
Or we can use Rout Attribute in that we can use different URL to call that method.
200 – OK
201 – Created
204 – No Content
For example, in a RESTful Web API for a social media platform, you might have endpoints like:
GET /users: Retrieve a list of all users.
GET /users/{id}: Retrieve a specific user by their ID.
POST /users: Create a new user.
PUT /users/{id}: Update an existing user.
DELETE /users/{id}: Delete a user.
Web API endpoints are fundamental to building APIs that allow clients to interact with the API and
perform various operations on resources.
UNIT Testing
1. What Is Unit Testing?
- Testing is a process to where each unit or component of an application is tested to determine
whether it is fit to use or not
- A single unit is any block of code either method or a class that has one responsibility
- A C# method can have multiple unit tests according to its uses and different outputs of that
method
ANGULAR
1. What is Angular? Why was it Introduced?
- Angular was introduced to create Single Page applications.
- It is a front-end framework to develop web application or mobile application.
- This framework brings structure and consistency to web applications
- Provides excellent scalability and maintainability.
- Angular is an open-source, JavaScript framework wholly written in TypeScript.
- It uses HTML's syntax to express your application's components clearly.
2. What is TypeScript?
- TypeScript is a superset of JavaScript that offers excellent consistency.
- Developed by Microsoft, its first version released in 2012.
- TypeScript code compiles down to JavaScript that can run efficiently in any environment.
- TypeScript contains all features of JavaScript along with its own feature.
- Today Typescript is used as a main language for front end frameworks like Angular, React, VueJS.
- Typescript is free and open-source programming language
- Typescript is Object Oriented Programming language which supports type safety, data types,
classes, interfaces, inheritance, modules etc.
3. What is Data Binding? Which type of Data Binding does Angular Deploy?
- Data binding is the way to communicate between your typescript code of your component
and your HTML view.
Mobile support Not supported by mobile browsers Supports all popular mobile browsers
Dependency
Doesn’t support Supports
Injection
Difficult to manage with an increase in Better structured, easy to create and manage
Management
source code size bigger applications
- Built in pipes
a. uppercase
b. lowercase
c. titlecase
d. currency
e. date
f. number/ decimal
g. json
- Custom Pipe
o Promises –
They emit a single value at a time.
execute immediately after creation and are not cancellable.
They are Push errors to the child promises.
o Observables –
They are only executed when subscribed to them using the subscribe() method.
They emit multiple values over a period of time.
They help perform operations like forEach, filter, and retry, among others.
They deliver errors to the subscribers.
When the unsubscribe() method is called, the listener stops receiving further values.
- “Let item” creates a local variable that will be available in the template
- “Of items” indicates that we are iterating over the items iterable.
- The * before ngFor creates a parent template.
- Lazy loading dynamically loads the feature modules when there's a demand.
- This makes the application faster.
- It is used for bigger applications where all the modules are not required at the start of the
application.
- Angular applications are also very scalable, as they can be divided into small modules that can be
loaded independently of each other.
- This means that an Angular application can be easily extended with new functionality without
having to rewrite the entire application.
- Overall, Angular applications are very fast, responsive, and scalable.
- They are easy to develop and extend, and provide a great user experience.
49. What Happens when we Use the Script tag Within a Template?
- Using the script tag within an Angular template is not a recommended practice.
- Angular templates are intended for defining the structure and layout of the user interface, and
including scripts directly within the template goes against the separation of concerns principle.
- When a script tag is used within a template, the browser treats it as part of the HTML content and
attempts to execute it.
- However, Angular's template compiler does not process or execute scripts within templates.
- Instead, scripts should be placed in separate JavaScript files and included using the appropriate
Angular mechanisms, such as component logic or Angular modules.
COMPANY QA
1. What Is SDLC
- Software development lifecycle
- It’s a process to develop and deliver any application / website/ software
- Phases :-
o Requirement Gathering
o Analysis
o Design
o Coding
o Testing
o Production/ Live
o Maintenance & Support
2. Coding Standards
- Code Analysis
o Naming conventions
o Performance
o Security
o Scalability
o Maintainability
o Two ways
During development time/ coding time using FxCop Tool
After commit/ check in using tools like SonarCube
- Code Metrics
o Maintainability Index
o Cyclomatic Complexity
o Depth Of Inheritance
o Class Coupling
o Lines of code
- Code Coverage
o How much written code is covered by test cases
- *code changes, commit, push, pull request required in case of code review comment
- Reviewer will merge changes from your branch to main/ base branch
GIT Branches
- Master Branch
o No direct commit
o Deployments done from this branch
- Release Branch
o Release specific branches
- Hotfix Branch
o Any escalation/ ticket/ incident fix on live environment
- Feature Branch (multiple)
o Feature means authentication, payment, etc.
- Developer specific branch for task completion
5. What is JIRA
- Project management tool
- Jira Software provides planning and tracking tools so teams can manage dependencies, feature
requirements, and stakeholders from day one.
- CI/CD integrations facilitate transparency throughout the software development life cycle.
- Here are some of the key reasons why organizations use Jira:
o Issue Tracking: Jira excels at tracking tasks, bugs, user stories, and other types of issues
in a project. It provides a centralized platform for teams to create, prioritize, assign, and
resolve tasks efficiently.
o Workflow Management: Jira allows you to define customized workflows that reflect
your team's specific processes. This helps in visualizing and managing the entire lifecycle
of a task or project, from creation to completion.
o Agile Project Management: Jira provides robust support for Agile methodologies like
Scrum and Kanban. It helps teams plan and manage sprints, backlog, and iterations,
making it an ideal tool for Agile development practices.
o User Story Management: For Agile teams, Jira allows you to create and manage user
stories, epics, and other backlog items. This helps in breaking down larger tasks into
smaller, manageable pieces.
o Sprint Planning: Teams can use Jira to plan and manage their sprints, set sprint goals,
estimate story points, and allocate tasks to team members.
o Scalability: Jira can be used by small teams as well as large enterprises. It can scale to
accommodate the needs of complex, multi-team projects.
o Traceability and Auditability: Jira provides a detailed history of all changes made to
issues, which can be important for compliance, auditing, and debugging purposes.
o Prioritization and Backlog Management: Teams can use Jira to prioritize tasks based
on factors like urgency, business value, or dependencies. This helps in ensuring that the
most critical work is addressed first.
o Release Management: Jira allows teams to plan and track releases, manage versioning,
and link issues to specific releases. This helps in coordinating development efforts
towards specific milestones.
7. What is IIS?
- Internet Information Service.
- It is simply redirecting request to kestrel server
- No need to install it separately, we get IIS installed with windows machine.
- IIS is use to host/deploy application like dot net, java, angular, web API etc.
- It is not responsible for running dot net core application.
- To Enable IIS
o Turn windows feature ON/OFF
o Check IIS option & save.
- To Host application in IIS
o Publish Code
o Host in IIS
o For hosting we need to install Hosting Bundle.
- Default Port Number
o http – 80
o https – 443
- Application Pool
o Provide identity to run the application.
o By Default Identity:
LocalService
LocalSystem
NetworkService
ApplicationPoolIdentity
It Create a new Identity for application-by-application Name.
PROGRAMS
1. How to Delete Duplicates Rows from Table.
with cte
as
(
select Name,
ROW_NUMBER() over (partition by Name order by Name) As
RowNumber from sample1
)
delete from cte
where RowNumber >1
2. How to Find 4th Highest Salary from Employees Table (Explain Different Ways).
Console.ReadLine();
}
- 2nd Way:
static void Main()
{
string originalString = "Shubham";
string reversedString = ReverseString(originalString);
- 3rd Way:
public static void Main(string[] args)
{
string input = "Shubham";
string reversed = ReverseString(input);
Console.WriteLine(reversed);
start++;
end--;
}
return new string(charArray);
}
x = x + y;
y = x - y;
x = x - y;
Console.ReadLine();
}
}
Console.ReadLine();
}
using System;
using System.Linq;
class Program
{
static void Main()
{
string strName = "Shubham Lambat";
Console.ReadLine();
}
}
// throw; // If you want to run Outer Exception also the Uncomment “throw” Keyword
}
}
catch(Exception ex)
{
Console.WriteLine(" Outer Exception ");
}
Console.ReadLine();
}
class B : A
{
public override void print()
{
Console.WriteLine("Print B");
}
}
static void Main()
{
A a1 = new A();
a1.print(); //Print A
A a2 = new B();
a2.print(); //Print B
B b1 = new B();
b1.print(); //Print B
.
B b2 = new A();
b2.print(); //Error
// This will give an error because you're trying to assign an instance of A to a variable of type B
}
}
class Vehicle
{
public void Start()
{
Console.WriteLine("Vehicle started");
}
}
class Car : Vehicle
{
public void Drive()
{
Console.WriteLine("Car is driving");
}
}
class SportsCar : Car
{
public void Race()
{
Console.WriteLine("Sports car is racing");
}
}
o Example -
interface IDriveable
{
void Drive();
}
interface IFlyable
{
void Fly();
}
class Car : IDriveable
{
public void Drive()
{
Console.WriteLine("Driving a car...");
}
}
Ref Parameter:
- Ref is used to pass arguments by reference.
- This means that any changes made to the parameter inside the method will also affect the original
variable outside the method.
- Scenario:
o When you want to pass a variable to a method, allow the method to modify it, and have
those modifications reflected in the calling code.
- Example:
void ModifyValue(ref int x)
{
x = x + 5;
}
// Usage
int number = 10;
ModifyValue(ref number);
Console.WriteLine(number); // Output: 15
- In this example, ModifyValue takes an int parameter x by reference. It adds 5 to x, which will
affect the original number variable because it was passed by reference using the ref keyword.
MODIFIED BY SHUBHAM LAMBAT
102
Out Parameter:
- Out is used when you want a method to return multiple values.
- The out parameter must be assigned a value inside the method before it returns.
- Scenario:
o When you need a method to return more than one value and you don't want to use a return
statement for each value.
- Example:
void GetValues(out int x, out int y)
{
x = 10;
y = 20;
}
// Usage
int firstValue, secondValue;
GetValues(out firstValue, out secondValue);
Console.WriteLine(firstValue); // Output: 10
Console.WriteLine(secondValue); // Output: 20
Key Points:
- When using Ref, the variable must be initialized before being passed to the method.
- When using Out, the variable does not need to be initialized before being passed to the method,
but it must be assigned a value inside the method.
- Out parameters are not required to be initialized by the caller before being passed to the method.
The method is responsible for initializing them.
- Both Ref and Out are useful in scenarios where you need to pass and modify variables in a
method, but they serve slightly different purposes.
int.TryParse
- int.TryParse attempts to convert a string representation of a number to an integer.
- If successful, it returns true and assigns the converted value to an output parameter.
- If the conversion fails, it returns false and assigns a default value (usually 0) to the output
parameter.
- Scenario:
o When you're not sure if the input string can be successfully converted to an integer, and
you want to handle conversion failures without throwing an exception.
- Example:
int.Parse
- int.Parse attempts to convert a string representation of a number to an integer. If successful, it
returns the converted value.
- If the conversion fails (e.g., if the input string is not a valid number), it throws a FormatException.
- Scenario:
o When you're confident that the input string will be a valid integer, and you want to get the
converted value directly.
o If the conversion fails, an exception will be thrown.
- Example:
string input = "123";
int number = int.Parse(input);
Console.WriteLine("Conversion successful. Value: " + number);
- In this example, the string "123" is successfully converted to an integer using int.Parse.
- Since we're confident that the input is valid, we use int.Parse directly.
- If the input was not a valid number, a FormatException would be thrown.
17. Write a program to find whether the given input is prime or not.
static bool IsPrime(int number)
{
if (number < 2)
return false;
return true;
}
static void Main()
{
Console.Write("Enter a number: ");
int num = Convert.ToInt32(Console.ReadLine());
if (IsPrime(num))
Console.WriteLine(num + " is a prime number.");
else
Console.WriteLine(num + " is not a prime number.");
}
18. Write a Program to Print all Prime Numbers till Target. (take target from user)
class Program
{
static void Main()
{
Console.Write("Enter a target number: ");
int target = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Prime numbers up to " + target + ":");
for (int i = 2; i <= target; i++)
{
bool isPrime = true;
for (int j = 2; j <= i/2; j++)
{
if (i % j == 0)
{
isPrime = false;
break;
}
}
if (isPrime)
Console.Write(i + " ");
}
Console.WriteLine();
}
}
19. Write a program for coffee shop. display menu to user - Please choose coffee size 1-Small
2-Medium 3-Large Total bill amount
class Program
{
static void Main()
{
DisplayMenu();
if (sum == originalNumber)
Console.WriteLine(originalNumber + " is an Armstrong number.");
else
Console.WriteLine(originalNumber + " is not an Armstrong number.");
Console.ReadLine();
}
}
21. Write a program which take input from user - print 'THREE' if that number is divisible by
3. print 'FIVE' if that number is divisible by 5. print 'THREEFIVE' if that number is
divisible by 3 & 5 both.
class Program
{
static void Main()
{
Console.Write("Enter a number: ");
int number = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Original Array:");
PrintArray(arr);
ReverseArray(arr);
Console.WriteLine("\nReversed Array:");
PrintArray(arr);
}
left++;
right--;
}
}
static void PrintArray(int[] arr)
{
foreach (int num in arr)
{
Console.Write(num + " ");
}
Console.WriteLine();
}
}
23. Write a program to print below series: (easy with 2 for loops but try with single for loop)
if input is 4 - o/p - 1 3 2 4 Also if input is 5 o/p - 1 3 5 2 4
class Program
{
static void Main()
{
Console.Write("Enter a number: ");
int n = Convert.ToInt32(Console.ReadLine());
for (int i = 1; i <= n; i++)
{
int num;
if (i % 2 == 0)
num = (n / 2) + (i / 2);
else
num = (i / 2) + 1;
Console.Write(num + " ");
}
}
}
Console.WriteLine("Original Array:");
PrintArray(arr);
// Bubble Sort
for (int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
// Swap arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
Console.WriteLine("\nSorted Array:");
PrintArray(arr);
}
static void PrintArray(int[] arr)
{
foreach (int num in arr)
{
Console.Write(num + " ");
}
Console.WriteLine();
}
}
Console.WriteLine("Fibonacci Series:");
PrintFibonacciSeries(count);
}
}
27. Write a program to find second highest number from array. (This program should be able
to change for nth highest number)
class Program
{
static void Main()
{
int[] arr = { 12, 45, 78, 23, 56, 89, 34, 67 };
int n = 2; // Change this to find the nth highest number
// Removing an element
numberList.Remove(20);
Dictionary:
- A dictionary is a collection of key-value pairs. It allows you to store and retrieve values based on
a unique key.
Example:
using System.Collections.Generic;
class Program
{
static void Main()
{
// Creating a dictionary of strings (key) and integers (value)
Dictionary<string, int> studentGrades = new Dictionary<string, int>();
// Updating a value
studentGrades["Jane"] = 95;
29. Write a Program for Method Overloading & Method Overriding & Method Hiding.
- Method Overloading:
class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
class Program
{
static void Main()
{
Calculator calculator = new Calculator();
- Method Overriding:
class Shape
{
public virtual void Draw()
{
Console.WriteLine("Drawing a shape");
}
}
class Circle : Shape
{
class Program
{
static void Main()
{
Shape shape = new Shape();
shape.Draw(); // Output: "Drawing a shape"
- Method Hiding:
class Shape
{
public void Draw()
{
Console.WriteLine("Drawing a shape");
}
}
class Program
{
static void Main()
{
Shape shape = new Shape();
shape.Draw(); // Output: "Drawing a shape"
}
}
30. I Have one Interface in that there are Three Method and i will Implemented it in one class
but I want to Implement only Two Method how can I do in c#.
- Default Implementation (C# 8 and later):
o In C# 8.0 and later versions, you can provide a default implementation for interface
methods.
o This allows you to implement them in the interface itself, providing a fallback
implementation that can be used by classes that don't explicitly implement the method.
interface IExample
{
void Method1();
void Method2();
void Method3()
{
Console.WriteLine("Default Method3 implementation");
}
}
- Throw NotImplementedException:
o You can throw a NotImplementedException in the method you don't want to implement.
o This indicates that the method is intentionally not implemented.
class MyClass : IExample
{
public void Method1()
{
Console.WriteLine("Method1 implementation");
}
public void Method2()
{
Console.WriteLine("Method2 implementation");
}
public void Method3()
{
throw new NotImplementedException();
}
}
31. Explain with Example First and FirstOrDefault, Single & SingleOrDefault
First –
- First returns the first element in a sequence that satisfies a given condition.
- If no element satisfies the condition, it will throw an exception.
- Ex:
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 1, 3, 5, 7, 9, 11 };
int firstOdd = numbers.First(n => n % 2 != 0);
Console.WriteLine("First odd number: " + firstOdd);
}
}
FirstOrDefault –
- FirstOrDefault is similar to First, but if no element satisfies the condition, it returns the default
value for the type (e.g., 0 for integers, null for reference types).
- Ex:
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 2, 4, 6, 8, 10 };
int firstOdd = numbers.FirstOrDefault(n => n % 2 != 0);
Console.WriteLine("First odd number: " + firstOdd);
}
}
Single –
- Single returns the only element in a sequence that satisfies a given condition.
- If there is more than one element that satisfies the condition or no elements match the condition, it
throws an exception.
- Ex:
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 1, 3, 5, 7, 9, 11 };
int singleElement = numbers.Single(n => n == 7);
Console.WriteLine("Single element: " + singleElement);
}
}
SingleOrDefault
- SingleOrDefault is similar to Single, but if there are no elements or more than one element that
satisfies the condition, it returns the default value for the type (e.g., 0 for integers, null for
reference types).
- Ex:
using System.Linq;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> numbers = new List<int> { 2, 4, 6, 8, 10 };
int singleElement = numbers.SingleOrDefault(n => n == 7);
Console.WriteLine("Single element: " + singleElement);
}
}
32. I have collection of Persons I want to check person leave in Pune using LINQ Query
using System.Collections.Generic;
using System.Linq;
class Person
{
public string Name { get; set; }
public string Location { get; set; }
public bool HasTakenLeave { get; set; }
}
class Program
{
static void Main()
{
List<Person> persons = new List<Person>
{
new Person { Name = "John", Location = "Pune", HasTakenLeave = true },
new Person { Name = "Jane", Location = "Mumbai", HasTakenLeave = false },
new Person { Name = "Bob", Location = "Pune", HasTakenLeave = true },
new Person { Name = "Alice", Location = "Delhi", HasTakenLeave = true },
};
var personsInPune = persons.Where(p => p.Location == "Pune" && p.HasTakenLeave);
// Instead Of Where we can use Any
33. I have Class B & class C and in that two class there are 2 Same Name method also and C : B
in B class method we declare I variable and C class method use this I variable then if we
create an object of C class then which method get called
class B
{
protected int i = 10;
public virtual void Display()
{
Console.WriteLine("Method in class B");
}
}
class C : B
{
public override void Display()
{
Console.WriteLine("Method in class C");
Console.WriteLine("Value of i from class B: " + i);
}
}
static void Main()
{ // Output
C objC = new C(); // Method in class C
objC.Display(); // Value of i from class B: 10
34. I have Emp table in that there is a Name, also I have Address table in that there is a address.
Find emp who's have more than one address