Dot Net
Dot Net
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.
.NET Framework
.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.
• 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
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
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
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
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
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);
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.
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;
} An object consists of :
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)
{
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
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;
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 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]);
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.
Events are basically used for the single user action like
button click.
If an Event has multiple subscribers then event
handlers are invoked synchronously.
Syntax:
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
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);
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);
} Advantages of Multithreading:
{
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.
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.
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.
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.
in your application.
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:
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
Example
try {
catch (DivideByZeroException e) {
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 −
WSDL (Web Services Description Language) Some Web services are also available on internet , which are free and
offer application-components like:
Working process
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
6) BufferResponse
URL:
https://www.tutorialspoint.com/asp.net/asp.net_web_service
s.htm
Windows Services
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:
{
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.
.NET components communicate with COM using RCW Localization is the process of customizing your
(Runtime Callable Wrapper) application for a given culture and locale.
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.
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
<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.
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.
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
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
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 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
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