Upload
others
View
7
Download
0
Embed Size (px)
Citation preview
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
1 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
TABLE OF CONTENTS
S.NO DATE TOPIC PAGE
NO
UNIT-I
1 Review OOP Concept 4
2 Structure of.NET Framework 7
3 Simple Input and Output Operations 10
4 Getting and displaying input/ output 11
5 Operators 12
6 Arrays 16
7 Structures 17
UNIT-II
8 Inheritance in C# 20
9 Namespace 24
10 Polymorphism 26
11 Interfaces 27
12 Delegataes 29
13 Publish /Subscribe design patterns 32
14 Operator Overloading 33
UNIT-III
15 C# Concepts for creating Data Structures 37
16 Stream and its usage of C# 39
17 Filestreams 39
18 File Operation in C# 41
19 Multithreading 46
20 S Synchronization. 47
UNIT-IV
21 XML Data 51
22 Reading & Writing XML File 52
23 Architecture of ADO.Net 54
24 ADO.NET Connected and Disconnected Models 55
25 XML and ADO.NET 59
26 Simple and Complex Data Binding 60
27 Data Grid View Class. 63
UNIT-V
28 Application Domains 66
29 Remoting 67
30 Leasing and Sponsorship 68
31 .NET Coding Design Guidelines 68
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
2 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
32 Assemblies 69
33 XML web service application 70
WSDL 70
SOAP 72
APPENDICES
A Glossary 73
B Question Bank 90
C Previous Year University question papers 103
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
3 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
CS2041 C# AND .NET FRAMEWORK L T P C 3 0 0 3
UNIT I 9 Review of OOP Concepts - Overview of .NET Framework - Basic Elements of C# - Program
Structure and simple Input and Output Operations – Operators and Expressions –
Statements – Arrays and Structures.
UNIT II 9 Inheritance - Namespace – Polymorphism – Interface and Overloading – Multiple Inheritance –
Property – Indexes – Delegates – Publish/Subscribe Design Patterns- Operator Overloading-
Method Overloading
UNIT II 9 C# Concepts for creating Data Structures - File Operation – File Management systems – Stream
Oriented Operations- Multitasking – Multithreading – Thread Operation – Synchronization.
UNIT IV 9 Working with XML – Techniques for Reading and Writing XML Data - Using XPath and
Search XML - ADO.NET Architecture – ADO.NET Connected and Disconnected Models
– XML and ADO.NET – Simple and Complex Data Binding– Data Grid View Class.
UNIT V 9 Application Domains – Remoting – Leasing and Sponsorship - .NET Coding Design Guidelines
–Assemblies – Security – Application Development – Web Services - Building an XML
Web Service - Web Service Client – WSDL and SOAP – Web Service with Complex Data Types
– Web Service Performance.
TOTAL = 45
TEXT BOOKS:
1. S. Thamarai Selvi and R. Murugesan ―A Textbook on C# ―, Pearson Education,2003.
2. Stephen C. Perry ― Core C# and .NET‖, Pearson Education,2006.
REFERENCES: 1. Jesse Liberty, ―Programming C#‖, Second Edition, O’Reilly Press, 2002.
2. Robinson et al, ―Professional C#‖, Fifth Edition, Wrox Press, 2002.
3. Herbert Schildt, ―The Complete Reference: C#‖, Tata McGraw Hill, 2004.
4. Andrew Troelsen, ―C# and the .NET Platform‖, A! Press, 2003.
5. Thuan Thai and Hoang Q. Lam, ―. NET Framework Essentials‖, Second
Edition, O’Reilly, 2002.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
4 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
UNIT – I
1.Review OOP Concept
Class is like the BLUEPRINT to make something.
Object is made from a BLUEPRINT. So you can make many Objects from 1 Class.
When you make an OBJECT from a CLASS, it is called an INSTANCE of a Class.
Objects have
1. Name like a name you give an object Identifier
2. Attributes like specific characteristics for the object Variables
3. Behaviours like actions the object can perform Instance Methods
UML – Unified Modeling Language
Because in Java everything is wrapped in a class, it can get very confusing!
We can use UML to show the structure of a Class.
Name of Class
± Attributes/Variables : Data-Type
± Behaviour/Methods (param name: param data-type, etc …): Return-Type
± plus or minus represent the ACCESS MODIFIERS, which are:
+ public
- private
Example
house1 OBJECT
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
5 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
House
-number: int
-street: String
-colour: String
-garage: boolean
House(n: int, s: String, c: String, g: boolean)
+getNumber(): int
+getStreet(): String
+getColour(): String
+haveGarage(): boolean
+paintHouse(String colour):void
number = 10
street = “Nabob Cres.”
colour = “beige”
garage = false
plus + Behaviours/Methods
House CLASS
house2 OBJECT
number = 2
street = “Milita Cres.”
colour = “blue”
garage = true
plus + Behaviours/Methods
Attributes /
Variables
Behaviours /
Methods
Name of Class
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
6 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
Encapsulation and Access Modifiers
We use public and private to add security to VARIABLES and METHODS. This is called
ENCAPSULATION.
public means a VARIABLE or METHOD can be used INSIDE & OUTSIDE the class
private means a VARIABLE or METHOD can only be used INSIDE the class
Public Example Private Example
public class Student
{
public int age =0;
} // Student class
public class Main
public class Student
{
private int age =10;
public void changeAge(int num){
if (num>0){
age=num;
}
}//end changeAge
public int getAge(){
return age;
}//end getAge
} // Student class
public class Main
{
name = john
mark1 = 50
mark2 = 70
average = 60
plus + Behaviours/Methods
name = tom
mark1 = 80
mark2 = 75
average = 77.5
plus + Behaviours/Methods
student2 OBJECT
Student
-name: String
-mark1: int
-mark2: int
-average: double
Student(n: String)
+setMarks(x : int, y : int) : void
+calcAverage() : void
+message() : String
Student CLASS
Name of Class
Attributes /
Variables
Behaviours /
Methods
student1 OBJECT
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
7 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
{
public static void main (String[] args)
{
//can change ―age‖ to anything
//they want! BAD THING!
s.age = -99;
System.out.println(s.age);
} // main method
} // Main class
public static void main (String[] args)
{
Student s = new Student();
//s.age = 100; no longer possible
because private
//won’t change to a negative because
//the method checks for that
s.changeAge(-100);
System.out.println(s.getAge());
} // main method
} // Main class
Why are the variables private and methods public?
Because we want to protect variables from being accessed directly; so they can’t be changed or
used incorrectly. To GET a value from a variable or to GIVE a variable a value we write public
methods to do this.
For example we could have changed the setMarks method from the Student Class to prevent users
from entering an incorrect value:
public void setMarks(int x, int y){
mark1 = x;
mark2 = y;
}//end setMarks
public void setMarks(int x, int y){
if (x > 100) {
mark1 = 100;
}else{
mark1 = x;
}//end if
if (y > 100){
mark2 = 100;
}else{
mark2 = y;
}//end if
}//end setMarks
2. STRUCTURE OF .NET FRAMEWORK The Microsoft .Net Framework is a new computing
platform that provides tools and technologies need to build networked applications as well as
distributed web services and web applications.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
8 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
The .Net Framework provides the necessary compile time and run time foundation to build
and run any language that conforms to the Common Language Specification(CLS)
Components of .Net Framework
Net Framework is a platform that provides tools and technologies to develop Windows,
Web and Enterprise applications. It mainly contains two components,
1. Common Language Runtime (CLR)
2. .Net Framework Class Library
Common Language Runtime (CLR)
.Net Framework provides runtime environment called Common Language Runtime
(CLR).It provides an environment to run all the .Net Programs.
The code which runs under the CLR is called as Managed Code.
Programmers need not to worry on managing the memory if the programs are running under
the CLR as it provides Programmatically, when our program needs memory, CLR allocates
the memory for scope and de-allocates the memory if the scope is completed.
Language Compilers (e.g. C#, VB.Net, J#) will convert the Code/Program to Microsoft
Intermediate memory management and thread management.
Language (MSIL) intern this will be converted to Native Code by CLR.
There are currently over 15 language compilers being built by Microsoft and other
companies also producing the code that will execute under CLR.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
9 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
Net Framework Class Library (FCL)
This is also called as Base Class Library and it is common for all types of applications i.e.
the way you access the Library Classes and Methods in VB.NET will be the same in C#,
and it is common for all other languages in .NET.
The following are different types of applications that can make use of .net class library.
1. Windows Application.
2. Console Application
3. Web Application.
4. XML Web Services.
5. Windows Services.
Common Type System (CTS)
It describes set of data types that can be used in different .Net languages in common. (i.e),
CTS ensures that objects written in different .Net languages can interact with each other.
For Communicating between programs written in any .NET complaint language, the types
have to be compatible on the basic level.
The common type system supports two general categories of types:
Value types:
Value types directly contain their data, and instances of value types are either
allocated on the stack or allocated inline in a structure. Value types can be built-in
(implemented by the runtime), user-defined, or enumerations.
Reference types: Reference types store a reference to the value's memory address, and are allocated on
the heap. Reference types can be self-describing types, pointer types, or interface types. The
type of a reference type can be determined from values of self-describing types. Self-
describing types are further split into arrays and class types. The class types are user-defined
classes, boxed value types, and delegates.
CommonLanguageSpecification(CLS)
It is a sub set of CTS and it specifies a set of rules that needs to be adhered or satisfied by all
language compilers targeting CLR. It helps in cross language inheritance and cross language
debugging.
Commonlanguagespecification
Rules:
It describes the minimal and complete set of features to produce code that can be hosted by
CLR. It ensures that products of compilers will work properly in .NET environment.
Sample Rules:
Representation of text strings
Internal representation of enumerations
Definition of static members and this is a subset of the CTS which all .NET
languages are expected to support.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
10 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
Microsoft has defined CLS which are nothing but guidelines that language to
follow so that it can communicate with other .NET languages in a seamless
manner.
3. PROGRAM STRUCTURE AND SIMPLE INPUT AND OUTPUT OPERATIONS.
A C# program consists of the following parts:
Namespace declaration
A class
Class methods
Class attributes
A Main method
Statements and Expressions
Comments
Let us look at a simple code that prints the words "Hello World":
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
/* my first program in C# */
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}
When this code is compiled and executed, it produces the following result:
Hello World
Let us look at the various parts of the given program:
The first line of the program using System; - the using keyword is used to include the
System namespace in the program. A program generally has multiple using statements.
The next line has the namespace declaration. A namespace is a collection of classes. The
HelloWorldApplication namespace contains the class HelloWorld.
The next line has a class declaration, the class HelloWorld contains the data and method
definitions that your program uses. Classes generally contain multiple methods. Methods
define the behavior of the class. However, the HelloWorld class has only one method Main.
The next line defines the Main method, which is the entry point for all C# programs. The
Main method states what the class does when executed.
The next line /*...*/ is ignored by the compiler and it is put to add comments in the program.
The Main method specifies its behavior with the statement Console.WriteLine("Hello
World");
WriteLine is a method of the Console class defined in the System namespace. This
statement causes the message "Hello, World!" to be displayed on the screen.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
11 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
The last line Console.ReadKey(); is for the VS.NET Users. This makes the program wait for
a key press and it prevents the screen from running and closing quickly when the program is
launched from Visual Studio .NET.
You can compile a C# program by using the command-line instead of the Visual Studio IDE:
Open a text editor and add the above-mentioned code.
Save the file as helloworld.cs
Open the command prompt tool and go to the directory where you saved the file.
Type csc helloworld.cs and press enter to compile your code.
If there are no errors in your code, the command prompt takes you to the next line and
generates helloworld.exe executable file.
Type helloworld to execute your program.
You can see the output Hello World printed on the screen.
4. GETTING AND DISPLAYING INPUT/ OUTPUT
The following programs show how the inputs to the program are provided interactively
through keyboard during the program execution
Command Line Arguments
The Main method is the entry point of a C# console application or windows application.
(Libraries and services do not require a Main method as an entry point.). When the
application is started, the Main method is the first method that is invoked.
There can only be one entry point in a C# program. If you have more than one class that has
a Main method, you must compile your program with the /main compiler option to specify
which Main method to use as the entry point. For more information, see /main (C# Compiler
Options).
class TestClass
{
static void Main(string[] args)
{
// Display the number of command line arguments:
System.Console.WriteLine(args.Length);
}
}
Overview
The Main method is the entry point of an .exe program; it is where the program control
starts and ends.
Main is declared inside a class or struct. Main must be static and it should not be publicThe
enclosing class or struct is not required to be static.
Main can either have a void or int return type.
The Main method can be declared with or without a string[] parameter that contains
command-line arguments. When using Visual Studio to create Windows Forms applications,
you can add the parameter manually or else use the Environment class to obtain the
command-line arguments. Parameters are read as zero-indexed command-line arguments.
Unlike C and C++, the name of the program is not treated as the first command-line
argument.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
12 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
Using ReadLine method
Example:
using System;
class csharp
{
Public static void main()
{
Console.Write(―Enter here‖);
String disp=console.ReadLine();
Console.WriteLine(―Hello‖+disp);
}}
Write() – Display the information within line break
WriteLine() – Display the information with line break
+ operator – used as concatenation operator
5. OPERATORS
C# Operators
C# provides a large set of operators, which are symbols that specify which operations to
perform in an expression. Operations on integral types such as ==, !=, <, >, <=, >=, binary
+, binary -, ^, &, |, ~, ++, --, andsizeof() are generally allowed on enumerations. In
addition, many operators can be overloaded by the user, thus changing their meaning when
applied to a user-defined type.
The following table lists the C# operators grouped in order of precedence. Operators within
each group have equal precedence.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
13 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
Operator category Operators
Primary x.y
f(x)
a[x]
x++
x--
new
typeof
checked
unchecked
->
Unary +
-
!
~
++x
--x
(T)x
true
false
&
sizeof
Multiplicative *
/
%
Additive +
-
Shift <<
>>
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
14 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
Relational and type
testing <
>
<=
>=
is
as
Equality ==
!=
Logical AND &
Logical XOR ^
Logical OR |
Conditional AND &&
Conditional OR ||
Conditional ?:
Assignment =
+=
-=
*=
/=
%=
&=
|=
^=
<<=
Arithmetic Overflow
The arithmetic operators (+, -, *, /) can produce results that are outside the range of possible
values for the numeric type involved. You should refer to the section on a particular operator
for details, but in general:
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
15 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
Integer arithmetic overflow either throws an Overflow Exception or discards the
most significant bits of the result. Integer division by zero always throws
a DivideByZeroException.
Floating-point arithmetic overflow or division by zero never throws an exception,
because floating-point types are based on IEEE 754 and so have provisions for
representing infinity and NaN (Not a Number).
Decimal arithmetic overflow always throws an OverflowException. Decimal
division by zero always throws a DivideByZeroException.
When integer overflow occurs, what happens depends on the execution context, which
can be checked or unchecked. In a checked context, an OverflowException is thrown. In
an unchecked context, the most significant bits of the result are discarded and execution
continues. Thus, C# gives you the choice of handling or ignoring overflow.
In addition to the arithmetic operators, integral-type to integral-type casts can cause
overflow, for example, casting a long to an int, and are subject to checked or unchecked
execution. However, bitwise operators and shift operators never cause overflow.
DECLARATION OF PRIMITIVE DATA TYPES IN C#
Data Type
The type of data that a variable contains is called Data Type (type). A Data Type is a
classification of things that share similar type of qualities or characteristics or behavior.
C# is strongly typed language so every variable and object must have a type.
There are two types of data type in C#
1. primitive types (or) predefined Ex: byte, short, int, float, double, long ,char, bool, DateTime, string, object etc..
2. non-primitive types (or) User Defined
Ex: class , struct , enum , interface, delegate, array.
In C#, based on what a variable contains there is two types of built-in data type
Value types
A variable holds actual values then that type of data types are value types. These value
types are stored in ―stack‖ memory and these value types are fixed in size. If you
assign a value of a variable to another variable it will create two copies.
Ex: byte, short, int, float, double, long ,char, bool, DateTime.
Primitive data types are value types except string, object.
Object type is superior to all types. It can store any type or any size of data. It helps in
inheritance process.
Struct, enum are value types.
Reference types
A variable holds a reference to the value, then that type of data types are reference types.
These reference types are stored in ―heap‖ memory and these types are not fixed in size.
They are maintained in system managed heap but it also uses stack to store reference of
the heap.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
16 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
Two primitive types (string and object) and non-primitive data types (class, interface &
delegate) are examples of reference type.
Ex: class, interface, delegate, string, object and array
Date and Time
Date time is one of the most commonly used data type in C#.
Ex:
DateTime currenttime = DateTime.Now;//display’s current date time.
Output:
current time: 6/13/2015 4:50:45 pm
int days = DateTime.DaysInMonth(2011, 7);// it displays ―31‖.
Output:
No of days 31
6.Arrays class SomeClass
{
struct MyStruct
{
private readonly string label;
private readonly int id;
public MyStruct (string label, int id)
{
this.label = label;
this.id = id;
}
public string Label { get { return label; } }
public string Id { get { return id; } }
}
static readonly IList<MyStruct> MyArray = new ReadOnlyCollection<MyStruct>
(new[] {
new MyStruct ("a", 1),
new MyStruct ("b", 5),
new MyStruct ("q", 29)
});
}
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
17 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
7.Structures In C#, a structure is a value type data type. It helps you to make a single variable hold related
data of various data types. The struct keyword is used for creating a structure.
Structures are used to represent a record. Suppose you want to keep track of your books in a
library. You might want to track the following attributes about each book:
Title
Author
Subject
Book ID
Defining a Structure
To define a structure, you must use the struct statement. The struct statement defines a new data
type, with more than one member for your program.
For example, here is the way you can declare the Book structure:
struct Books
{
public string title;
public string author;
public string subject;
public int book_id;
};
The following program shows the use of the structure:
using System;
struct Books
{
public string title;
public string author;
public string subject;
public int book_id;
};
public class testStructure
{
public static void Main(string[] args)
{
Books Book1; /* Declare Book1 of type Book */
Books Book2; /* Declare Book2 of type Book */
/* book 1 specification */
Book1.title = "C Programming";
Book1.author = "Nuha Ali";
Book1.subject = "C Programming Tutorial";
Book1.book_id = 6495407;
/* book 2 specification */
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
18 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
Book2.title = "Telecom Billing";
Book2.author = "Zara Ali";
Book2.subject = "Telecom Billing Tutorial";
Book2.book_id = 6495700;
/* print Book1 info */
Console.WriteLine( "Book 1 title : {0}", Book1.title);
Console.WriteLine("Book 1 author : {0}", Book1.author);
Console.WriteLine("Book 1 subject : {0}", Book1.subject);
Console.WriteLine("Book 1 book_id :{0}", Book1.book_id);
/* print Book2 info */
Console.WriteLine("Book 2 title : {0}", Book2.title);
Console.WriteLine("Book 2 author : {0}", Book2.author);
Console.WriteLine("Book 2 subject : {0}", Book2.subject);
Console.WriteLine("Book 2 book_id : {0}", Book2.book_id);
Console.ReadKey();
}
}
When the above code is compiled and executed, it produces the following result:
Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700
Features of C# Structures
You have already used a simple structure named Books. Structures in C# are quite different from
that in traditional C or C++. The C# structures have the following features:
Structures can have methods, fields, indexers, properties, operator methods, and events.
Structures can have defined constructors, but not destructors. However, you cannot define
a default constructor for a structure. The default constructor is automatically defined and
cannot be changed.
Unlike classes, structures cannot inherit other structures or classes.
Structures cannot be used as a base for other structures or classes.
A structure can implement one or more interfaces.
Structure members cannot be specified as abstract, virtual, or protected.
When you create a struct object using the New operator, it gets created and the
appropriate constructor is called. Unlike classes, structs can be instantiated without using
the New operator.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
19 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
If the New operator is not used, the fields remain unassigned and the object cannot be
used until all the fields are initialized.
Class versus Structure
Classes and Structures have the following basic differences:
classes are reference types and structs are value types
structures do not support inheritance
structures cannot have default constructor
In the light of the above discussions, let us rewrite the previous example:
using System;
struct Books
{
private string title;
private string author;
private string subject;
private int book_id;
public void getValues(string t, string a, string s, int id)
{
title = t;
author = a;
subject = s;
book_id = id;
}
public void display()
{
Console.WriteLine("Title : {0}", title);
Console.WriteLine("Author : {0}", author);
Console.WriteLine("Subject : {0}", subject);
Console.WriteLine("Book_id :{0}", book_id);
}
};
public class testStructure
{
public static void Main(string[] args)
{
Books Book1 = new Books(); /* Declare Book1 of type Book */
Books Book2 = new Books(); /* Declare Book2 of type Book */
/* book 1 specification */
Book1.getValues("C Programming",
"Nuha Ali", "C Programming Tutorial",6495407);
/* book 2 specification */
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
20 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
Book2.getValues("Telecom Billing",
"Zara Ali", "Telecom Billing Tutorial", 6495700);
/* print Book1 info */
Book1.display();
/* print Book2 info */
Book2.display();
Console.ReadKey();
}
}
UNIT - II
8. INHERITANCE IN C#.
Inheritance means parent-child relationship.By using Inheritance methodology we can
create a new class by using existing class code (i.e. reuse existing methods, properties etc).It also
referred to as reusability of the code so by using Inheritance we can reuse the code again and
again.
What We Call
In Inheritance main existing class is called as generalized class, base class, super class
and parent class and the new class created from existing class is called as specialized class, sub
class, child class and derived class. We normally talk in terms of base class and derived class.
Syntax of Inheritance
class ParentClass{
...parent class code
}
class ChildClass : ParentClass{
...child class code
}
Special Character ":" in Inheritance
Inheritance uses special character called ":" colon to make a relationship between parent
and child as you can see in above syntax of code.
When to Implement Interitance
When we create a new class and we want to reuse some of the methods or properties
from existing class then that is an ideal time to implement inheritance.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
21 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
Advantage of Interitance Reusability of the code.
Types of inheritance in c#
There are 5 types of inheritance as shown below.
Single Inheritance
Multilevel Inheritance
Multiple Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Single Inheritance
Single Inheritance means when a single base is been implemented to single derived class
is called as Single Inheritance. Means we have only one parent class and one child class.
Example of Single Inheritance class Company{
public void CompanyName(){
Console.WriteLine("Name of the Company");
}
public void CompanyAddress(){
Console.WriteLine("Address of the Company");
}
}
class Employee : Company {
public void NameofEmployee(){
Console.WriteLine("Name of the Employee");
}
public void Salary(){
Console.WriteLine("Salary of the Employee");
}
}
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
22 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
Multilevel Inheritance
When a derived class is created from another derived class or let me put it in this way that
a class is created by using another derived class and this type of implementation is called as
multilevel Inheritance
Example of Multilevel Inheritance class HeadOffice
{
public void HeadOfficeAddress(){
Console.WriteLine("Head Office Address");
}
}
Now let's assume that class "HeadOffice" is our Parent class or Base class. Now in my
next step i will create one derived class.
class BranchOffice : HeadOffice{
public void BranchOfficeAddress(){
Console.WriteLine("Branch Office Address");
}
}
So as you can see that i have created a derived class "BranchOffice" by implementing the
class "HeadOffice" to it.
It means now we have one parent class and one derived class. In the next step i will
create another derived class by implementing our existing derived class "BranchOffice" to
achieve multilevel Inheritance.
class Employee : BranchOffice {
public void NameofEmployee(){
Console.WriteLine("Name of the Employee");
}
public void Salary(){
Console.WriteLine("Salary of the Employee");
}
}
From the above souce code you can see that we have achieved multilevel Inheritance by
implementing one derived class to another derived class. Now the class "Employee" will have
the access of all the properties and methods of class "BranchOffice" and class "HeadOffice".
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
23 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
Multiple Inheritance
Due to the complexity of a code multiple inheritance is not been supported in C# or in
DOT.NET but DOT.NET or C# supports multiple interfaces.
Hierarchical Inheritance
When more than one derived classes are implemented from a same parent class or base
class then that type of implementation is known as hierarchical inheritance.
In short it means single base class having more than one derived classes.
class HeadOffice
{
public void HeadOfficeAddress()
{
Console.WriteLine("Head Office Address");
}
}
class BranchOffice1 : HeadOffice
{
public void BranchOfficeAddress()
{
Console.WriteLine("Branch Office Address");
}
}
class BranchOffice2 : HeadOffice
{
public void BranchOfficeAddress()
{
Console.WriteLine("Branch Office Address");
}
}
As you can see from above the code that we have one base class "HeadOffice" and two
derived classes "BranchOffice1" and "BranchOffice2" which are implemented from same base
class i.e. "HeadOffice".
Hybrid Inheritance
This is a special type of inheritance and can be achieved from any combination of single,
hierarchical and multi level inheritance known as hybrid inheritance.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
24 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
In the below code example i have combined hierarchical inheritance and multi level inheritance
together.
class HeadOffice{
public void HeadOfficeAddress(){
Console.WriteLine("Head Office Address");
}
}
class BranchOffice1 : HeadOffice{
public void BranchOfficeAddress(){
Console.WriteLine("Branch Office Address");
}
}
class BranchOffice2 : HeadOffice{
public void BranchOfficeAddress(){
Console.WriteLine("Branch Office Address");
}
}
9. Namespace
Namespaces are C# program elements designed to help you organize your programs. They also
provide assistance in avoiding name clashes between two sets of code. Implementing
Namespaces in your own code is a good habit because it is likely to save you from problems later
when you want to reuse some of your code. For example, if you created a class named Console,
you would need to put it in your own namespace to ensure that there wasn't any confusion about
when the System.Console class should be used or when your class should be used. Generally, it
would be a bad idea to create a class named Console, but in many cases your classes will be
named the same as classes in either the .NET Framework Class Library or a third party library
and namespaces help you avoid the problems that identical class names would cause.
Namespaces don't correspond to file or directory names. If naming directories and files to
correspond to namespaces helps you organize your code, then you may do so, but it is not
required.
The C# Station Namespace: NamespaceCSS.cs
// Namespace Declaration
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
25 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
using System;
// The C# Station Namespace
namespace csharp_station
{
// Program start class
class NamespaceCSS
{
// Main begins program execution.
public static void Main()
{
// Write to console
Console.WriteLine("This is the new C# Station Namespace.");
}
}
}
We declare the new namespace by putting the word namespace in front of csharp_station. Curly
braces surround the members inside the csharp_station namespace.
Nested Namespace 1: NestedNamespace1.cs
// Namespace Declaration
using System;
// The C# Station Tutorial Namespace
namespace csharp_station
{
namespace tutorial
{
// Program start class
class NamespaceCSS
{
// Main begins program execution.
public static void Main()
{
// Write to console
Console.WriteLine("This is the new C# Station Tutorial Namespace.");
}
}
}
}
Namespaces allow you to create a system to organize your code. A good way to organize your
namespaces is via a hierarchical system. You put the more general names at the top of the
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
26 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
hierarchy and get more specific as you go down. This hierarchical system can be represented by
nested namespaces.
10. POLYMORPHISM
Polymorphism means many forms (ability to take more than one form). In Polymorphism poly
means ―multiple‖ and morph means ―forms‖ so polymorphism means many forms.
In polymorphism we will declare methods with same name and different parameters in
same class or methods with same name and same parameters in different classes.
Polymorphism has ability to provide different implementation of methods that are
implemented with same name.
In Polymorphism we have 2 different types those are
- Compile Time Polymorphism (Called as Early Binding or Overloading or static binding)
- Run Time Polymorphism (Called as Late Binding or Overriding or dynamic binding)
Compile Time Polymorphism
Compile time polymorphism means we will declare methods with same name but
different signatures because of this we will perform different tasks with same method
name. This compile time polymorphism also called as early binding or method
overloading.
Method Overloading or compile time polymorphism means same method names with
different signatures (different parameters)
Example
public class Class1
{
public void NumbersAdd(int a, int b)
{
Console.WriteLine(a + b);
}
public void NumbersAdd(int a, int b, int c)
{
Console.WriteLine(a + b + c);
}
}
In above class we have two methods with same name but having different input
parameters this is called method overloading or compile time polymorphism or early
binding.
Run Time Polymorphism
Run time polymorphism also called as late binding or method overriding or dynamic
polymorphism. Run time polymorphism or method overriding means same method
names with same signatures.
In this run time polymorphism or method overriding we can override a method in base
class by creating similar function in derived class this can be achieved by using
inheritance principle and using ―virtual & override‖ keywords.
In base class if we declare methods with virtual keyword then only we can override those
methods in derived class using override keyword
Example
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
27 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
//Base Class
public class Bclass
{
public virtual void Sample1()
{
Console.WriteLine("Base Class");
}
}
// Derived Class
public class DClass : Bclass
{
public override void Sample1()
{
Console.WriteLine("Derived Class");
}
}
// Using base and derived class
class Program
{
static void Main(string[] args)
{
// calling the overriden method
DClass objDc = new DClass();
objDc.Sample1();
// calling the base class method
Bclass objBc = new DClass();
objBc.Sample1();
}
}
If we run above code we will get output like as shown below
Output
----------------------------------
Derived Class
Derived Class
11.INTERFACES
An interface is defined as a syntactical contract that all the classes inheriting the interface
should follow. The interface defines the 'what' part of the syntactical contract and the deriving
classes define the 'how' part of the syntactical contract.
Interfaces define properties, methods, and events, which are the members of the interface.
Interfaces contain only the declaration of the members. It is the responsibility of the deriving
class to define the members. It often helps in providing a standard structure that the deriving
classes would follow.Abstract classes to some extent serve the same purpose, however, they
are mostly used when only few methods are to be declared by the base class and the deriving
class implements the functionalities.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
28 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
Declaring Interfaces
Interfaces are declared using the interface keyword. It is similar to class declaration. Interface
statements are public by default. Following is an example of an interface declaration:
public interface ITransactions
{
// interface members
void showTransaction();
double getAmount();
}
Example
The following example demonstrates implementation of the above interface:
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
namespace InterfaceApplication
{
public interface ITransactions
{
// interface members
void showTransaction();
double getAmount();
}
public class Transaction : ITransactions
{
private string tCode;
private string date;
private double amount;
public Transaction()
{
tCode = " ";
date = " ";
amount = 0.0;
}
public Transaction(string c, string d, double a)
{
tCode = c;
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
29 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
date = d;
amount = a;
}
public double getAmount()
{
return amount;
}
public void showTransaction()
{
Console.WriteLine("Transaction: {0}", tCode);
Console.WriteLine("Date: {0}", date);
Console.WriteLine("Amount: {0}", getAmount());
}
}
class Tester
{
static void Main(string[] args)
{
Transaction t1 = new Transaction("001", "8/10/2012", 78900.00);
Transaction t2 = new Transaction("002", "9/10/2012", 451900.00);
t1.showTransaction();
t2.showTransaction();
Console.ReadKey();
}
}
}
12. DELEGATES
Whenever we want to create delegate methods we need to declare with delegate keyword
and delegate methods signature should match exactly with the methods which we are
going to hold like same return types and same parameters otherwise delegate
functionality won’t work if signature not match with methods.
Syntax of Delegate & Methods Declaration
public delegate int Delegatmethod(int a,int b);
public class Sampleclass
{
public int Add(int x, int y)
{
return x + y;
}
public int Sub(int x, int y)
{
return x + y;
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
30 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
}
}
If you observe above code I declared Delegatmethod method with two parameters which
matching with methods declared in Sampleclass class.
Complete Example
public delegate int DelegatSample(int a,int b);
public class Sampleclass
{
public int Add(int x, int y)
{
return x + y;
}
public int Sub(int x, int y)
{
return x - y;
}
}
class Program
{
static void Main(string[] args)
{
Sampleclass sc=new Sampleclass();
DelegatSample delgate1 = sc.Add;
int i = delgate1(10, 20);
Console.WriteLine(i);
DelegatSample delgate2 = sc.Sub;
int j = delgate2(20, 10);
Console.WriteLine(j);
}
}
Output
Whenever we run above code we will get output like as shown below
Add Result : 30
Sub Result : 10
Use of Delegates
Suppose if you have multiple methods with same signature (return type & number of
parameters) and want to call all the methods with single object then we can go for
delegates.
Delegates are two types
Single Cast Delegates
Multi Cast Delegates
Single Cast Delegates
Single cast delegate means which hold address of single method like as explained in
above example.
Multicast Delegates
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
31 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
Multi cast delegate is used to hold address of multiple methods in single delegate. To
hold multiple addresses with delegate we will use overloaded += operator and if you
want remove addresses from delegate we need to use overloaded operator -=
Multicast delegates will work only for the methods which have return type only void. If
we want to create a multicast delegate with return type we will get the return type of last
method in the invocation list
Example of Multicast Delegate & Method Declaration
public delegate void MultiDelegate(int a,int b);
public class Sampleclass
{
public static void Add(int x, int y)
{
Console.WriteLine("Addition Value: "+(x + y));
}
public static void Sub(int x, int y)
{
Console.WriteLine("Subtraction Value: " + (x - y));
}
public static void Mul(int x, int y)
{
Console.WriteLine("Multiply Value: " + (x * y));
}
}
Complete Example
public delegate void MultiDelegate(int a,int b);
public class Sampleclass
{
public static void Add(int x, int y)
{
Console.WriteLine("Addition Value: "+(x + y));
}
public static void Sub(int x, int y)
{
Console.WriteLine("Subtraction Value: " + (x - y));
}
public static void Mul(int x, int y)
{
Console.WriteLine("Multiply Value: " + (x * y));
}
}
class Program
{
static void Main(string[] args)
{
Sampleclass sc=new Sampleclass();
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
32 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
MultiDelegate del = Sampleclass.Add;
del += Sampleclass.Sub;
del += Sampleclass.Mul;
del(10, 5);
Console.ReadLine();
}
}
Output
Addition Value : 15
Subtraction Value : 5
Multiply Value : 50
13. Publish/Subscribe Design Patterns
UDP allows directly sending and receiving messages without establishing any connection. Here,
the UDP protocol is used for all the communication between the pub/sub server and the
publisher/subscriber. When a sbscriber application sends a message for subscription to the
pub/sub server, the pub/sub server keeps the address (IP, port) of the subscriber topic-wise.
When an event message of a particular topic is sent to a pub/sub server by the publisher
application, the pub/sub server takes the address list for the corresponding topic and sends the
event to every address of the list.
Implementation
Step 1: Making the filter class
The filter class has the following responsibilities and is used by both the Publish Service and the
Subscriber Service.
Keeps the list of subscriber topic-wise, and
Exposes a method to add a new subscriber,
Exposes a method to remove a subscriber,
Returns a list of subscribers for a topic.
Hide Shrink Copy Code
class Filter
{
static Dictionary<string, List<EndPoint>>
_subscribersList = new Dictionary<string, List<EndPoint>>();
static public Dictionary<string, List<EndPoint>> SubscribersList
{
get { return _subscribersList; }
}
static public List<EndPoint> GetSubscribers(String topicName)
{
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
33 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
if (SubscribersList.ContainsKey(topicName))
{
return SubscribersList[topicName];
}
else
return null;
}
static public void AddSubscriber(String topicName, EndPoint subscriberEndPoint)
{
if (SubscribersList.ContainsKey(topicName))
{
if (!SubscribersList[topicName].Contains(subscriberEndPoint))
{
SubscribersList[topicName].Add(subscriberEndPoint);
}
}
else
{
List<EndPoint> newSubscribersList = new List<EndPoint>();
newSubscribersList.Add(subscriberEndPoint);
SubscribersList.Add(topicName, newSubscribersList);
}
}
static public void RemoveSubscriber(String topicName, EndPoint subscriberEndPoint)
{
if (SubscribersList.ContainsKey(topicName))
{
if (SubscribersList[topicName].Contains(subscriberEndPoint))
{
SubscribersList[topicName].Remove(subscriberEndPoint);
}
}
}
}
14. OPERATOR OVERLOADING
You can redefine or overload most of the built-in operators available in C#.
Thus a programmer can use operators with user-defined types as well. Overloaded
operators are functions with special names the keyword operator followed by the
symbol for the operator being defined.
Similar to any other function, an overloaded operator has a return type and a
parameter list.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
34 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
For example, go through the following function:
public static Box operator+ (Box b, Box c)
{
Box box = new Box();
box.length = b.length + c.length;
box.breadth = b.breadth + c.breadth;
box.height = b.height + c.height;
return box;
}
The above function implements the addition operator (+) for a user-defined class Box. It adds the
attributes of two Box objects and returns the resultant Box object.
Implementing the Operator Overloading
The following program shows the complete implementation:
using System;
namespace OperatorOvlApplication
{
class Box
{
private double length; // Length of a box
private double breadth; // Breadth of a box
private double height; // Height of a box
public double getVolume()
{
return length * breadth * height;
}
public void setLength( double len )
{
length = len;
}
public void setBreadth( double bre )
{
breadth = bre;
}
public void setHeight( double hei )
{
height = hei;
}
// Overload + operator to add two Box objects.
public static Box operator+ (Box b, Box c)
{
Box box = new Box();
box.length = b.length + c.length;
box.breadth = b.breadth + c.breadth;
box.height = b.height + c.height;
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
35 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
return box;
}
}
class Tester
{
static void Main(string[] args)
{
Box Box1 = new Box(); // Declare Box1 of type Box
Box Box2 = new Box(); // Declare Box2 of type Box
Box Box3 = new Box(); // Declare Box3 of type Box
double volume = 0.0; // Store the volume of a box here
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
Console.WriteLine("Volume of Box1 : {0}", volume);
// volume of box 2
volume = Box2.getVolume();
Console.WriteLine("Volume of Box2 : {0}", volume);
// Add two object as follows:
Box3 = Box1 + Box2;
// volume of box 3
volume = Box3.getVolume();
Console.WriteLine("Volume of Box3 : {0}", volume);
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400
9. Method Overloading
The process of creating more than one method in a class with same name or creating a
method in derived class with same name as a method in base class is called as method
overloading.
In VB.net when you are overloading a method of the base class in derived class, then you
must use the keyword ―Overloads‖.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
36 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
But in C# no need to use any keyword while overloading a method either in same class or
in derived class.
While overloading methods, a rule to follow is the overloaded methods must differ either
in number of arguments they take or the data type of at least one argument.
Example for Method Overloading
using System;
namespace ProgramCall
{
class Class1
{
public int Sum(int A, int B)
{
return A + B;
}
public float Sum(int A, float B)
{
return A + B;
}
}
class Class2 : Class1
{
public int Sum(int A, int B, int C)
{
return A + B + C;
}
}
class MainClass
{
static void Main()
{
Class2 obj = new Class2();
Console.WriteLine(obj.Sum(10, 20));
Console.WriteLine(obj.Sum(10, 15.70f));
Console.WriteLine(obj.Sum(10, 20, 30));
Console.Read();
}
}
}
Output
30
25.7
60
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
37 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
UNIT – III
15.C# Concepts for creating Data Structures
The most common and likely well-known data structure is the array, which contains a contiguous
collection of data items that can be accessed by an ordinal index.
Before jumping into the content for this article, let's first take a quick peek at the roadmap for
this six-part article series, so that you can see what lies ahead. If there are any topics you think
are missing from this outline, I invite you to e-mail me at [email protected] and
share your thoughts. Space permitting, I'll be happy to add your suggestions to the appropriate
installment or, if needed, add a seventh part to the series.
In this first part of the six-part series, we'll look at why data structures are important, and their
effect on the performance of an algorithm. To determine a data structure's effect on performance,
we'll need to examine how the various operations performed by a data structure can be rigorously
analyzed. Finally, we'll turn our attention to two data structures present in the .NET
Framework—the Array and ArrayList. Chances are you've used both of these data structures in
past projects. In this article, we'll examine what operations they provide and the efficiency of
these operations.
In Part 2, we'll explore the ArrayList class in more detail and examine its counterparts, the
Queue class and Stack class. Like the ArrayList, both the Queue and Stack classes store a
contiguous collection of data and are data structures available in the .NET Framework Base
Class Library. However, unlike an ArrayList from which you can retrieve any data item, Queues
and Stacks only allow data to be accessed in a predetermined sequential order. We'll examine
some applications of Queues and Stacks, and see how to implement both of these classes by
extending the ArrayList class. After examining Queues and Stacks, we'll look at HashTables,
which allow for direct access like an ArrayList, but store data indexed by a string key.
While ArrayLists are ideal for directly accessing and storing contents, they are suboptimal
candidates when the data needs to be searched. In Part 3, we'll examine the binary search tree
data structure, which provides a much more efficient means for searching than the ArrayList.
The .NET Framework does not include any built-in binary search tree data structures, so we will
have to build our own.
The efficiency of searching a binary search trees is sensitive to the order with which the data was
inserted into the tree. If the data was inserted in sorted or near-sorted order, the binary search tree
loses virtually all of its efficiency advantages over the ArrayList. To combat this issue, in Part 4
we'll examine an interesting randomized data structure—the SkipList. SkipLists provide the
efficiency of searching a binary search tree, but without the sensitivity to the order with which
data is entered.
In Part 5 we'll turn our attention to data structures that can be used to represent graphs. A graph
is a collection of nodes, with a set of edges connecting the various nodes. For example, a map
can be visualized as a graph, with cities as nodes and the highways between them as edged
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
38 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
between the nodes. Many real-world problems can be abstractly defined in terms of graphs,
thereby making graphs an often-used data structure.
Finally, in Part 6 we'll look at data structures to represent sets and disjoint sets. A set is an
unordered collection of items. Disjoint sets are a collection of sets that have no elements in
common with one another. Both sets and disjoint sets have many uses in everyday programs,
which we'll examine in detail in this final part.
Analyzing the Performance of Data Structures
When thinking about a particular application or programming problem, many developers (myself
included) find themselves most interested in writing the algorithm to tackle the problem at hand,
or adding cool features to the application to enhance the user's experience. Rarely, if ever, will
you hear someone excited about what type of data structure they are using. However, the data
structures used for a particular algorithm can greatly impact its performance. A common
example is finding an element in a data structure. With an array, this process takes time
proportional to the number of elements in the array. With binary search trees or SkipLists, the
time required is sub-linear. When searching large amounts of data, the data structure chosen can
make a difference in the application's performance that can be visibly measured in seconds or
even minutes.
Since the data structure used by an algorithm can greatly affect the algorithm's performance, it is
important that there exists a rigorous method by which to compare the efficiency of various data
structures. What we, as developers utilizing a data structure, are primarily interested in is how
the data structures performance changes as the amount of data stored increases. That is, for each
new element stored by the data structure, how are the running times of the data structure's
operations effected?
Consider a scenario in which you have a program that uses the
System.IO.Directory.GetFiles(path) method to return the list of the files in a specified directory
as a string array. Now, imagine that you wanted to search through the array to determine if an
XML file existed in the list of files (namely one whose extension was .xml). One approach to do
this would be to scan through the array and set some flag once an XML file was encountered.
The code might look like so:
using System;
using System.Collections;
using System.IO;
public class MyClass
{
public static void Main()
{
string [] fs = Directory.GetFiles(@"C:\Inetpub\wwwroot");
bool foundXML = false;
int i = 0;
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
39 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
for (i = 0; i < fs.Length; i++)
if (String.Compare(Path.GetExtension(fs[i]), ".xml", true) == 0)
{
foundXML = true;
break;
}
if (foundXML)
Console.WriteLine("XML file found - " + fs[i]);
else
Console.WriteLine("No XML files found.");
}
}
16..STREAM AND ITS USAGE OF C#
STREAM
In C#, all I/O operations are handled using streams. A stream is an abstraction of
continuous one way flow of data.
Stream is the abstract base class of all streams. A stream is an abstraction of a sequence
of bytes, such as a file, an input/output device, an inter-process communication pipe, or a
TCP/IP socket.
Streams helps to achieve
Persistent storage of objects
Transmitting objects between nodes in a network
Encrypting message streams
Data compression
A stream is a path along which data flows. Once the link is established by associating the
stream with Source/Destination,Data Flow commences.
An analogy can be flow of water in a pipe from a tank to a bucket. The tank is the source
of water and the bucket is the destination.
The pipe is a path along which water flows. The tap controls the flow of water. Opening
the tap commences the flow of water. Closing the tap stops the flow of water.
A similar concept of datqa flow from source to destination is achieved using stgreams in
c#.
A stream is a path along which data flows.
17.FILESTREAMS
FileStreams
A FileStream object is created to process a stream of bytes associated with a backing
store —a term used to refer to any storage medium such as disk or memory.
The following code segment demonstrates how it is used for reading and writing bytes:
try
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
40 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
{
// Create FileStream object
FileStream fs = new FileStream(@"c:\artists\log.txt",
FileMode.OpenOrCreate, FileAccess.ReadWrite);
byte[] alpha = new byte[6] {65,66,67,68,69,70}; //ABCDEF
// Write array of bytes to a file
// Equivalent to: fs.Write(alpha,0, alpha.Length);
foreach (byte b in alpha) {
fs.WriteByte(b);}
// Read bytes from file
fs.Position = 0; // Move to beginning of file
for (int i = 0; i< fs.Length; i++)
Console.Write((char) fs.ReadByte()); //ABCDEF
fs.Close();
catch(Exception ex)
{
Console.Write(ex.Message);
}
As this example illustrates, a stream is essentially a byte array with an internal pointer
that marks a current location in the stream.
The ReadByte and WriteByte methods process stream bytes in sequence. The Position
property moves the internal pointer to any position in the stream.
By opening the FileStream for ReadWrite , the program can intermix reading and writing
without closing the file.
Creating a FileStream
The FileStream class has several constructors.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
41 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
The most useful ones accept the path of the file being associated with the object and
optional parameters that define file mode, access rights, and sharing rights. The possible
values for these parameters are shown in Figure.
The FileMode enumeration designates how the operating system is to open the file and
where to position the file pointer for subsequent reading or writing.
Table is worth noting because you will see the enumeration used by several classes in the
System.IO namespace.
Value Description
Append Opens an existing file or creates a new one. Writing begins at the
end of the file.
Create Creates a new file. An existing file is overwritten.
CreateNew Creates a new file. An exception is thrown if the file already exists.
Open Opens an existing file.
OpenOrCreate Opens a file if it exists; otherwise , creates a new one.
truncate Opens an existing file, removes its contents, and positions the file
pointer to the beginning of the file.
The FileAccess enumeration defines how the current FileStream may access the file;
FileShare defines how file streams in other processes may access it.
For example, FileShare.Read permits multiple file streams to be created that can
simultaneously read the same file.
18. FILE OPERATIONS IN C#.
Objectives
Using the File class for reading and writing data.
Using the File and FileInfo class to manipulate files.
Using the DirectoryInfo and Directory classes to manipulate directories.
Using the File class for reading and writing data.
The File class of the System.IO namespace offers various static methods that enable a developer
to do direct reading and writing of files. Typically, to read data from a file, you:
Get a hold on the file handle.
Open a stream to the file.
Buffer the file data into memory.
Release the hold of file handle once done.
Reading Data from Files
The following list describes some of these methods:
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
42 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
The "ReadAllText" method reads the data of a file.
string filePath = @"C:\MyData\TestFile.txt";
string testData = File.ReadAllText(filePath);
The "ReadAllLines" method reads all the contents of a file and stores each line at a new index in
an array of string type.
string filePath = @"C:\MyData\TestFile.txt";
string[] testDataLineByLine = File.ReadAllLines(filePath)
The "ReadAllBytes" method reads the contents of a file as binary data and stores the data in a
byte array.
string filePath = @"C:\MyData\TestFile.txt";
byte[] testDataRawBytes = File.ReadAllBytes(filePath);
Each of these methods enable the developer to read the contents of a file and load into memory.
The ReadAllText method will enable the developer to cache the entire file in memory via a
single operation. Whereas the ReadAllLines method will read line-by-line into an array.
Writing Data to Files
The File class also provides methods for writing various types of data to a file. For each
of the various types of data you can write, the File class provides two methods.
If the specified file does not exist, then the Writexxx methods create a new file with the
new data. If the file does exist then the Writexxx methods overwrite the existing file with
the new data.
If the specified file does not exist then the Appendxxx methods also create a new file
with the new data.
However, if the file does exist then the new data is written to the end of the existing file.
The following list describes some of these methods:
The "WriteAllText" method enables the developers to write the contents of string
variable into a file. If the file exists, its contents will be overwritten.
The following code example shows how to write the contents of a string named settings
to a new file named settings.txt.
string filePath = @"C:\MyData\TestFile.txt";
string data = "C# Corner MVP & Microsoft MVP;";
File.WriteAllText(filePath, data);
The "WriteAllLines" method enables the developers to write the contents of a string array
to a file. Each entry in the string array will be a new line in the new file.
string filePath = @"C:\MyData\TestFile.txt";
string[] data = { "MCT", "MCPD", "MCTS", "MCSD.NET", "MCAD.NET", "CSM" };
File.WriteAllLines(filePath, data);
The "AppendAllText" method enables the developers to write the contents of a string
variable at the end of an existing file.
string filePath = @"C:\MyData\TestFile.txt";
string data = "Also Certified from IIT Kharagpur";
File.AppendAllText(filePath, data);
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
43 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
The "AppendAllLines" method enables the developers to write the contents of a string
array to the end of an existing file.
string filePath = @"C:\MyData\TestFile.txt";
string[] otherData = { "Worked with Microsoft", "Lived in USA" };
File.AppendAllLines(filePath, otherData);
File and FileInfo class to Manipulating Files
File manipulation is as important as file creation. Many applications typically require the ability
to interact with files stored on the file system. For example, copying a file from a directory to
another location for further processing.
Developers can implement this type of functionality by using the File and FileInfo classes.
Using File class to manipulate files
The File class consists of various static methods that a developer can use to perform basic file
manipulation. The following list describes some of those methods.
The "Copy" method enables the developers to copy an existing file to a different directory
location on the file system.
string sourceFilePath = @"C:\MyData\TestFile.txt";
string destinationFilePath = @"C:\temp\Data.txt";
bool overWrite = true;
File.Copy(sourceFilePath, destinationFilePath, overWrite);
Note: The overwrite parameter passed to the Copy method call indicates that the copy process
should overwrite an existing file if it exists at the destination path. If you pass false to the Copy
method call, and the file already exists then the Common Language Runtime (CLR) will throw a
System.IO.IOException.
The "Delete" method deletes an existing file from the file system.
string sourceFilePath = @"C:\MyData\TestFile.txt";
File.Delete(sourceFilePath);
The "Exists" method checks whether a file exists on the file system.
string sourceFilePath = @"C:\MyData\TestFile.txt";
bool doesFileExist = File.Exists(sourceFilePath);
The "GetCreationTime" method obtains the date time stamp that describes when a file was
created, from the metadata associated with the file.
string sourceFilePath = @"C:\MyData\TestFile.txt";
DateTime fileCreatedOn = File.GetCreationTime(sourceFilePath);
Using FileInfo class to manipulate files
Unlike the File class the FileInfo class provides instance members that you can use to manipulate
an existing file. Also in contrast to the File class that provides static methods for direct
manipulation, the FileInfo class works like an in memory representation of the physical file.
Instantiating the FileInfo Class
string sourceFilePath = @"C:\MyData\TestFile.txt";
FileInfo fInfo = new FileInfo(sourceFilePath);
Once the instance of the FileInfo class is created, you can use the properties and methods to
interact with the file. The following list describes some of these properties and methods.
The "CopyTo" method enables the developers to copy an existing file to a different directory on
the file system.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
44 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
string sourceFilePath = @"C:\MyData\TestFile.txt";
string destinationFilePath = @"C:\temp\Data.txt";
bool overwrite = true;
FileInfo fInfo = new FileInfo(sourceFilePath);
fInfo.CopyTo(destinationFilePath, overwrite);
Note: The overwrite parameter in the CopyTo method indicates that the copy process should
overwrite an existing file if it exists at the specified destination file path. If you pass false to the
CopyTo method, and the file already exists then the CLR will throw a System.IO.IOException.
The "Delete" method enables the developers to delete a file.
string sourceFilePath = @"C:\MyData\TestFile.txt";
FileInfo fInfo = new FileInfo(sourceFilePath);
fInfo.Delete();
The "DirectoryName" property enables the developers to get the directory path to the file.
string sourceFilePath = @"C:\MyData\TestFile.txt";
FileInfo fInfo = new FileInfo(sourceFilePath);
string directoryPath = fInfo.DirectoryName;
// returns C:\MyData
The "Exists" method enables the developers to determine if the specified file exists within the
file system.
string sourceFilePath = @"C:\MyData\TestFile.txt";
FileInfo fInfo = new FileInfo(sourceFilePath);
bool filesExists = fInfo.Exists;
The "Extension" property enables you to get the file extension of a file.
string sourceFilePath = @"C:\MyData\TestFile.txt";
FileInfo fInfo = new FileInfo(sourceFilePath);
bool filesExtn = fInfo.Extension;
The "Length" property enables the developers to get the length of the file in bytes.
string sourceFilePath = @"C:\MyData\TestFile.txt";
FileInfo fInfo = new FileInfo(sourceFilePath);
long length = fInfo.Length;
DirectoryInfo and Directory class to Manipulating Directories
In an operating system’s file system, the files are organized into directories.
Hence, it is very crucial for an application to interact and manipulate the file system’s
directory structure. Interaction with directories may include checking that a directory
exists before writing a file or to remove directories after the process is complete as a
cleanup policy.
The .NET Framework class library provides the Directory and DirectoryInfo classes for
such operations.
Using Directory class to manipulate directories
Similar to the File class, the "Directory" class provides static methods that enable you to interact
with directories, without instantiating a directory-related object in your code.
The "CreateDirectory" method creates a new directory on the file system.
string sourceDirPath = @"C:\MyData\Data";
Directory.CreateDirectory(sourceDirPath);
The "Delete" method deletes a directory at a specific path.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
45 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
string sourceDirPath = @"C:\MyData\Data";
bool deleteRecursively = true;
Directory.Delete(sourceDirPath, deleteRecursively);
Note: The deleteRecursively parameter passed into the Delete method specifies whether the
delete process should delete any content that may exist in the directory. If you pass false into the
Delete method, and the directory is not empty then the CLR will throw a
System.IO.IOException.|
The "Exists" method determines if a directory exists on the file system.
string sourceDirPath = @"C:\MyData\Data";
bool tempDataDirectoryExists = Directory.Exists(sourceDirPath);
The "GetDirectories" method gets a list of all subdirectories within a specific directory on the file
system.
string sourceDirPath = @"C:\MyData\Data";
string[] subDirectories = Directory.GetDirectories(sourceDirPath);
The "GetFiles" method gets a list of all the files within a specific directory on the file system.
string sourceDirPath = @"C:\MyData\Data";
string[] files = Directory.GetFiles(sourceDirPath);
The "DirectoryInfo" class provides instance members that enable you to access directory
metadata and manipulate the directory structure.
Using DirectoryInfo class to manipulate directories.
The "DirectoryInfo" class acts as an in-memory representation of a directory. Before you can
access the properties and execute the methods that the DirectoryInfo class exposes, you must
create an instance of the class.
Instantiating the DirectoryInfo Class
string sourceDirPath = @"C:\MyData\Data";
DirectoryInfo directory = new DirectoryInfo(sourceDirPath);
When you have created an instance of the DirectoryInfo class, you can then use its properties and
methods to interact with the directory. The following list describes some of these properties and
methods:
The "Create" method creates a new directory on the file system.
string sourceDirPath = @"C:\MyData\Data";
DirectoryInfo directory = new DirectoryInfo(sourceDirPath);
directory.Create();
The "Delete" method deletes a directory at a specific path.
string sourceDirPath = @"C:\MyData\Data";
bool deleteRecursively = true;
DirectoryInfo directory = new DirectoryInfo(sourceDirPath);
directory.Delete(deleteRecursively);
Note: The recursivelyDeleteSubContent parameter passed to the Delete method call indicates
whether the delete process should delete any content that may exist in the directory. If you pass
false to the Delete method call, and the directory is not empty then the CLR will throw a
System.IO.IOException.
The "Exists" property determines if a directory exists on the file system.
string sourceDirPath = @"C:\MyData\Data";
DirectoryInfo directory = new DirectoryInfo(sourceDirPath);
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
46 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
bool directoryExists = directory.Exists
The "FullName" property gets the full path to the directory. The following example shows how
to get the full path to the tempData directory.
string sourceDirPath = @"C:\MyData\Data";
DirectoryInfo directory = new DirectoryInfo(sourceDirPath);
string fullPath = directory.FullName;
The "GetDirectories" method gets a list of all subdirectories within a specific directory on the file
system.
In contrast to the static File.GetDirectories method, this instance method returns an array of type
DirectoryInfo, that enables you to use each of the instance properties for each subdirectory.
string sourceDirPath = @"C:\MyData\Data";
DirectoryInfo directory = new DirectoryInfo(sourceDirPath);
DirectoryInfo[] subDirectories = directory.GetDirectories();
19. MULTITHREADING
Multithreading is a feature provided by the operating system that enables your application
to have more than one execution path at the same time. Technically, multithreaded
programming requires a multitasking operating system.
Let’s understand this concept with a very basic example. Everyone has used Microsoft
Word. It takes input from the user and displays it on the screen in one thread while it
continues to check spelling and grammatical mistakes in another thread and at the same
time another thread saves the document automatically at regular intervals.
Now let’s understand a program. In this program we will try to implement the concept of
multithreading and will define multiple concurrent execution paths.
Now through the use of threads, we cannot be sure of the sequence of the output program. Now
if you write this program without the threading concept, like this:
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
47 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
You will see that func2() will execute only after func1() and in the first program you will be able
to execute both functions simultaneously.
The thread class provides a number of useful methods and properties to control and manage
thread execution.
Most Commonly used Static Member of System.Threading.Thread class The following are the most commonly used static members of the System.Threading.Thread
class:
CurrentThread(): gives a reference to the currently executing thread
Thread.Sleep(): cause the currently executing thread to pause temporarily for the
specified amount of time
When you execute the preceding program, you will notice a delay of 1 second between the
printing of the two lines.
Most Common Instance Member of the System.Threading.Thread class The following are the most common instance members of the System.Threading.Thread class:
Name
A property of string type used to get/set the friendly name of the thread instance.
Priority
A property of type System.Threading.ThreadPriority to schedule the priority of threads.
IsAlive
A Boolean property indicating whether the thread is alive or terminated.
ThreadState
A property of type System.Threading.ThreadState, used to get the value containing the
state of the thread.
Start()
Starts the execution of the thread.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
48 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
Abort()
Allows the current thread to stop the execution of the thread permanently.
Suspend()
Pauses the execution of the thread temporarily.
Resume()
Resumes the execution of a suspended thread.
Join()
Make the current thread wait for another thread to finish.
20. SYNCHRONIZATION.
Synchronization is particularly important when threads access the same data; it’s
surprisingly easy to run aground in this area.
Synchronization constructs can be divided into four categories:
Simple blocking methods
Locking constructs
Signaling constructs
No blocking synchronization constructs
Synchronization in Threads- Synchronization is needed in thread when we have multiple
threads that share data, we need to provide synchronized access to the data. We have to deal with
synchronization issues related to concurrent access to variables and objects accessible by
multiple threads at the same time.
using System;
using System.Threading;
namespace CSharpThreadExample
{
class Program
{
static void Main(string[] arg)
{
Console.WriteLine("-----> Multiple Threads ---->");
Printer p=new Printer();
Thread[] Threads=new Thread[3];
for(int i=0;i<3;i++)
{
Threads[i]=new Thread(new ThreadStart(p.PrintNumbers));
Threads[i].Name="Child "+i;
}
foreach(Thread t in Threads)
t.Start();
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
49 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
Console.ReadLine();
}
}
class Printer
{
public void PrintNumbers()
{
for (int i = 0; i < 5; i++)
{
Thread.Sleep(100);
Console.Write(i + ",");
}
Console.WriteLine();
}
}
}
Syntax:
lock (objecttobelocked)
{
objecttobelocked.somemethod();
}
objecttobelocked is the object reference which is used by more than one thread to call the
method on that object.
The lock keyword requires us to specify a token (an object reference) that must be
acquired by a thread to enter within the lock scope.
Using of Monitor- The lock scope actually resolves to the Monitor class after being processed
by the C# compiler. Lock keyword is just a notation for using System.Threading.Monitor class.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
50 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
using System;
using System.Threading;
namespace CSharpThreadExample
{
class Program
{
static void Main(string[] arg)
{
Console.WriteLine(" -----> Multiple Threads ----->");
Printer p = new Printer();
Thread[] Threads = new Thread[3];
for (int i = 0; i < 3; i++)
{
Threads[i] = new Thread(new ThreadStart(p.PrintNumbers));
Threads[i].Name = "Child " + i;
}
foreach (Thread t in Threads)
t.Start();
Console.ReadLine();
}
}
class Printer
{
public void PrintNumbers()
{
Monitor.Enter(this);
try
{
for (int i = 0; i < 5; i++)
{
Thread.Sleep(100);
Console.Write(i + ",");
}
Console.WriteLine();
}
finally
{
Monitor.Exit(this);
}
}
}
}
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
51 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
UNIT – IV
21. XML DATA.
Writing XML Files
We can use the XmlWriter class to write XML files. It allows you to write XML text into a
stream and then save it into an xml file.
using System.Xml;
public class Program
{
public static void Main()
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
XmlWriter writer = XmlWriter.Create("Products.xml", settings);
writer.WriteStartDocument();
writer.WriteComment("This file is generated by the program.");
writer.WriteStartElement("Product");
writer.WriteAttributeString("ID", "001");
writer.WriteAttributeString("Name", "Soap");
writer.WriteElementString("Price", "10.00");
writer.WriteStartElement("OtherDetails");
writer.WriteElementString("BrandName", "X Soap");
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
52 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
writer.WriteElementString("Manufacturer", "X Company");
writer.WriteEndElement();
writer.WriteEndDocument();
writer.Flush();
writer.Close();
}
}
22.Reading & Writing XML Files
To read xml files, we can use the XmlReader class. We will use the XML file we created earlier
to assign the values into variables. Note that we will simply use variables for storing the values
from the XML. A better approach is by creating a Products class the follows the heirarchy of the
XML file. The following program demonstrates the use of XmlReader class.
using System;
using System.Xml;
public class Program
{
public static void Main()
{
XmlReader reader = XmlReader.Create("Products.xml");
while (reader.Read())
{
if (reader.NodeType == XmlNodeType.Element
&& reader.Name == "Product")
{
Console.WriteLine("ID = " + reader.GetAttribute(0));
Console.WriteLine("Name = " + reader.GetAttribute(1));
while (reader.NodeType != XmlNodeType.EndElement)
{
reader.Read();
if (reader.Name == "Price")
{
while (reader.NodeType != XmlNodeType.EndElement)
{
reader.Read();
if (reader.NodeType == XmlNodeType.Text)
{
Console.WriteLine("Price = {0:C}", Double.Parse(reader.Value));
}
}
reader.Read();
} //end if
if (reader.Name == "OtherDetails")
{
while (reader.NodeType != XmlNodeType.EndElement)
{
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
53 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
reader.Read();
if (reader.Name == "BrandName")
{
while (reader.NodeType != XmlNodeType.EndElement)
{
reader.Read();
if (reader.NodeType == XmlNodeType.Text)
{
Console.WriteLine("Brand Name = " + reader.Value);
}
}
reader.Read();
} //end if
if (reader.Name == "Manufacturer")
{
while (reader.NodeType != XmlNodeType.EndElement)
{
reader.Read();
if (reader.NodeType == XmlNodeType.Text)
{
Console.WriteLine("Manufacturer = " + reader.Value);
}
}
} //end if
}
} //end if
} //end while
} //end if
} //end while
}
}
Output:
ID = 001
Name = Soap
Price = $10.00
Brand Name = X Soap
Manufacturer = X Company
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
54 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
23. ARCHITECTURE OF ADO.NET
ADO.NET
ADO.NET is a data access technology from Microsoft .Net Framework , which provides
communication between relational and non-relational systems through a common set of
components .
ADO.NET consist of a set of Objects that expose data access services to the .NET
environment. ADO.NET is designed to be easy to use, and Visual Studio provides several
wizards and other features that you can use to generate ADO.NET data access code.
Data Providers and DataSet
The two key components of ADO.NET are Data Providers and DataSet .
The .Net Framework includes mainly three Data Providers for ADO.NET.
They are the
Microsoft SQL Server Data Provider ,
OLEDB Data Provider
ODBC Data Provider .
SQL Server uses the SqlConnection object , OLEDB uses the OleDbConnection Object
and ODBC uses OdbcConnection Object respectively.
C# SQL Server Connection
C# OLEDB Connection
C# ODBC Connection
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
55 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
The four Objects from the .Net Framework provides the functionality of Data Providers
in the ADO.NET. They are
Connection Object,
Command Object ,
DataReader Object
DataAdapter Object.
The Connection Object provides physical connection to the Data Source.
The Command Object uses to perform SQL statement or stored procedure to be executed
at the Data Source.
The DataReader Object is a stream-based , forward-only, read-only retrieval of query
results from the Data Source, which do not update the data.
Finally the DataAdapter Object , which populate a Dataset Object with results from a
Data Source .
C# Connection
C# Command
C# DataReader
C# DataAdapter
DataSet
DataSet provides a disconnected representation of result sets from the Data Source, and it
is completely independent from the Data Source.
DataSet provides much greater flexibility when dealing with related Result Sets.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
56 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
DataSet consists of a collection of DataTable objects that you can relate to each other
with DataRelation objects.
The DataTable contains a collection of DataRow and DataCoulumn Object which
contains Data. The DataAdapter Object provides a bridge between the DataSet and the
Data Source.
24. ADO.NET Connected and Disconnected Models
Connected Architecture of ADO.NET
The architecture of ADO.net, in which connection must be opened to access the data retrieved
from database is called as connected architecture. Connected architecture was built on the classes
connection, command, datareader and transaction.
Connected architecture is when you constantly make trips to the database for any CRUD (Create,
Read, Update and Delete) operation you wish to do. This creates more traffic to the database but
is normally much faster as you should be doing smaller transactions.
Disconnected Architecture in ADO.NET
The architecture of ADO.net in which data retrieved from database can be accessed even when
connection to database was closed is called as disconnected architecture. Disconnected
architecture of ADO.net was built on classes connection, dataadapter, commandbuilder and
dataset and dataview.
Disconnected architecture is a method of retrieving a record set from the database and storing it
giving you the ability to do many CRUD (Create, Read, Update and Delete) operations on the
data in memory, then it can be re-synchronized with the database when reconnecting. A method
of using disconnected architecture is using a Dataset.
DataReader is Connected Architecture since it keeps the connection open until all rows are
fetched one by one
DataSet is DisConnected Architecture since all the records are brought at once and there is no
need to keep the connection alive
Difference between Connected and disconnected architecture
onnected Disconnected
It is connection oriented. It is dis_connection oriented.
Datareader DataSet
Connected methods gives faster performance Disconnected get low in speed and performance.
connected can hold the data of single table disconnected can hold multiple tables of data
connected you need to use a read only forward
only data reader
disconnected you cannot
Data Reader can't persist the data Data Set can persist the data
It is Read only, we can't update the data. We can update data
Example
Create Database ―Student‖
CREATE TABLE [dbo].[Student]
(
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
57 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
[ID] [int] PRIMARY KEY IDENTITY(1,1) NOT NULL,
[Name] [varchar](255) NULL,
[Age] [int] NULL,
[Address] [varchar](255) NULL
)
INSERT INTO Student([Name],[Age],[Address])VALUES('NAME 1','22','PUNE')
INSERT INTO Student([Name],[Age],[Address])VALUES('NAME 2','25','MUMBAI')
INSERT INTO Student([Name],[Age],[Address])VALUES('NAME 3','23','PUNE')
INSERT INTO Student([Name],[Age],[Address])VALUES('NAME 4','21','DELHI')
INSERT INTO Student([Name],[Age],[Address])VALUES('NAME 5','22','PUNE')
HTML
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Pagetitle>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" BackColor="White"
BorderColor="#CC9966"
BorderStyle="None" BorderWidth="1px" CellPadding="4">
<FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
<RowStyle BackColor="White" ForeColor="#330099" />
<PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center"
/>
<SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
</asp:GridView>
<br />
<asp:Button ID="Connected" runat="server" OnClick="Connected_Click"
Text="Connected" />
<asp:Button ID="Disconnected" runat="server" EnableTheming="False"
OnClick="Disconnected_Click"
Text="Disconnected" />
</div>
</form>
</body>
</html>
Code Behind
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
58 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
String StrSQL = "", StrConnection = "";
protected void Page_Load(object sender, EventArgs e)
{
StrSQL = "SELECT * FROM Student";
StrConnection = "Data Source=ServerName;Initial Catalog=Database;User
ID=Username;Password=password";
}
protected void Connected_Click(object sender, EventArgs e)
{
using (SqlConnection objConn = new SqlConnection(StrConnection))
{
SqlCommand objCmd = new SqlCommand(StrSQL, objConn);
objCmd.CommandType = CommandType.Text;
objConn.Open();
SqlDataReader objDr = objCmd.ExecuteReader();
GridView1.DataSource = objDr;
GridView1.DataBind();
objConn.Close();
}
}
protected void Disconnected_Click(object sender, EventArgs e)
{
SqlDataAdapter objDa = new SqlDataAdapter();
DataSet objDs = new DataSet();
using (SqlConnection objConn = new SqlConnection(StrConnection))
{
SqlCommand objCmd = new SqlCommand(StrSQL, objConn);
objCmd.CommandType = CommandType.Text;
objDa.SelectCommand = objCmd;
objDa.Fill(objDs, "Student");
GridView1.DataSource = objDs.Tables[0];
GridView1.DataBind();
}
}
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
59 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
25. XML and ADO.NET
ADO.NET can be used as a powerful XML middleware. Although coming from ADO, it has
been entirely redesigned for a better support for Web applications. A main feature of ADO.NET
is its disconnected recordsets, known as DataSet. It acts as a feature-rich in-memory database or
data cache. In other words, it does not maintain any database server cursors. All recordset’s
database characteristics are available in DataSet, such as sorting, paging, filtered views,
relations, indexing, and primary/foreign keys.
Native support for XML is another principal feature for ADO.NET. In native mode, record tables
are stored as XML documents where schema and data are treated as distinct and replaceable
elements. It is quite different from ADO. The ADO native storage format for a recordset is the
Advanced Data Table Gram (ADTG) file format, which is a proprietary, binary schema that
represents a recordset’s in-memory image. The DataSet objects in ADO.NET can load its data
from variant sources: a database server, a local or remote XML file and any accessible system
resources. Once the data is loaded, they can be either treated as a record table or a virtual XML
document. We principally discuss the latter. Now, I will give you several use cases. Each use
case is a standalone unit test which can be run under NUnit. So you should install a latest version
of NUnit. More information about its installation and usage can be found here.
Before executing these examples, you should also setup an ODBC connection for the database
with the following steps:
1. Extract the download package. There is an access file ―NWIND_2002.MDB‖ in the folder
―UnitTest_ADO.NET_XML‖.
2. Open Control Panel -> Administrative Tools -> Data Source.
3. Choose the System Data Sources tab.
4. Click ―Add‖ button and choose ―Microsoft Access Driver (*.mdb)‖ from the list. Then an
ODBC configuration dialog appears.
5. Enter ―XmlDb_NorthWind‖ as the Data Source Name (DSN), and choose the Access file
―NWIND_2002.MDB‖ as the data source.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
60 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
26. Simple and Complex Data Binding
What is DataBinding?
DataBinding is a powerful feature provided by the .NET framework that enables visual elements
in a client to connect to a datasource such as DataSets, DataViews, Arrays etc. Some of the
visual elements in the client can be TextBox, Datagrid etc. A two-way connection is established
such that any changes made to the datasource are reflected immediately in the visual element and
vice versa.
Below is a graphical description of the concept of databinding:
DataBinding Before .NET
In the earlier databinding models, the datasource that could be used was usually limited to a
database. All DBMS systems provided their own API's to help in building GUI applications and
quickly bind them to the data. Programmer did not have the flexibility to control the databinding
process with the result that most developers avoided the use of databinding.
DataBinding with .NET
The .NET framework provides a very flexible and powerful approach to databinding and allows
the programmer to have a fine control over the steps involved in the whole process. One of the
biggest improvements with .Net has been the introduction of databinding to web pages through
the use of .Net server-side web controls. Hence, building data driven web applications has been
greatly simplified. Please note that this article only deals with data binding in .NET windows
forms.
Advantages of DataBinding
1. Databinding in .NET can be used to write data driven applications quickly. .NET data
binding allows you to write less code with fast execution but still get the work done in the
best way.
2. .NET automatically writes a lot of databinding code for you in the background (you can
see it in "Windows Generated Code" section), so the developer does not have to spend
time writing code for basic databinding, but still has the flexibility of modifying any code
that he would like to. We get the benefits of bound as well as unbound approach.
3. Control over the Databinding process by using events. This is discussed in more detail
later in the article.
Disadvantages of DataBinding
1. More optimized code can be written by using the unbound or traditional methods.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
61 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
2. Complete flexibility can only be achieved by using the unbound approach.
Databinding Concepts
For databinding to take place data provider and a data consumer should exist so that a
synchronized link is established between the two. Data providers contain the data and the data
consumers use the data exposed by the data providers and display them.
.NET has expanded the scope of possible data providers. In .NET any class or component that
implements the IList interface is a valid DataSource. If a component implements the IList
interface then it is transformed into an index based collection.
Some of the classes that support the IList interface in the NET framework are given below.
Please note that any class that implements the IList interface is a valid data provider.
1. Arrays
2. DataColumn
3. DataTable
4. DataView
5. DataSet
Please note that IList interface only allows you to bind at run time. If you want to support
DataBinding at design time you will have to implement the IComponent interface as well. Also
note that you cannot bind to DataReaders in windows forms (you can in web forms).
The .NET framework supports simple and complex DataBinding. Simple databinding is
supported by controls like TextBoxes. In Simple databinding, only one data value can be
displayed by the control at a time. In complex databinding, which is supported by controls like
the DataGrid, more than one data value from the DataSource can be displayed.
Dataflow during DataBinding
A good understanding of the dataflow from the control to the datasource is very important. The
diagram below gives an overview of the dataflow and the objects involved.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
62 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
In .NET, controls can have many properties that can be bound to a DataSource. Each databound
property has an associated Binding object. Since a control can have many Binding objects, the
control has a collection (instance of ControlBindingsCollection class) of all the Binding objects.
Also remember that different properties of the same control can be bound to different
datasource's.
Each Binding object talks to a CurrencyManager or a PropertyManager. CurrencyManager and
PropertyManager classes merit a little explanation, as they are important. CurrencyManager and
PropertyManager are derived from the base class BindingManagerBase. The purpose of
BindingManagerBase class is to maintain the concurrency between the datasource and the
control. Of the two classes, the CurrencyManager is used when the datasource implements the
IList Interface. Examples of such datasources are DataView, DataSet, ArrayList etc. The
CurrencyManager can be used for simple as well as complex databinding. However, the
PropertyManager is used when the datasource is an instance of a user-defined class. The
Control's property is bound to the property exposed by this object. PropertyManager can only be
used for simple databinding.
As a rule of thumb if you want your class to be a datasource, you should use CurrencyManager
when your class is a data container. However, if you are interested in binding a control to
properties exposed by your own class, then using a PropertyManager is easier, since you do not
have to implement the IList Interface.
Since a form can contain many controls each binding to a different datasource, a class is needed
to manage the CurrencyManager and PropertyManager objects. Therefore, each windows form
in .NET has a default BindingContext object associated with it. But, you can always create more
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
63 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
BindingContext objects on the form. The BindingContext object is a collection of
CurrencyManager and PropertyManager objects.
27. DATA GRID VIEW CLASS.
C# programmers have made extensive use of forms to build user interfaces.
Each time you create a Windows application, Visual Studio will display a default blank
form, onto which you can drag the controls onto your applications main form and adjust
their size and position.
The first step is to start a new project and build a form.
Open your Visual Studio and select File->New Project and from the new project dialog
box select Other Languages->Visual C# and select Windows Forms Application.
Enter a project name at the bottom of the ialogue box and click OK button. The
following picture shows how to create a new Form in Visual Studio.
Select Windows Forms Application from New Project dialog box.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
64 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
After selecting Windows Forms Application , you can see a default Form (Form1) in
your new C# project.
The Windows Form you see in Designer view is a visual representation of the window
that will open when your application is opened.
You can switch between this view and Code view at any time by right-clicking the design
surface or code window and then clicking View Code or View Designer.
The following picture shows how is the default Form (Form1) looks like.
At the top of the form there is a title bar which displays the forms title. Form1 is the
default name, and you can change the name to your convenience .
The title bar also includes the control box, which holds the minimize, maximize, and
close buttons.
If you want to set any properties of the Form, you can use Visual Studio Property
window to change it. If you do not see the Properties window, on the View menu, click
Properties window.
This window lists the properties of the currently selected Windows Form or control, and
its here that you can change the existing values.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
65 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
For example , to change the forms title from Form1 to MyForm, click on Form1 and
move to the right side down Properties window, set Text property to MyForm. Then you
can see the Title of the form is changed.
Likewise you can set any properties of Form through Properties window.
You can also set the properties of the Form1 through coding. For coding, you should
right-click the design surface or code window and then clicking View Code.
When you right click on Form then you will get code behind window, there you can write
your code
For example, if you want to change the back color of the form to Brown , you can code in
the Form1_Load event like the following.
Private void Form1_Load(object sender, EventArgs e)
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
66 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
{
this.BackColor = Color.Brown;
}
UNIT – V
28. Application Domains
n .NET, each application runs in an application domain under the control of a host. The host
creates the application domain and loads assemblies into it. The host has access to information
about the code via evidence. This information can include the zone in which the code originates
or the digital signatures of the assemblies in the application domain. The System.AppDomain
class provides the application domain functionality and is used by hosts. A host can be trusted if
it provides the CLR with all the evidence the security policy requires.
There are several types of application hosts:
Browser host-includes applications hosted by Microsoft Internet Explorer; runs code
within the context of a Web site.
Server host-regarding ASP.NET, refers to the host that runs the code that handles
requests submitted to a server.
Shell host-refers to a host that launches applications, namely .exe files, from the
operating system shell.
Custom-designed host-a host that creates domains or loads assemblies into domains (e.g.,
dynamic assemblies).
Running an Application with a Specific Evidence and Zone
String myApplication = @"C:\MyApp.exe";
String[] argsToApp = null;
String myURL = @"http://www.mindcracker.com";
SecurityZone myZone = SecurityZone.Internet;
Evidence myEvidence = new Evidence();
myEvidence.AddHost(new Zone(myZone));
myEvidence.AddHost(new Url(myURL));
AppDomain app = AppDomain.CreateDomain(myApplication, myEvidence);
app.ExecuteAssembly(myApplication, myEvidence, argsToApp);
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
67 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
29.Remoting
The .NET Remoting provides an inter-process communication between Application Domains by
using Remoting Framework. The applications can be located on the same computer , different
computers on the same network, or on computers across separate networks. The .NET Remoting
supports distributed object communications over the TCP and HTTP channels by using Binary
or SOAP formatters of the data stream.
The main three components of a Remoting Framework are :
1. C# Remotable Object
2. C# Remote Listener Application - (listening requests for Remote Object)
3. C# Remote Client Application - (makes requests for Remote Object)
The Remote Object is implemented in a class that derives from System.MarshalByRefObject .
You can see the basic workflow of .Net Remoting from the above figure. When a client calls the
Remote method, actually the client does not call the methods directly . It receives a proxy to the
remote object and is used to invoke the method on the Remote Object . Once the proxy receives
the method call from the Client , it encodes the message using appropriate formatter ( Binary
Formatter or SOAP Formatter ) according to the Configuration file. After that it sends the call
to the Server by using selected Channel ( TcpChannel or HttpChannel ). The Server side
channel receives the request from the proxy and forwards it to the Server on Remoting system,
which locates and invokes the methods on the Remote Object. When the execution of remote
method is complete, any results from the call are returned back to the client in the same way.
Before an object instance of a Remotable type can be accessed, it must be created and initialized
by a process known as Activation. Activation is categorized in two models , they are Client-
activated Objects and Server-activated Objects.
C# Remote Activation
The real difference between client-activated and server-activated objects is that a server-
activated object is not really created when a client instantiates it. Instead, it is created as needed.
By default the .NET Framework ships with two formatters(Binary Formatter or SOAP Formatter
) and two channels(TcpChannel ,HttpChannel).
C# Remote Channels
C# Remote Formatters
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
68 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
Formatters and Channel are configured by using Configuration files. It can be easily Configured
by using XML-based files.
C# Remote Configuration
30. Leasing and Sponsorship
.NET manages the lifecycle of objects using garbage collection. .NET keeps track of
memory allocation and objects accessed by all the clients in the app domain. When an object
becomes unreachable by its clients, the garbage collector eventually collects it. If the objects
are in the same app domain as the clients, garbage collection functions fine. In fact, even in
the case of a client in one app domain accessing an object in a different app domain in the
same process, garbage collection still works, because all app domains in the same process
share the same managed heap. In the case of remote objects accessed across processes and
machines, however, the strategy breaks down because the object may not have any local
clients. In this case, if garbage collection were to take place, the garbage collector would not
find any references to the object and would deem it garbage, even though there are remote
clients (on other machines, or even in separate processes on the same machine) who wish to
use the object. The rest of this section addresses this challenge.
In the following discussion, a "remote object" is an object in a different process. The core
piece of the .NET remoting architecture designed to address this problem is called leasing
and sponsorship. The idea behind leasing is simple: each server object accessed by remote
clients is associated with a lease object. The lease object literally gives the server object a
lease on life. When a client creates a remote server object (that is, actually creates it, rather
than connects to an existing instance), .NET creates a lease object and associates it with the
server object. A special entity in .NET remoting called the lease manager keeps track of the
server objects and their lease objects. Each lease object has an initial lease time. The clock
starts ticking as soon as the first reference to the server object is marshaled across the app
domain boundary, and the lease time is decremented as time goes by. As long as the lease
time doesn't expire, .NET considers the server object as being used by its clients. The lease
manager keeps a reference to the server object, which prevents the server object from being
collected in case garbage collection is triggered. When the lease expires, .NET assumes that
the server object has no remaining remote clients. .NET then disconnects the server object
from the remoting infrastructure. The server object becomes a candidate for garbage
collection and is eventually destroyed. After the object is disconnected, any client attempt to
access it results in an exception of type RemotingException, letting the client know the
object has been disconnected. This may appear strange at first, because the object may very
well still be alive. .NET behaves this way because otherwise, the client's interaction with the
remote object will be nondeterministic. If .NET allowed remote clients to access objects
past their lease time, it would work some of the time but would fail in those cases in which
garbage collection had already taken place.
31. NET Coding Design Guidelines
Naming Guidelines
Class Member Usage Guidelines
Guidelines for Exposing Functionality to COM
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
69 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
Error Raising & Handling Guidelines
Array Usage Guidelines
Operator Overloading Usage Guidelines
Guidelines for Casting Types
Common Design Patterns
Callback Function Usage
Time-Out Usage
Security in Class Libraries
Threading Design Guidelines
Formatting Standards
Commenting Code
Code Reviews
Additional Notes for VB .NET Developers
32.Assemblies
The .NET assembly is the standard for components developed with the Microsoft.NET. Dot NET
assemblies may or may not be executable, i.e., they might exist as the executable (.exe) file or
dynamic link library (DLL) file. All the .NET assemblies contain the definition of types,
versioning information for the type, meta-data, and manifest. The designers of .NET have
worked a lot on the component (assembly) resolution.
There are two kind of assemblies in .NET;
private
shared
Private assemblies are simple and copied with each calling assemblies in the calling assemblies
folder.
Shared assemblies (also called strong named assemblies) are copied to a single location (usually
the Global assembly cache). For all calling assemblies within the same application, the same
copy of the shared assembly is used from its original location. Hence, shared assemblies are not
copied in the private folders of each calling assembly. Each shared assembly has a four part
name including its face name, version, public key token and culture information. The public key
token and version information makes it almost impossible for two different assemblies with the
same name or for two similar assemblies with different version to mix with each other.
An assembly can be a single file or it may consist of the multiple files. In case of multi-file, there
is one master module containing the manifest while other assemblies exist as non-manifest
modules. A module in .NET is a sub part of a multi-file .NET assembly. Assembly is one of the
most interesting and extremely useful areas of .NET architecture along with reflections and
attributes, but unfortunately very few people take interest in learning such theoretical looking
topics.
What are the basic components of .NET platform?
The basic components of .NET platform (framework) are:
.Net Applications
(Win Forms,Web Applications,Web Services)
Data(ADO.Net) and XML Library
FrameWork Class Library(FCL) (IO,Streams,Sockets,Security,Reflection,UI)
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
70 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
Common Language Runtime(CLR) (Debugger,Type Checker,JITer,GC)
Operating System (Windows,Linux,UNIX,Macintosh,etc.,)
33. XML WEB SERVICE APPLICATION
On your local computer (localhost), start Visual Studio .NET. On the File menu, click
New and then click Project. Under Project types click Visual Basic Projects, then click
ASP.NET Web Service under Templates. Name the project TestService.
In Solution Explorer, change the name of Service1.asmx to Services.asmx.
Open Services.asmx in the visual designer. In the Properties window, change the Name
property of the Service1 class to Services.
Save the project.
Create the XML Web Service Methods
Open Services.asmx in the code editor.
Add the following code within the Services class definition to create various Web
methods:
<WebMethod()> Public Function GetMessage() As String
Return "Today is the day"
End Function
<WebMethod()> _
Public Function SendMessage(ByVal message As String) As String
Return "Message received as: " & message
End Function
<WebMethod()> _
Public Function ReverseMessageFunction(ByVal message As String) As String
Return StrReverse(message)
End Function
<WebMethod()> Public Sub ReverseMessageSub(ByRef message As String)
message = StrReverse(message)
End Sub
Save and build the project.
Test the Services with Visual Studio .NET
In Solution Explorer, right-click Services.asmx and then click View in Browser.
Follow these steps to use the built-in browser to test each Web method:NOTE: You
cannot test the ReverseMessageSub procedure because it expects a ByRef argument.
Click the hyperlink for the method that you want to test.
Fill in any requested message parameter values.
Click Invoke.
View the resulting XML and close the results window.
Click the Back button to return to the method list and repeat the steps for the
remaining Web methods.
Close the built-in browser.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
71 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
Create the Test Client Application
On the File menu, click Add Project, and then click New Project.
Select Visual Basic Console Application, and then name the project TestHarness.
On the Project menu, click Add Web Reference.
In the Address field, type http://localhost/TestService/Services.asmx, and then click Go.
Click Add Reference to finish creating the Web reference.
In Solution Explorer, right-click localhost in the Web References folder, click Rename,
and then change the name to WebService. This becomes the namespace that is used
within the test application to refer to the Services class.
Create the Test Code
Open Module1.vb and locate the Sub Main procedure.
Paste the following code in the file to call the appropriate Web methods:
Dim strValue As String = "This is my message"
Dim myService As New WebService.Services()
Console.WriteLine(myService.GetMessage)
Console.WriteLine(myService.SendMessage(strValue))
Console.WriteLine(myService.ReverseMessageFunction(strValue))
myService.ReverseMessageSub(strValue)
Console.WriteLine(strValue)
Test the Client Application
Create a breakpoint on the following line:
Console.WriteLine(myService.GetMessage)
In Solution Explorer, right-click the TestHarness project, and then click Set as StartUp
Project.
On the Debug menu, click Start and wait for the program to enter debug mode.
On the Debug menu, click Windows, and then click Locals. Use the Locals window to
view the value of the strValue variable during the debugging to observe any changes that
are made to the variable.
On the Debug toolbar, use Step Into to step through each line of code from the
TestHarness client into the XML Web service.
Before you end the Main subroutine, confirm that the output in the console window is as
expected.
When the program ends, remove the breakpoint and close Visual Studio .NET.
34. WSDL
Web Services Description Language (WSDL)
Web Services Description Language (WSDL) is a format for describing a Web Services
interface. It is a way to describe services and how they should be bound to specific
network addresses. WSDL has three parts:
Definitions
Operations
Service bindings
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
72 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
Definitions are generally expressed in XML and include both data type definitions and
message definitions that use the data type definitions.
These definitions are usually based upon some agreed upon XML vocabulary. This
agreement could be within an organization or between organizations.
Vocabularies within an organization could be designed specifically for that organization.
They may or may not be based on some industry-wide vocabulary.
If data type and message definitions need to be used between organizations, then most
likely an industry-wide vocabulary will be used.
XML, however, is not necessary required for definitions. The OMG Interface Definition
Language (IDL), for example, could be used instead of XML.
If a different definitional format were used, senders and receivers would need to agree on
the format as well as the vocabulary. Nevertheless, over time, XML-based vocabularies
and messages are likely to dominate.
XML Namespaces are used to ensure uniqueness of the XML element names in the
definitions, operations, and service bindings.
Operations describe actions for the messages supported by a Web service. There are four
types of operations:
One-way: Messages sent without a reply required
Request/response: The sender sends a message and the received sends a reply.
Solicit response: A request for a response. (The specific definition for this
action is pending.)
Notification: Messages sent to multiple receivers. (The specific definition for
this action is pending.)
Operations are grouped into port types. Port types define a set of operations supported by
the Web service.
Service bindings connect port types to a port. A port is defined by associating a network
address with a port type. A collection of ports defines a service. This binding is
commonly created using SOAP, but other forms may be used. These other forms could
include CORBA Internet Inter-ORB Protocol (IIOP), DCOM, .NET, Java Message
Service (JMS), or WebSphere MQ to name a few.
The following figure shows the relationship of the basic parts of WSDL:
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
73 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
35. SOAP
SOAP (Simple Object Access Protocol) is a messaging protocol that allows programs that
run on disparate operating systems (such as Windows and Linux) to communicate using
Hypertext Transfer Protocol (HTTP) and its Extensible Markup Language (XML).
Since Web protocols are installed and available for use by all major operating system
platforms, HTTP and XML provide an at-hand solution that allows programs running
under different operating systems in a network to communicate with each other.
SOAP specifies exactly how to encode an HTTP header and an XML file so that a
program in one computer can call a program in another computer and pass along
information.
SOAP also specifies how the called program can return a response. Despite its frequent
pairing with HTTP, SOAP supports other transport protocols as well.
SOAP defines the XML-based message format that Web service-enabled applications use
to communicate and inter-operate with each other over the Web.
The heterogeneous environment of the Web demands that applications support a common
data encoding protocol and message format. SOAP is a standard for encoding messages
in XML that invoke functions in other applications.
SOAP is analogous to Remote Procedure Calls (RPC), used in many technologies such as
DCOM and CORBA, but eliminates some of the complexities of using these interfaces.
SOAP enables applications to call functions from other applications, running on any
hardware platform, regardless of different operating systems or programming languages.
SOAP calls are much more likely to get through firewall servers, since HTTP is typically
Port 80 compliant, where other calls may be blocked for security reasons. Since HTTP
requests are usually allowed through firewalls, programs using SOAP to communicate
can be sure that the program can communicate with programs anywhere.
Some of the advantages of leveraging SOAP include:
It is platform and language independent.
SOAP provides simplified communications through proxies and firewalls, as
mentioned above.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
74 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
It has the ability to leverage different transport protocols, including HTTP and
SMTP, as well as others.
Some disadvantages of leveraging SOAP include:
SOAP is typically much slower than other types of middleware standards,
including CORBA. This due to the fact that SOAP uses a verbose XML
format. You need to fully understand the performance limitations before
building applications around SOAP.
SOAP is typically limited to pooling, and not event notifications, when
leveraging HTTP for transport. What's more, only one client can use the
services of one server in typical situations.
Again, when leveraging HTTP as the transport protocol, there tends to be
firewall latency due to the fact that the firewall is analyzing the HTTP
transport. This is due to the fact that HTTP is also leveraged for Web
browsing, and many firewalls do not understand the difference between the
use of HTTP within a Web browser, and the use of HTTP within SOAP.
SOAP has different levels of support, depending upon the programming
language supported. For example, SOAP support within Python and PHP is
not as strong as it is within Java and .NET.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
75 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
GLOSSARY
Accessibility (JFC) The Accessibility API of the JFC classes provides interaction with assistive technologies such as
speech recognition, Braille displays, and screen magnification. It contains interfaces for user
interface components that allow the developer to access information in accessibility-enabled
components.
ActiveX (OCX) An ActiveX component can be visual or non-visual. Depending on the visual interface, OCXs
are compatible with any environment that supports ActiveX which includes all Microsoft
languages, Borland Delphi, and Borland C++ Builder.
ActiveX Designer This is a design-time tool that is used to create and modify classes for use in applications.
Components created from these classes are private and cannot be placed on a form - if they are
visual components, they always appear in their own window.
Add-In Any tool that extends the Integrated Development Environment (IDE). An Add-in provides
functionality to the IDE. Used only at design-time.
ADO Microsoft ActiveX Data Objects are used to perform object-oriented access to data. The objects
represent the structure and data of any OLE DB or ODBC database and can be used to query or
change this data.
Apartment Model Threading Apartment-Model Threading is a multi-threading model that provides thread safety by treating
each thread as an apartment. Just as people who live in different apartments are separate even
though they live in the same building, any components created (instantiated) in the thread are
unaware of components created in any other threads, but can directly call components in the
same thread (apartment).
API Application Programming Interface. An API is an interface to a specific environment. For
example: The Windows API exposes interfaces to the Windows environment, allowing
developers to access and control Windows functions. The Java API provides similar interfaces to
a Java Virtual Machine. Even components, such as ActiveX or JavaBean components expose
their interfaces to be accessed via their particular component APIs.
Applet An applet is a self contained Java program designed for Web applications. Applet is downloaded
and run on the client to provide specific functionality.
Application Any stand-alone program that accomplishes a pre-determined task, such as converting Microsoft
Word documents to Adobe PDF files. Not generally used in development, but rather used to
support development.
Application Server (EJB) Enterprise JavaBeans are designed to run inside EJB application servers. Application servers are
the EJB server-side equivalent of containers for client-side components. If an EJB is compatible
with a particular application server, then it is, by extension, compatible with any platform that
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
76 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
the app server is compatible with. Application server compatibility is the primary consideration
when determining if an EJB will work in your environment.
Application Server (Win32) An application server is a network server that hosts and runs applications or components. This
can be in the form of simple executables, or in the case of MTS application servers, COM+
components. MTS application servers allow applications to be distributed and scalable, by
placing the components on one or more servers.
ASP (Active Server Pages) An Active Server Page is an application designed to run on Microsoft Internet Information
Server with Active Server Pages installed. ASP allows developers to create dynamic Web-based
applications.
ASP (Application Service Provider) An Application Service Provider is an organization that provides access to applications and
related services via the Internet. Depending on the business model, these applications may be
provided free or licensed on a "rental" or "per use" basis.
ASP.NET Active Server Pages.NET is the next generation of Active Server Pages and is part of the
Microsoft .NET Framework. It supports code written in any .NET Consumer (see Glossary:
.NET Consumer). It fully leverages .NET Assemblies and the use of ASP.NET Server Controls.
ATL COM Components built with the ActiveX Template Library are smaller and faster than
components built with MFC, and they only require the ATL runtime. They are better suited to
components - which, by definition are designed for very specific operations - as they don't offer
all the built-in functionality that the MFC classes provide, whereas MFC is better suited to
applications.
AWT (JFC) The Abstract Window Toolkit is a JFC API for providing Graphical User Interfaces (GUI) to
Java applications. It includes user interface components and graphics and imaging tools.
BaseCLX BaseCLX components are Borland CLX components designed for business logic functionality
such as math, system utilities, etc. They are cross platform components that can be used in the
Microsoft Windows environment - via Delphi - and on several distributions of Linux - via the
Kylix development environment.
Black Box A black box component is a compiled component that a developer can only access through
exposed interfaces. Black box components are inherently more secure than white box
components because there is no risk that a developer could alter the source code and change the
behavior of the component.
Built Using In certain instances, a developer is required to know in what environment a component was built.
For example, a C++ component might be built using MFC or ATL. This information is specified
to give the developer the information they require.
Business Component A business component encapsulates specific business logic in a component that does not
necessarily include a visual element. One example is encryption, where the component is sent a
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
77 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
string of text or a file and it encrypts it. No visual interface was necessary. By comparison A user
interface component must have a visual element, a business component may have a visual
element.
C# (C-sharp) C# (pronounced "C sharp") is a new development language from Microsoft that combines the
strength of C++ with the ease of use of Visual Basic. It allows developers to build robust, object-
oriented applications with fewer lines of code than C++ requires, thus reducing the possibility of
introducing errors. It has been designed to work seamlessly with the .NET Framework. Microsoft
is collaborating with ECMA, the international standards body, to create a standard for C#.
CAB A Cabinet file is a special type of archive for holding compressed files. Used primarily for the
distribution of files packaged with an application, a CAB file is capable of being "digitally
signed" by the author, thus verifying the validity of the source and insuring that the files have not
been tampered with.
CBD Component-based development extends object oriented programming by allowing developers to
build applications from smaller, specialized components. These components can be used and
reused over and over in any application that requires the functionality that they provide.
CCM (CORBA Component Model) The CORBA Component Model is a specification of a server-side component model for building
enterprise-class applications as a set of interconnected components and deploying it in a CCM-
compliant runtim environment. The CCM component specification is defined in the CORBA 3.0
specification. All that is required for a CCM component to be deployed is a CORBA 3.0-
compliant ORB (see Glossary: ORB).
CCW (COM Callable Wrapper) The COM Callable Wrapper is a compatibility mechanism that allows existing COM
applications to leverage .NET components. It wraps the .NET assembly to give it the same
"shape" as a COM component. It exposes standard COM interfaces such as IDispatch,
IUnknown, etc. To the COM application, the .NET component "looks" like a standard COM
component.
Client-side component A client-side component is designed to run on the same machine as the application that uses it.
Client-side components can be either visual or non-visual. Client-side components must be
packaged and deployed with the application and installed on every machine where the
application is installed.
CLR (Common Language Runtime) The .NET Common Language Runtime is the root layer of the .NET Framework. Applications
and components are compiled to MSIL (see Glossary: MSIL). The CLR then uses JIT (Just-
inTime compilation) to compile the IL code to native code for the underlying platform.
Currently, the CLR runs on the Windows platform. However, a version of the CLR for Unix is in
development.
CLX The Component Library for Cross Platform was created by Borland to allow developers to create
components that can be used on both the Windows and Linux platforms. Based on Borland's
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
78 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
Visual Component Library (VCL) and using Delphi syntax, CLX components can be used to
create single-source applications for use on multiple platforms.
COM Microsoft's Component Object Model. It is a reference model for how components are built, and
it specifies how components "speak" to each other and how they are referenced within an
application.
COM Add-In for Office 2000 These are add-ins that use COM to extend the functionality of Office 2000 applications. They
use a specific interface (IDTExtensibility2) in order to work properly within Office applications
such as Word, Excel, Access, etc.
COM Object/ActiveX DLL/In-Process Server ActiveX DLLs are a special type of DLL. They are ActiveX components that run within the
address space of the calling application or component and provide functions for the application
to use. They are compatible with any COM-enabled environment.
COM Object/ActiveX EXE/Out-of-Process Server These are ActiveX components that run in their own address space when called. When an
application or component references the functions provided by this object, execution is
independent of the calling application or component so the application is free to perform other
functions. They are compatible with any COM-enabled client environment.
COM+ Revised COM specification that essentially joins COM and DCOM, although the whole is
greater than the sum of its parts. In everyday conversation, COM, DCOM, and COM+
components are generally referred to as "COM".
Compaq (DEC) Alpha A Compaq Alpha component or application is only compatible with operating systems running
on the Alpha processor manufactured by Compaq. These operating systems include Windows
NT 3.51, Windows NT 4.0, Windows 2000, and several implementations of Unix.
Component Self-contained object with pre-determined functionality and accessed via exposed interfaces.
Examples include ActiveX components, JavaBeans, Enterprise JavaBeans, and VCLs.
Component Categories A component category is a registry entry that specifies whether or not the specified component
supports the interfaces required by its category. The Component Category Manager implements
interfaces that create the categories, place the components in specified categories, and retrieve
information about the categories.
Component Type Components are available for a variety of platforms and development environments. This field
specifies the component type, such as a .NET component, ActiveX, JavaBean, etc. The
developer can use this information to determine if the component is suitable for his purposes.
Cookies Cookies are files that are downloaded via a client browser to identify a user to a particular Web
site. It can contain a variety if information including username, password, profile, etc. Cookies
are used to enhance a user's Web experience by "remembering" session information, user
preferences, etc. Most browsers allow you to either notify the user before accepting cookies or
simply not accept them.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
79 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
CORBA (Component) Common Object Request Broker Architecture (CORBA) components are distributed, server-side
components that are designed to run on CORBA ORBs (Object Request Brokers). ORBs are the
CORBA equivalent of EJB Application Servers. As long as a CORBA component is compliant
with the version of CORBA on the ORB, the component will run.
CORBA (Platform) The Common Object Request Broker Architecture is a specification - created by the Object
Management Group (OMG) - for distributed, scalable components . It defines how CORBA
objects communicate with each other via CORBA-compliant ORBs.
CS-ERS ComponentSource® SAVE-IT™ is the latest version of the ComponentSource Enterprise Reuse
Solution (CS ERS). SAVE-IT offers the business model and technology for recouping the costs
of software development organization-wide. (see Glossary: SAVE-IT)
CSS A Cascading Style Sheet is used to control the appearance of Web pages. It allows the author of
the Web page to determine how items such as frames, hyperlinks, titles, and text are displayed,
while maintaining compatibility with most browsers.
CWM The Common Warehouse Metamodel is a specification published by the Object Management
Group (OMG) that supports distributed metadata analysis. The CWM provides a solution for
extensive metadata analysis by building on the standards of UML (Unified Modeling Language),
XML (eXtensible Markup Language), and XMI (XML Metadata Interchange).
DAO Microsoft Data Access Objects provide an object oriented approach to accessing data via the
Microsoft Jet database engine. It is a shared component of Microsoft Office and can be used by
any application that supports automation.
DataCLX DataCLX components are Borland CLX components designed for providing access to data
sources. They are cross platform components that can be used in the Microsoft Windows
environment - via Delphi - and on several distributions of Linux - via the Kylix development
environment.
DCOM Microsoft's Distributed COM. It is a reference model for building components that can
communicate with other components and application on different computers, usually in a
client/server relationship.
DLL DLLs are "callable" dynamically-linked libraries that can be used in any environment with call
capability. A DLL can contain one or more functions that can be used by other applications or
components. Not to be confused with ActiveX DLLs.
EJB 1.0 Enterprise JavaBeans are components written in Java that can be used to add functionality to
Java applications. They can be used in any environment that runs Java and are designed to run in
server-side applications.
EJB 1.1
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
80 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
Enterprise JavaBeans are components written in Java that can be used to add functionality to
Java applications. They can be used in any environment that runs Java and are designed to run in
server-side applications. In the EJB V1.1 update, one of the most significant changes is that the
"deployment descriptor" - which defines how EJB classes are built and deployed - is rendered as
an XML document. In the previous version it was rendered as a group of Java objects.
EJB 2.0 Enterprise JavaBeans are components written in Java that can be used to add functionality to
Java applications. They can be used in any environment that runs Java and are designed to run in
server-side applications. EJB V2.0 components offer integration with the Java Message Service
and support Container-Managed Persistence.
Enterprise JavaBean Enterprise JavaBeans are components written in Java that can be used to add functionality to
Java applications. They can be used in any environment that runs Java and are designed to run in
server-side applications.
EULA An End User License Agreement is a legal contract between the publisher of a software
application or component and the user of that software. Often referred to as the "license
agreement" or "software license", it is similar to a rental agreement: The user agrees to pay for
the privilege of using the software and promises to comply with all of the publishers restrictions.
Executable An executable is essentially a program. It can be run independently of a host application. The
only requirements for an executable are a compatible operating system and any associated
runtime library.
Free Threading Free Threading is a multi-threading model that supports more than one thread per apartment.
Multiple calls to a component can occur on different threads. While free threading can be faster
than apartment threading, care must be taken with free threaded components to insure that the
threads are synchronized properly.
FTP The File Transfer Protocol is an Internet Standard Protocol for transferring files between
computers over TCP/IP. It is most commonly used to download files from an Internet server to
the local machine. FTP servers require the client to logon, but can be configured to allow that
logon to be anonymous.
HailStorm HailStorm is part of the Microsoft .NET initiative and is designed to make it easier to integrate
the vast knowledge bases of information that exist today. It is based on the Passport user
authentication system and bases services around a "person" instead of around a specific device,
application, service, etc.
HTML The Hypertext Markup Language is a "tagged" language for transferring data using HTTP. It
allows you to format text, include pictures, and insert hyperlinks to other data. The Web browser
reads the "tags" and displays the data accordingly.
HTTP
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
81 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
The Hypertext Transmission Protocol is an Internet standard protocol for exchanging files (text,
images, sound, video, etc.) over the Internet. It is generally used to copy a Web page from an
Internet Web server to the client machine, and to send the client page requests to the server.
HTTPS The Secure Hypertext Transmission Protocol is an Internet standard protocol that allows Web
clients to create a secure connection to a Web server. All data (text, images, sound, etc.) is
encryptedbefore being sent by the server, then decrypted by the client. HTTPS requires that the
server has a digital certificate in order to validate its identity to the client.
IDE An Integrated Development Environment (IDE) is a tool used to develop applications and
components in the specified development language. For example, a developer can write a Visual
Basic application in any text editor. The VB IDE simplifies development by integrating all
aspects of the development process including modules, forms, components, syntax checking, the
VB compiler, and the package and deployment wizard.
IDL An Interface Definition Language file is a file that contains definitions of interfaces to
components, consisting of an interface header and interface body. The header contains attributes
that apply to the interface as a whole. The body contains individual interface definitions such as
data types used in remote procedure calls and prototypes for the remote procedures. While not
required, an IDL makes it easier for a developer to define and query information about a
component's interfaces.
IE Microsoft Internet Explorer is an Internet Web browser used to display information downloaded
from Web sites. It is also a component container capable of using ActiveX components. This
gives IE the ability to display dynamic content that is impossible to display with only HTML.
IIS Internet Information Server is Microsoft's Web server software for making content available on
the Internet. It consists of a WWW service for providing Web pages and Web applications on the
World Wide Web, an FTP service to allow files to be uploaded/downloaded, an SMTP service
for sending email, and an NNTP service for hosting newsgroup forums. IIS V3.0 and higher also
provide Active Server Page functionality.
IMAP The Internet Message Access Protocol is an Internet standard protocol for accessing E-Mail from
your local server. It is a client/server protocol in which the e-mail is received and held for you by
the Internet Server. Using IMAp requires a continuous connection to the server during the email
session.
Internet Enhanced A component marked as Internet Enhanced is designed to be dynamically loaded onto Web
pages. This is accomplished by using the CODEBASE property which tells the browser where to
download the component if it doesn't already exist on the system or if the version has changed.
J# (J Sharp) Microsoft Visual J# .NET is a development tool for Java-language developers for building
applications components, and services on the .NET Framework. It is designed to allows
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
82 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
customers to migrate Java investments to .NET. Existing Visual J++ solutions can be quickly
modified to execute on the .NET Framework. J# solutions will only run on .NET and not on any
Java Virtual Machine.
J2EE The Java 2 Platform Enterprise Edition is a platform upon which multi-tier, distributed, and
scalable enterprise-wide applications and components can be built. This functionality is provided
via Enterprise JavaBeans (EJB) components - which are distributed components, deployed on
J2EE Application Servers, and Java Server Pages (JSP) and Servlets - which are used to provide
functionality to Web applications.
Java (The language) Java is a development language used to build components and applications. It is a compiled
language, which means that the computer that runs the application is not required to have a Java
interpreter installed.
Java (The Virtual Machine) A Java VM is required on any computer where you intend to run a Java application. Sun
Microsystems, who owns Java, has licensed the specifications for the virtual machine so that
manufacturers of operating systems can build Java VMs for their environment. As a result, the
Java language is compatible with a wide range of platforms.
JavaBean JavaBeans are components written in Java that can be used to add functionality to Java
applications. They can be used in any environment that runs Java and are designed to run in
client-side applications.
JavaClass A Java Class is where compiled Java code, in the form of JavaBeans, Applets, and Servlets is
stored. These class files make up the "minimum" deployment unit for Java components.
Typically they are compressed into Java Archive (JAR) files for distribution and deployment.
JDBC Java Database Connectivity is an API for connecting Java applications to databases. JDBC is
very similar to ODBC. You can use JDBC to connect to any ODBC-compliant database from a
Java application. (see Glossary: API, ODBC)
JDK (Java Development Kit) The Java Development Kit contains the software and tools that developers need to compile,
debug, and run components, applets and applications written using the Java language. The
created software is then specified as being compliant with a particular version of the JDK
specification (such as JDK 1.1).
JET The Microsoft Jet database engine is the core of the Microsoft Access database system. It is
through the Jet engine that developers are able to read and write data to Access (.MDB)
databases. In addition to Access, the Jet engine supports dBASE, Paradox, and FoxPro database
file formats. It also supports accessing data in spreadsheets and text files.
JFC The Java Foundation Classes are a set of five APIs that allow developers to build feature-rich
Java applications. The JFC classes are Swing, AWT, Java 2D, Accessibility, and Drag and Drop.
They provide support for forms, handicapped accessibility, and other user interface
enhancements.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
83 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
JIT A Just-in-time compiler (JIT) is the mechanism used by the Microsoft .NET Framework to
compile an application or component into the Microsoft Intermediary Language (MSIL). This
compiled code is interpreted by the Common Language Runtime to interface with the operating
system. By using this two-step process, JITs can be constructed for virtually any development
language, enabling it to interface with the .NET Framework.
JSP (Java Server Pages) A Java Server Page is a technology for displaying dynamic content on Web pages. JSPs use
servlets (see Glossary: Servlet) that run on the Web server to create content that is sent as HTML
to the Web client.
Kylix Borland Kylix is an Integrated Development Environment created by Borland for the Linux
platform. It provides a visual, component-based development environment for creating Linux
desktop and server applications.
License Agreement A binding legal agreement between the component or software publisher and the end user. In the
case of a component, "End User" refers to the developer who purchased the component, not end
users of that developer's application built with the component. License agreements specify terms
of use for the software.
Lines of Code This is the number of lines of code that are in the current version of this product. If your
company knows how much it costs to write a "Line of Code" in a specific development language
such as C++ or Java, then in conjunction with "Development Language Used" this value can be
used to determine the cost of building this product yourself, which you can compare with the
cost of purchasing it "off-the-shelf".
Linux Linux is an open source version of Unix that is available in several implementations from
different companies such as RedHat, Slackware, Caldera, and TurboLinux. These companies
offer Linux distributions that run on Intel x86 processors, Sun Solaris, COMPAQ Alpha, and
more.
MAC MAC refers to the Macintosh platform which consists of Apple Macintosh hardware and the
MAC-OS operating system.
MAC (as in MAC address) The Media Access Control address is a 48-bit address that is burned into the circuits of a
Network Interface Card (NIC). It is globally unique and identifies that machine on the network.
In a TCP/IP network, the IP address is resolved to the MAC address in order to deliver packets to
the correct computer.
MDAC Microsoft Data Access Components are the connectors that allow Microsoft Development
Environments to access heterogeneous data sources. It includes connectors for MS Access, MS
SQL, data files, and more.
Metadata
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
84 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
Metadata refers to an organization's entire accumulated data. In addition to traditional warehouse
data such as personnel, products, prices, services, etc., metadata also refers to documented
processes, formats, even intellectual property.
MFC V4.0 COM Components built with the Microsoft Foundation Class Library V4.0 use the MFC V4.0
DLL to provide the necessary libraries. MFC V4.0 must be installed on the machine that this
component/application is run on.
MFC V4.2/5.0/6.0 COM Components built with the Microsoft Foundation Class Library V4.2/5.0/6.0 use the MFC
V4.2 DLL to provide the necessary libraries. This DLL must be installed on the machine that this
application/component is run on.
MSIL (Microsoft Intermediate Language) MSIL is the common language that all .NET development languages compile to. This allows
components and applications written in any .NET development language to interoperate. MSIL is
the "common" language used by the .NET Common Language Runtime (CLR). It is compiled to
native code for the underlying platform by the CLR.
MTS Compatible These are COM components that execute in the Microsoft Transaction Server (MTS) runtime
environment. They are inherently scalable for distributed, enterprise-wide computing because a
component on a client machine(s) can communicate with a component on a server(s). MTS
components must be DLLs. EXEs and OCXs are not supported.
NetCLX NetCLX components are Borland CLX components designed for networking functionality such
as HTTP, FTP, CGI, and Sockets programming. They are cross platform components that can be
used in the Microsoft Windows environment - via Delphi - and on several distributions of Linux
- via the Kylix development environment.
Obfuscation Code obfuscation is the process of making code difficult to understand by hiding (renaming)
program references such as methods, namespaces, properties, etc. Byte code such as Java and
.NET MSIL are particularly vulnerable to reverse engineering. Obfuscation provides a level of
protection against such reverse engineering.
OCX96 Compatible Not all ActiveX components are visual. A component marked as OCX96 Compatible supports
being loaded into OCX96 containers that allow transparent components or non-rectangular
windows.
ODBC Open Database Connectivity is an Application Programming Interface (API) that provides access
to a variety of data sources. It is an industry standard for exchanging data. As such, it allows
computers in a multi-platform environment to access data on a SQL (or any ODBC-compliant)
database.
OLE Object Linking and Embedding is a technology that uses the Microsoft Component Object
Model (COM) to allow for the creation of compound documents. OLE-enabled applications can
contain a variety of objects. For example: a Word document can contain an Excel spreadsheet, or
a PowerPoint presentation can contain an AVI file.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
85 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
OLE DB OLE DB is an Application Programming Interface (API) that provides access to a variety of data
sources. It is designed to give clients in a Microsoft COM environment access to all types of data
such as Microsoft SQL.
OMG The Object Management Group is a not-for-profit corporation founded by eleven companies
including 3Com, American Airline, Hewlett-Packard, Sun Microsystems, and Unisys. It supports
a component-based software marketplace through industry standards. Some of the standards the
OMG has been intrumental in creating are the CORBA specification and its related IIOP
(Internet Inter-ORB Protocol).
OOP Object Oriented Programming is the process of building applications by encapsulating
functionality into individual objects. These objects feature polymorphism and inheritance. OOP
is the foundation of component-based development (CBD)
Operating System Many component and tool types are only supported by specific operating systems such as
Microsoft Windows, Sun Solaris, Unix, Linux, etc. This information is specified to provide the
developer with the supported operating systems for the product.
ORB Object Request Broker (CORBA). ORBs are the middle-tier servers that house CORBA
components. ORBs are defined as being built upon a particular version of the CORBA
specification, such as 2.0 or 2.3. It is this version number to determines if a CORBA component
can be run on a given ORB. ORBs can be compared to EJB Application Servers. In fact, many
EJB App Servers also contain CORBA ORB software, enabling them to run both EJB and
CORBA components.
Polymorphism Polymorphism allows you to have related classes with methods of the same name. At runtime the
correct procedure is determined based on the class of the object. For example, if you pass an
object as an argument to a procedure, the procedure can invoke methods of the object without
knowing what type of object it is.
POP3 The Post Office Protocol 3 is an Internet standard protocol for receiving e-mail. POP3 is a
client/server protocol in which email is received and held for you by the Internet server. Once the
client connects, the POP3 server forwards all messages to the client and terminates the
connection.
Primary Development Language Used This is the development language used to build the current version of this product. If your
company knows how much it costs to write a "Line of Code" in a specific development language
such as C++ or Java, then in conjunction with the "Lines of Code" value this can be used to
determine the cost of building this product yourself, which you can compare with the cost of
purchasing it "off-the-shelf".
RCS The ComponentSource Reusable Component Specification is the unifying type model on which
all externally visible marketplace information is based. It constitutes our public marketplace
community standard - it is used by our author and customer networks and is surfaced in a
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
86 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
number of "physical" forms. These forms include the public marketplace Web catalog pages, the
publisher product submission form, and the XML schemas used by the ComponentSource
SAVE-IT Web services. (see Glossary: SAVE-IT)
RCW (Runtime Callable Wrapper) The Runtime Callable Wrapper is a compatibility mechanism that allows .NET to support
existing COM components. The RCW "wraps" the COM component and gives it the same
"shape" as a .NET Assembly. To .NET applications, the component "looks" like a .NET
component.
RDBMS Remote Database Management System. Refers to the back-end database system that houses an
organization's data. There are several types of RDBMS including SQL, Oracle, dBase, Paradox,
and more.
Repository A repository is a database containing software rather than data. This software can be in the form
of executables, components, libraries, UML models, and more. Most repositories include an
application that is used to manage its own database.
Reusable Component Reusable component is a generic term for any self-contained block of code that encapsulates
specific business logic or user interface functionality. It can exist as either a "white box"
component (source code) or as a "black box" component (binary code, accessed via exposed
interfaces).
Reverse Engineering Software reverse engineering is the process of "de-compiling" byte code back into usable source
code to determine how a program works. In order to protect their intellectual property, many
software developers use code obfuscation to make reverse engineering more difficult.
RMI Remote Method Invocation is the technology that allows Java developers to access distributed
components in an enterprise environment. It is similar to a remote procedure call, but it has the
ability to pass one or more objects along with the request. The object can include information
that will change the service that is performed on the remote computer.
ROPE The Remote Object Proxy Engine is an object model that developers can use to implement and
use SOAP Web services. It actually consists of two parts The Proxy Object, and the
SOAPPackager Object. The Proxy object allows a client to access a Web service as if it were a
local COM object., thus allowing any COM-enabled language access to the Web service. The
SOAPPackager object provides a lower-level model for handling SOAP messages and is
typically used on the server-side.
RPC Remote Procedure Call is a protocol that an application or component can use to request a
service from an application or component located on another computer, without being required to
understand network details.
Runtime License A runtime license is a restriction that is placed on a component or application which specifies
how it can be used by the end-user. Some runtime licenses consist simply of a legal agreement
entered into by the manufacturer and the end user. Other runtime licenses are actually enforced
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
87 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
by the software and can limit its functionality based upon a license key. As it pertains to
components, a runtime license specifies how the developer can deploy a component within their
application.
Safe for Initialization When an ActiveX component is marked as Safe for Initialization, the developer is certifying - via
his digital signature - that the component can be loaded into a Web page and "instantiated" or
created. In Active Server Pages this is done by assigning the component to a variable SET
objMyVar=Server.CreateObject("MyObject.MyClass")
Safe for Scripting When a component is marked as Safe for Scripting, the developer has used his digital signature
to certify that the component is safe to code against strMyString=objMyVar.GetMyString
SAVE-IT™ - (Software Asset Value Engineering in Information Technology) The latest version of ComponentSource Enterprise Reuse Solution, ComponentSource® SAVE-
IT™ offers the business model and technology for recouping the costs of software development
organization-wide. SAVE-IT™ consists of an enhanced and proven three-pronged commercial
approach to establish the business drivers for reuse of software assets inside of an organization,
and a scalable asset rich infrastructure to institutionalize reuse. The customizable solution may
be packaged according to a customer's needs. It differentiates itself in the market on three proven
levels comprising: SAVE-IT PROCESS™, SAVE-IT CATALOG™, and SAVE-IT
CONTENT™.
Server-side Component A server-side component is any component that is optimized to run in the middle tier of a multi-
tier environment. This includes Web servers and application servers. These components are
generally non-visual except for those that are specially designed to send user interface data to the
client, such as server-side graphing and charting components and the forthcoming .NET server-
side user interface components.
Servlet A Servlet is a self contained Java program designed for Web applications. Servlets are run on the
Web server and data is sent to the client via HTML or XML.
SMTP The Simple Mail Transfer Protocol is an Internet standard protocol for sending and receiving E-
Mail. It is limited in its ability to queue messages and, as such, is usually used with either the
POP3 or IMAP protocols at the receiving end. (see Glossary: POP3, IMAP)
SOAP The Simple Object Access Protocol is an industry standard protocol for component
interoperability over the Internet. It is built on the existing standards of XML and HTTP to allow
components of all platforms to communicate via standard protocols.
Source Code Source code is a listing of the actual commands of a component or application and is written in a
particular development language such as Visual Basic, Visual C++, or Java. Components that
come with source code are referred to as "White box" components, since all of the underlying
logic is exposed. Developers can modify source code to add functionality.
SQL The Structured Query Language is an industry standard programming language for accessing and
updating a database. SQL is also used to refer to the the database management system (DBMS)
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
88 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
that stores this data. SQL queries allow you to select, insert, update, and find data in the SQL
database.
Static Link Library Static Link Libraries are class libraries that can be linked into C++ applications. These are
packaged as .LIB files.
Swing (JFC) The JFC Swing classes provide support for forms-based Java programming. It provides the
ability to include trees, tabbed panes, splitter panes, and other user interface enhancements to
Java applications, giving them the look-and-feel expected in today's application marketplace.
TCP/IP The Transmission Control Protocol/Internet Protocol is the base protocol used for
communication over the Internet. It allows both connection-based and non connection-based (fire
and forget) transmission of data over the Internet. Essentially, TCP/IP is tha language spoken by
the Internet Protocols/Services such as HTTP, SMTL, FTP, etc.)
Thread A thread is the smallest unit of execution. It is what the operating system allocates CPU time to.
A process consists of one or more threads. An application or component consists of one or more
processes.
Tool Type In addition to components, ComponentSource provides useful tools to assist developer in
creating components and applications. These tools may be components, applications, add-ins,
etc. They are specified here to clearly define the functionality provided.
UDDI The Universal Description, Discovery, and Integration service is a platform-independent, XML-
based registry that is used to dynamically discover Web Services. It uses WSDL to communicate
the service information. WSDL sits on top of SOAP, which in turn sits on top of XML. (See
related definitions: WSDL, SOAP, XML.) UDDI allows Web services to list themselves by
name, product, location, or Web Services offerred.
UML The Unified Modeling Language is designed to specify and document the structure of and
interfaces to a software component or system. It is a graphical language for expressing program
design in a standard way. A UML model is essentially a blueprint for the construction of that
component or system.
VB Class Library These consist of either source code (.CLS) or compiled (.DLL) libraries that can be referenced
from Visual Basic.
VB5 A COM component built using Microsoft Visual Basic V5.0 has no external dependencies. The
only requirement is that the Visual Basic V5.0 runtime is installed on the development machine
and any end user machines.
VB6 A COM component built using Microsoft Visual Basic V6.0 has no external dependencies. The
only requirement is that the Visual Basic V6.0 runtime is installed on the development machine
and any end user machines.
VBX
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
89 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
Visual Basic Extensions are 16Bit components only compatible with Visual Basic running on
operating systems that support 16Bit.
VC++ Class Library These are source code or complied (.DLL) libraries that can be referenced from Visual C++.
VCL Visual Class Library components are visual or non-visual components that are compatible only
with Borland environments such as Delphi and C++ Builder.
Visual Basic Microsoft Visual Basic consists of two parts the Visual Basic language and the VB Integrated
Development Environment (IDE). VB is a high-level, easily learned programming language for
developing applications and components. If a component is listed as being compatible with a
particular version of VB (i.e. VB 3.0, VB 4.0), it requires the specified version. For example, the
current version of VB is V6.0. VB 6 is 32Bit only and does NOT support 16Bit VBXs.
Visual Studio Microsoft Visual Studio is a suite of programming languages for developing applications and
components. It consists of Visual Basic, Visual C++, Visual Interdev, Visual J++, and Visual
FoxPro. If a component is listed as compatible with a particular version of Visual Studio, it is by
definition compatible with all five IDEs.
Visual Studio.NET Visual Studio.NET is the suite of development languages writen by Microsoft to allow
development for the .NET platform. It includes Visual Basic.NET, C++.NET, and a new
language: C#. All Visual Studio.NET languages are considered .NET Extenders (see Glossary:
.NET Extenders).
VisualCLX VisualCLX components are Borland CLX components designed for user interface functionality
such as grids, treeviews, listboxes, etc. They are cross platform components that can be used in
the Microsoft Windows environment - via Delphi - and on several distributions of Linux - via the
Kylix development environment.
WAP (Wireless Application Protocol) The Wireless Application Protocol is a specification for standard protocols used by wireless
devices such as cellular phone, handheld and palmsize computers, etc., for Internet access, E-
Mail, newsgroups, and more.
Web Service A Web Service is programmable logic that is accessible via standard Web protocols. It uses
SOAP to describe the interfaces to the service, enabling cross-platform Internet clients to use that
logic via XML protocols.
White Box A white box component is a class library that is available as source code. All functions are
exposed and the component can be modified with no restrictions other than those outlined in the
component author's license agreement.
Win 2000 Windows 2000 is built on NT technology to provide robust, secure network servers and
workstations.
Win 3.x Microsoft Windows 3.1, 3.11. 16Bit operating system.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
90 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
Win 95 Microsoft Windows 95. Supports both 16Bit and 32Bit components.
Win 98 Microsoft Windows 98. Supports both 16Bit and 32Bit components.
Win CE 2.x Microsoft's operating system for palm-size and handheld devices.
Windows DNS A Windows Digital Nervous System is Microsoft's vision of multi-tier, integrated systems of
applications, distributed components, and services, utilizing industry standards such as HTTP,
XML, SOAP, and MTS, used to create scalable, enterprise-wide systems.
Windows Foundation Class These are components that are created from the WFC and can be used in Java applications as
well as other environments that support ActiveX components such as Visual Basic and Visual
C++.
WinNT 3.51 Windows NT is Microsoft's robust, secure operating system for network servers and
workstations. WinNT 3.51 has a user interface similar to Windows 3.x.
WinNT 4.0 Windows NT is Microsoft's robust, secure operating system for network servers and
workstations. WinNT 4.0 has a user interface similar to Windows 9x.
Wizard Tool used to enhance development environment or add functionality to application at design-
time. Also describes applications that perform a type of conversion, such as a "Data Migration
Wizard" to transform a database from one type to another.
WML (Wireless Markup Language) The Wireless Markup Language allows the text of Web pages to be displayed on handheld
devices and cellular telephones. It is part of the Wireless Application Protocol (see Glossary:
WAP).
WSDL (Web Services Description Language) The Web Services Description Language is an XML-based language that is used to describe Web
services. It is the language used by the UDDI registry to allow businesses to list their Web
services.
XML The Extensible Markup Language (XML) is an industry standard method for using "tags" to
describe data for exchange between different platforms, languages, and applications. Since it is
an open standard, it is ideal for exchanging data over the Internet.
XSL The Extensible Stylesheet Language is used to describe XML data that is sent over the Web is
presented to the user. It is an industry standard language that gives the Web page author control
over how XML data is displayed, which fields are presented, where they are displayed on the
page, and in what order.
XSLT XSL Transformations is an industry standard that describes how to change an XML document
from one structure to another structure. It is used to transform the source tree of one XML
document into a result tree for a new XML document.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
91 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
Question Bank
UNIT – I
PART - A
1. Define in brief Object Oriented Principles.
OOP is based on three key principles: encapsulation, inheritance, and polymorphism.
Encapsulation binds together code and data,
Inheritance is the mechanism by which one class can inherit the functionality of another.
Polymorphism lets you define one interface that describes a general set of actions.
These attributes work together in a powerful way that enables the construction of reliable,
reusable, and extensible programs.
2. What are the applications of C# ?
console applications
Windows applications
Developing windows controls
Developing ASP.NET projects
Creating Web Controls
Providing web services
Developing .NET component library
3. What is c#?
C# is Microsoft premium language for .Net development such as Enterprise
applications, web applications , windows applications and embedded systems.
C# is intended to be a simple, modern, general- purpose , type safe object oriented
programming language that enables programmers to quickly and easily build
solutions for the Microsoft .Net platform.
A programming infrastructure created by Microsoft for building, deploying, and
running applications and services that use .NET technologies, such as desktop
applications and Web services.
4. Draw the structure of .Net Framework.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
92 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
5. What are boxing and unboxing?(Apr/May 2008)
Boxing:
The operation of converting a value type to a reference type is called boxing
Example:
int i=123;
object obj=(object)i;
Unboxing: The operation of converting a reference type to a value type is called
unboxing.
Example:
Object obj=123;
int i=(int)obj;
6. How C #does differ from Java?(Nov/Dec 2009)
C# Java
C# allows operator overloading Does not include operator overloading
Methods are non virtual by default Methods are virtual by default
It Support struct type It does not Support struct type
Support decimal type No unsigned integer types.
7. Name any four applications that are supported by .Net platform.(Nov/Dec 2009)
Console Applications
Windows Applications
Creating web controls
Providing web services
Developing .net component library.
8. Compare value type and reference type. (Apr/May 2010) (Nov / Dec 2011)
Value types Reference Types
Value types hold actual value Reference types hold references to values
stored somewhere in memory
Value types are allocated on the stack Reference types are allocated on the heap
9. What are the basic elements of C#? (May/June 2012)
Formatting
Designing
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
93 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
Naming
Packaging
Documentation
Programming
10. List out the different types of I/O Commands in c#.
Command Line Arguments
Readline Method
Compilation error
11. Give the benefits of .NET framework. (May /June 2012)
Simple
Consistent
Modern
Object Oriented
Type-safe
12. Discuss .NET namespaces
The .NET Framework Class Libraries(FCL) are arranged into a logical grouping according
to their functionality and usability is called Namespaces.
13. Is it possible to have two main () in a C# code? If so, how it is resolved?
Yes, If the program contains several mains that could be the startup function then you need
to specify which to use, either on the command line or in a project properties application startup
object.
14. What are the types of string?
Immutable String
Mutable String
Regular Expression
15. List out the advantages of using the methods.
Reducing duplication of code
Decomposing complex problems into simpler pieces.
Improving clarity of the code
Reuse of code
Information hiding
16. What are the types of branching?
Conditional Branching
Conditional branching is the branching is based on particular condition.
Unconditional Branching
Unconditional branching is the branching without any decision
17. Give the syntax of foreach loop.
foreach(type<iteration variable>in list)
{
Statements;
}
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
94 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
18. How is class declared?
Classes are declared by using the keyword class followed by the class name and the set of
class members surrounded by curly braces.
Syntax:
[modifiers]class class_name
{
[Class members declaration;]
}
19. How are the class members accessed?
Once the object are created, the dot operator is used to access any class members by using
the object name.
Syntax:
To access the variables inside the class
Objectname.variable name;
To call the method inside the class
Objectname.methodname(argument_list)
Part-B
1. Explain in detail about the activities of CLR.
2. Explain about various Namespaces of .NET framework.
3. Briefly explain all the control structures in C#.
4. Explain in detail about various operators available in C#.
5. Explain about various string handling methods.
6. Explain about Enumerators and structures in C#
UNIT - II
Part A
1. What is a constructor?
A constructor initializes an object when it is created. It has the same name as its class and
is syntactically similar to a method. However, constructor have no explicit return type. The
general form of constructor if shown here:
Access class-name()
{
//constructor code
}
2. What is a static constructor? (Nov / Dec 2011)
A static constructor is called before any object of the class is created. This is useful to do
any housekeeping work that needs to be done once. it is usually used to assign initial values to
static data members.
3. What are the restrictions of static methods?
That there is no access modifier on static constructors. It cannot take any. A class can
have only one static constructor.
4. What is property?
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
95 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
Another type of class members is the property. A property combines a field with the
methods that access it. if you want to create a field that is available to users of an objects, but you
want to maintain control over the operations allowed on that field.
5. What is read-only property?
There are situations where we would like to decide the value of a constant member at
run- time. We may also like to have different constant values for different objects of the class. To
overcome these shortcomings, c# provides another modifier known as read only
6. What is an indexer? (Apr / May 2011)
Array indexing is performed using the []operator. An indexer allows an object to be
indexed like an array. The main use of indexes is to support the creation of specified arrays that
are subjects to one or more constraints.
7. What are the two form of inheritance?
The two form of inheritance classical form, containment form
8. What is hiding a method?
We can use the modifier new to tell the compiler that the derived class method ―hides‖
the base class method.
9. What is polymorphism? (May / June 2012)
Polymorphism means ’one name, many form’. Polymorphism can be achieved in two
ways. c# supports both of them
Operation polymorphism
Inclusion polymorphism
10.What is early binding?
The compiler is able to select and bind the appropriate method to the object for a
particular call at complier time itself. this process is called early binding, or static binding ,it is
also known as complier time polymorphism
11. What is late binding?
The decision on exactly which method to call is delayed until runtime and, therefore, it is
also known as runtime polymorphism. Since the method is linking with a particular class much
later after compilation, this process is termed late binding.
12. What is operator overloading? (May / June 2012)
This means, c# has the ability to provide the operator with a special meaning for data
type .this mechanism of giving such special meaning to an operator is known as operator
overloading.
13. List the operators that can be overloaded?
Category Operations
Binary arithmetic +,*,?,-,%
Unary arithmetic +,-,++,--
Binary bitwise &,|,^,<<,>>
Unary bitwise !,~,true, false
14. List the operators that cannot be overloaded?
Category Operations
Conditional operators &&,||
Compound assignment +=,-=,*=,/=,%=
15. What is a delegate? (May / June 2012)
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
96 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
The dictionary meaning of delegate is ―a person acting for another person‖. In c#, it
really means method acting for another method. Creating and using delegates involves four
steps. They include:
Delegate declaration
Delegate methods definition
Delegate instantiation
Delegate invocation
16. What delegate method?
Delegate methods are any functions (defined in a class) whose signature matches the
declare signature matches the delegate signature exactly.
17. What is multicast delegate?
It is possible for certain delete to hold and invoke multiple methods. Such delegates are
called multicast delegates. Multicast delegates, also known as combinable delegates, must satisfy
the following conditions:
The return types of the delegate must be void.
None of the parameter of the delegate type can be declared as out put parameter,
using out keyword.
18. What is an event?
An event is a delegate type class member that is used by the objects or class to provide a
notification to other objects that event has occurred. The client object can act on an event by
adding an event handler to the event
19. What is an interface?
An interface can contain one or more methods, properties, indexers and events but none
of them are implemented in the interface itself. It is the responsibility of the class that
implements to define the code for implementation of theses members.
20. What is the purpose of using the finally block?
C# supports another statements known as a finally statements that can be used to handle
an exception that is not caught by any of the previous catch statements. A finally blocks can be
used to handle any exception generated within a try block.
Part B
1. Explain about interfaces in C#.
2. Explain in detail about Exception Handling.
3. Briefly explain the concept of Delegates.
4. What is event? How events are created? Give example.
5. Explain in detail about Inheritance?
6. Explain in detail about the concept of operator overloading.
UNIT – III
PART – A
1. Name some of the Operation on Data Structures
Insertion
Deletion
Traverse
reversing
Searching
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
97 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
Sorting
Copying
Merging
2. Define a) FileInfo b) DirectoryInfo
FileInfo and DirectoryInfo are the classes that support file management operations
Such as
creating,
copying ,
renaming,
deleting a file / Directory.
FileSystemInfo is an abstract class from which FileInfo and DirectoryInfo classes have
been derived.
The methods provided in the classes FileInfo and DirectoryInfo are instance methods.
3. Define thread.
A thread is a path of execution within a program that can be executed separately. In .NET
framework threads run in application domains. A thread is also known as lightweight process.
4. What are the characteristics or advantages of threads?
Threads have execution states and may synchronize with another.
Threads share the same address space.
Context switching between threads is normally inexpensive.
Communication between threads is also inexpensive.
5. What is Multitaking ?
Modern OS hold more than one activity(program) in memory and the processor can
switch among all to execute them. Simultaneous execution of many programs on the computer is
known as multitasking.
6. What is multithreading? (May / June 2012)
C# allows the concept of Multithreading , which enables execution of two or more parts
of a program concurrently. Each part is known as a thread.
The execution of C# program starts with a single thread known as main thread and that is
automatically run by the CLR and the OS. From the main thread, we can create other
threads for performing desired tasks.
The process of execution of multiple threads is known as multithreading.
7. What are the characteristics and advantages of multithreading?
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
98 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
Multithreading allows us to develop efficient programs that could optimize the use of
computer resources such as CPU, memory and I/O devices.
Threading namespace contains classes and interfaces that are required for developing and
running multithreaded programs.
8. Differentiate a process and a thread.
A process is a program in execution.
The creations of processes are controlled by the operating system.
A thread is a unit of execution which is a part of a program. Simultaneously many threads
can be created and they can be started. It is called multi threading.
A thread is under the control of the programmer.
9. What is synchronization? How it is enforced in C#?
We can easily create multiple thread of execution. It is often necessary for multiple
threads to share a resource without control.
The behaviour of multi threaded programs sharing a resource yields non-deterministic
results.
To provide control over multiple threads under execution, C# allocates methods to co-
ordinate activities between threads.
A process which is used to coordinate the activities of two or more threads is called
synchronization.
The need for Syncronization arises when two or more threads try to access shared
resource that can be used only one thread at a time.
Synchronization enables performance benefits of multithreading as well as maintaining
the integrity of the object state and data.
C# uses lock keyword to provide data synchronization.
10. What is critical section?
A method containing code involving shared access/update of data by many threads, is
known as a critical section.
A critical section can be defined in C# using :
Monitor class
Mutex class
Lock statement
Part B
1. Explain in detail about creation of Menus.
2. What is status bar? Write a program to create status bar and explain.
3. Write short notes on the following controls.
(i) Checkbox (ii) Radio button (iii) Group box
4. Explain with suitable example the control Error provider.
5. Write a program for the controls List box and Combo box.
6. What is dialog box? What are the different types of dialog box? Write
the program for creating
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
99 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
dialog boxes.
UNIT – IV
PART - A
1. List out the different types of applications that can be created on .net?
.Net offers closely related but distinguishable suites of tools for building windows or web
applications. Both are based on the premises that many application have user interfaces centered
on interacting with the user through form and controls, such as buttons, list boxes, text, and so
forth
2. What are the advantages in using a dataset?
Dataset is a subset of the entire database catched on your machines without a continuous
connection to the database-disconnected architecture which reduce burden on the database server
which may help your application scale well.
3. Define relational database?
A database is a repository of data. A relational database organizes your data into tables.
Consider the north wind database provided with Microsoft SQL server and Microsoft access.
4. What are the advantages of ADO.NET?
The significant advantage to disconnecting your data architecture from your database.
The biggest advantage is that your application, whether running on the web or on a local
machine, will create a reduced burden on the database server which may help your application to
scale well. A disconnected architecture is resource frugal.
5. What is declarative reference integrity?
Relational database use declarative reference integrity to establish constraints on the
relationship among the various tables.
This helps avoid two types of mistakes.
First, you can’t enter a record with an invalid customer ID
Secondly, you can’t delete a customer record it that customerID is used in any order. The
integrity of your data and its relationship is thus protected.
6. Define Data Adapter?
The dataset is an abstraction of relational data base.ADO.NET uses a data Adapter as a
bridge between the dataset and data source, which is the underlying database.dataAdapter
provides the Fill () method to retrieve data from the database and populate the dataset.
7. Define Data Reader?
The data reader provides connected, forward-only, read-only access to a Collection of
tables. By executing either a SQL statement or stored procedures. Datareader is a lightweight
object.
8. What are the advantages of web applications?
They can be accessed from any browser that can connect to the server.
Update can be made at the server
You can achieve better performance by building a desktop application.
9. What is the step to create windows application?
First open visual studio and file ----->new ----> project.
In project window, create a new c# windows application and name it sharpwindowsform.
10. Differentiate between data reader and dataset?
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
100 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
The actually uses a data reader to populate itself. A data reader is lean, mean access
methods that return results as soon as they are available, rather than for the whole of the query to
be populated into a dataset.
11. How to implement the copy button event.
Now that you can check the files and pick the target directory,you are ready to handle the
copy button-click event.The very first thing you need to do is to get a list of which files were
selected .
12. What is ADO.NET?
ADO.NET looks very similar to ADO,its predecessor.they differences are that
ADO.NET is native to .NET and that it is primarily a disconnected data architecture.data is
retrieved from a database and cached on your local machine.
13. Define normalization.
Normalization not only makes your use of the database more efficient,but also it reduces
the likelihood of data corruption.if you kept the customer’s name in both the customer table and
the order table,you would run the risk that a change in one table might not be reflected in the
order table.by keeping only the customerID in order,you are free to chage the address in
customers,and the change is automatically reflected for each order.
14. Define SQL.
The most popular language for querying and manipulating database is SQL, usually
pronounced ―Sequel‖.SQL is a declarative language,as opposed to a procedural language.the
heart of SQL is query.query is statement that return a set of record from the database.
15. Define ADO.NET object model.
The ADO.NET object model is rich,but at its heart it is a fairly straightforward set of
classes.the most important of these is dataset.the dataset represent a subset of the entire
database,cached on your machine without a continous connection to the database.
16. Define DBCommand.
The DBCommand object allows you to send a command to the database.often these
objects are implicitly create when you create a dataadapter, but you can explicitly access these
object.
17. Define DBConnection.
The DBConnection objects represent a connection to data source. This connection can be
shared among different command object.
18. Define Data tables and data columns.
The data table has a number of public properties, including the columns connection,
which returns the data columns connection object .each data column object represent a column in
a table.
19. Define rows.
Data table’s rows collection returns a set of rows for that table. use this collection to
examine the results of queries against the database, iterating through the rows to examine each
record in turn.
20. What are the advantages of ADO.NET model?
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
101 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
Highly efficient, but to be effective the dataset must be a robust subset of the database,
capturing not just a few rows from a single table, but also a set of tables with all metadata
necessary to represent the relationship and constraints of the original database.
21. Name the techniques used for reading and writing the XML Data. (May / June 2012)
XmlTextReader textReader = new XmlTextReader(―c:\\books.xml‖);
XmlTextWriter textWriter = new XmlTextWriter(―c:\\myxmlfile.xml‖,null);
22. Distinguish between XML and ADO.net. (May / June 2012)
ADO.NET is its ability to convert the data stored in the data source in XML.
In native mode, record tables are stored as XML documents where schema and data
are treated as distinct and replaceable elements.
The ADO native storage format for the recordset is the Advanced Data Table
Gram(ADTG)file format.
PART - B
1. Explain in detail about various methods for handling files and directories.
2. Briefly explain stream Writes and StreamWriters.
3. What is the use of Binary Reader and Binary Writer? Explain with suitable
example program.
4. Explain in detail about the steps to be followed to create the complete data table.
5. What is OLeDbDataReader? How to insert update and delete Records using OleDb
command.
UNIT – V
PART - A
1. What are assemblies?
An assembly is an collection of file that appear to be a single dill or executable(exe)
Assemblies are .NET unit of reuse, versioning, security and deployment.
2. What is the difference between single call and singleton?
With a well-known singleton object, all messages for the object, from all clients, are
dispatched to a single objet running on the server.
With a well-known single-call object, each new message from a client is handling by new
objects.
3. Define metadata?
Assemblies are the .NET unit of reuse, versioning, security, and deployment. In addition
to the objects code for the application, assemblies contain resources.
4. What are PF files?
On disk, assemblies are portable executable files, PF files are not new. The format of
a.NET PE file is exactly the same as a normal windows PE files. PE files are implemented as
DLLS or EXEs.it consists of one or more modules.
5. Define multimodule assemblies
A multimodule assembly consist of multiple files . The assembly manifest in this case
can reside in a standalone file, or it can be embedded in one of the modules.
When the assembly is referred the runtime loads the file containing the manifest and then
loads the required modules as needed.
6. Define shared assemblies
If you want to share your assembly, it must meet certain stringent requirement
Your assembly must have a strong name. strong name are globally unique.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
102 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
To share your assembly place it in the global assembly cach .this is an area of the file
system set aside by the CLR to hold shared assemblies.
7. Define private assemblies
Assemblies come in two flavor:
o Private
o shared
Private assemblies are intended to be used by only one application.
Shared assemblies are intended to be shared among many applications.
8. Define attributes
Attributes are a mechanism for adding metadata, such as compiler instructions and other
data about your data, method, and classes to the program itself.
Attributes are inserted into the metadata and are visible through ILDasam and other
metadata-reading tools.
9. Define reflection
Reflection is the process by which a program can read its own metadata or metadata from
another program.
A program is said to reflect on itself or on another program, extracting metadata from the
reflected assembly and using that metadata either to inform the user or to modify the
program’s behavior
10. Define Marshaling
The process of moving an object to be remoted is called marshaling.
11. What are the uses of server side controls?
.NET want you to use server side controls that can often generate unnecessary trips back
to the server by default.plus .NET also wants to make the determination as to how the control
will act with various browsers.while not impossible,it makes it much more cumbersome to create
custom workarounds for special situation.
12. List out the server side state management option suppoted by asp.net?
Application state
Session state
Profile properties
Database support
13. Define DLL hell?
DLL hell is where loading one program breaks another program. Windows file protection
(WTP) protects system DLLs from being updated or Deleted by unauthorized agents.
14. Define Joining threads?
A thread to stop processing and wait until a second thread complete its work, you are said
to be joining the first thread to the second.
15. Define Starting threads?
The simplest way to create a thread is to create a new instance of the thread class. The
thread constructor takes a single argument.
16. Define Remoting?
When an object is marshaled, either by value or by proxy, across a process or machine
boundary, it is said to be remoted.
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
103 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
17. Define application (app) domain?
App domain can be independently started and halted. They are secure, lightweight and
versatile. An app domain can provide fault tolerance. If you start an object in a second app
domain and it crashes.
18. What are the methods and properties of the app domain class.
CurrentDomain
createDomain()
GetcurrentthreadID()
Unload ()
FriendlyName ()
GetData ()
Load ()
setData()
19. Define Member Filter?
A delegate that filter the list of members in the member info array of object. You use a
type.filtername filter, which is a field of the type class that filter on the name.
20. List out the four task of reflections?
Viewing metadata
Performing type discovery
Late binding to method and properties
Creating types at runtime (reflection emit)
PART – B
1. Explain in detail about Web Service Description Language (WSDL).
2. Explain about the building blocks of an XML webservice.
3. Briefly explain the concept of cookies.
4. Explain in detail about various ASP.NET webform controls
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
104 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
105 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
106 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
107 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
108 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
109 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)
C# and .NET FRAMEWORK IV YEAR/ VII SEM DEPT OF CSE
110 J.SATHISHKUMAR, AP/CSE 2015-2016(ODD SEM)