0% found this document useful (0 votes)
10 views

Dot Net

The document discusses the .NET Framework, which was introduced by Microsoft to compete with Java. It provides an environment for building and running web and Windows applications. The .NET Framework includes the Common Language Runtime (CLR) which executes programs, the Common Type System (CTS) which defines common data types, and a Base Class Library (BCL) containing reusable classes. It allows applications to be written in multiple languages like C# and VB.NET while sharing the same libraries.

Uploaded by

sumiipwra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Dot Net

The document discusses the .NET Framework, which was introduced by Microsoft to compete with Java. It provides an environment for building and running web and Windows applications. The .NET Framework includes the Common Language Runtime (CLR) which executes programs, the Common Type System (CTS) which defines common data types, and a Base Class Library (BCL) containing reusable classes. It allows applications to be written in multiple languages like C# and VB.NET while sharing the same libraries.

Uploaded by

sumiipwra
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

.

NET Framework and C# lecture Notes

Unit - I

Introduction
Master of Computer Applications
.NET technology was introduced by Microsoft, to catch the
market from the SUN's Java. Few years back, Microsoft had
only VC++ and VB to compete with Java, but Java was
MCAC404: .NET FRAMEWORK and C# catching the market very fast. With the world depending more
and more on the Internet/Web and java related tools
becoming the best choice for the web applications, Microsoft
seemed to be loosing the battle. Thousands of programmers
moved to java from VC++ and VB. To recover the
market,Microsoft announced .NET.
UNIT I to V
The .NET is the technology, on which all other Microsoft
technologies will be depending on in future.

It is a new framework platform for developing web-based and


windows-based applications within the Microsoft
environment.

.NET is not a language. (runtime and a library for execution


Lecture Notes .net application)
R.GANAPATHYRAJA
.NET Environment/Platform

Visual studio .NET is an Integrated Development


Environment(IDE) from Microsoft.

It provides the tools to design ,develop, compiling and


debugging the all .net applications.

DIVISION OF COMPUTER AND INFORMATION SCIENCE


FACULTY OF SCIENCE
ANNAMALAI UNIVERSITY

Division of Computer and Information Science


.NET Framework and C# lecture Notes

.NET Framework

.NET Framework is a computing model that makes things


easier for application development for the distributed
environment of the internet.

.NET Framework is an environment for building, deploying .NET Components/ Features of the .Net Framework:
and running web services and others applications. The first
The .NET Framework is composed of five main components:
version of the .Net framework was released in the year 2002.
 Common Language Runtime (CLR)
The version was called .Net framework 1.0. The .Net
framework has come a long way since then, and the current  Common Language Specification(CLS)
version is 4.8.  Common Type System(CTS)
 Base Class Library(BCL)/Framework Class
.NET framework comes with a single class library. Whether write the Library(FCL)
code in C# or VB.NET or J# just use the .NET class library. There is  Microsoft Intermediate language(MSIL or IL)
no classes specific to any language. Because it is support multiple
CLR-stands for Common Language Runtime is a managed
programming languages.
execution environment that is part of Microsoft’s .NET
framework. CLR manages the execution of programs written
in different supported languages.

CLR transforms source code into a form of bytecode known as


Common Intermediate Language (CIL). At run time, CLR
handles the execution of the CIL code.

Division of Computer and Information Science


.NET Framework and C# lecture Notes

CTS-stands for Common Type System Common The language


interoperability, and .NET Class Framework, are not possible
without all the language sharing the same data types. What
this means is that an "int" should mean the same in VB,
VC++, C# and all other .NET compliant languages. Same idea
follows for all the other data types. It is an important part of the
runtimes support for cross language integration.

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. It enables cross-language
interoperability between various programming languages.

BCL - stands for Base Class Library ( Unified Classes) is a


subset of Framework class library (FCL). Class library is the
collection of reusable types that are closely integrated with
CLR. All .NET-based languages also access the same libraries.

The .NET Framework has an extensive set of class libraries.


This includes classes for:

• Data Access: High Performance data· access classes for


connecting to SQL Server or any other OLEDB provider.

• XML Supports: Next generation XML support that goes far


beyond the functionality of MSXML.

Division of Computer and Information Science


.NET Framework and C# lecture Notes

• Directory Services: Support for accessing Active each function is called. This process is called Just In Time
directory/LDPA using ADSI. (JIT) compilation, also known as Dynamic Translation . With
the help of Just In Time Compiler (JIT) the Common
• Regular Expression: Support for above and beyond that Language Runtime (CLR) doing these tasks.
found in Perl 5.
Garbage Collection (GC)
• Queuing Supports: Provides a clean object-oriented set of The Garbage collection is the important technique in the .Net
classes for working with MSMQ. framework to free the unused managed code objects in the
memory and free the space to the process.
MSIL-stands for Microsoft Intermediate Language
A .NET programming language (C#, VB.NET, J# etc.) does The garbage collection (GC) is new feature in Microsoft .net
not compile into executable code; instead it compiles into an framework. When a class that represents an object in the
intermediate code called MSIL or IL. A source code in runtime that allocates a memory space in the heap memory.
automatically converted to MSIL. The MSIL code is then All the behavior of that objects can be done in the allotted
send to the CLR that converts the code to machine language memory in the heap.
which is then run on the host machine.
Microsoft was planning to introduce a method that should
automate the cleaning of unused memory space in the heap
after the life time of that object. Eventually they have
introduced a new technique "Garbage collection". It is very
important part in the .Net framework. Now it handles this
object clear in the memory implicitly. It overcomes the
existing explicit unused memory space clearance.

Assemblies

Assemblies form the fundamental units of deployment,


version control, reuse, activation scoping, and security
Just In Time Compiler – JIT permissions for .NET-based applications. An assembly is a
collection of types and resources that are built to work
The .Net languages , which is conforms to the Common together and form a logical unit of functionality. Assemblies
Language Specification (CLS), uses its corresponding runtime take the form of executable (.exe) or dynamic link library (.dll)
to run the application on different Operating Systems . files, and are the building blocks of .NET applications. They
During the code execution time, the Managed Code compiled provide the common language runtime with the information it
only when it is needed, that is it converts the appropriate needs to be aware of type implementations.
instructions to the native code for execution just before when

Division of Computer and Information Science


.NET Framework and C# lecture Notes

Every Assembly create contains one or more program files UNIT- II


and a Manifest. There are two types program files : Process C# Basics
Assemblies (EXE) and Library Assemblies (DLL). Each Introduction
Assembly can have only one entry point (that is, DllMain,
WinMain, or Main). C# pronounced as 'C- Sharp'. C# is a simple, modem, object
oriented, and type safe programming language derived from
There are two types: C and C++. C# is a purely object-oriented language like as
1. Private Assembly Java. It has been designed to support the key features of
.NET framework.
2. Shared Assembly C# was developed by Microsoft within its .NET initiative led
by Anders Hejlsberg.
1.Private Assembly It is used only by a single application, C# is designed for Common Language Infrastructure (CLI),
and usually it is stored in that application's install directory. which consists of the executable code and runtime
environment that allows use of various high-level languages
Private Assembly cannot be references outside the scope of
on different computer platforms and architectures.
the folder.

2. Shared Assembly Shared Assembly is a public assembly Features of C#


that is shared by multiple applications. 1. Simplicity All the Syntax of java is like C++. There is no
preprocessor, and much larger library. C# code
Shared Assembly is one that can be referenced by more than does not require header files. All code is written inline.
one application. 2. Consistent behavior C# introduced an unified type
system which eliminates the problem of varying ranges of
.Net Assembly Manifest
integer types. All types are treated as objects and developers
An Assembly Manifest is a file that containing Metadata can extend the type system simply and easily.
about .NET Assemblies. Assembly Manifest contains a 3. Modern programming language
collection of data that describes how the elements in the
C# supports number of modern features, such as:
assembly relate to each other. It describes the relationship
and dependencies of the components in the Assembly,  Automatic Garbage Collection
versioning information, scope information and the security
 Error Handling features
permissions required by the Assembly.
 Modern debugging features
 Robust Security features
4. Pure Object- Oriented programming language
In C#, every thing is an object. There are no more global
functions, variable and constants.

Division of Computer and Information Science


.NET Framework and C# lecture Notes

It supports all three object oriented features: Example


 Encapsulation
 Inheritance
using System;
 Polymorphism
namespace HelloWorldApplication
{
5. Type Safety Type safety promotes robust programming.
class HelloWorld
Some examples of type safety are:
{
 All objects and arrays are initialized by zero
static void Main(string[] args)
dynamically
{
 An error message will be produced , on use of any
/* my first program in C# */
uninitialized variable
Console.WriteLine("Hello World");
 Automatic checking of array out of bound and etc.
}
6. Feature of Versioning Making new versions of software
}
module work with the existing applications is known as
}
versioning. Its achieve by the keywords new and override.
7. Compatible with other language C# enforces the .NET
 using System
common language specifications (CLS) and therefore allows
This "using" keyword is used to contain the System
interoperation with other .NET language.
namespace in the program. Every program has
multiple using statements.
Structure of C#

 namespace declaration
C# program consists of the following things.
It’s a collection of classes. The HelloCSharp namespace
contains the class prog1HelloWorld.
1. Namespace declaration
2. A Class
 class declaration
3. Class methods
The class prog1HelloWorld contains the data and
4. Class attributes
method definitions that your program.
5. The Main method
6. Statements and Expressions
 defines the Main method
7. Comments
This is the entry point for all C# programs. The main
method states what the class does when executed.

 WriteLine

Division of Computer and Information Science


.NET Framework and C# lecture Notes

It’s a method of the Console class distinct in the System reference types can be defined using 'class', 'interface', and
namespace. This statement causes the message "Hello, 'delegate' declarations. Therefore the reference types are :
World!" to be displayed on the screen.
Predefined Reference Types
Important in C#
 Object
 C# is case sensitive.  String
 C# program execution starts at the Main method.
 All C# expression and statements must end with a User Defined Reference Types
semicolon (;).  Classes
 File name is different from the class name. This is  Interfaces
unlike Java.
 Delegates
Data types  Arrays

The variables in C#, are categorized into the following types: Object Type is the ultimate base class for all data types in
C# Common Type System (CTS). Object is an alias for
 Value types System.Object class. The object types can be assigned values
 Reference types of any other types, value types, reference types, predefined or
userdefined types.
Value types - variables can be assigned a value directly. They
are derived from the class System.ValueType. String Type allows you to assign any string values to a
variable. The string type is an alias for the System.String
The value types directly contain data. Some examples are int, class. It is derived from object type.
char, and float, which stores numbers, alphabets, and
floating point numbers, respectively.
Ex: String str = "Tutorials Point";
Example:
Char to String
int i = 75;
float f = 53.005f;
string s1 = "hello";
double d = 2345.7652; char[] ch = { 'c', 's', 'h', 'a', 'r', 'p' };
bool b = true; string s2 = new string(ch);
Console.WriteLine(s1);
Console.WriteLine(s2);
Reference Types Converting Number to String
int num = 100;
The pre-defined reference types are object and string, where
string s1= num.ToString();
object - is the ultimate base class of all other types. New Inserting String

Division of Computer and Information Science


.NET Framework and C# lecture Notes

string s1 = Wel; Example


string s2 = s1.insert(3,‖come‖);
class Marks {
// s2 = Welcome
string s3 = s1.insert(3,‖don‖); // These variables are instance variables.
// s3 = Weldon; // These variables are in a class and
// are not inside any function
int Marks;
Variable
A variable is a name given to a memory location and all the // Main Method
operations done on the variable effects that memory location. public static void Main(String[] args)
The value stored in a variable can be changed during program {
execution.
// first object
Marks obj1 = new Marks();
Type of Variables obj1.Marks = 90;
o Local variables
o Instance variables or Non – Static Variables // second object
Marks obj2 = new Marks();
o Static Variables or Class Variables obj2.Marks = 95;
o Constant Variables
o Readonly Variables // displaying marks for first object
Console.WriteLine("Marks for first object:");
Local Variable Console.WriteLine(obj1.Marks);

A variable defined within a block or method or constructor is // displaying marks for second object
called local variable. Console.WriteLine("Marks for second object:");
Console.WriteLine(obj2.Marks);
}
Example
}
static void Main(String args[])
{
// Declare local variable Static Variables or Class Variables
int age = 24;
Console.WriteLine("Student age is : " + age);
} Static variables are also known as Class variables. These
variables are declared similarly as instance variables, the
Instance variables difference is that static variables are declared using the static
keyword within a class outside any method constructor or
As instance variables are declared in a class, these variables block.
are created when an object of the class is created and To access static variables use class name, there is no need to
destroyed when the object is destroyed. Unlike local variables, create any object of that class.
we may use access specifiers for instance variables.

Division of Computer and Information Science


.NET Framework and C# lecture Notes

Example It’s not compulsory to initialize a read-only variable at the


time of the declaration, they can also be initialized under the
class Emp {
constructor.
// static variable salary
static double salary;
Example
static String name = "E.Kumaran";
Class rc
// Main Method
public static void Main(String[] args) {
{
// readonly variables
// accessing static variable
readonly int k;
// without object
Emp.salary = 50000;
// constructor

Console.WriteLine(Emp.name + "'s average salary:" Public rc()


+
Emp.salary); { // initializing readonly variable k
}
} this.k = 90; }

Type conversion is converting one type of data to another


Constants Variables type. It is also known as Type Casting. In C#, type casting has
A variable is declared by using the keyword “const” then it as two forms
a constant variable and these constant variables can’t be Implicit type conversion : smaller to larger integral
modified once after their declaration, so it’s must initialize at types int i=100; long l=i;
the time of declaration only. Explicit type conversion : Larger to small integral
types
Example double d = 5673.74;
int i;
Const int max=500; // cast double to int.
i = (int)d;
Read-Only Variables Boxing
A variable is declared by using the readonly keyword then it When a value type is converted to object type
will be read-only variables and these variables can’t be Ex:
modified like constants but after initialization. int i=100;

Division of Computer and Information Science


.NET Framework and C# lecture Notes

object o=i; Arithmetic Operators

UnBoxing These are used to perform arithmetic/mathematical


when an object type is converted to a value type, it is operations on operands. The Binary Operators falling
called unboxing. in this category are :
Ex:
object o=245;  Addition: ‘+’ operator
int j=(int)o;  Subtraction: ‘-‘ operator
 Multiplication: ‘*’ operator
 Division: ‘/’ operator
Input Statements  Modulus: ‘%’ operator
The Console class in the System namespace provides a
function ReadLine() for accepting input from the user Example
and store it into a variable.
// Addition
result = (x + y);
For example, Console.WriteLine("Addition Operator: " +
result);
int num;
// Subtraction
Double r; result = (x - y);
num = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Subtraction Operator: " +
r = Convert.ToDouble(Console.ReadLine()); result);
string s = console.ReadLine();
// Multiplication
Char c =Convert.ToChar(Console.ReadLine()); result = (x * y);
Operators - It Can be categorized based upon their Console.WriteLine("Multiplication Operator:
different functionality: "+ result);

// Division
 Arithmetic Operators result = (x / y);
 Relational Operators Console.WriteLine("Division Operator: " +
result);
 Logical Operators
 Bitwise Operators // Modulo
 Assignment Operators result = (x % y);
 Conditional Operator Console.WriteLine("Modulo Operator: " +
result);
Relational Operators

Division of Computer and Information Science


.NET Framework and C# lecture Notes

result = (x <= y);


Console.WriteLine("Lesser than or Equal to: "+
Relational operators are used for comparison of two result);
values. Let’s see them one by one: // Not Equal To Operator
result = (x != y);
o ‘=='(Equal To) operator Console.WriteLine("Not Equal to Operator: " +
o ‘!='(Not Equal To) operator result);
o ‘>'(Greater Than) operator
Logical Operators
o <‘(Less Than) operator They are used to combine two or more
conditions/constraints or to complement the
o ‘>='(Greater Than Equal To) operator evaluation of the original condition in consideration.
They are described below:
o ‘<=‘(Less Than Equal To) operator  Logical AND: The ‘&&’ operator
 Logical OR: The ‘||’ operator
Example  Logical NOT: The ‘!’ operator

bool result;
Example
int x = 5, y = 10;
bool a = true,b = false, result;
// Equal to Operator
result = (x == y); // AND operator
Console.WriteLine("Equal to Operator: " +
result); result = a && b;
Console.WriteLine("AND Operator: " + result);
// Greater than Operator
result = (x > y);
Console.WriteLine("Greater than Operator: " + // OR operator
result); result = a || b;
Console.WriteLine("OR Operator: " + result);
// Less than Operator
result = (x < y);
Console.WriteLine("Less than Operator: " + // NOT operator
result); result = !a;
Console.WriteLine("NOT Operator: " + result);
// Greater than Equal to Operator
result = (x >= y);
Console.WriteLine("Greater than or Equal to: "+ Control Statements
result);

// Less than Equal to Operator  Decision-Making Statements

Division of Computer and Information Science


.NET Framework and C# lecture Notes

 Looping Statements Example

int x = 21;
Decision Making (if, if-else, if-else-if ladder, nested if, do
switch, nested switch) {
// The line will be printed even
Looping in programming language is a way to execute // if the condition is false
a statement or a set of statements multiple number of Console.WriteLine("GeeksforGeeks");
times depending on the result of condition to be x++;
}
evaluated to execute statements. The result condition while (x < 20);
should be true to execute statements within loops.

Loops are mainly divided into two categories:


Structure
Entry Controlled Loops: The loops in which condition Structure is a value type and a collection of variables of
to be tested is present in beginning of loop body are different data types under a single unit. It is almost
known as Entry Controlled Loops. while loop and for similar to a class because both are user-defined data
loop are entry controlled loops. types and both hold a bunch of different data types.

Example Example
int x = 1; public struct Person
// Exit when x becomes greater than 4 {
while (x <= 4) // Declaring different data types
{ public string Name;
Console.WriteLine("GeeksforGeeks"); public int Age;
public int Weight;
// Increment the value of x for
// next iteration }
x++; static void Main(string[] args)
}
{
// Declare P1 of type Person
Person P1;
Exit Controlled Loops: The loops in which the testing
condition is present at the end of loop body are termed // P1's data
as Exit Controlled Loops. do-while is an exit controlled P1.Name = "Keshav Gupta";
loop. P1.Age = 21;
P1.Weight = 80;

// Displaying the values

Division of Computer and Information Science


.NET Framework and C# lecture Notes

Console.WriteLine("Data Stored in P1 is " + A class is a user-defined blueprint or prototype from which


P1.Name + ", age is " +
objects are created. Basically, a class combines the fields and
P1.Age + " and weight is " +
P1.Weight); methods.

} An object consists of :

Difference between Class and Structure  State: It is represented by attributes of an object. It


also reflects the properties of an object.
Class Structure  Behavior: It is represented by methods of an object. It
Classes are of reference types.
Structs are of value types. also reflects the response of an object with other
objects.
All the reference types are All the value types are
 Identity: It gives a unique name to an object and
allocated on heap memory. allocated on stack memory.
enables one object to interact with other objects.
Allocation of large referenceAllocation and de-allocation is
type is cheaper than cheaper in value type as Example
allocation of large value type.
compare to reference type.
Class has limitless features.Struct has limited features. using System;
class A
Class is generally used in Struct are used in small {
large programs. programs. public int x=100;
Classes can contain Structure does not contain }
constructor or destructor. constructor or destructor. class mprogram
{
Classes used new keyword for Struct can create an instance, static void Main(string[] args) {
creating instances. without new keyword. A a = new A();
A Struct is not allowed to Console.WriteLine("Class A variable x
A Class can inherit from is " +a.x);
inherit from another struct or
another class. }
class.
}
The data member of a class The data member of struct
can be protected. can’t be protected. Static Class
Function member of the class Function member of the struct
can be virtual or abstract. cannot be virtual or abstract. A static class can only contain static data members, static
methods, and a static constructor.It is not allowed to create
objects of the static class. Static classes are sealed, cannot
Class and Object inherit a static class from another class.
Class and Object are the basic concepts of Object Oriented Note: Not allowed to create objects.
Programming which revolve around the real-life entities.

Division of Computer and Information Science


.NET Framework and C# lecture Notes

Syntax Partial Class

static class Class_Name A partial class is a special feature of C#. It provides a special
{
ability to implement the functionality of a single class into
// static data members multiple files and all these files are combined into a single
// static method class file when the application is compiled using the partial
} modifier keyword. The partial modifier can be applied to a
Example
class, method, interface or structure.
static class Author {
Advantages:
// Static data members of Author
public static string A_name = "Ankita"; It avoids programming confusion (in other words better
public static string L_name = "CSharp"; readability).
public static int T_no = 84;
Multiple programmers can work with the same class using
// Static method of Author different files.
public static void details()
{ Even though multiple files are used to develop the class all
Console.WriteLine("The details of Author is:");
}
} such files should have a common class name.
// Main Method
static public void Main() Example
{
Filename: partial1.cs
// Calling static method of Author
Author.details(); using System;
partial class A
// Accessing the static data members of Author {
Console.WriteLine("Author name : {0} ", public void Add(int x,int y)
Author.A_name); {
Console.WriteLine("Language : {0} ", Console.WriteLine("sum is {0}",(x+y));
Author.L_name);
}
Console.WriteLine("Total number of articles :
{0} ", }
Author.T_ Filename: partial2.cs
no); using System;
} partial class A
{
public void Substract(int x,int y)
{

Division of Computer and Information Science


.NET Framework and C# lecture Notes

Console.WriteLine("Subtract is {0}", (x-y)); Example:


}
} class Demo
Filename joinpartial.cs {
class Demo public int a;
{ internal int x;
public static void Main() protected double d;
{ float m; // private by default
A obj=new A();
}
obj.Add(7,3);
obj.Substract(15,12);
}
Inheritance Inheritance supports the concept of
} “reusability”
Member Access Modifiers
one class is allowed to inherit the features(fields and
Access modifiers provide the accessibility control for the methods) of another class.
members of classes to outside the class. They also provide the
Important terminology:
concept of data hiding. There are five member access
modifiers provided by the C# Language. Super Class: The class whose features are inherited is
known as super class(or a base class or a parent class).
Modifier Accessibility
Members only accessible Sub Class: The class that inherits the other class is known
private
with in class as subclass(or a derived class, extended class, or child class).
Members may accessible The subclass can add its own fields and methods
public
anywhere outside class
Members only accessible Reusability: To create a new class and there is already a
protected
with in class and class that includes some of the code that need to derive new
derived class class from the existing class.
Members accessible only
internal 1)Single Inheritance
within assembly
Members accessible in
protected internal 2) Multilevel Inheritance
assembly, derived class
or containing program 3) Multiple Inheritance (interface)

By default all member of class have private accessibility. If we 4) Hierarchical Inheritance


want a member to have any other accessibility, then we must
specify a suitable access modifier to it individually. Example

Division of Computer and Information Science


.NET Framework and C# lecture Notes

Class A {
{
Int x; // implementing the method
// of interface A
Void display() public void mymethod1()
{ {
System.Consolw.WriteLine(“x=”+x); Console.WriteLine("Implement method 1");
} }
// Implement the method
Class B : A // of interface B
{ public void mymethod3()
Display(); {
} Console.WriteLine("Implement method 3");
}
}
Interface

C# allows the user to inherit one interface into another Sealed classes
interface. When a class implements the inherited interface.
Sealed classes are used to restrict the users from inheriting
Example the class. A class can be sealed by using the sealed keyword.
using System; The keyword tells the compiler that the class is sealed, and
therefore, cannot be extended. No class can be derived from a
// declaring an interface sealed class.
public interface A {
sealed class SealedClass {
// method of interface
void mymethod1(); // Calling Function
void mymethod2(); public int Add(int a, int b)
} {
return a + b;
// The methods of interface A }
// is inherited into interface B }
public interface B : A { Important

// method of interface B  Sealed class is used to stop a class to be inherited. You cannot
void mymethod3(); derive or extend any class from it.
}
// Below class is inherting  Sealed method is implemented so that no other class can overthrow
// only interface B it and implement its own method.
// This class must  The main purpose of the sealed class is to withdraw the inheritance
// implement both interfaces
class Geeks : B
attribute from the user so that they can’t attain a class from a sealed

Division of Computer and Information Science


.NET Framework and C# lecture Notes

class. Sealed classes are used best when you have a class with static base class for overridden that particular method in the
members. derived class.

Method Overloading 2.override: This modifier or keyword use with derived class
method. It is used to modify a virtual or abstract method into
Method Overloading is the common way of implementing derived class which presents in base class.
polymorphism. It is the ability to redefine a function in more
than one form. A user can implement function overloading by 3. base Keyword: This is used to access members of the base
defining two or more functions in a class sharing the same class from derived class.
name. i.e. the methods can have the same name but with
Example
different parameters list.
// method overriding
Example using System;

// adding two integer values.


// base class
public int Add(int a, int b)
public class web {
{
int sum = a + b;
return sum; string name = "Method";
}
// declare as virtual
// adding three integer values. public virtual void showdata()
public int Add(int a, int b, int c) {
{ Console.WriteLine("Base class: " + name);
int sum = a + b + c; }
return sum; }
}
Method Overriding class stream : web {

Method Overriding is a technique that allows the invoking of string s = "Method";


functions from another class (base class) in the derived class.
public override void showdata()
Creating a method in the derived class with the same {
signature as a method in the base class is called as method
overriding. base.showdata();
Console.WriteLine("Sub Class: " + s);
Three types of keywords for Method Overriding: }
}
1. virtual keyword: This modifier or keyword use within class mc {
base class method. It is used to modify a method in
static void Main()

Division of Computer and Information Science


.NET Framework and C# lecture Notes

{ ArrayList is a powerful feature of C# language. It is the non-


generic type of collection which is defined in
stream E = new stream();
System.Collections namespace. It is used to create a dynamic
array means the size of the array is increase or decrease
E.showdata(); automatically according to the requirement.

} Arraylist in use the program, must be add System.Collections


} namespace.
Array An array is a group of homogeneous data stored to
variables And each data item is called an element of the Syntax:
array. ArrayList list_name = new ArrayList();

Syntax : Example

type [ ] < Name_Array > = new < datatype > [size]; // Creating ArrayList
ArrayList My_array = new ArrayList();
Examples
int[] intArray1 = new int[5]; // This ArrayList contains elements
int[] intArray2 = new int[5]{1, 2, 3, 4, 5}; // of different types
int[] intArray3 = {1, 2, 3, 4, 5}; My_array.Add(112.6);
My_array.Add("C# program");
Jagged Arrays Jagged array is a array of arrays such that My_array.Add(null);
member arrays can be of different sizes. In other words, the My_array.Add('Q');
length of each array index can differ. My_array.Add(1231);

// Access the array list


Syntax:
foreach(var elements in My_array)
data_type[][] name_of_array = new data_type[rows][]
{
Example: Console.WriteLine(elements);
}
// Declare the Jagged Array of four elements:
Note: Array List allow add insert remove elements, change
int[][] jagged_arr = new int[4][]; element.

// Initialize the elements Indexers An indexer allows an instance of a class or struct to


jagged_arr[0] = new int[] {1, 2, 3, 4}; be indexed as an array. If the user will define an indexer for a
jagged_arr[1] = new int[] {11, 34, 67}; class, then the class will behave like a virtual array. Array
jagged_arr[2] = new int[] {89, 23};
jagged_arr[3] = new int[] {0, 45, 78, 53, 99};

Division of Computer and Information Science


.NET Framework and C# lecture Notes

access operator i.e ([ ]) is used to access the instance of the private field. Properties can be used as if they are public data
class which uses an indexer. members, but they are actually special methods called
accessors.
Syntax:
Accessors : The block of “set” and “get”
[access_modifier] [return_type] this [argument_list]
{ There are different types of properties based on the “get” and
get
{
set accessors:
// get block code
} Read and Write Properties: When property contains both
set get and set methods.
{
// set block code Read-Only Properties: When property contains only get
}
method.
}
Example Write Only Properties: When property contains only set
public string this[int index] method.
{
Auto Implemented Properties: When there is no additional
get logic in the property accessors and it introduce in C# 3.0.
{
Delegates
return val[index];
} A delegate is a reference type variable that holds the reference
to a method. The reference can be changed at runtime.
set
{
Delegates are especially used for implementing events and the
val[index] = value;
} call-back methods. All delegates are implicitly derived from
the System.Delegate class.

IndexerCreation ic = new IndexerCreation(); A delegate will call only a method which agrees with its
signature and return type. A method can be a static method
ic[0] = "C"; associated with a class or can be instance method associated
ic[1] = "CPP";
ic[2] = "CSHARP"; with an object, it doesn’t matter.

Properties Syntax:
Properties are the special type of class members that provides
[modifier] delegate [return_type] [delegate_name]
a flexible mechanism to read, write, or compute the value of a
([parameter_list]);

Division of Computer and Information Science


.NET Framework and C# lecture Notes

Example Delegates with Events

public delegate void addnum(int a, int b); C# and .NET supports event driven programming via
delegates.The events are declared and raised in a class and
using System;
associated with the event handlers using delegates within the
class TestDelegate { same class or some other class. The class containing the
delegate int NumberChanger(int n);
event is used to publish the event. This is called the publisher
static int num = 10; class. Some other class that accepts this event is called the
subscriber class. Events use the publisher-subscriber model.
public static int AddNum(int p) {
num += p;
return num; A publisher is an object that contains the definition of the
} event and the delegate. The event-delegate association is also
public static int MultNum(int q) {
defined in this object. A publisher class object invokes the
num *= q;
return num; event and it is notified to other objects.
}
public static int getNum() { A subscriber is an object that accepts the event and provides
return num;
} an event handler. The delegate in the publisher class invokes
static void Main(string[] args) { the method (event handler) of the subscriber class.
//create delegate instances
NumberChanger nc1 = new NumberChanger(AddNum); To declare an event inside a class, first of all, you must
NumberChanger nc2 = new NumberChanger(MultNum);
declare a delegate type for the even as:
//calling the methods using the delegate objects
nc1(25); public delegate string BoilerLogHandler(string
Console.WriteLine("Value of Num: {0}", getNum());
str);
nc2(5);
Console.WriteLine("Value of Num: {0}", getNum());
Console.ReadKey(); Following are the key points about Event,
}
}  Event Handlers in C# return void and take two
}
parameters.
Events  The First parameter of Event - Source of Event means
publishing object.
Events are user actions such as key press, clicks, mouse
 The Second parameter of Event - Object derived from
movements, etc., or some occurrence such as system
EventArgs.
generated notifications. Applications need to respond to
 The publishers determines when an event is raised and
events when they occur. For example, interrupts. Events are
the subscriber determines what action is taken in
used for inter-process communication.
response.
 An Event can have so many subscribers.

Division of Computer and Information Science


.NET Framework and C# lecture Notes

 Events are basically used for the single user action like
button click.
 If an Event has multiple subscribers then event
handlers are invoked synchronously.

Division of Computer and Information Science


.NET Framework and C# lecture Notes

UNIT –III class TestClass {


static void Main(string[] args) {
C# - using Libraries.
abc fc = new abc();
Namespace efg sc = new efg();
A namespace is designed for providing a way to keep one set fc.func();
of names separate from another. The class names declared in sc.func();
Console.ReadKey();
one namespace does not conflict with the same class names }
declared in another. }

Syntax:

namespace namespace_name { I/O Stream


// code declarations
} A stream is linked to a physical device by the I/O system.
The using keyword states that the program is using the
names in the given namespace. For example, we are using the The type of streams
System namespace in our programs
Byte Streams − It includes Stream, FileStream,
It can also avoid prepending of namespaces with the using
MemoryStream and BufferedStream.
namespace directive. This directive tells the compiler that the
subsequent code is making use of names in the specified Character Streams − It includes Textreader-TextWriter,
namespace StreamReader, StreamWriter and other streams.
Example
Predefined Streams
using System;
using first_space; Three predefined streams, which are exposed by the
using second_space;
properties called Console.In, Console.Out,and
namespace first_space { Console.Error, are available to all programs that use the
class abc { System namespace. Console.Out
public void func() {
Console.WriteLine("Inside first_space");
}
refers to the standard output stream.
}
} File I/O
namespace second_space {
class efg { A file is a collection of data stored in a disk with a specific
public void func() { name and a directory path. When a file is opened for reading
Console.WriteLine("Inside second_space");
}
or writing, it becomes a stream.
}
}

Division of Computer and Information Science


.NET Framework and C# lecture Notes

The stream is basically the sequence of bytes passing through Append − It opens an existing file and puts cursor at the
the communication path. There are two main streams: the end of file, or creates the file, if the file does not exist.
input stream and the output stream. The input stream is
used for reading data from file (read operation) and the Create − It creates a new file.
output stream is used for writing into the file (write CreateNew − It specifies to the operating system, that it
operation). should create a new file.
The System.IO namespace has various classes that are used Open − It opens an existing file.
for performing numerous operations with files, such as
creating and deleting files, reading from or writing to a file, OpenOrCreate − It specifies to the operating system that it
closing a file etc. should open a file if it exists, otherwise it should create a new
file.
FileStream Class -The FileStream class in the System.IO
namespace helps in reading from, writing to and closing files. Truncate − It opens an existing file and truncates its size to
This class derives from the abstract class Stream. zero bytes

Using System.io; FileAccess

To create a FileStream object to create a new file or open an FileAccess enumerators have members: Read, ReadWrite and
existing file. Write.

Syntax FileShare

FileStream <object_name> = new FileStream( <file_name>, Inheritable − It allows a file handle to pass inheritance to
<FileMode Enumerator>,<FileAccess Enumerator>, the child processes
<FileShare Enumerator>);
Example None − It declines sharing of the current file

FileStream F = new FileStream("sample.txt", Read − It allows opening the file for readin.
FileMode.Open, FileAccess.Read,
FileShare.Read);

ReadWrite − It allows opening the file for reading and


FileMode writing
The FileMode enumerator defines various methods for Write − It allows opening the file for writing
opening files. The members of the FileMode enumerator are −
Example

Division of Computer and Information Science


.NET Framework and C# lecture Notes

using System; Multithreading


using System.IO;
It is a process which contains multiple threads within a single
namespace FileIOApplication {
class Program { process. Here each thread performs different activities. For
static void Main(string[] args) { example, we have a class and this call contains two different
FileStream F = new FileStream("test.dat", methods, now using multithreading each method is executed
FileMode.OpenOrCreate,
FileAccess.ReadWrite); by a separate thread. So the major advantage of
multithreading is it works simultaneously, means multiple
for (int i = 1; i <= 20; i++) { tasks executes at the same time. And also maximizing the
F.WriteByte((byte)i);
}
utilization of the CPU because multithreading works on time-
F.Position = 0; sharing concept mean each thread takes its own time for
for (int i = 0; i <= 20; i++) { execution and does not affect the execution of another thread,
Console.Write(F.ReadByte() + " ");
this time interval is given by the operating system.
}
F.Close();
Console.ReadKey(); Example
}
} public class GFG {
}
// static method one
Multithreading
public static void method1()
Multitasking is the simultaneous execution of multiple tasks
or processes over a certain time interval. Windows operating {
system is an example of multitasking because it is capable of
// It prints numbers from 0 to 10
running more than one process at a time like running Google
Chrome, Notepad, VLC player etc. at the same time. for (int I = 0; I <= 10; I++) {

Thread Console.WriteLine("Method1 is : {0}", I);

A thread is a lightweight process, or in other words, a thread // When the value of I is equal to 5 then
is a unit which executes the code under the program.
// this method sleeps for 6 seconds
Every program by default carries one thread to executes the
logic of the program and the thread is known as the Main if (I == 5) {
Thread. Thread.Sleep(6000);

Division of Computer and Information Science


.NET Framework and C# lecture Notes

} Advantages of Multithreading:

} It executes multiple process simultaneously.

// static method two Maximize the utilization of CPU resources.

public static void method2() Time sharing between multiple process.

{
Networking and sockets
// It prints numbers from 0 to 10
The .NET framework provides two namespaces, System.Net
for (int J = 0; J <= 10; J++) { and System.Net.Sockets for network programming. The
classes and methods of these namespaces help us to write
Console.WriteLine("Method2 is : {0}", J);
programs,which can communicate across the network. The
} communication can be either connection oriented or
connectionless. They can also be either stream oriented or
} data-gram based. The most widely used protocol TCP is used
for stream-based communication and UDP is used for data-
// Main Method
grams based applications.
static public void Main()
The System.Net.Sockets.Socket is an important class from the
{ System.Net.Sockets namespace. A Socket instance has a local
and a remote end-point associated with it. The local end-point
// Creating and initializing threads
contains the connection information for the current socket
Thread thr1 = new Thread(method1); instance.

Thread thr2 = new Thread(method2); The .NET framework supports both synchronous and
asynchronous communication between the client and server.
thr1.Start();
A synchronous method is operating in
thr2.Start();
blocking mode, in which the method waits until the operation
} is complete before it returns. But an asynchronous method is
operating in non-blocking mode, where it returns
}
immediately, possibly before the operation has completed.

Division of Computer and Information Science


.NET Framework and C# lecture Notes

Dns class The basic idea of a socket has been around for decades, and
appears in many operating systems. The central concept is to
The System.net namespace provides this class, which can be present network communication through the same
used to creates and send queries to obtain information about abstractions as file I/O.
the host server from the Internet Domain Name Service
(DNS). streams are concerned with the body of an HTTP request or
response. With sockets, the streams are at a lower level,
Example encompassing all the data.
using System;
using System.Net;
using System.Net.Sockets; Socket Programming: Synchronous Clients
class MyClient
The steps for creating a simple synchronous client are as
{
follows.
public static void Main()
{ 1. Create a Socket instance.
IPHostEntry IPHost = Dns.Resolve("www.hotmail.com");
2. Connect the above socket instance to an end-point.
Console.WriteLine(IPHost.HostName);
string []aliases = IPHost.Aliases; 3. Send or Receive information.
Console.WriteLine(aliases.Length);
IPAddress[] addr = IPHost.AddressList; 4. Shutdown the socket
Console.WriteLine(addr.Length);
for(int i= 0; i < addr.Length ; i++) 5. Close the socket
{ The Socket class provides a constructor for creating a Socket
Console.WriteLine(addr[i]); instance.
}
} public Socket (AddressFamily af, ProtocolType pt, SocketType
} st)

Data handling
Socket
DBMS - Database Management System (DBMS) as a "software
Sockets are the most powerful networking mechanism
system that enables users to define, create, maintain and
available in .NET—HTTP is layered on top of sockets, and in
control access to the database.
most cases WCF is too. Sockets provide more or less direct
access to the underlying TCP/IP network services.

Division of Computer and Information Science


.NET Framework and C# lecture Notes

Database languages • Concurrency is easier to control.

Database languages are special-purpose languages, which • Data is more likely to be current than in other scenarios.
allow one or more of the following tasks, sometimes
distinguished as sublanguages: A connected scenario has the following disadvantages:

Data control language (DCL) – controls access to data. • It must have a constant network connection.

Data definition language (DDL) – defines data types such • Scalability


as creating, altering, or dropping and the relationships among Disconnected
them.
A disconnected environment is one in which a user or an
Data manipulation language (DML) – performs tasks such application is not constantly connected to a source of data.
as inserting, updating, or deleting data occurrences. Mobile users who work with laptop computers are the
Data query language (DQL) – allows searching for primary users in disconnected environments. Users can take
information and computing derived information. a subset of data with them on a disconnected computer, and
then merge changes back into the central data store.
ADO.NET
A disconnected environment provides the following
ADO.NET is the new database technology used in .NET advantages:
platform. ADO.NET is the next step in the evolution of
Microsoft ActiveX Data Objects (ADO). It does not share the • You can work at any time that is convenient for you, and
same programming model, but shares much of the ADO can connect to a data source at any time to process requests.
functionality. The ADO.NET as a marketing term that covers • Other users can use the connection.
the classes in the System.Data namespace. ADO.NET is a set
of classes that expose the data access services of the .NET • A disconnected environment improves the scalability and
Framework. performance of applications.

Connected Vs Disconnected A disconnected environment has the following disadvantages:

Connected • Data is not always up to date.

A connected environment is one in which a user or an • Change conflicts can occur and must be resolved.
application is constantly connected to adata source. A
connected scenario offers the following advantages: ADVANTAGES OF ADO.NET

• A secure environment is easier to maintain. ADO.NET provides the following advantages over other data
access models and components:
Division of Computer and Information Science
.NET Framework and C# lecture Notes

Interoperability. ADO.NET uses XML as the format for be lightweight, creating a minimal layer between the data
transmitting data from a data source to a local in-memory source and your code, increasing performance without
copy of the data. sacrificing functionality. The ADO.NET object model includes
the following data provider classes:
Maintainability. When an increasing number of users work
with an application, the increased use can strain resources. 1. SQL Server .NET Data Provider
By using n-tier applications, you can spread application logic
across additional tiers. ADO.NET architecture uses local in- 2. OLE DB .NET Data Provider
memory caches to hold copies of data, making it easy for 3. Oracle .NET Data Provider
additional tiers to trade information.
4. ODBC .NET Data Provider
Programmability. The ADO.NET programming model uses
strongly typed data. Strongly typed data makes code more 5. Other Native .NET Data Provider
concise and easier to write because Microsoft Visual Studio
.NET provides statement completion. Windows Forms/Applications

Performance. ADO.NET helps you to avoid costly data type The Windows Forms is a collection of classes and types that
conversions because of its use of strongly typed data. encapsulate and extend the Win32 API in an organized object
model. The .NET Framework contains an entire subsystem
Scalability. The ADO.NET programming model encourages devoted to Windows programming called Windows Forms. The
programmers to conserve system primary support for Windows Forms is contained in the
System.Windows.Forms namespace. A form encapsulates the
resources for applications that run over the Web. Because basic functionality necessary to create a window, display it on
data is held locally in memory caches, there is no need to the screen, and receive messages. A form can represent any
retain database locks or maintain active database type of window, including the main window of the application,
connections for extended periods. a child window, or even a dialog box.

The Form Class


.NET DATA PROVIDER Form contains significant functionality of its own, and it
A .NET data provider is used for connecting to a database, inherits additional functionality.
executing commands, and retrieving results. Those results Two of its most important base classes are
are either processed directly, or placed in an ADO.NET System.ComponentModel.Component, which supports the
DataSet in order to be exposed to the user in an ad-hoc .NET component model, and
manner, combined with data from multiple sources, or System.Windows.Forms.Control. The Control class defines
remoted between tiers. The .NET data provider is designed to features common to all Windows controls.

Division of Computer and Information Science


.NET Framework and C# lecture Notes

Creating Windows form Application

Creating a Windows Forms application is largely just a matter


of instantiating and extending theWindows Forms and GDI+
classes. In a nutshell, you typically complete the following
steps:

1. Create a new project defining the structure of a Windows


Forms application.

2. Define one or more Forms (classes derived from the Form


class) for the windows

in your application.

3. Use the Designer to add controls to your forms (such as


textboxes and checkboxes), and The Purpose of Web Forms
then configure the controls by setting their properties and Web Forms and ASP.NET were created to overcome some of
attaching event handlers. the limitations of ASP. Thesenew strengths include:
4. Add other Designer-managed components, such as menus • Separation of HTML interface from application logic
or image lists.
• A rich set of server-side controls that can detect the browser
5. Add code to your form classes to provide functionality. and send out appropriate markup language such as HTML
6. Compile and run the program • Less code to write due to the data binding capabilities of the
new server-side .NET controls
Web Forms/Application
• Event-based programming model that is familiar to
Web Forms are the heart and soul of ASP.NET. Web Forms
Microsoft Visual Basic programmers
are the User Interface (UI) elements that give Web
applications their look and feel. Web Forms are similar to • Compiled code and support for multiple languages, as
Windows Forms in that they provide properties, methods, and opposed to ASP which was interpreted as Microsoft Visual
events for the controls that are placed onto them. Basic Scripting (VBScript) or Microsoft Jscript.
Web Forms are made up of two components: the visual •Allows third parties to create controls that provide additional
portion (the ASPX file), and the code behind the form, which functionality
resides in a separate class file.

Division of Computer and Information Science


.NET Framework and C# lecture Notes

Exception Handling finally − The finally block is used to execute a given set of
statements, whether an exception is thrown or not thrown.
An exception is an unwanted or unexpected event, which For example, if you open a file, it must be closed whether an
occurs during the execution of a program i.e at runtime, that exception is raised or not.
disrupts the normal flow of the program’s instructions.
throw − A program throws an exception when a problem
This unwanted event is known as Exception. shows up. This is done using a throw keyword.
Errors:

Errors are unexpected issues that may arise during computer


program execution.
Exception Hierarchy
Errors cannot be handled.
All the exceptions are derived from the base class Exception
All Errors are exceptions. which gets further divided into two branches as
Exceptions: ApplicationException and SystemException.

Exceptions are unexpected events that may arise during run- SystemException is a base class for all CLR or program code
time. generated errors.

Exceptions can be handled using try-catch mechanisms. ApplicationException is a base class for all application
related exceptions.
All exceptions are not errors.
There are different kinds of exceptions which can be
Exceptions provide a way to transfer control from one part of generated in C# program:
a program to another. C# exception handling is built upon
four keywords: try, catch, finally, and throw. Divide By Zero exception: It occurs when the user attempts
to divide by zero
try − A try block identifies a block of code for which
particular exceptions is activated. It is followed by one or Out of Memory exceptions: It occurs when then the
more catch blocks. program tries to use excessive memory

catch − A program catches an exception with an exception Index out of bound Exception: Accessing the array element
handler at the place in a program where you want to handle or index which is not present in it.
the problem. The catch keyword indicates the catching of an Stackoverflow Exception: Mainly caused due to infinite
exception. recursion process

Division of Computer and Information Science


.NET Framework and C# lecture Notes

Null Reference Exception : Occurs when the user attempts


to reference an object which is of NULL type.

Example

public void division(int num1, int num2) {

try {

result = num1 / num2;

catch (DivideByZeroException e) {

Console.WriteLine("Exception caught: {0}", e);

Division of Computer and Information Science


.NET Framework and C# lecture Notes

UNIT – IV A web service enables communication among various


applications by using open standards such as HTML, XML,
Advanced featured using in C# WSDL, and SOAP. A web service takes the help of −

Web Services -WS XML to tag the data

A web service is any piece of software that makes itself SOAP to transfer a message
available over the internet and uses a standardized XML
messaging system. XML is used to encode all WSDL to describe the availability of service.
communications to a web service. Web services allow applications to share data. Web services
Web services are self-contained, modular, distributed, can be called across platforms and operating systems
dynamic applications that can be described, published, regardless of programming language. .NET is Microsoft's
located, or invoked over the network to create products, platform for XML Web services.
processes, and supply chains. These applications can be Web Service Applications
local, distributed, or web-based. Web services are built on top
of open standards such as TCP/IP, HTTP, Java, HTML, and There are several web service available with .Net Framework, such
XML. as:
Web services are XML-based information exchange systems 1) Validation Controls:
that use the Internet for direct application-to-application
interaction. These systems can include programs, objects, 1. E-mail address validator,
messages, or documents. A web service is a collection of open
protocols and standards used for exchanging data between 2. Regular expression validator,
applications or systems.
3. Range Validator, etc.
Components of Web Services
2) Login Controls:
The basic web services platform is XML + HTTP. All the
1. Create user
standard web services work using the following components −

SOAP (Simple Object Access Protocol)


2. Delete user

UDDI (Universal Description, Discovery and Integration) 3. Manage users, etc.

WSDL (Web Services Description Language) Some Web services are also available on internet , which are free and
offer application-components like:
Working process

Division of Computer and Information Science


.NET Framework and C# lecture Notes

 Currency Conversion Declaring WebMethod methods


 Weather Reports
A WebMethod represents a method for web. WebMethod has
 Language Translation six properties they are :
 Search Engines
 Document Convertor, etc. 1) Description

Some are paid and can be use by authorized sites, such as: 2) MessageName

3) EnableSession
 Credit and Debit card payment
 Net Banking, etc. 4) CacheDuration

Web Service Architecture 5) TransactionOption

6) BufferResponse

Create web service

URL:
https://www.tutorialspoint.com/asp.net/asp.net_web_service
s.htm

Windows Services

Windows Services is previously called as NT Service. The Idea


of creating a windows service application is two fold one is to
create a long running application and the other is service
Creating Web Service applications are the application that run directly in the
windows session itself.
To create and expose ASP.NET Web Servies by authoring and
saving text files with the file extension ―asmx within the Windows Services are non-UI software applications that run
virtual path of an ASP.NET Web Application. in the background. Windows services are usually started
when an operating system boots and scheduled to run in the
To understand the concept of Web Services we have given an
background to execute some tasks. Windows services can
example of Web Service,which provides the current time of
also be started automatically or manually. You can also
day on its machine.
manually pause, stop and restart Windows services.

Division of Computer and Information Science


.NET Framework and C# lecture Notes

There are basically two types of Services that can be created Refer the following url:
in .NET Framework. Services that are only service in a
process are assigned the type Win32OwnProcess. Services https://docs.microsoft.com/en-
that share a process with another service are assigned the us/dotnet/framework/windows-services/walkthrough-
type Win32ShareProcess.The type of the service can be creating-a-windows-service-application-in-the-component-
queried. There are other types of services which are designer
occasionally used they are mostly for hardware, Kernel, File
System. https://dotnetcoretutorials.com/2019/09/19/creating-
windows-services-in-net-core-part-1-the-microsoft-way/
The Main method for your service application must issue the
Run command for the services your project contains. The Run
method loads the services into the Services Control Manager Reflection
on the appropriate server. If you use the Windows Services
project template, this method is written for you automatically. Reflection objects are used for obtaining type information at
runtime. The classes that give access to the metadata of a
Window service application development can be divided to two running program are in the System.Reflection namespace.
phases. One is the development of Service functionality and
the last phases is about the development. The 3 Mainclasses The System.Reflection namespace contains classes that allow
involved in Service development are: you to obtain information about the application and to
dynamically add types, values, and objects to the application.
 System.ServiceProcess.ServiceBase
Applications of Reflection
 System.ServiceProcess.ServiceProcessInstaller
 ServiceController Reflection has the following applications −
Developing Window Service It allows view attribute information at runtime.
To develop and run a Window Service application on .NET It allows examining various types in an assembly and
frame to the he following steps. instantiate these types.
Step 1: Create Skeleton of the Service It allows late binding to methods and properties
Step 2: Add functionality to your service It allows creating new types at runtime and then performs
some tasks using those types.
Step 3: Install and Run the Service

Step 4: Start and Stop the Service Reflection is a process to get metadata of a type at runtime.
The System.Reflection namespace contains required classes
Create a Windows service Application for reflection such as:

Division of Computer and Information Science


.NET Framework and C# lecture Notes

Class Description Gets the Attributes associated with


Attributes
describes an assembly which is a reusable, the type.
Assembly versionable, and self-describing building block of a BaseType Gets the base or parent type.
common language runtime application Gets the fully qualified name of the
FullName
AssemblyName Identifies an assembly ith a unique name type.
is used to check if the type is
Describes a class constructor and gives access to the IsAbstract
ConstructorInfo Abstract.
metadata
Describes the class method and gives access to its
MethodInfo
metadata C# Type Methods
Describes the parameters of a method and gives
ParameterInfo
access to its metadata Method Description
Describes the event info and gives accessto its Returns all the public
EventInfo GetConstructors()
metadata constructors for the Type.
Discovers the attributes of a property and provides Returns all the constructors
PropertyInfo GetConstructors(BindingFlags) for the Type with specified
access to property metadata
BindingFlags.
Obtains information about the attributes of a
MemberInfo Returns all the public fields
member and provides access to member metadata GetFields()
for the Type.
Returns all the public
Viewing Metadata GetFields(BindingFlags) constructors for the Type with
specified BindingFlags.
The MemberInfo object of the System.Reflection class needs Returns all the public
GetMembers()
to be initialized for discovering the attributes associated with members for the Type.
a class. Returns all the members for
GetMembers(BindingFlags) the Type with specified
System.Reflection.MemberInfo info = typeof(MyClass); BindingFlags.
Returns all the public
GetMethods()
methods for the Type.
Returns all the methods for
C# Type Properties GetMethods(BindingFlags) the Type with specified
BindingFlags.
Property Description Returns all the public
GetProperties()
Assembly Gets the Assembly for this type. properties for the Type.
Gets the Assembly qualified name for Returns all the properties for
AssemblyQualifiedName GetProperties(BindingFlags)
this type. the Type with specified

Division of Computer and Information Science


.NET Framework and C# lecture Notes

BindingFlags. programming mechanisms that simplify the implementation


GetType() Gets the current Type. of COM objects. The family of COM technologies includes
Gets the Type for the given COM+, Distributed COM (DCOM) and ActiveX® Controls.
GetType(String)
name.
COM (Component Object Model) was the first programming
model that provided component based approach to software
Example development. This component based approach of COM
allowed us to develop small, logical reusable and standalone
C# Reflection Example: Get Type
modules that integrates into a single application. But these
using System; components could not be displayed over a network. So these
drawback produce another model that is DCOM
public class ReflectionExample (Distributed COM).

{
The DCOM programming model enables you to display COM
public static void Main() components over a network and easily distribute
applications across platforms. DCOM components also help
{ in two-tier client/server applications. These models also have
some drawbacks that help the development of the COM+
int a = 10;
approach.
Type type = a.GetType();
Creating COM components in .NET
Console.WriteLine(type);
The following steps explain the way to create the COM
}
server in C#:
}
 Create a new Class Library project.
COM  Create a new interface, say IManagedInterface, and
declare the methods required. Then provide the Guid
Component Object Model (COM) is a method to facilitate
(this is the IID) for the interface using the
communication between different applications and
GuidAttribute defined in
languages. COM is used by developers to create re-usable
System.Runtime.InteropServices. The Guid can be
software components, link components together to build
created using the Guidgen.exe.
applications, and take advantage of Windows services. COM
 Define a class that implements this interface. Again
objects can be created with a variety of programming
provide the Guid (this is the CLSID) for this class
languages. Object-oriented languages, such as C++, provide
also.
Division of Computer and Information Science
.NET Framework and C# lecture Notes

 Mark the assembly as ComVisible. For this go to proxy called the Runtime Callable Wrapper (RCW). Although
AssemblyInfo.cs file and add the following statement the RCW appears to be an ordinary object to .NET clients, it's
[assembly: ComVisible (true)]. This gives the primary function is to marshal calls between a .NET client
accessibility of all types within the assembly to and a COM object.
COM.
 Build the project. This will generate an assembly in To use a COM component,
the output path. Now register the assembly using 
regasm.exe (a tool provided with the .NET Right click the Project and click on Add References.
Framework) - regasm \bin\debug\ComInDotNet.dll  Select the COM tab
\tlb:ComInDotNet.tlb this will create a TLB file after  And at last select COM component
registration.
 Alternatively this can be done in the Project
properties --> Build --> check the Register for COM
interop.

The COM server is ready. Now a client has to be created. It


can be in any language. If the client is .NET, just add the
above created COM assembly as a reference and use it.
Localization

Call COM components from .NET

COM components and .NET Components have a different


internal architecture. For both of them to communicate with
each other, the inter-operation feature is required, this Globalization and Localization
feature is called interoperability. Enterprises that have
written their business solutions using the old native COM Globalization is the process of designing and
technology need a way for re-using these components in the developing applications that function for multiple
new .NET environment. cultures.

.NET components communicate with COM using RCW Localization is the process of customizing your
(Runtime Callable Wrapper) application for a given culture and locale.

RCW:- RCW Means Runtime Callable Wrappers, The Common Globalization


Language Runtime (CLR) exposes COM objects through a
Division of Computer and Information Science
.NET Framework and C# lecture Notes

Globalization involves designing and developing a Localization


world-ready app that supports localized interfaces and
regional data for users in multiple cultures. Before Localization is the process of translating an application's
beginning the design phase, you should determine resources into localized versions for each culture that the
which cultures your app will support. Although an app application will support. You should proceed to the
targets a single culture or region as its default, you can localization step only after completing the Localizability
design and write it so that it can easily be extended to Review step to verify that the globalized application is ready
users in other cultures or regions. for localization.

As developers, we all have assumptions about user An application that is ready for localization is separated into
interfaces and data that are formed by our cultures. For two conceptual blocks: a block that contains all user
example, for an English-speaking developer in the United interface elements and a block that contains executable
States, serializing date and time data as a string in the code. The user interface block contains only localizable
format MM/dd/yyyy hh:mm:ss seems perfectly reasonable. user-interface elements such as strings, error messages,
However, deserializing that string on a system in a different dialog boxes, menus, embedded object resources, and so on
culture is likely to throw a FormatException exception or for the neutral culture. The code block contains only the
produce inaccurate data. Globalization enables us to application code to be used by all supported cultures. The
identify such culture-specific assumptions and ensure that common language runtime supports a satellite assembly
they do not affect our app's design or code. resource model that separates an application's executable
code from its resources. For more information about
Strings implementing this model, see Resources in .NET.

The handling of characters and strings is a central focus of For each localized version of your application, add a new
globalization, because each culture or region may use satellite assembly that contains the localized user interface
different characters and character sets and sort them block translated into the appropriate language for the target
differently. This section provides recommendations for using culture. The code block for all cultures should remain the
strings in globalized apps. same. The combination of a localized version of the user
Use Unicode internally interface block with the code block produces a localized
version of your application.
By default, .NET uses Unicode strings. A Unicode string
consists of zero, one, or more Char objects, each of which The Windows Software Development Kit (SDK) supplies the
represents a UTF-16 code unit. There is a Unicode Windows Forms Resource Editor (Winres.exe) that allows
representation for almost every character in every character you to quickly localize Windows Forms for target cultures.
set in use throughout the world.

Division of Computer and Information Science


.NET Framework and C# lecture Notes

Cultures and Locales You create a global resource file by putting it in the
reserved folder App_GlobalResources at the root of the
The language needs to be associated with the particular application.
region where it is spoken, and this is done by using locale Any .resx file that is in the App_GlobalResources
(language + location). For example: fr is the code for French folder has global scope.
language. fr-FR means French language in France. So, for
specifies only the language whereas fr-FR is the locale.
Similarly, fr-CA defines another locale implying French
language and culture in Canada. If we use only fr, it implies
a neutral culture (i.e., location neutral).
Set culture information

Application level -In web.config file

<configuration>
<system.web>
<globalization culture="fr-FR" uiCulture="fr-FR"/>
</system.web>
</configuration> Local Resource Files

Resource Files A local resources file is one that applies to only one ASP. NET
page or user control (an ASP. NET file that has a file-name
extension of .aspx, .ascx, or .master).
A resource file is an XML file that contains the strings that
you want to translate into different languages or paths to
images.
The resource file contains key/value pairs. Each pair is an
individual resource. Key names are not case sensitive.

e.g. A resource file might contain a resource with the key


Button1 and the value Submit
Resource files in ASP. NET have an .resx extension. At run
time, the .resx file is compiled into an assembly.

Global Resource Files

Division of Computer and Information Science


.NET Framework and C# lecture Notes

Unit-V required as share resources. This is done with the help of a


Distributed application network.

A distributed system contains multiple nodes that are Advantages of Distributed Systems
physically separate but linked together using the network.
All the nodes in this system communicate with each other  All the nodes in the distributed system are connected to
and handle processes in tandem. Each of these nodes each other. So nodes can easily share data with other
contains a small part of the distributed operating system nodes.
software.  More nodes can easily be added to the distributed
system i.e. it can be scaled as required.
 Failure of one node does not lead to the failure of the
entire distributed system. Other nodes can still
communicate with each other.
 Resources like printers can be shared with multiple
nodes rather than being restricted to just one.

Disadvantages of Distributed Systems

 It is difficult to provide adequate security in distributed


Types of Distributed Systems
systems because the nodes as well as the connections
The nodes in the distributed systems can be arranged in the
need to be secured.
form of client/server systems or peer to peer systems. Details
 Some messages and data can be lost in the network
about these are as follows:
while moving from one node to another.
Client/Server Systems
 The database connected to the distributed systems is
In client server systems, the client requests a resource and
quite complicated and difficult to handle as compared to
the server provides that resource. A server may serve multiple
a single user system.
clients at the same time while a client is in contact with only
one server. Both the client and server usually communicate  Overloading may occur in the network if all the nodes of
via a computer network and so they are a part of distributed the distributed system try to send data at once.
systems.
Peer to Peer Systems
Refer URL:
The peer to peer systems contains nodes that are equal https://www.tutorialspoint.com/software_archit
participants in data sharing. All the tasks are equally divided ecture_design/distributed_architecture.htm
between all the nodes. The nodes interact with each other as

Division of Computer and Information Science


.NET Framework and C# lecture Notes

Distributed Applications Environment/Remote Procedure Calls (DEC/RPC),


Microsoft Distributed Component Object Model (DCOM),
Enterprises and users demand distributed applications. Common Object Request Broker Architecture (CORBA), and
Distributed applications allow objects to talk across process Java Remote Method Invocation (RMI). Some of these
boundaries. Often, distributed applications also meet the implementations are widely deployed in enterprises.
following objectives:
However, modern business requirements are different from
 Establish communication between objects that run in those of earlier days. Today, businesses seek solutions that
different application domains and processes, whether on the can be developed rapidly, that integrate well with their
same computer or across the Internet. legacy applications, and that interoperate well with their
business partners. Each of the technologies already
 Enable enterprise application integration by mentioned failed to satisfy one or more of these
establishing communication between objects that run on requirements.
heterogeneous architectures.
In 2000, Microsoft introduced the .NET Framework for
 Enable application availability by making sure that designing next-generation distributed applications. As you'll
portions of an application run even if some components are explore more in this book, the .NET Framework is
busy or have failed. specifically targeted to meet the needs of modern business,
whether the need is rapid development or integration or
 Provide increased security and scalability by dividing interoperability.
the application into several layers (or tiers).

Using the .NET Framework to Develop Distributed


Evolution of Distributed Applications Applications

A well-designed distributed application has the potential to The .NET Framework provides various mechanisms to
be more connected, more available, more scalable, and more support distributed application development. Most of this
robust than an application where all components run on a functionality is present in the following three namespaces
single computer. This is a desirable model for an enterprise of the Framework Class Library (FCL):
application.
 The System.Net Namespace—This namespace
Traditionally, there have been several efforts to design includes classes to create standalone listeners and
frameworks for developing distributed applications. A few custom protocol handlers to start from scratch and
well-known frameworks are Distributed Computing create your own framework for developing a
distributed application. Working with the

Division of Computer and Information Science


.NET Framework and C# lecture Notes

System.Net namespace directly requires a good  The functionality offered by .NET remoting and
understanding of network programming. ASP.NET Web services appears very similar. In fact,
ASP.NET Web services are actually built on the
 The System.Runtime.Remoting Namespace—This .NET remoting infrastructure. It is also possible to
namespace includes the classes that constitute the use .NET remoting to design Web services. Given
.NET remoting framework. The .NET remoting the amount of similarity, how do you choose one
framework allows communication between objects over the other in your project? Simply put, the
living in different application domains, whether or decision depends on the type of application you
not they are on the same computer. Remoting want to create. You'll use
provides an abstraction over the complex network
programming and exposes a simple mechanism for  .NET Remoting when both the end points (client
inter-application domain communication. The key and server) of a distributed application are in your
objectives of .NET remoting are flexibility and control. This might be a case when an application
extensibility. has been designed for use within a corporate
network.
 The System.Web.Services Namespace—This
namespace includes the classes that constitutes the  ASP.NET Web services when one end point of a
ASP.NET Web services framework. ASP.NET Web distributed application is not in your control. This
services allow objects living in different application might be a case when your application is
domains to exchange messages through standard interoperating with your business partner's
protocols such as HTTP and SOAP. ASP.NET Web application.
services, when compared to remoting, provide a
much higher level of abstraction and simplicity. The Refer URL:
key objectives of ASP.NET Web services are the ease https://www.pearsonitcertification.com/articles/ar
of use and interoperability with other systems. ticle.aspx?p=31490

 Both .NET remoting and ASP.NET Web services


provide a complete framework for designing
distributed applications. Most programmers will
use either .NET remoting or ASP.NET Web services XML
rather than build a distributed programming XML stands for Extensible Markup Language. It is a text-
framework from scratch with the System.Net based markup language derived from Standard
namespace classes. Generalized Markup Language (SGML).
XML tags identify the data and are used to store and
organize the data, rather than specifying how to display it
Division of Computer and Information Science
.NET Framework and C# lecture Notes

like HTML tags, which are used to display the data. XML ASP.NET use the XmlSerializer class to create XML
is not going to replace HTML in the near future, but it streams that pass data between XML Web service
introduces new possibilities by adopting many successful applications throughout the Internet or on intranets.
features of HTML. Conversely, deserialization takes such an XML stream
There are three important characteristics of XML that and reconstructs the object.
make it useful in a variety of systems and solutions −
 XML is extensible − XML allows you to create your XML serialization can also be used to serialize objects
own self-descriptive tags, or language, that suits your into XML streams that conform to the SOAP specification.
application. SOAP is a protocol based on XML, designed specifically to
 XML carries the data, does not present it − XML transport procedure calls using XML.
allows you to store the data irrespective of how it will
be presented.
 XML is a public standard − XML was developed by an Namespaces to use XmlSerializer
organization called the World Wide Web Consortium
using System.Xml.Serialization
(W3C) and is available as an open standard.

Serialization Deserializing XML Data

Serialization is the process of converting an object into a Deserialization is the process of taking XML-formatted
stream of bytes. In this article, I will show you how to data and converting it to a .NET framework object: the
serialize object to XML in C#. XML serialization converts reverse of the process shown above. Providing that the
the public fields and properties of an object into an XML XML is well-formed and accurately matches the structure
stream. of the target type, deserialization is a relatively
XML serialization converts (serializes) the public fields straightforward task.
and properties of an object, and the parameters and
return values of methods, into an XML stream that In the example below, the XML output of the preceding
conforms to a specific XML Schema definition language examples is hard-coded into a string, but it could be
(XSD) document. XML serialization results in strongly fetched from a network stream or external file. The
typed classes with public properties and fields that are XmlSerializer class is used to deserialize the string to an
converted to a serial format (in this case, XML) for storage instance of the Test class, and the example then prints
or transport. the fields to the console. To obtain a suitable stream that
can be passed into the XmlSerializer’s constructor, a
Because XML is an open standard, the XML stream can StringReader (from the System.IO namespace) is
be processed by any application, as needed, regardless of declared.
platform. For example, XML Web services created using

Division of Computer and Information Science


.NET Framework and C# lecture Notes

Refer URL: http://csharp.net- Console.WriteLine("Inside the unsafe code


block");
informations.com/xml/xml-serialization-tutorial.htm
Console.WriteLine("The value of x is " +
*ptr);
Unsafe Mode } // end
The unsafe code or the unmanaged code is a code block
Unsafe code in C# is the part of the program that runs outside that uses a pointer variable.
the control of the Common Language Runtime (CLR) of the
.NET frameworks. The CLR is responsible for all of the Pointers
background tasks that the programmer doesn’t have to worry
A pointer is a variable whose value is the address of
about like memory allocation and release, managing stack etc.
another variable i.e., the direct address of the memory
Using the keyword “unsafe” means telling the compiler that
location. similar to any variable or constant, you must
the management of this code will be done by the programmer. declare a pointer before you can use it to store any
Making a code content unsafe introduces stability and variable address.
security risks as there are no bound checks in cases of arrays,
memory related errors can occur which might remain Syntax
unchecked etc.
type *var-name;
A programmer can make the following sub-programs as
unsafe:

 Code blocks Following are valid pointer declarations


 Methods
int *ip; /* pointer to an integer */
 Types
double *dp; /* pointer to a double */
 Class float *fp; /* pointer to a float */
 Struct char *ch /* pointer to a character */

Example Graphical Device Interface (GDI)


unsafe
{
int x = 10; Graphics Device Interface + (GDI+) is a graphical
int* ptr; subsystem of Windows that consists of an application
ptr = &x;
programming interface (API) to display graphics and
// displaying value of x using pointer formatted text on both video display and printer.

Division of Computer and Information Science


.NET Framework and C# lecture Notes

GDI+ acts as an intermediate layer between applications


and device drivers for rendering two-dimensional
graphics, images and text.

GDI was the tool by which the what you see is what you
get (WYSIWYG) capability was provided in Windows
applications. GDI+ is an enhanced C++-based version of
GDI. GDI+ helps the developer to write device-
The features included in GDI+ are:
independent applications by hiding the details of graphic
hardware. It also provides graphic services in a more
 Gradient brushes used for filling shapes, paths
optimized manner than earlier versions. Due to its object-
and regions using linear and path gradient pushes
oriented structure and statelessness, GDI+ provides an
 Cardinal splines for creating larger curves formed
easy and flexible interface developers can use to interact
out of individual curves
with an application's graphical user interface (GUI).
 Independent path objects for drawing a path
Although GDI+ is slightly slower than GDI, its rendering
multiple times
quality is better.
 A matrix object tool for transforming (rotating,
The GDI+ services can be categorized into 2D vector translating, etc.) graphics
graphics, imaging and typography. Vector graphics  Regions stored in world coordinates format, which
include drawing primitives like rectangles, lines and allows them to undergo any transformation stored
curves. These primitives are drawn using objects of a in a transformation matrix
specific class, which has all the information required.  Alpha blending to specify the transparency of the
Imaging involves displaying complex images that cannot fill color
be displayed using vector graphics and performing image  Multiple image formats (BMP, IMG, TIFF, etc.)
operations such as stretching and skewing. Simple text supported by providing classes to load, save and
can be printed in multiple fonts, sizes and colors using manipulate them
typography services of GDI+.  Sub-pixel anti-aliasing to render text with a
smoother appearance on a liquid crystal display
(LCD) screen

Managed and Unmanaged Code

Code written in the Microsoft .NET development


environment is divided into two categories: managed and

Division of Computer and Information Science


.NET Framework and C# lecture Notes

unmanaged. In brief, code written in the .NET Framework


that is being managed by the common language runtime
(CLR) is called managed code. Code this is not being
managed by the CLR is called unmanaged code.

Managed code enjoys many rich features provide by the


CLR, including automatic memory management and
garbage collection, cross-language integration, language
independence, rich exception handling, improved
security, debugging and profiling, versioning, and
deployment. With the help of garbage collector (GC), the
CLR automatically manages the life cycle of the objects.
When the GC finds that an object has not been used after
a certain amount of time, the CLR frees resources
associated with that object automatically and removes
the object from the memory. You can also control the life
cycle of the objects programmatically.

To write both managed and unmanaged applications


using Microsoft Visual Studio .NET. You can use Visual
C++ to write unmanaged code in Visual Studio .NET.
Managed Extensions to C++ (MC++) is the way to write
C++ managed code. Code written using C# and Visual
Basic .NET is managed code.

Division of Computer and Information Science

You might also like