UNIT-I Dotnet (2018)
UNIT-I Dotnet (2018)
INTRODUCTION:
The .NET Framework has two main components: the common language runtime and the .NET
Framework class library. The common language runtime is the foundation of the .NET
Framework. You can think of the runtime as an agent that manages code at execution time,
providing core services such as memory management, thread management, and remoting, while
also enforcing strict type safety and other forms of code accuracy that promote security and
robustness. In fact, the concept of code management is a fundamental principle of the runtime.
Code that targets the runtime is known as managed code, while code that does not target the
runtime is known as unmanaged code. The class library, the other main component of the .NET
Framework, is a comprehensive, object-oriented collection of reusable types that you can use to
develop applications ranging from traditional command-line or graphical user interface (GUI)
applications to applications based on the latest innovations provided by ASP.NET, such as Web
Forms and XML Web services. The .NET Framework can be hosted by unmanaged components
that load the common language runtime into their processes and initiate the execution of
managed code, thereby creating a software environment that can exploit both managed and
unmanaged features. The .NET Framework not only provides several runtime hosts, but also
supports the development of third-party runtime hosts.
The version was called .Net framework 1.0. The .Net framework has come a long way since
then, and the current version is 4.7.1.
The .Net framework can be used to create both - Form-based and Web-based applications. Web
services can also be developed using the .Net framework.
The framework also supports various programming languages such as Visual Basic and C#. So
developers can choose and select the language to develop the required application. In this
chapter, you will learn some basics of the .Net framework.
The first version of the .Net framework was released in the year 2002. The version was called
.Net framework 1.0. The .Net framework has come a long way since then, and the current
version is 4.7.1.
Below is the table of .Net framework versions, which have been released with their release dates.
Every version has relevant changes to the framework.
For example, in framework 3.5 and onwards a key framework called the Entity framework was
released. This framework is used to change the approach in which the applications are developed
while working with databases.
4.0 4 2010-04-12
4.5 4 2012-08-15
4.5.1 4 2013-10-17
4.5.2 4 2014-05-05
4.6 4 2015-07-20
4.6.1 4 2015-11-17
4.6.2 4 2016-08-02
4.7 4 2017-04-05
4.7.1 4 2017-10-17
The biggest advantage of the .Net framework is that it supports Windows platform. Almost
everyone works with Windows machines.
Microsoft always ensures that .Net frameworks are in compliance with all the supported
Windows operating systems.
Assemblies may be either private, which are used only by the application to which they
belong or Global assemblies, which are used by any application in the system.Two
assemblies of the same name but with different versions can run side-by-side allowing
applications that depend on a specific version to use assembly of that version. The four
parts of an assembly are: Assembly Manifest - Contains name, version, culture, and
information about referenced assemblies. Type metadata - Contains information about
types defined in the assembly. MSIL – MSIL code. Resources - Files such as BMP or
JPG file or any other files required by application. Note: Assembly that contains only
resources is called as Satellite assembly. The following are different types of applications
that can be developed in .NET:
Windows applications – typical Client/Server applications.
Web services – Programs that are accessible from anywhere using universal protocols
like HTTP and SOAP.
Console Applications – Simple console based applications without any GUI. Run from
command prompt. Best suited to learn fundamentals and also for applications such as
server sockets.
Mobile Applications – Contain web pages that run in mobile devices such as PDAs
(Personal Digital Assistant) and Cell phones.
Though .NET supports many languages, but the two languages will dominate programming in
.NET: VB.NET and C#. VB.NET is the successor to VB 6.0, but language wise, it was modified
substantially as it became complete OOPL – no more "object-based language." C# resembles
Java. Though Microsoft claims, C# resembles C++, but it resembles Java more than C++.
NOTE: The Common Language Runtime, Unified Programming classes and ASP.NET are
considered as the three major parts of .NET framework.
1. Common Language Runtime: This acts as the execution engine for the .NET
Framework. All .NET programs executes under the supervision of CLR.
2. Base Class Library: This is a library of functionalities which are available to all
languages using the .NET Framework. It consists of classes, interfaces of reusable types
that integrates with CLR
3. Portable Class Library: The Portable Class Library project in Visual Studio 2012 allows
you to develop and build managed assemblies that work on multiple .NET Framework
platforms. Using a Portable Class Library project, you choose the platforms (such as
Windows Phone and .NET for Windows Store apps) to target.
4. Managed Extensibility Framework (MEF): MEF is a library for creating lightweight,
extensible applications. It allows application developers to discover and use extensions
with no configuration required.
5. Dynamic Language Runtime: This provides the runtime environment for dynamic
languages like python etc. for executing under the full control of CLR.
6. WinRT: WinRT or Windows Runtime APIs provides the user interface elements for
building Windows Store apps, and provides access to Windows 8 or Windows RT OS
features. WinRT supports development in C and other managed languages C# and
VB.NET, as well as JavaScript and TypeScript.
JIT COMPILER
JIT (Just-in-Time):Just - in - Time (JIT) compiler, which compiles MSIL into native code that
is specific to the OS and machine architecture being targeted. Only at this point can the OS
execute the application. The just - in - time part of the name reflects the fact that MSIL code is
only compiled as, and when, it is needed. In the past, it was often necessary to compile your code
into several applications, each of which targeted a specific operating system and CPU
architecture. Often, this was a form of optimization. This is now unnecessary, because JIT
compilers (as their name suggests) use MSIL code, which is independent of the machine,
operating system, and CPU. Several JIT compilers exist, each targeting a different architecture,
and the appropriate one will be used to create the native code required.
JIT are of three types:
1. Pre JIT
2. Econo JIT
3. Normal JIT
Pre JIT: It converts all the code in executable code and it is slow
Econo JIT: It will convert the called executable code only. But it will convert code every time
when a code is called again.
Normal JIT: It will only convert the called code and will store in cache so that it will not require
converting code again. Normal JIT is fast.
1. Normal JIT
This complies only those methods that are called at runtime. These methods are compiled
only first time when they are called, and then they are stored in memory cache. This
memory cache is commonly called as JITTED. When the same methods are called again,
the complied code from cache is used for execution.
2. Econo JIT
This complies only those methods that are called at runtime and removes them from
memory after execution.
3. Pre JIT
This complies entire MSIL code into native code in a single compilation cycle. This is done
at the time of deployment of the application.
CTS and CLS are parts of .NET CLR and are responsible for type safety with in the code. Both
allow cross language communication and type safety. In this article I would like to expose the
relationship between these two.
Common Type System (CTS): CTS stands for Common Type System. It defines the rules
which Common Language Runtime follows when declaring, using, and managing types. The
common type system performs the following functions:
Common Language Specification (CLS) :CLS stands for Common Language Specification and
it is a subset of CTS. It defines a set of rules and restrictions that every language must follow
which runs under .NET framework. The languages which follows these set of rules are said to be
CLS Compliant. In simple words, CLS enables cross-language integration.
For example, one rule is that you cannot use multiple inheritance within .NET Framework. As
you know C++ supports multiple inheritance but; when you will try to use that C++ code within
C#, it is not possible because C# doesn‟t supports multiple inheritance.
One another rule is that you cannot have members with same name with case difference only i.e.
you cannot have add() and Add() methods. This easily works in C# because it is case-sensitive
but when you will try to use that C# code in VB.NET, it is not possible because VB.NET is not
case-sensitive.
In .NET, every Data Type is internally represented by a class or structure. All the classes and
structures related to Data Types are collectively known as CTS. As you know every language
provides its own keywords for Data Types but internally all the languages which run under .NET
framework use the classes and structures available in CTS.
For example, C# has int Data Type and VB.Net has Integer Data Type. Hence a variable
declared as int in C# or Integer in vb.net, finally after compilation, use the same structure Int32
from CTS.
All the structures and classes available in CTS are common for all .NET Languages and purpose
of these is to support language independence in .NET. Hence it is called CTS.
Managed Code: The resource, which is with in your application domain is, managed code. The
resources that are within domain are faster. The code, which is developed in .NET framework, is
known as managed code. This code is directly executed by CLR with help of managed code
execution. Any language that is written in .NET Framework is managed code.
Managed code uses CLR which in turns looks after your applications by managing memory,
handling security, allowing cross - language debugging, and so on.
Unmanaged Code: The code, which is developed outside .NET, Framework is known as
unmanaged code. Applications that do not run under the control of the CLR are said to be
unmanaged, and certain languages such as C++ can be used to write such applications, which,
for example, access low - level functions of the operating system. Background compatibility with
code of VB, ASP and COM are examples of unmanaged code.
The managed heap is a series of allocated memory segments (approx 16Mb in size each) to store
and manage objects. The memory for newly created object is allocated at the next available
location on the managed heap. If there is available free memory, the garbage collector doesn't
search the dead objects for memory reclaim and memory allocations has been done very fast. If
the memory is insufficient to create the object, the garbage collector search the dead objects for
memory reclaim for the newly object.
An object is created using the new operator. This operator first makes sure that the bytes required
by the new object fit in the reserved region (committing storage if necessary). If the object
fits, NextObjPtr points to the object in the heap and object's constructor is called and the new
operator returns the address of the object.
1. All objects in the heap are allocated from one contiguous range of memory address and
heap is divided into generations so that it is easy to eliminate the garbage objects by looking
at only a small fraction of the heap.
2. Gen 0 and Gen 1 occupy a single segment known as the ephemeral segment. Gen 2 is a set
of further segments and the large object heap is yet another group of segments.
3. Almost, all objects with-in a generation are of the same age.
4. The newest objects are created at higher memory address while oldest memory objects are
at lowest memory address with in the heap.
5. The allocation pointer for the new objects marks the boundary between the allocated and
free memory.
6. Periodically the heap is compacted by removing the dead objects and sliding up the live
objects towards the lower memory address end of the heap as shown in above fig.
7. The order of objects (after memory reclaims) in memory remains the same as they were
created.
8. There are never any gaps among the objects in the heap.
9. Only some of the free memory is committed when required and more memory is acquired
from the OS in the reserved address range.
The managed heap is organized into three generations so that it can handle short lived and long
lived objects efficiently. Garbage collector first reclaim the short lived objects that occupy a
small part of the heap.
1. Generation 0: This is the youngest generation and contains the newly created objects.
Generation 0 has short-lived objects and collected frequently. The objects that survive the
Generation 0 are promoted to Generation 1.
Example : A temporary object.
2. Generation 1: This generation contains the longer lived objects that are promoted from
generation 0. The objects that survive the Generation 1 are promoted to Generation 2.
Basically this generation serves as a buffer between short-lived objects and longest-lived
objects.
3. Generation 2: This generation contains the longest lived objects that are promoted from
generation 1 and collected infrequently.
Example : An object at application level that contains static data which is available for the
duration of the process.
Memory Reclaim Process: Now the garbage collector starts go through the roots and make a
graph of all the objects reachable from the roots. The below fig. shows a heap with allocated
objects. In this heap the application roots directly refer to the objects 1,3,4,6 and object 3 & 6
refers to the objects 8 & 10. Hence all these objects will become the part of the live objects
graph.
The objects which are not reachable from application's roots, are considered as garbage since
these are not accessible by the application. In above heap objects 2,5,7,9 will be considered as
dead objects.
The garbage collector then remove the dead objects from the heap and live objects will move
toward the older end of the memory segment as shown in below fig. Garbage collector also
updates all the references(including root references) to the moving objects in the heap.
Assemblies are the core building blocks of .NET applications. In simple terms, assembly is the
.dll or .exe file that is created while building any .NET application. You can find many
definitions for assembly over the internet also. In my point of view, assembly is the building
block which is created after a successful build operation of your application.
After compilation of each project, an .exe or .dll file is generated, known as Assembly. The name
of an assembly file is the same as the project name. The assembly of a project present under
bin\Debug folder of that project folder. After successful build of each project an assembly is
generated inside that folder.We can use assembly files by our requirement we may directly take
the assembly file and install into client meachine if it is .exe type or we can consume the file in
another project if the assembly is dll type.
Class Library and Windows Forms Control Library projects generate a .dll assembly where as
Windows Forms Applications, Console Applications, WPF Applications, and Windows Services
projects generate an .exe assembly.
.Exe type assembly are run by their own as well as they provide the support to other in their
execution process so these assembly are know as in-process component where as .dll type
assembly are called as out process component because they are only developed for the purpose to
consume inside .exe type of application.
Note: Every application is a blend of both .dll and .exe assemblies combined together to give
better efficiency.
Types of Assembly:
1. Private Assembly
2. Shared Assembly
Private Assembly: When we build any project we found a corresponding assembly inside
bin/Debug folder; so by default these assembly is private type.It' private because when we add
that assembly reference to another project then a copy of that assembly created inside that
project. Bellow figure is an example of Private assembly.
Creating an assembly to test if it is private, by default:
Start a new project inside Visual studio of type Class Library and name it as “PAssembly”,we
take class librery because we can consume this project dll file inside another project. Here i am
using VS2012 for my project creation.
in this project you find a file called as Class1.cs. Now, write the following code under the class:
Now, compile the project by opening the Solution Explorer, right clicking on the project, and
selecting “Build” or Press "Ctrl+shift+B" which will bulid + compile your project and generate
an assembly with the name as PAssembly.dll.
Note: We can find the path for our assembly in the output window.
Open a new project of type Windows, name it as “TestPAssembly”, place a button on the Form,
and set its text as “Call TestHello method of Class1 in PAssembly.dll”. Now, add the reference
of PAssembly.dll from its physical location and write the following code under click of button:
Run the project to test it. Then, go and verify under bin/debug folder of current project where we
can find a copy of PAssembly.dll as it is private assembly.
Note: The advantage of a private assembly is faster execution because it is available in the local
folder, whereas its drawback is that multiple copies get created when multiple projects add the
reference to consume it.
Shared Assemblies: As we saw above while consuming private assembly it always created a
copy of that file inside the project bin/debug folder;so if we want to use that assembly in several
application then we required to put that assembly inside a shared folder. That shared folder in
.Net called as Global Assembly Cache folder. We can add number of assembly inside that folder
and consume that assembly any project.
Note: Before consuming we need to add the assembly inside GAC folder; due to GAC is present
under window directory so read,write and delete can only available when we give the permission
to that folder.
Note: Assemblies deployed in the GAC must have a strong name. When an assembly is added to
the global assembly cache, integrity checks are performed on all files that make up the
assembly.
When an assembly created by using Name + Version + Public Key then it's called as strong name
1. Name: Every assembly has it's own name which comes by default when you build your
project.
2. Version: All software comes with Version number; without version number we can not
identify it, so when we created assembly it's comes with default version number called as
"1.0.0.0"
3. Public Key: A public key is a key thrugh which GAC can identify the assembly. As we
know GAC contain all the assembly so to identify uniquely GAC uses this public key.
You can ensure that a name is globally unique by signing an assembly with a strong name. In
particular, strong names satisfy the following requirements:
Strong names guarantee the name uniqueness by relying on unique key pairs. No one can
generate the same assembly name that you can. Strong names protect the version lineage of an
assembly.
A strong name can ensure that no one can produce a subsequent version of your assembly. Users
can be sure that a version of the assembly they are loading comes from the same publisher who
created the version the application was built with.
Strong names provide a strong integrity check. Passing the .NET Framework security checks
guarantees that the contents of the assembly have not been changed since it was built.
Versioning Assemblies
Every assembly has a version number; so to define the version number we have some protocol
through which we can give the version name with their different build. So all this information
can found inside AssemblyInfo.cs file inside each project.
Major Version
Minor Version
Build Number
Revision
INTRODUCTION TO C#:
What is C#
By the help of C# programming language, we can develop different types of secured and robust
applications:
o Window applications
o Web applications
o Distributed applications
o Web service applications
o Database applications etc.
C# is approved as a standard by ECMA and ISO. C# is designed for CLI (Common Language
Infrastructure). CLI is a specification that describes executable code and runtime environment.
C# programming language is influenced by C++, Java, Eiffel, Modula-3, Pascal etc. languages.
C++ vs C#
There are many differences and similarities between C++ programming language and C#. A list
of top differences between C++ and C# are given below:
No. C++ C#
2) In C++, multiple inheritance is possible through In C#, multiple inheritance is not possible
class. through class.
4) In C++, pointers can be used anywhere in a program. In C#, pointers can be used only in unsafe
6) C++ is a programming language that runs on all C# is a programming language that rarely
platforms. outside Windows.
7) C++ programming can be used to create console C# programming can be used to create con
applications. applications, Windows applications, Mo
applications, etc.
Java vs C#
There are many differences and similarities between Java and C#. A list of top differences
between Java and C# are given below:
No. Java C#
4) In java, built-in data types that are passed by value are In C#, built-in data types that are passed b
called primitive types. value are called simple types.
5) Arrays in Java are direct specialization of Object. Arrays in C# are specialization of System
6) Java does not support conditional compilation. C# supports conditional compilation using
preprocessor directives.
8) Java doesn't support structures and unions. C# supports structures and unions.
C# was developed by Anders Hejlsberg and his team during the development of .Net
Framework.
C# is designed for Common Language Infrastructure (CLI), which consists of the executable
code and runtime environment that allows use of various high-level languages on different
computer platforms and architectures.
Boolean Conditions
Automatic Garbage Collection
Standard Library
Assembly Versioning
Properties and Events
Delegates and Events Management
Easy-to-use Generics
Indexers
Conditional Compilation
Simple Multithreading
LINQ and Lambda Expressions
Integration with Windows
C# History
History of C# language is interesting to know. Here we are going to discuss brief history of C#
language.
C# is pronounced as "C-Sharp". It is an object-oriented programming language provided
by Microsoft that runs on .Net Framework.
It is based on C++ and Java, but it has many additional extensions used to perform component
oriented programming approach.
C# has evolved much since their first release in the year 2002. It was introduced with .NET
Framework 1.0 and the current version of C# is 5.0.
C# FEATURES:
C# is object oriented programming language. It provides a lot of features that are given below.
1) Simple-C# is a simple language in the sense that it provides structured approach (to break the
problem into parts), rich set of library functions, data types etc.
2) Modern Programming Language-C# programming is based upon the current trend and it is
very powerful and simple for building scalable, interoperable and robust applications.
3) Object Oriented-C# is object oriented programming language. OOPs makes development and
maintenance easier where as in Procedure-oriented programming language it is not easy to
manage if code grows as project size grow.
4) Type Safe-C# type safe code can only access the memory location that it has permission to
execute. Therefore it improves a security of the program.
6) Scalable and Updateable-C# is automatic scalable and updateable programming language. For
updating our application we delete the old files and update them with new ones.
9) Rich Library - C# provides a lot of inbuilt functions that makes the development fast.
10) Fast Speed - The compilation and execution time of C# language is fast.
C# Version History
ABSTRACTION:
Abstraction is one of the principle of object oriented programming. It is used to display only
necessary and essential features of an object to outside the world. Means displaying what is
necessary and encapsulate the unnecessary things to outside the world. Hiding can be achieved
by using "private" access modifiers.
Note - Outside the world means when we use reference of object then it will show only
necessary methods and properties and hide methods which are not necessary.
Implementation of Abstraction
To implement abstraction let's take an example of a car. We knows a car, Car is made of name of
car, color of car, steering, gear, rear view mirror, brakes, silencer, exhaust system, diesal engine,
car battery, car engine and other internal machine details etc.
Now lets think in terms of Car rider or a person who is riding a car. So to drive a car what a car
rider should know from above category before he starts a car driving.
1. Name of Car
2. Color of Car
3. Steering
4. Rear View Mirror
5. Brakes
6. Gear
Unnecessary things means not that compulsory to know for a Car rider
1. Internal Details of a Car
2. Car Engine
3. Diesal Engine
4. Exhaust System
5. Silencer
Now above same thing let me put in the coding style using C#
01 public class Car
02
03 private string _nameofcar = "My Car";
04 private string _colorofcar = "Red";
05
06 public string NameofCar
07
08 set
09
10 _nameofcar = value;
11 }
12 get
13
14 return _nameofcar;
15 }
16 }
17
18 public string ColorofCar
19
20 set
21
22 _colorofcar = value;
23 }
24 get
25
26 return _colorofcar;
27 }
28 }
29
30 public void Steering()
31
32 Console.WriteLine("Streering of Car");
33 }
34
35 public void RearViewMirror()
36
37 Console.WriteLine("RearViewMirror of Car");
38 }
39
40 public void Brakes()
41
42 Console.WriteLine("Brakes of Car");
43 }
44 public void Gear()
45
46 Console.WriteLine("Gear of Car");
47 }
48
49
50 private void InternalDetailsofCar()
51
52 Console.WriteLine("InternalDetailsofCar of Car");
53 }
54
55 private void CarEngine()
56
57 Console.WriteLine("CarEngine of Car");
58 }
59
60 private void DiesalEngine()
61
62 Console.WriteLine("DiesalEngine of Car");
63 }
64
65 private void ExhaustSystem()
66
67 Console.WriteLine("ExhaustSystem of Car");
68 }
69
70 private void Silencer()
71
72 Console.WriteLine("Silencer of Car");
73 }
74
75
76 }
As you can see from above code that necessary methods and properties exposed by using
"public" access modifier and unnecessary methods and properties (not compulsary) hidden by
using "private" access modifier.
As you see to achieve abstraction we used access modifier "public" to expose some methods and
properties to outside the class or world.
As you see to achieve abstraction we used access modifier "private" to hide some methods and
properties from outside the class or world.
Finally lets check by creating an object of above class "Car" in our main program of a console
application and by using object lets see weather we are getting all exposed necessary methods
and properties.
1 class Program
2
3 static void Main(string[] args)
4
5 Car objCar = new Car();
6
7 }
8}
Conclusion
Sucessfully we have exposed necessary methods and properties to outside the world or class.
This is how we need to implement abstraction or we can achieve abstraction in our code or
application