Dot Net Notes 1
Dot Net Notes 1
.NET is a set of technologies designed to transform the internet into a full scale distributed platform.
It provides new ways of connecting systems, information and devices through a collection of web
services. It also provides a language independent, consistent programming model across all tiers of
an application.
The goal of the .NET platform is to simplify web development by providing all of the tools and
technologies that one needs to build distributed web applications.
The .NET Framework has two main components: the common language runtime (CLR) and .NET
Framework class library. The CLR is the foundation of the .NET framework and provides a common
set of services for projects that act as building blocks to build up applications across all tiers.
What is CLR?
The .NET Framework provides a runtime environment called the Common Language Runtime or CLR.
The CLR can be compared to the Java Virtual Machine or JVM in Java. CLR handles the execution of
code and provides useful services for the implementation of the program. In addition to executing
code, CLR provides services such as memory management, thread management, security
management, code verification, compilation, and other system services. It enforces rules that in turn
provide a robust and secure execution environment for .NET applications.
What is CTS?
Common Type System (CTS) describes the datatypes that can be used by managed code. CTS defines
how these types are declared, used and managed in the runtime. It facilitates cross- language
integration, type safety, and high performance code execution. The rules defined in CTS can be used
to define your own classes and values.
What is CLS?
PGDAC-MS.Net Page 1
Common Language Specification (CLS) defines the rules and standards to which languages must
adhere to in order to be compatible with other .NET languages. This enables C# developers to inherit
from classes defined in VB.NET or other .NET compatible languages.
CLR and CTS advantages
Language interoperability
Code reusability
Faster development.
What is MSIL?
When the code is compiled, the compiler translates your code into Microsoft intermediate language
(MSIL). MSIL is understood by any environment where .Net framework is installed i.e.write once run
anywhere. It is platform independent. MSIL is a part of assembly. The common language runtime
includes a JIT compiler for converting this MSIL then to native code.
MSIL contains metadata that is the key to cross language interoperability. Since this metadata is
standardized across all .NET languages, a program written in one language can understand the
metadata and execute code, written in a different language.
What is JIT?
JIT(Just in time) is a compiler that converts MSIL to native code JIT is a part of CLR. The nativecode
consists of hardware specific instructions that can be executed by the CPU.
Rather than converting the entire MSIL (in a portable executable[PE]file) to native code, the JIT
converts the MSIL as it is needed during execution. This converted native code is stored so that it is
accessible for subsequent calls. This quality makes it faster compiler.
PGDAC-MS.Net Page 2
How does an AppDomain get created?
AppDomains are usually created by hosts. Examples of hosts are the Windows Shell, ASP.NET and IE.
When you run a .NET application from the command-line, the host is the Shell. The Shellcreates a
new AppDomain for every application. AppDomains can also be explicitly created by
.NET applications.
What is an assembly?
An assembly is a collection of one or more .exe or dll’s. An assembly is the fundamental unit for
application development and deployment in the .NET Framework. An assembly contains a collection
of types and resources that are built to work together and form a logical unit of functionality. An
assembly provides the CLR with the information it needs to be aware of type implementations.
1.Assembly manifest - Contains the assembly metadata. An assembly manifest contains the
information about the identity and version of the assembly. It also contains the information
required to resolve references to types and resources.
2.Type metadata - Binary information that describes a program.
Microsoft intermediate language (MSIL) code.
A set of resources.
We also have satellite assemblies that are often used to deploy language-specific resources for an
application.
PGDAC-MS.Net Page 3
You need to assign a strong name to an assembly to place it in the GAC and make it globally
accessible. A strong name consists of a name that consists of an assembly's identity (text name,
version number, and culture information), a public key and a digital signature generated over the
assembly. The .NET Framework provides a tool called the Strong Name Tool (Sn.exe), which allows
verification and key pair and signature generation.
What is GAC? What are the steps to create an assembly and add it to the GAC?
The global assembly cache (GAC) is a machine-wide code cache that stores assemblies specifically
designated to be shared by several applications on the computer. You should share assemblies by
installing them into the global assembly cache only when you need to.
Steps
- Create a strong name using sn.exe tool eg: sn -k mykey.snk
- in AssemblyInfo.cs, add the strong name eg: [assembly: AssemblyKeyFile("mykey.snk")]
- recompile project, and then install it to GAC in two ways :
· drag & drop it to assembly folder (C:\WINDOWS\assembly OR C:\WINNT\assembly)
(shfusion.dll tool)
· gacutil -i abc.dll
PGDAC-MS.Net Page 4
in the he ap stays intact.
Dispose Finalize
It is used to free unmanaged resources at any It can be used to free unmanaged resources held by
time. an object before that object is destroyed.
What is Finalizer?
inalizers (which are also called destructors) are used to perform any necessary final clean-up
when a class instance is being collected by the garbage collector.
Remarks
• Finalizers cannot be defined in structs. They are only used with classes.
• A class can only have one finalizer.
• Finalizers cannot be inherited or overloaded.
• Finalizers cannot be called. They are invoked automatically.
PGDAC-MS.Net Page 5
• A finalizer does not take modifiers or have parameters.
This means that the Finalize method is called recursively for all instances in the inheritance
chain, from the most-derived to the least-derived.
The programmer has no control over when the finalizer is called because this is determined by
the garbage collector.
Explicit release of resources
If your application is using an expensive external resource, we also recommend that you
provide a way to explicitly release the resource before the garbage collector frees the object.
You do this by implementing a Dispose method from the IDisposable interface that performs the
necessary cleanup for the object. This can considerably improve the performance of the
application. Even with this explicit control over resources, the finalizer becomes a safeguard to
clean up resources if the call to the Dispose method failed.\
WHAT IS DELEGATE?
A delegate is reference type that basically encapsulates the reference of methods. It is a similarto
class that store the reference of methods which have same signature as delegate has.
It is very similar to a function pointer in C++, but delegate is type safe, object oriented and
secure as compare to C++ function pointer.
When we are going to call this method using Delegate for callback, only need to pass this
method name as a reference.
PGDAC-MS.Net Page 8
Attributes have the following properties:
• Attributes add metadata to your program. Metadata is information about the types
defined in a program.
• You can apply one or more attributes to entire assemblies, modules, or smaller program
elements such as classes and properties.
• Attributes can accept arguments in the same way as methods and properties.
• Your program can examine its own metadata or the metadata in other programs by using
reflection.
There are two types of attributes:
1. Predefined attributes: these are provided by FCL. Ex. Obsolete, Serializable,
Conditional etc.
2. Custom attributes: these are developed by developers as per the requirements.
Note: All the attributes are derived directly or indirectly from System.Attribute class.
AttributeTargets Member
In the previous example, AttributeTargets.All is specified, indicating that this attribute can be
applied to all program elements. Alternatively, you can specify AttributeTargets.Class, indicating
that your attribute can be applied only to a class, or AttributeTargets.Method, indicating that
your attribute can be applied only to a method. All program elements can bemarked for
description by a custom attribute in this manner.
You can also pass multiple AttributeTargets values. The following code fragment specifies
that acustom attribute can be applied to any class or method.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
Inherited Property
The AttributeUsageAttribute.Inherited property indicates whether your attribute can be
inherited by classes that are derived from the classes to which your attribute is applied. This
property takes either a true (the default) or false flag. In the following
PGDAC-MS.Net Page 9
AllowMultiple Property
The AttributeUsageAttribute.AllowMultiple property indicates whether multiple instances ofyour
attribute can exist on an element. If set to true, multiple instances are allowed; if set to false(the
default), only one instance is allowed.
If both the AllowMultiple property and the Inherited property are set to true, a class that is inherited
from another class can inherit an attribute and have another instance of the same attribute applied in the
same child class. If AllowMultiple is set to false, the values of any attributes in the parent class will be
overwritten by new instances of the same attribute in thechild class.
Declaring Constructors
Attributes are initialized with constructors in the same way as traditional classes. The followingcode
fragment illustrates a typical attribute constructor. This public constructor takes a parameter and
sets a member variable equal to its value.
public MyAttribute(bool myvalue)
{
this.myvalue = myvalue;
}
You can overload the constructor to accommodate different combinations of values. If you also
define a property for your custom attribute class, you can use a combination of named and
positional parameters when initializing the attribute.. Note that in Visual Basic, constructors for an
attribute class should not use a ParamArray argument.
Declaring Properties
If you want to define a named parameter or provide an easy way to return the values stored byyour
attribute, declare a property. Attribute properties should be declared as public entities with a
description of the data type that will be returned. Define the variable that will hold the value of
your property and associate it with the get and set methods. The following code example
demonstrates how to implement a simple property in your attribute.
public bool MyProperty
PGDAC-MS.Net Page 10
{
get {return this.myvalue;}
set {this.myvalue = value;}
}
What is reflection?
Reflection provides objects (of type Type) that describe assemblies, modules and types. You can use
reflection to dynamically create an instance of a type, bind the type to an existing object, or get the
type from an existing object and invoke its methods or access its fields and properties. If you are
using attributes in your code, reflection enables you to access them.
Uses for Reflection C#
1. Use Module to get all global and non-global methods defined in the module.
2. Use MethodInfo to look at information such as parameters, name, return type, access
modifiers and implementation details.
3. Use EventInfo to find out the event-handler data type, the name, declaring type and
custom attributes.
4. Use ConstructorInfo to get data on the parameters, access modifiers, and implementation
details of a constructor.
5. Use Assembly to load modules listed in the assembly manifest.
6. Use PropertyInfo to get the declaring type, reflected type, data type, name and writable
status of a property or to get and set property values.
Other uses for Reflection include constructing symbol tables, to determine which fields to
persist and through serialization.
File Handling in C#
All the objects created at runtime reside on heap section primary memory. Once they are out of
scope the objects are released by garbage collector. So the data stored in an object cannot be
reused once the program is terminated. Therefore we store the data on secondary storage devices
in the form of file. File handling is an unmanaged resource in your application system. It is outside
your application domain (unmanaged resource). It is not managed by CLR.
What is a stream?
A stream is a sequence of bytes. In the file system, streams contain the data that is written to a file,
and that gives more information about a file than attributes and properties. When you open a file
for reading or writing, it becomes stream. Stream is a sequence of bytes traveling from a source to a
PGDAC-MS.Net Page 11
destination over a communication path. The two basic streams are input and output streams. Input
stream is used to read and output stream is used to write. The System.IO namespace
includes various classes for file handling.
Stream is the abstract base class of all streams. A stream is an abstraction of a sequence of bytes,
such as a file, an input/output device, an inter-process communication pipe, or a TCP/IP socket. The
Stream class and its derived classes provide a generic view of these different types of input and
output, and isolate the programmer from the specific details of the operating system and the
underlying devices.
As shown in the picture above, FileStream is byte oriented. But if we want to read and write
characters then we need character reader and writer streams .
PGDAC-MS.Net Page 12
TextReader is the abstract base class of StreamReader and StringReader, which read characters from
streams and strings, respectively. Use these derived classes to open a text file for reading a
specified range of characters, or to create a reader based on an existing stream.
TextWriter is the abstract base class of StreamWriter and StringWriter, which write characters to
streams and strings, respectively. Create an instance of TextWriter to write an object to a string,
write strings to a file, or to serialize XML.
The BinaryReader class is used to read binary data from a file. A BinaryReader object is createdby
passing a FileStream object to its constructor.
The BinaryWriter class is used to write binary data to a stream. A BinaryWriter object is created
by passing a FileStream object to its constructor.
What is Serialization?
Serialization is converting object to stream of bytes. It is a process of bringing an object into aform
that it can be written on stream. It's the process of converting the object into a form so that it can be
stored on a file, database or memory. It is transferred across the network. Mainpurpose is to save
the state of the object.
What is deserialization?
Deserialization is converting stream of byte to object. Deserialization is the reverse process of
serialization. It is the process of getting back the serialization object (so that) it can be loaded into
memory. It lives the state of the object by setting properties, fields etc.
XML Serialization
XML serialization allows the public properties and fields of an object to be reduced to an XML
document that describes the publicly visible state of the object. This method serializes only public
properties and fields—private data will not be persisted, so XML serialization does not provide full
fidelity with the original object in all cases. However, because the persistence
PGDAC-MS.Net Page 13
format is XML, the data being saved can be read and manipulated in a variety of ways and on
multiple platforms.
Easy to implement. Does not require any custom serialization-related code in the object to be
serialized.The XML Schema Definition tool (xsd.exe) can generate an XSD Schema from a set of
serializable classes, and generate a set of serializable classes from an XSD Schema, making it easy to
programmatically consume and manipulate nearly any XML data in an object-oriented (rather than
XML-oriented) fashion.
Objects to be serialized do not need to be explicitly configured for serialization, either by the
SerializableAttribute or by implementing the ISerializable interface.
The restrictions of XML serialization include the following:
SOAP Serialization
SOAP serialization is similar to XML serialization in that the objects being serialized are persisted as
XML. The similarity, however, ends there. The classes used for SOAP serialization reside in
theSystem.Runtime.Serialization namespace rather than the System.Xml.Serializationnamespace
used by XML serialization. The run-time serialization classes (which include both the SoapFormatter
and the BinaryFormatter classes) use a completely different mechanism for serialization than the
XmlSerializer class.
PGDAC-MS.Net Page 14
Binary Serialization
Binary serialization allows the serialization of an object into a binary stream, and restoration from a
binary stream into an object. This method can be faster than XML serialization, and the binary
representation is usually much more compact than an XML representation. However, this
performance comes at the cost of cross-platform compatibility and human readability.
Supports either objects that implement the ISerializable interface to control its own serialization, or
objects that are marked with the SerializableAttribute attribute.
DotNet ADO.NET
Application (Data Access DB
Mechanism)
software components providing data access services.
ADO.NET is designed to enable developers to write managed code for access to data sources, which
can be relational or non-relational (such as XML or application data). This feature of ADO.NET
Helps to create data-sharing, distributed applications. ADO.NET provides connected access to a
database connection using the .NET-managed providers and disconnected access using datasets,
which are applications using the database connection only during retrieval of data or for data
update. Dataset is the component helping to store the persistent data in memory to provide
disconnected access for using the database resource efficiently and with better scalability.
The architecture of ADO.NET is based on two primary elements:
Oracle
MySQL
DataSet
The huge mainstream of applications built today involves data manipulation in some way -- whether
it be retrieval, storage, change, translation, verification, or transportation. For an application to be
scalable and allow other apps to interact with it, the app will need a common mechanism to pass the
data around. Ideally, the vehicle that transports the data should contain the base data, any related
data, and metadata, and should be able to track changes to the data.Here's where the ADO.NET
There are two ways of Data access mechanisms.
1.Connected Architecture 2.Disconnected Architecture
Connected Architecture
PGDAC-MS.Net Page 16
.Net Provider
Connection
Command
DB
DataReader
The Connection objects define the data provider, database manager instance, database,security
credentials, and other connection-related properties.Important methods of connection object
Open() - Opens a database connection with the property settings specified bythe
ConnectionString.
Close() - Closes the database connection.
The Command object works with the Connection object and used to execute SQL queries or Stored
Procedures against the data source. You can perform insert, update, delete, and select operations
with this object. It requires an instance of a Connection Object for executing the SQL statements as
Steps for executing SQL query with command object
1.Create a Connection Object and initialize with connection string.
2.Create the command object and initialize with SQL query and connection object.
3.Open the connection.
4.Execute query with the help of any one method of command object.
5.Store the result in DataReader object (In case of select SQL query)
6.Close the connection.
PGDAC-MS.Net Page 17
Important method of command object
ExecuteReader: This method works on select SQL query. It returns the DataReader object. UseDataReader
read () method to retrieve the rows.
ExecuteScalar: This method returns single value. Its return type is Object. When you want
single value (First column of first row), then use ExecuteScalar () method. Extra columns or rows
are ignored. ExecuteScalar method gives better performance if SQL statements have aggregate
function.
ExecuteNonQuery: If you are using Insert, Update or Delete SQL statement then use thismethod.
Its return type is Integer (The number of affected records).
ExecuteXMLReader: It returns an instance of XmlReader class. This method is used to returnthe
result set in the form of an XML document.
For initializing the DataReader object, call the ExecuteReader method of the Command object.It
returns an instance of the DataReader.
SqlCommand cmd = new SqlCommand("Your SQL query", conn);
SqlDataReader readerObj = cmd.ExecuteReader();
Once your task completed with the data reader, call Close() method to close the dataReader.
readerObj.Close();
PGDAC-MS.Net Page 18
Important properties of DataReader object
FieldCount: It provides the number of columns in the current row.
HasRows: It provides information that, whether data reader contains row or not.
IsClosed: It indicates that whether data reader is closed or not.
RecordsAffected: Returns the number of affected records.
You can also get the value of particular column of the table by using the data reader object.
Disconnected Architecture
A connected mode of operation in ADO.Net is one in which the connection to the underlyingdatabase is
alive throughout the lifetime of the operation. Meanwhile, a disconnected mode of operation is one in
which ADO.Net retrieves data from the underlying database, stores the data retrieved temporarily in the
memory, and then closes the connection to the database.
The architecture of ADO.net in which data retrieved from database can be accessed even when
connection to database was closed is called as disconnected architecture. Disconnected architecture
of ADO.net was built on classes connection, dataadapter, commandbuilder and dataset and
dataview.
Connection : Connection object is used to establish a connection to database and connectionit self
will not transfer any data.
DataAdapter : DataAdapter is used to transfer the data between database and dataset. It has
commands like select, insert, update and delete. Select command is used to retrieve data
from database and insert, update and delete commands are used to send changes to the datain
dataset to database. It needs a connection to transfer the data.
PGDAC-MS.Net Page 19
CommandBuilder : by default dataadapter contains only the select command and it doesn’tcontain
insert, update and delete commands. To create insert, update and delete commands for the
dataadapter, commandbuilder is used. It is used only to create these commands for the dataadapter
and has no other purpose.
DataSet : Dataset is used to store the data retrieved from database by dataadapter and makeit
available for .net application.
To fill data in to dataset fill() method of dataadapter is used and has the following syntax.
Da.Fill(Ds,”TableName”);
When fill method was called, dataadapter will open a connection to database, executes select
command, stores the data retrieved by select command in to dataset and immediately closes the
connection.
As connection to database was closed, any changes to the data in dataset will not be directly sent to
the database and will be made only in the dataset. To send changes made to data in dataset to the
database, Update() method of the dataadapter is used that has the following syntax.
Da.Update(Ds,”Tablename”);
When Update method was called, dataadapter will again open the connection to database, executes
insert, update and delete commands to send changes in dataset to database and immediately closes
the connection. As connection is opened only when it is required and will be automatically closed
when it was not required, this architecture is called disconnected architecture. A dataset can
contain data in multiple tables.
PGDAC-MS.Net Page 20
Difference between Connected and Disconnected Architecture
What is LINQ?
LINQ is an acronym for Language Integrated Query, which is descriptive for where it’s used and what
it does. The Language Integrated part means that LINQ is part of programming language syntax. In
particular, both C# and VB are languages that ship with .NET and have LINQ capabilities. Another
PGDAC-MS.Net Page 21
programming language that supports LINQ is Delphi Prism. The other part of the definition, Query,
explains what LINQ does; LINQ is used for querying data. Notice that I used the generic term “data”
and didn’t indicate what type of data. That’s because LINQ can be used to query many different
types of data, including relational, XML, and even objects.
Another way to describe LINQ is that it is programming language syntax that is used to query
data.
LINQ queries return results as objects. It enables you to uses object-oriented approach on the
result set and not to worry about transforming different formats of results into objects
ADO.NET is an object-oriented library, yet we must still reason about data from a relational
perspective. In simple scenarios, we can bind ADO.
Note: The operative term in the previous paragraph is “reduce”. LINQ does not eliminate
Impedance Mismatch, because you must still reason about your data store format. However,LINQ
does remove a lot of the plumbing work you have to do to re-shape your data as an object.
In the query, we select elements from an array in descending order (high to low). We filter out
elements <= 2. In the loop, we evaluate the expression and print the results.Var
PGDAC-MS.Net Page 22
.NET INTERVIEW QUESTIONS
: C# is a simple, modern and a general-purpose Object-oriented programming language
developed by Microsoft within its .NET framework. Beginner’s Level
Q1. List down the differences between Public, Static and void keywords?
Keyword Description
Public It is an access specifier which states that the method of a class can be accessed
publicly
Static It is a keyword used for declaring a member of a type, specific to that type
void It states that the method does not return any value
Q7. List down the access modifiers available in C#. Ans- Following are the access modifiers
• Public- When an attribute or method is defined as public it can be accessed from any part
of code.
PGDAC-MS.Net Page 23
• Private- A private attribute or method can be accessed from within the class itself. •
Protected- When a user defines a method or attribute as protected then it can be accessed
only within that class and the one inheriting the class.
• Internal- When an attribute or method is defined as internal then it will be accessed from
that class at the current assembly position.
• Protected Internal- When you define an attribute or method as protected internal, then
it’s access restricted to classes within the current project assembly or different types
defined by that class.
Q8. List down the different IDE’s Provided by Microsoft for C# Development.
1.Visual Studio Express (VCE) 2.Visual Studio (VS) 3.Visual Web Developer 4.MonoDevelop
5.browxy
Q25. List the difference between the Virtual method and the Abstract method?
Ans- A Virtual method must always have a default implementation. However, it can be
overridden in a derived class by the keyword override.
An Abstract method doesn’t have any implementation. It resides in the abstract class, and
also it is mandatory that the derived class must implement abstract class. Use of override
keyword is not necessary.
Q26. Illustrate Namespaces in C#?
Ans- Namespaces are used for organizing large code projects. “System” is one of the most
popular and widely used namespaces in C#. One can create their own namespace and use
one into another called nesting.
Q27. Define using statement in C#?
Ans- “Using” keyword simply denotes that the particular namespace is being used by the
program. For ex- using System, Here System is a namespace. The class console is defined
under system, so we can use the Console.Writeline(…) or Readline in our program.
Q42. List down the differences between “dispose” and “finalize” methods in C#.
Ans- Dispose() is called when we want an object to release unmanaged resources with
them. Whereas, Finalize() is used for the same purpose but it doesn’t assure garbage
collection of an object.