Overview of .NET Framework Components
Overview of .NET Framework Components
UNITI
The .NET Framework : Introduction, Common Language Runtime, Common Type System,
Common Language Specification, The Base Class Library, The .NET class library
Intermediate language, Justin Time compilation, garbage collection, Application installation
& Assemblies, Web Services, Unified classes.C# Basics -Introduction, DataTypes,
Identifiers, variables & constants, C# statements, Object Oriented Concept, Object and
Classes, Arrays and Strings, System Collections, C# - Regular Expressions.
UNIT II
C# Using Libraries -Namespace-System, Input Output, Multi-Threading, Networking and
Sockets, Data Handling, Windows Forms, C# in Web application, Error Handling.
UNIT III
Advanced Features Using C#: Delegates and Events, Indexes Attributes, versioning, Web
Services, Windows services, messaging, Reflection, COM and C#, localization. Distributed
Application in C#, XML and C#, Unsafe Mode, Case Study (Messenger Application).
UNIT IV
Advanced Programming Constructs: Database Connectivity with ADO.NET Creating
Distributed Web Applications, XML and ADO.NET, Graphics, Printing, data Reports,
crystal Reports,C# libraries for Image Processing, .Net applications to Azure platform
UNIT V
Web Forms Processing, Introduction to Server Controls, HTML Controls, Validation
Controls, User control, Data Binding Controls, Master-detail forms, Configuration,
Personalization, Session State, Database Connectivity with ADO.NET.
LECTURE NOTES
UNIT-1
NET Framework
The main objective of this framework is to develop an application that can run on
the windows platform. The current version of the .Net framework is 4.8.
Note: The .NET Framework is not only a language, but it is also a software and
language neutral platform.
It is an important part of a .NET framework that works like a virtual component of the
.NET Framework to executes the different languages program like c#, Visual Basic,
etc. A CLR also helps to convert a source code into the byte code, and this byte code
is known as CIL (Common Intermediate Language) or MSIL (Microsoft Intermediate
Language). After converting into a byte code, a CLR uses a JIT compiler at run time
that helps to convert a CIL or MSIL code into the machine or native code.
It specifies a standard that represent what type of data and value can be defined and
managed in computer memory at runtime. A CTS ensures that programming data
defined in various languages should beinteract with each other to share information.
For example, in C# we define data type as int, while in VB.NET we define integer as a
data type.
The base class library has a rich collection of libraries features and functions that help
to implement many programming languages in the .NET Framework, such as C #, F #,
Visual C ++, and more. Furthermore, BCL divides into two parts:
A .NET assembly is the main building block of the .NET Framework. It is a small unit
of code that contains a logical compiled code in the Common Language
infrastructure (CLI), which is used for deployment, security and versioning. It defines
in two parts (process) DLL and library (exe) assemblies. When the .NET program is
compiled, it generates a metadata with Microsoft Intermediate Language, which is
stored in a file called Assembly.
It provides the various system functionality in the .NET Framework, that includes
classes, interfaces and data types, etc. to create multiple functions and different types
of application such as desktop, web, mobile application, etc. In other words, it can be
defined as, it provides a base on which various applications, controls and
components are built in .NET Framework.
Two types of instruction sets are included with IL; base instructions,
similar to native CPU instructions, and Object model instructions used by
the high-level language. IL includes all instructions necessary for loading,
storing, initializing, and calling methods on objects. It also includes
arithmetic and logical operations, control flow, direct memory access,
exception handling and other operations. Unlike the common object file
format used for executable content in the traditional Microsoft portable
executable, the portable executable generated, after the compilation of
managed code, contains both IL instructions and metadata.
The two tools associated with IL code are the MSIL Assembler (Ilasm.exe)
and the MSIL Disassemble (Ildasm.exe). The former generates a portable
executable file from IL code and permits viewing the IL code in human-
readable format, while the latter converts a portable executable file back
to a text file, for viewing and modification. Both are automatically
installed as part of Visual Studio.
However, because of the time it takes to load and compile bytecode, there
is a startup delay in the initial execution of an application. To help anticipate
startup times, a good rule of thumb to follow is that the more JIT compilers
are used to optimize a system, the longer the initial startup delay will be.
There are a few ways to decrease initial startup delays, such as separating
startup modes. For example, including both a client and server mode could
allow minimal compilation and optimization when in one mode versus the
other, meaning that the chosen mode will have a faster startup time.
Another way is to combine JIT compilers with either AOT (ahead-of-time)
compilers or interpreters.
JIT compilers combine both principals to get the best of both worlds.
Ahead-of-time, or AOT compilers, compile code into a native machine
language similar to a normal compiler; however, AOT will transform
bytecode of a virtual machine into machine code.
As you can see in the figure, Java, .net, and PHP applications can communicate with
other applications through web service over the network. For example, the Java
application can interact with Java, .Net, and PHP applications. So web service is a
language independent way of communication.
Loosely Coupled
A client of a web service is not fixed to the web service directly. The web service
interface can support innovation over time without negotiating the client's ability to
communicate with the service. A tightly coupled system means that the client and
server logic are closely tied to one another, indicating that if one interface changes,
then another must be updated. Accepting a loosely coupled architecture tends to
make software systems more manageable and allows more straightforward
integration between various systems.
Coarse-Grained
Object-oriented technologies such as Java expose their functions through individual
methods. A specific process is too fine an operation to provide any suitable capability
at a corporate level. Building a Java program from scratch needed the creation of
various fine-grained functions that are then collected into a coarse-grained role that
is consumed by either a client or another service.
Businesses and the interfaces that they prove should be coarse-grained. Web
services technology implement a natural method of defining coarse-grained services
that approach the right amount of business logic.
Asynchronous clients fetch their result at a later point in time, while synchronous
clients receive their effect when the service has completed. Asynchronous capability
is an essential method in enabling loosely coupled systems.
A web function supports RPC by providing services of its own, equivalent to those of
a traditional role, or by translating incoming invocations into an invocation of an EJB
or a .NET component.
Introduction to C#
C# is a general-purpose, modern and object-oriented programming language
pronounced as “C sharp”. It was developed by Microsoft led by Anders Hejlsberg
and his team within the .Net initiative and was approved by the European Computer
Manufacturers Association (ECMA) and International Standards Organization (ISO).
C# is among the languages for Common Language Infrastructure and the current
version of C# is version 7.2. C# is a lot similar to Java syntactically and is easy for the
users who have knowledge of C, C++ or Java.
A bit about .Net Framework
.Net applications are multi-platform applications and framework can be used from
languages like C++, C#, Visual Basic, COBOL etc. It is designed in a manner so that
other languages can use it.
know more about .Net Framework
Why C#?
C# has many other reasons for being popular and in demand. Few of the reasons are
mentioned below:
1. Easy to start: C# is a high-level language so it is closer to other popular
programming languages like C, C++, and Java and thus becomes easy to learn for
anyone.
2. Widely used for developing Desktop and Web Application: C# is widely used
for developing web applications and Desktop applications. It is one of the most
popular languages that is used in professional desktop. If anyone wants to create
Microsoft apps, C# is their first choice.
3. Community:The larger the community the better it is as new tools and software
will be developing to make it better. C# has a large community so the
developments are done to make it exist in the system and not become extinct.
4. Game Development: C# is widely used in game development and will continue to
dominate. C# integrates with Microsoft and thus has a large target audience. The
C# features such as Automatic Garbage Collection, interfaces, object-oriented, etc.
make C# a popular game developing language.
Beginning with C# programming:
Finding a Compiler:
There are various online IDEs such as GeeksforGeeks ide, CodeChef ide etc. which
can be used to run C# programs without installing.
Windows: Since the C# is developed within .Net framework initiative by Microsoft, it
provide various IDEs to run C# programs: Microsoft Visual Studio, Visual Studio
Express, Visual Web Developer
Linux: Mono can be used to run C# programs on Linux.
Programming in C#:
Since the C# is a lot similar to other widely used languages syntactically, it is easier to
code and learn in C#.
Programs can be written in C# in any of the widely used text editors like Notepad++,
gedit, etc. or on any of the compilers. After writing the program save the file with the
extension .cs.
Example: A simple program to print Hello Geeks
// C# program to print Hello Geeks
using System;
namespace HelloGeeksApp
class HelloGeeks
// Main function
Console.WriteLine("Hello Geeks");
Console.ReadKey();
Output:
Hello Geeks
Explanation:
1. Comments: Comments are used for explaining code and are used in similar manner
as in Java or C or C++. Compilers ignore the comment entries and does not execute
them. Comments can be of single line or multiple lines.
Single line Comments:
Syntax:
// Single line comment
Multi line comments:
Syntax:
/* Multi line comments*/
2. using System: using keyword is used to include the System namespace in the
program.
namespace declaration: A namespace is a collection of classes. The HelloGeeksApp
namespace contains the class HelloGeeks.
3. class: The class contains the data and methods to be used in the program. Methods
define the behavior of the class. Class HelloGeeks has only one method Main similar
to JAVA.
4. static void Main(): static keyword tells us that this method is accessible without
instantiating the class. 5. void keywords tells that this method will not return
anything. Main() method is the entry-point of our application. In our program, Main()
method specifies its behavior with the statement Console.WriteLine(“Hello Geeks”); .
6. Console.WriteLine(): WriteLine() is a method of the Console class defined in the
System namespace.
7. Console.ReadKey(): This is for the VS.NET Users. This makes the program wait
for a key press and prevents the screen from running and closing quickly.
Note: C# is case sensitive and all statements and expressions must end with semicolon
(;).
Advantages of C#:
C# is very efficient in managing the system. All the garbage is automatically
collected in C#.
There is no problem of memory leak in C# because of its high memory backup.
Cost of maintenance is less and is safer to run as compared to other languages.
C# code is compiled to a intermediate language (Common (.Net) Intermediate
Language) which is a standard language, independently irrespective of the target
operating system and architecture.
Disadvantages of C#:
C# is less flexible as it depends alot on .Net framework.
C# runs slowly and program needs to be compiled each time when any changes are
made.
Applications:
C# is widely used for developing desktop applications, web applications and web
services.
It is used in creating applications of Microsoft at a large scale.
C# is also used in game development in Unity.
C# Identifiers
In programming languages, identifiers are used for identification purposes. Or in other
words, identifiers are the user-defined name of the program components. In C#, an
identifier can be a class name, method name, variable name, or label.
Example:
The only allowed characters for identifiers are all alphanumeric characters([A-
Z], [a-z], [0-9]), „_„ (underscore). For example “geek@” is not a valid C#
identifier as it contain „@‟ – special character.
Identifiers should not start with digits([0-9]). For example “123geeks” is not valid
in the C# identifier.
Identifiers should not contain white spaces.
Identifiers are not allowed to use as keywords unless they include @ as a prefix.
For example, @as is a valid identifier, but “as” is not because it is a keyword.
C# identifiers allow Unicode Characters.
C# identifiers are case-sensitive.
C# identifiers cannot contain more than 512 characters.
Identifiers do not contain two consecutive underscores in their name because such
types of identifiers are used for the implementation.
Example:
CSharp
// Simple C# program to illustrate identifiers
using System;
class GFG {
// Main Method
// variable
int a = 10;
int b = 39;
int c;
// simple addition
c = a + b;
Output:
Keywords Identifiers
using GFG
public Main
static a
void b
int c
C# Variables
A typical program uses various values that may change during its execution. For
example, a program that performs some operations on the values entered by the user.
The values entered by one user may differ from those entered by another user. Hence
this makes it necessary to use variables as another user may not use the same values.
When a user enters a new value that will be used in the process of operation, can store
temporarily in the Random Access Memory of computer and these values in this part
of memory vary throughout the execution and hence another term for this came which
is known as Variables. So basically, a Variable is a placeholder of the information
which can be changed at runtime. And variables allows to Retrieve and
Manipulate the stored information.
Syntax:
type variable_name = value;
or
type variable_names;
Example:
char var = 'h'; // Declaring and Initializing character variable
int a, b, c; // Declaring variables a, b and c of int type
Characteristics of Variables:
name : It must be a valid identifier. In above example, var is a valid identifier.
type : It defines the types of information which is to be stored into the variable. In
above example char is a type.
value : It is the actual data which is to be stored in the variable. In above example
„h‟ is the value.
Rules for Naming Variables
Variable names can contain the letters „a-z‟ or ‟A-Z‟ or digits 0-9 as well as the
character „_‟.
The name of the variables cannot be started with a digit.
The name of the variable cannot be any C# keyword say int, float, null, String, etc.
Examples:
Valid Variables Names
int age;
float _studentname;
Invalid Variables Names
int if; // "if" is a keyword
using System;
class Geeks {
int y;
// Main Method
// Assigning value 32 to x
int x = 32;
// the variable y
Console.WriteLine("Value of y is "+gfg.y);
Output :
Value of x is 32
Value of y is 0
In this, the user has to enter the value and that value is copied to the required variable.
In this type of initialization, there is one more possibility in which value is assigned to
variable after completion of a function call.
Example:
Input : 45
Output : Value of num is 45
Input : 27
Output : Value of num is 27
using System;
class Geeks {
// Main Method
// num
Output :
Value of num is 45
Note: Here the Console.ReadLine() method asks the user to enter the value and later
on it puts the same value in the “num” variable. Hence the value will be displayed
according to the user input.
C# | Data Types
Data types specify the type of data that a valid C# variable can hold. C# is a strongly
typed programming language because in C#, each type of data (such as integer,
character, float, and so forth) is predefined as part of the programming language and
all constants or variables defined for a given program must be described with one of
the data types.
Data types in C# is mainly divided into three categories
Value Data Types
Reference Data Types
Pointer Data Type
1. Value Data Types : In C#, the Value Data Types will directly store the variable
value in memory and it will also accept both signed and unsigned literals. The
derived class for these data types are System.ValueType. Following are different
Value Data Types in C# programming language :
Signed & Unsigned Integral Types : There are 8 integral types which provide
support for 8-bit, 16-bit, 32-bit, and 64-bit values in signed or unsigned form.
Default
Alias Type Name Type Size(bits) Range Value
-32768 to
short System.Int16 signed integer 16 32767 0
unsigned
byte System.byte integer 8 0 to 255 0
unsigned
ushort System.UInt16 integer 16 0 to 65535 0
unsigned
uint System.UInt32 integer 32 0 to 232 0
unsigned
ulong System.UInt64 integer 64 0 to 263 0
Floating Point Types :There are 2 floating point data types which contain the
decimal point.
Float: It is 32-bit single-precision floating point type. It has 7 digit
Precision. To initialize a float variable, use the suffix f or F. Like,
float x = 3.5F;. If the suffix F or f will not use then it is treated as
double.
Double:It is 64-bit double-precision floating point type. It has 14 –
15 digit Precision. To initialize a double variable, use the suffix d or
D. But it is not mandatory to use suffix because by default floating
data types are the double type.
Alias Type name Size(bits) Range (aprox) Default Value
Decimal Types : The decimal type is a 128-bit data type suitable for financial
and monetary calculations. It has 28-29 digit Precision. To initialize a decimal
variable, use the suffix m or M. Like as, decimal x = 300.5m;. If the suffix m or
M will not use then it is treated as double.
Default
Alias Type name Size(bits) Range (aprox) value
2. Example :
// C# program to demonstrate
using System;
namespace ValueTypeTest {
class GeeksforGeeks {
// Main function
// declaring character
char a = 'G';
int i = 89;
short s = 56;
// short s1 = 87878787878;
long l = 4564;
uint ui = 95;
ushort us = 76;
ulong ul = 3624573;
// is double in C#
double d = 8.358674532;
float f = 3.7330645f;
// for float use 'm' as suffix
3. Output :
4. char: G
5. integer: 89
6. short: 56
7. long: 4564
8. float: 3.733064
9. double: 8.358674532
10. decimal: 389.5
11. Unsinged integer: 95
12. Unsinged short: 76
13. Unsinged long: 3624573
14. Example :
using System;
namespace ValueTypeTest {
class GeeksforGeeks {
// Main function
sbyte a = 126;
// sbyte is 8 bit
// singned value
Console.WriteLine(a);
a++;
Console.WriteLine(a);
// It overflows here because
a++;
Console.WriteLine(a);
// the range
a++;
Console.WriteLine(a);
15. Output :
16. 126
17. 127
18. -128
19. -127
20. Example :
// C# program to demonstrate
using System;
namespace ValueTypeTest {
class GeeksforGeeks {
// Main function
byte a = 0;
// byte is 8 bit
// unsigned value
Console.WriteLine(a);
a++;
Console.WriteLine(a);
a = 254;
// 0 to 255
a++;
Console.WriteLine(a);
a++;
Console.WriteLine(a);
21. Output :
22. 0
23. 1
24. 255
25. 0
Boolean Types : It has to be assigned either true or false value. Values of type
bool are not converted implicitly or explicitly (with casts) to any other type.
But the programmer can easily write conversion code.
Alias Type name Values
Example :
using System;
namespace ValueTypeTest {
class GeeksforGeeks {
// Main function
bool b = true;
if (b == true)
Console.WriteLine("Hi Geek");
Output :
Hi Geek
26. Reference Data Types : The Reference Data Types will contain a memory
address of variable value because the reference types won‟t store the variable value
directly in memory. The built-in reference types are string, object.
String : It represents a sequence of Unicode characters and its type name
is System.String. So, string and String are equivalent.
Example :
string s1 = "hello"; // creating through string keyword
String s2 = "welcome"; // creating through String class
Object : In C#, all types, predefined and user-defined, reference types and
value types, inherit directly or indirectly from Object. So basically it is the base
class for all the data types in C#. Before assigning values, it needs type
conversion. When a variable of a value type is converted to object, it‟s
called boxing. When a variable of type object is converted to a value type, it‟s
called unboxing. Its type name is System.Object.
Example :
// C# program to demonstrate
using System;
namespace ValueTypeTest {
class GeeksforGeeks {
// Main Function
// declaring string
string a = "Geeks";
//append in a
a+="for";
a = a+"Geeks";
Console.WriteLine(a);
// declare object obj
object obj;
obj = 20;
Console.WriteLine(obj);
// using GetType()
Console.WriteLine(obj.GetType());
Output :
GeeksforGeeks
20
System.Int32
27. Pointer Data Type : The Pointer Data Types will contain a memory address of the
variable value.
To get the pointer details we have a two symbols ampersand (&) and asterisk
(*).
ampersand (&): It is Known as Address Operator. It is used to determine the
address of a variable.
asterisk (*): It also known as Indirection Operator. It is used to access the value of
an address.
Syntax :
28. type* identifier;
Example :
int* p1, p; // Valid syntax
int *p1, *p; // Invalid
Example :
// Note: This program will not work on
// online compiler
// unsafe code.
using System;
namespace Pointerprogram {
class GFG {
// Main function
unsafe
// declare variable
int n = 10;
// store variable n address
int* p = &n;
C# | String
In C#, string is a sequence of Unicode characters or array of characters. The range of
Unicode characters will be U+0000 to U+FFFF. The array of characters is also termed
as the text. So the string is the representation of the text. A string is an important
concept and sometimes people get confused whether the string is a keyword or an
object or a class. So let‟s clear out this concept.
A string is represented by class System.String. The “string” keyword is an alias for
System.String class and instead of writing System.String one can use String which is a
shorthand for System.String class. So we can say string and String both can be used as
an alias of System.String class. So string is an object of System.String class.
Example:
string s1 = “GeeksforGeeks”; // creating the string using string keyword
String s2 = “GFG”; // creating the string using String class
System.String s3 = “Pro Geek”; // creating the string using String class
The String class is defined in the .NET base class library. In other words a String
object is a sequential collection of System.Char objects which represents a string. The
maximum size of String object in memory is 2GB or about 1 billion
characters. System.String class is immutable, i.e once created its state cannot be
altered.
Program: To illustrate how to declare the string and initialize the string. Also, below
program show the declaration and initialization of a string in a single line.
C#
using System;
class Geeks {
// Main Method
// "System.String" class
System.String Name;
// initialization of String
Name = "Geek";
// declare a string id using
// using an alias(shorthand)
// "String" of System.String
// class
String id;
// initialization of String
id = "33";
// string keyword
string mrk;
// initialization of String
mrk = "97";
Output:
Name: Geek
Id: 33
Marks: 97
Rank: 1
String Characteristics:
It is a reference type.
It‟s immutable( its state cannot be altered).
It can contain nulls.
It overloads the operator(==).
Differences between String and System.String :
The string is an alias for System.String. Both String and System.String means same
and it will not affect the performance of the application. “string” is keyword in C#. So
the main difference comes in the context, how to use these:
The String is used for the declaration but System.String is used for accessing static
string methods.
The String is used to declare fields, properties etc. that it will use the predefined
type System.String. It is the easy way to use.
The String has to use the System.String class methods, such as String.SubString,
String.IndexOf etc. The string is only an alias of System.String.
Note: In .NET, the text is stored as a sequential collection of the Char objects so there
is no null-terminating character at the end of a C# string. Therefore a C# string can
contain any number of embedded null characters („\0‟).
String arrays: We can also create the array of string and assigns values to it. The
string arrays can be created as follows:
Syntax:
String [] array_variable = new String[Length_of_array]
Example: To illustrate the creation of string arrays and assigning values to it
C#
using System;
class Geeks {
// Main Method
str_arr[0] = "Geeks";
str_arr[1] = "For";
str_arr[2] = "Geeks";
Output:
value at Index position 0 is Geeks
value at Index position 1 is For
value at Index position 2 is Geeks
Reading String from User-Input: A string can be read out from the user input.
ReadLine() method of console class is used to read a string from user input.
Example:
C#
using System;
class Geeks {
// Main Method
// ReadLine() method
Input:
Hello Geeks !
Output:
Enter the String
User Entered: Hello Geeks !
Different Ways for Creating a String:
Create a string from a literal
Create a string using concatenation
Create a string using a constructor
Create a string using a property or a method
Create a string using formatting
Create a string from a literal: It is the most common way to create a string. In this, a
user has to define string variable and then assign the value within the double quotes.
We can use any type of characters within double quotes except some special character
like a backslash (\).
using System;
class Geeks {
// Main Method
Console.WriteLine(str1);
// Console.WriteLine(str3);
Console.WriteLine(str2);
}
Output:
GeeksforGeeks
X:\Home\GFG\program.cs
using System;
class Geeks {
// Main Method
string s1 = "Geek";
string s2 = "s";
string s3 = "For";
string s4 = "Geek";
Console.WriteLine(str);
Output:
GeeksForGeeks
Create a string using Constructor: The String class has been several overloaded
constructors which take an array of characters or bytes. Some of the constructors
include pointers to character arrays or signed byte arrays as parameters.
Program: To illustrates Creation of a string using the constructor
C#
using System;
class Geeks {
// Main Method
Console.WriteLine(str1);
Console.WriteLine(str2);
unsafe
// to a character array.
Output:
GEEKS
GGGGGGGGGG
using System;
class Geeks {
// Main Method
Output:
For
Create a string using Format: The “Format” method is used to convert the value or
object to its string representation. The String.Format method returns a string.
Program: To illustrate the creation of string using Format method
C#
using System;
class Geeks {
// Main Method
int no = 10;
Console.WriteLine(str);
Output:
10 BMW Cars color are Red
String Class Properties: The String class has two properties as follows:
1. Chars: It is used to get the Char object at a specified position in the current String
object.
2. Length: It is used to get the number of characters in the current String object. To
know more about the string class properties please go toString Properties in
SHORT QUESTIONS
LONG QUESTIONS
System Namespace
Classes
AccessViolationException The exception that is thrown when there is an attempt to read or write
protected memory.
Activator Contains methods to create types of objects locally or remotely, or
obtain references to existing remote objects. This class cannot be
inherited.
AggregateException Represents one or more errors that occur during application execution.
AppContext Provides members for setting and retrieving data about an
application's context.
AppDomain Represents an application domain, which is an isolated environment
where applications execute. This class cannot be inherited.
AppDomainSetup Represents assembly binding information that can be added to an
instance of AppDomain.
AppDomainUnloadedException The exception that is thrown when an attempt is made to access an
unloaded application domain.
ApplicationException Serves as the base class for application-defined exceptions.
ApplicationId Contains information used to uniquely identify a manifest-based
application. This class cannot be inherited.
ArgumentException The exception that is thrown when one of the arguments provided to a
method is not valid.
ArgumentNullException The exception that is thrown when a null reference (Nothing in Visual
Basic) is passed to a method that does not accept it as a valid
argument.
ArgumentOutOfRangeException The exception that is thrown when the value of an argument is outside
the allowable range of values as defined by the invoked method.
ArithmeticException The exception that is thrown for errors in an arithmetic, casting, or
conversion operation.
Array Provides methods for creating, manipulating, searching, and sorting
arrays, thereby serving as the base class for all arrays in the common
language runtime.
ArrayTypeMismatchException The exception that is thrown when an attempt is made to store an
element of the wrong type within an array.
AssemblyLoadEventArgs Provides data for the AssemblyLoad event.
Attribute Represents the base class for custom attributes.
AttributeUsageAttribute Specifies the usage of another attribute class. This class cannot be
inherited.
BadImageFormatException The exception that is thrown when the file image of a dynamic link
library (DLL) or an executable program is invalid.
BitConverter Converts base data types to an array of bytes, and an array of bytes to
base data types.
Buffer Manipulates arrays of primitive types.
CannotUnloadAppDomainException The exception that is thrown when an attempt to unload an application
domain fails.
CharEnumerator Supports iterating over a String object and reading its individual
characters. This class cannot be inherited.
CLSCompliantAttribute Indicates whether a program element is compliant with the Common
Language Specification (CLS). This class cannot be inherited.
Console Represents the standard input, output, and error streams for console
applications. This class cannot be inherited.
ConsoleCancelEventArgs Provides data for the CancelKeyPress event. This class cannot be
inherited.
ContextBoundObject Defines the base class for all context-bound classes.
ContextMarshalException The exception that is thrown when an attempt to marshal an object
across a context boundary fails.
ContextStaticAttribute Indicates that the value of a static field is unique for a particular
context.
Convert Converts a base data type to another base data type.
DataMisalignedException The exception that is thrown when a unit of data is read from or
written to an address that is not a multiple of the data size. This class
cannot be inherited.
DBNull Represents a nonexistent value. This class cannot be inherited.
Delegate Represents a delegate, which is a data structure that refers to a static
method or to a class instance and an instance method of that class.
DivideByZeroException The exception that is thrown when there is an attempt to divide an
integral or Decimal value by zero.
DllNotFoundException The exception that is thrown when a DLL specified in a DLL import
cannot be found.
DuplicateWaitObjectException The exception that is thrown when an object appears more than once
in an array of synchronization objects.
EntryPointNotFoundException The exception that is thrown when an attempt to load a class fails due
to the absence of an entry method.
Enum Provides the base class for enumerations.
Environment Provides information about, and means to manipulate, the current
environment and platform. This class cannot be inherited.
EventArgs Represents the base class for classes that contain event data, and
provides a value to use for events that do not include event data.
Exception Represents errors that occur during application execution.
ExecutionEngineException The exception that is thrown when there is an internal error in the
execution engine of the common language runtime. This class cannot
be inherited.
FieldAccessException The exception that is thrown when there is an invalid attempt to access
a private or protected field inside a class.
FileStyleUriParser A customizable parser based on the File scheme.
FlagsAttribute Indicates that an enumeration can be treated as a bit field; that is, a set
of flags.
FormatException The exception that is thrown when the format of an argument is
invalid, or when a composite format string is not well formed.
FormattableString Represents a composite format string, along with the arguments to be
formatted.
FtpStyleUriParser A customizable parser based on the File Transfer Protocol (FTP)
scheme.
GC Controls the system garbage collector, a service that automatically
reclaims unused memory.
GenericUriParser A customizable parser for a hierarchical URI.
GopherStyleUriParser A customizable parser based on the Gopher scheme.
HttpStyleUriParser A customizable parser based on the HTTP scheme.
IndexOutOfRangeException The exception that is thrown when an attempt is made to access an
element of an array or collection with an index that is outside its
bounds.
InsufficientExecutionStackException The exception that is thrown when there is insufficient execution stack
available to allow most methods to execute.
InsufficientMemoryException The exception that is thrown when a check for sufficient available
memory fails. This class cannot be inherited.
InvalidCastException The exception that is thrown for invalid casting or explicit conversion.
InvalidOperationException The exception that is thrown when a method call is invalid for the
object's current state.
InvalidProgramException The exception that is thrown when a program contains invalid
Microsoft intermediate language (MSIL) or metadata. Generally this
indicates a bug in the compiler that generated the program. This
exception is also thrown when internal runtime implementation limits
have been exceeded by the program.
InvalidTimeZoneException The exception that is thrown when time zone information is invalid.
Lazy<T> Provides support for lazy initialization.
Lazy<T,TMetadata> Provides a lazy indirect reference to an object and its associated
metadata for use by the Managed Extensibility Framework.
LdapStyleUriParser A customizable parser based on the Lightweight Directory Access
Protocol (LDAP) scheme.
LoaderOptimizationAttribute Used to set the default loader optimization policy for the main method
of an executable application.
LocalDataStoreSlot Encapsulates a memory slot to store local data. This class cannot be
inherited.
MarshalByRefObject Enables access to objects across application domain boundaries in
applications that support remoting.
Math Provides constants and static methods for trigonometric, logarithmic,
and other common mathematical functions.
MathF Provides constants and static methods for trigonometric, logarithmic,
and other common mathematical functions.
MemberAccessException The exception that is thrown when an attempt to access a class
member fails.
MemoryExtensions Provides extension methods for the memory- and span-related types,
such as Memory<T>, ReadOnlyMemory<T>, Span<T>,
and ReadOnlySpan<T>.
MethodAccessException The exception that is thrown when there is an invalid attempt to access
a method, such as accessing a private method from partially trusted
code.
MissingFieldException The exception that is thrown when there is an attempt to dynamically
access a field that does not exist. If a field in a class library has been
removed or renamed, recompile any assemblies that reference that
library.
MissingMemberException The exception that is thrown when there is an attempt to dynamically
access a class member that does not exist or that is not declared as
public. If a member in a class library has been removed or renamed,
recompile any assemblies that reference that library.
MissingMethodException The exception that is thrown when there is an attempt to dynamically
access a method that does not exist.
MTAThreadAttribute Indicates that the COM threading model for an application is
multithreaded apartment (MTA).
MulticastDelegate Represents a multicast delegate; that is, a delegate that can have more
than one element in its invocation list.
MulticastNotSupportedException The exception that is thrown when there is an attempt to combine two
delegates based on the Delegate type instead of
the MulticastDelegate type. This class cannot be inherited.
NetPipeStyleUriParser A parser based on the NetPipe scheme for the "Indigo" system.
NetTcpStyleUriParser A parser based on the NetTcp scheme for the "Indigo" system.
NewsStyleUriParser A customizable parser based on the news scheme using the Network
News Transfer Protocol (NNTP).
NonSerializedAttribute Indicates that a field of a serializable class should not be serialized.
This class cannot be inherited.
NotFiniteNumberException The exception that is thrown when a floating-point value is positive
infinity, negative infinity, or Not-a-Number (NaN).
NotImplementedException The exception that is thrown when a requested method or operation is
not implemented.
NotSupportedException The exception that is thrown when an invoked method is not
supported, or when there is an attempt to read, seek, or write to a
stream that does not support the invoked functionality.
Nullable Supports a value type that can be assigned null. This class cannot be
inherited.
NullReferenceException The exception that is thrown when there is an attempt to dereference a
null object reference.
Object Supports all classes in the .NET class hierarchy and provides low-
level services to derived classes. This is the ultimate base class of all
.NET classes; it is the root of the type hierarchy.
ObjectDisposedException The exception that is thrown when an operation is performed on a
disposed object.
ObsoleteAttribute Marks the program elements that are no longer in use. This class
cannot be inherited.
OperatingSystem Represents information about an operating system, such as the version
and platform identifier. This class cannot be inherited.
OperationCanceledException The exception that is thrown in a thread upon cancellation of an
operation that the thread was executing.
OutOfMemoryException The exception that is thrown when there is not enough memory to
continue the execution of a program.
OverflowException The exception that is thrown when an arithmetic, casting, or
conversion operation in a checked context results in an overflow.
ParamArrayAttribute Indicates that a method will allow a variable number of arguments in
its invocation. This class cannot be inherited.
PlatformNotSupportedException The exception that is thrown when a feature does not run on a
particular platform.
Progress<T> Provides an IProgress<T> that invokes callbacks for each reported
progress value.
Random Represents a pseudo-random number generator, which is an algorithm
that produces a sequence of numbers that meet certain statistical
requirements for randomness.
RankException The exception that is thrown when an array with the wrong number of
dimensions is passed to a method.
ResolveEventArgs Provides data for loader resolution events, such as
the TypeResolve, ResourceResolve, ReflectionOnlyAssemblyResolve,
and AssemblyResolve events.
SerializableAttribute Indicates that a class can be serialized using binary or XML
serialization. This class cannot be inherited.
StackOverflowException The exception that is thrown when the execution stack exceeds the
stack size. This class cannot be inherited.
STAThreadAttribute Indicates that the COM threading model for an application is single-
threaded apartment (STA).
String Represents text as a sequence of UTF-16 code units.
StringComparer Represents a string comparison operation that uses specific case and
culture-based or ordinal comparison rules.
StringNormalizationExtensions Provides extension methods to work with string normalization.
SystemException Serves as the base class for system exceptions namespace.
ThreadStaticAttribute Indicates that the value of a static field is unique for each thread.
TimeoutException The exception that is thrown when the time allotted for a process or
operation has expired.
TimeZone Represents a time zone.
TimeZoneInfo Represents any time zone in the world.
TimeZoneInfo.AdjustmentRule Provides information about a time zone adjustment, such as the
transition to and from daylight saving time.
TimeZoneNotFoundException The exception that is thrown when a time zone cannot be found.
Tuple Provides static methods for creating tuple objects.
Tuple<T1> Represents a 1-tuple, or singleton.
Tuple<T1,T2> Represents a 2-tuple, or pair.
Tuple<T1,T2,T3> Represents a 3-tuple, or triple.
Tuple<T1,T2,T3,T4> Represents a 4-tuple, or quadruple.
Tuple<T1,T2,T3,T4,T5> Represents a 5-tuple, or quintuple.
Tuple<T1,T2,T3,T4,T5,T6> Represents a 6-tuple, or sextuple.
Tuple<T1,T2,T3,T4,T5,T6,T7> Represents a 7-tuple, or septuple.
Tuple<T1,T2,T3,T4,T5,T6,T7,TRest> Represents an n-tuple, where n is 8 or greater.
TupleExtensions Provides extension methods for tuples to interoperate with language
support for tuples in C#.
Type Represents type declarations: class types, interface types, array types,
value types, enumeration types, type parameters, generic type
definitions, and open or closed constructed generic types.
TypeAccessException The exception that is thrown when a method attempts to use a type
that it does not have access to.
TypeInitializationException The exception that is thrown as a wrapper around the exception
thrown by the class initializer. This class cannot be inherited.
TypeLoadException The exception that is thrown when type-loading failures occur.
TypeUnloadedException The exception that is thrown when there is an attempt to access an
unloaded class.
UnauthorizedAccessException The exception that is thrown when the operating system denies access
because of an I/O error or a specific type of security error.
UnhandledExceptionEventArgs Provides data for the event that is raised when there is an exception
that is not handled in any application domain.
Uri Provides an object representation of a uniform resource identifier
(URI) and easy access to the parts of the URI.
UriBuilder Provides a custom constructor for uniform resource identifiers (URIs)
and modifies URIs for the Uri class.
UriFormatException The exception that is thrown when an invalid Uniform Resource
Identifier (URI) is detected.
UriParser Parses a new URI scheme. This is an abstract class.
UriTypeConverter Converts a String type to a Uri type, and vice versa.
ValueType Provides the base class for value types.
Version Represents the version number of an assembly, operating system, or
the common language runtime. This class cannot be inherited.
WeakReference Represents a weak reference, which references an object while still
allowing that object to be reclaimed by garbage collection.
WeakReference<T> Represents a typed weak reference, which references an object while
still allowing that object to be reclaimed by garbage collection.
Structs
ArgIterator Represents a variable-length argument
list; that is, the parameters of a function
that takes a variable number of arguments.
ArraySegment<T>.Enumerator Provides an enumerator for the elements
of an ArraySegment<T>.
ArraySegment<T> Delimits a section of a one-dimensional
array.
Boolean Represents a Boolean (true or false)
value.
Byte Represents an 8-bit unsigned integer.
Char Represents a character as a UTF-16 code
unit.
ConsoleKeyInfo Describes the console key that was
pressed, including the character
represented by the console key and the
state of the SHIFT, ALT, and CTRL
modifier keys.
DateOnly Represents dates with values ranging from
January 1, 0001 Anno Domini (Common
Era) through December 31, 9999 A.D.
(C.E.) in the Gregorian calendar.
DateTime Represents an instant in time, typically
expressed as a date and time of day.
DateTimeOffset Represents a point in time, typically
expressed as a date and time of day,
relative to Coordinated Universal Time
(UTC).
Decimal Represents a decimal floating-point
number.
Double Represents a double-precision floating-
point number.
GCGenerationInfo Represents the size and the fragmenation
of a generation on entry and on exit of the
GC reported in GCMemoryInfo.
GCMemoryInfo Provides a set of APIs that can be used to
retrieve garbage collection information.
Guid Represents a globally unique identifier
(GUID).
Half Represents a half-precision floating-point
number.
HashCode Combines the hash code for multiple
values into a single hash code.
Index Represents a type that can be used to
index a collection either from the
beginning or the end.
Int128 Represents a 128-bit signed integer.
Int16 Represents a 16-bit signed integer.
Int32 Represents a 32-bit signed integer.
Int64 Represents a 64-bit signed integer.
IntPtr Represents a signed integer where the bit-
width is the same as a pointer.
Memory<T> Represents a contiguous region of
memory.
MemoryExtensions.TryWriteInterpolatedStringHandler Provides a handler used by the language
compiler to format interpolated strings
into character spans.
ModuleHandle Represents a runtime handle for a module.
Nullable<T> Represents a value type that can be
assigned null.
Range Represents a range that has start and end
indexes.
ReadOnlyMemory<T> Represents a contiguous region of
memory, similar to ReadOnlySpan<T>.
Unlike ReadOnlySpan<T>, it is not a
byref-like type.
ReadOnlySpan<T>.Enumerator Provides an enumerator for the elements
of a ReadOnlySpan<T>.
ReadOnlySpan<T> Provides a type-safe and memory-safe
read-only representation of a contiguous
region of arbitrary memory.
RuntimeArgumentHandle References a variable-length argument
list.
RuntimeFieldHandle Represents a field using an internal
metadata token.
RuntimeMethodHandle RuntimeMethodHandle is a handle to the
internal metadata representation of a
method.
RuntimeTypeHandle Represents a type using an internal
metadata token.
SByte Represents an 8-bit signed integer.
SequencePosition Represents a position in a non-contiguous
set of memory. Properties of this type
should not be interpreted by anything but
the type that created it.
Single Represents a single-precision floating-
point number.
Span<T>.Enumerator Provides an enumerator for the elements
of a Span<T>.
Span<T> Provides a type-safe and memory-safe
representation of a contiguous region of
arbitrary memory.
TimeOnly Represents a time of day, as would be
read from a clock, within the range
00:00:00 to 23:59:59.9999999.
TimeSpan Represents a time interval.
TimeZoneInfo.TransitionTime Provides information about a specific time
change, such as the change from daylight
saving time to standard time or vice versa,
in a particular time zone.
TypedReference Describes objects that contain both a
managed pointer to a location and a
runtime representation of the type that
may be stored at that location.
UInt128 Represents a 128-bit unsigned integer.
UInt16 Represents a 16-bit unsigned integer.
UInt32 Represents a 32-bit unsigned integer.
UInt64 Represents a 64-bit unsigned integer.
UIntPtr Represents an unsigned integer where the
bit-width is the same as a pointer.
UriCreationOptions Provides options that control how a Uri is
created and behaves.
ValueTuple Provides static methods for creating value
tuples.
ValueTuple<T1> Represents a value tuple with a single
component.
ValueTuple<T1,T2> Represents a value tuple with 2
components.
ValueTuple<T1,T2,T3> Represents a value tuple with 3
components.
ValueTuple<T1,T2,T3,T4> Represents a value tuple with 4
components.
ValueTuple<T1,T2,T3,T4,T5> Represents a value tuple with 5
components.
ValueTuple<T1,T2,T3,T4,T5,T6> Represents a value tuple with 6
components.
ValueTuple<T1,T2,T3,T4,T5,T6,T7> Represents a value tuple with 7
components.
ValueTuple<T1,T2,T3,T4,T5,T6,T7,TRest> Represents an n-value tuple, where n is 8
or greater.
Void Specifies a return value type for a method
that does not return a value.
Multithreading in C#
Multithreading is a specialized form of multitasking and a multitasking is the feature
that allows your computer to run two or more programs concurrently. In general,
there are two types of multitasking: process-based and thread-based.
Process-based multitasking handles the concurrent execution of programs. Thread-
based multitasking deals with the concurrent execution of pieces of the same
program.
A multithreaded program contains two or more parts that can run concurrently. Each
part of such a program is called a thread, and each thread defines a separate path
of execution.
C does not contain any built-in support for multithreaded applications. Instead, it
relies entirely upon the operating system to provide this feature.
This tutorial assumes that you are working on Linux OS and we are going to write
multi-threaded C program using POSIX. POSIX Threads, or Pthreads provides API
which are available on many Unix-like POSIX systems such as FreeBSD, NetBSD,
GNU/Linux, Mac OS X and Solaris.
The following routine is used to create a POSIX thread −
#include <pthread.h>
pthread_create (thread, attr, start_routine, arg)
Here, pthread_create creates a new thread and makes it executable. This routine
can be called any number of times from anywhere within your code. Here is the
description of the parameters.
Parameter Description
thread An opaque, unique identifier for the new thread returned by the subroutine.
attr An opaque attribute object that may be used to set thread attributes. You can specify a
thread attributes object, or NULL for the default values.
Parameter Description
start_routine The C routine that the thread will execute once it is created.
arg A single argument that may be passed to start_routine. It must be passed by reference
as a pointer cast of type void. NULL may be used if no argument is to be passed.
Terminating Threads
There is following routine which we use to terminate a POSIX thread –
#include <pthread.h>
pthread_exit (status)
Here pthread_exit is used to explicitly exit a thread. Typically, the pthread_exit()
routine is called after a thread has completed its work and is no longer required to
exist.
If main() finishes before the threads it has created, and exits with pthread_exit(), the
other threads will continue to execute. Otherwise, they will be automatically
terminated when main() finishes.
Example Code
#include <iostream>
#include <cstdlib>
#include <pthread.h>
using namespace std;
#define NUM_THREADS 5
void *PrintHello(void *threadid) {
long tid;
tid = (long)threadid;
printf("Hello World! Thread ID, %d
", tid);
pthread_exit(NULL);
}
int main () {
pthread_t threads[NUM_THREADS];
int rc;
int i;
for( i = 0; i < NUM_THREADS; i++ ) {
cout << "main() : creating thread, " << i << endl;
rc = pthread_create(&threads[i], NULL, PrintHello, (void *)i);
if (rc) {
printf("Error:unable to create thread, %d
", rc);
exit(-1);
}
}
pthread_exit(NULL);
}
Output
$gcc test.cpp -lpthread
$./a.out
main() : creating thread, 0
main() : creating thread, 1
main() : creating thread, 2
main() : creating thread, 3
main() : creating thread, 4
Hello World! Thread ID, 0
Hello World! Thread ID, 1
Hello World! Thread ID, 2
Hello World! Thread ID, 3
Hello World! Thread ID, 4
Socket Programming in C#
Socket programming is a way of connecting two nodes on a network to communicate
with each other. Basically, it is a one-way Client and Server setup where a Client
connects, sends messages to the server and the server shows them using socket
connection. One socket (node) listens on a particular port at an IP, while other socket
reaches out to the other to form a connection. Server forms the listener socket while
the client reaches out to the server. Before going deeper into Server and Client code, it
is strongly recommended to go through TCP/IP Model.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace Client {
class Program {
// Main Method
ExecuteClient();
}
// ExecuteClient() Method
try {
// computer.
SocketType.Stream, ProtocolType.Tcp);
try {
// Connect Socket to the remote
sender.Connect(localEndPoint);
sender.RemoteEndPoint.ToString());
// Data buffer
Encoding.ASCII.GetString(messageReceived,
0, byteRecv));
sender.Shutdown(SocketShutdown.Both);
sender.Close();
Console.WriteLine("ArgumentNullException : {0}",
ane.ToString());
catch (Exception e) {
catch (Exception e) {
Console.WriteLine(e.ToString());
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace Server {
class Program {
// Main Method
ExecuteServer();
SocketType.Stream, ProtocolType.Tcp);
try {
// Address
listener.Bind(localEndPoint);
// to connect to Server
listener.Listen(10);
while (true) {
// Data buffer
while (true) {
data += Encoding.ASCII.GetString(bytes,
0, numByte);
break;
clientSocket.Send(message);
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
}
catch (Exception e) {
Console.WriteLine(e.ToString());
Pictographs
Now, draw the pictures according to information presented, for example, there will
be 3 smilies for Rahul as he completed 3 books in an hour
The graphical representation of any quantity, number or data in the form of bars is
called a bar graph. With the help of Bar Graph, not only the data look neat and
understanding but also it is easier to compare the data given.
Types of Bar Graph
Vertical Bar Graph
Horizontal Bar Graph
Vertical Bar Graph
These are the most common bar graph we come across, the bars of grouped data in
vertical bar graphs lie vertically. Sometimes when the data categorized have long
names, then Horizontal bar graphs are preferred since, in vertical bar graphs, there is
not much space on the x-axis.
Question: There are 800 students in a school and the table for their birthdays in
all 12 months is given below, Draw the Vertical Bar graph and answer,
1. Maximum number of students have their birthdays in which month?
2. Which two months have equal number of birthday?
3. The minimum number of birthdays occur in which month?
Solution:
The vertical bar graph for the table given in the question will be,
From the Bar graph we can figure out the answer of the questions
1. August is that month in which maximum birthdays are happening, since the bar
above august is the longest(there are 110 students whose birthday come in August)
2. From the graph, we can tell that January and April have equal lengths of bars,
That means they have the same number of birthdays (both have 50 birthdays)
3. The minimum number of birthdays occur in December since it has the smallest
bar.(20 students have their birthdays in December.
Horizontal Bar Graph
The graphs that have their rectangular bars lying horizontally, which means that the
frequency of the data lie on the x-axis while the categories of the data lie on the y-axis
are known as Horizontal bar graphs.
Horizontal bar graphs are preferred when the name of the categories of data are long
and the minimum space on the x-axis is not sufficie
SHORT QUESTIONS
LONG QUESTIONS
UNIT-3
For example, consider sorting a list of stars in an astronomy application. You may
choose to sort those stars by their distance from the earth, or the magnitude of the
star, or their perceived brightness.
In all those cases, the Sort() method does essentially the same thing: arranges the
items in the list based on some comparison. The code that compares two stars is
different for each of the sort orderings.
These kinds of solutions have been used in software for half a century. The C#
language delegate concept provides first class language support, and type safety
around the concept.
As you'll see later in this series, the C# code you write for algorithms like this is type
safe. The compiler ensures that the types match for arguments and return types.
Function pointers were added to C# 9 for similar scenarios, where you need more
control over the calling convention. The code associated with a delegate is invoked
using a virtual method added to a delegate type. Using function pointers, you can
specify different conventions.
The team wanted a common language construct that could be used for any late
binding algorithms. Delegates enable developers to learn one concept, and use that
same concept across many different software problems.
Second, the team wanted to support both single and multicast method calls.
(Multicast delegates are delegates that chain together multiple method calls. You'll
see examples later in this series.)
The team wanted delegates to support the same type safety that developers expect
from all C# constructs.
Finally, the team recognized an event pattern is one specific pattern where delegates,
or any late binding algorithm, is useful. The team wanted to ensure the code for
delegates could provide the basis for the .NET event pattern.
The result of all that work was the delegate and event support in C# and .NET.
The remaining articles in this series will cover language features, library support, and
common idioms used when you work with delegates and events. You'll learn about:
For situations of this sort (& many other), we have techniques like Web Services.
With Web Services, you can reuse someone else's business logic instead of
replicating it yourself, using just a few lines of code. This technique is similar to what
programmers currently do with libraries of APIs, DLLs or plug-ins. The main
difference is that Web Services can be located remotely on another server.
When HTML pages (or the HTML output generated by ASP.NET web forms) are
rendered in a browser for the end user, Web Services are invoked by other
applications. They are pieces of business logic that are hosted somewhere on the
internet and can be accessed by other applications.
Note 1: Web Services are not limited to the .NET Framework. The standards were
defined before .NET was released and they are exposed, used and supported by
vendors other than Microsoft.
Note 2: Web Services are cross-platform; a service written in one language can be
invoked by an application in some other language. The only requirement for
accessing a service is an internet connection to make the HTTP request.
As a result, the set of data types Web Services can use is limited to the set of data
types recognized by the XML Schema standard. So you can use simple data types
such as strings and numbers to communicate with a web service and you can't send
proprietary .NET objects such as a FileStream, an Image or an EventLog. This
restriction makes a lot of sense. Since other programming languages have no way to
interpret these .NET objects, even if you could devise a way to send them over the
wire, the client might not be able to interpret them, that would thwart interoperability.
Note 3: If you need to work with .NET proprietary objects, you can go for .NET
remoting. It is a distributed technology that allows use of .NET objects. But non-.NET
clients can't consume it.
Here's the list of supported data types
Built-in types (The Basics): The built in C# data types such as short, int, long, ushort,
uint, ulong, float, double, decimal, bool, string, char, byte and DateTime.
Objects: You can use an object of any user defined class. If your class has methods,
these methods will not be transmitted to the client.
Arrays: Arrays of any supported type (built-in or custom objects). You can also use an
ArrayList (that is simply converted into an array).
Enumerations: Enums are supported. However, a web service uses the string name
of the enumeration value, not the underlying integer.
XmlNode: Objects based on System.Xml.XmlNode represent a portion of an XML
document. You can use this to send arbitrary XML.
DataSet and DataTable : DataSet and DataTable are allowed. But other ADO.NET
data objects, such as DataColumns and DataRows, aren't supported.
Create a web service
A web service is a simple asmx page.
Here I will use Visual Studio 2012 (though you can use any editor), with the .Net
Framework 3.5 to create a web service.
Up to framework 3.5, Visual Studio provides a direct template for Web Services.
Starting from 4, it doesn't provide any direct template, so you need to create a web
application and add a web service to your application (right-click on your web
application → Add → New Item → WebService).
Open Visual Studio in Administrator mode. File → New → Project then select .Net
Framework 3.5 (on the top) then select ASP.NET web service application then name
your project (I named it MyWebServiceDemo) then click OK.
Visual Studio will create a web service boilerplate (Service1.asmx and
Service1.asmx.cs) for you. Now, let's analyze this template created by Visual Studio.
6. The Service1 class has a method HelloWorld that is decorated with a ―[WebMethod]‖
attribute. The methods of the service that are to be accessed by the client application
should be decorated with this attribute. There may be some method that the service is
using for some internal functionality, client applications don't need to access them.
Don't decorate such methods with a WebMethod attribute. The WebMethod attribute
also has Name and Description properties that you can use to provide a self describing
name or description respectively.
Now let's see the mark up. Right-click on Service1.asmx in Solution Explorer then
select view mark up. In Service1.asmx, you will see that there is only a WebService
directive with some attributes, since a service will be invoked by some application
not by any end user. So the asmx page has no mark up.
<%@ WebService Language="C#" CodeBehind="Service1.asmx.cs"
Class="MyWebServiceDemo.Service1"%>
ASP.NET (C#)
Copy
As you can see here Visual Studio is unable to resolve ―Service1‖ in the class
property, since the class indicates a fully qualified name of the service and we
renamed our Service1 class to MyService. So Visual Studio is unable to resolve it.
So, now change the class property to ―MyWebServiceDemo.MyService‖. Change
the ―CodeBehind‖ property from ―Service1.asmx.cs‖ to ―MyService.asmx.cs‖ as we
renamed the file also.
MyService.asmx
<%@ WebService Language="C#" CodeBehind="MyService.asmx.cs"
Class="MyWebServiceDemo.MyService"%>
ASP.NET (C#)
Copy
MyService.asmx.cs
using System.Web.Script.Serialization;
using System.Web.Services;
namespace MyWebServiceDemo
{
// Use "Namespace" attribute with an unique name,to make service
uniquely discoverable
[WebService(Namespace = "http://tempuri.org/")]
// To indicate service confirms to "WsiProfiles.BasicProfile1_1"
standard,
// if not, it will throw compile time error.
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To restrict this service from getting added as a custom tool
to toolbox
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using
ASP.NET AJAX
[System.Web.Script.Services.ScriptService]
public class MyService : WebService
{
[WebMethod]
public int SumOfNums(int First, int Second)
{
return First + Second;
}
}
}
C#
Copy
Now, the service is ready to be used, let's compile and test it.
Let's use method overloading of the OOP concept. Add the following WebMethod in
MyService class.
[WebMethod]
public float SumOfNums(float First, float Second)
{
return First + Second;
}
C#
Copy
Hit F5 to run the application, you will get ―Both Single SumOfNums(Single, Single)
and Int32 SumOfNums(Int32, Int32) use the message name 'SumOfNums'. Use the
MessageName property of the WebMethod custom attribute to specify unique
message names for the methods.‖ error message. We just used method overloading
concept, so why this error message? This is because these methods are not unique
for a client application. As the error message suggests let's use the MessageName
property of the WebMethod attribute as shown below:
Copy
Now, compile and run the application. Again it's showing some different error
message ―Service 'MyWebServiceDemo.MyService' does not conform to WS-I Basic
Profile v1.1‖. As, WsiProfiles.BasicProfile1_1 doesn't support method overloading
we are getting this exception. Now, either remove this
―[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]‖ attribute or
make it ―[WebServiceBinding(ConformsTo = WsiProfiles.None)]‖.
using System.Web.Script.Serialization;
using System.Web.Services;
namespace MyWebServiceDemo
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.None)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class MyService : WebService
{
[WebMethod]
public int SumOfNums(int First, int Second)
{
return First + Second;
}
[WebMethod(MessageName = "SumOfFloats")]
public float SumOfNums(float First, float Second)
{
return First + Second;
}
}
}
C#
Copy
MyService.asmx.cs
using System.Web.Script.Serialization;
using System.Web.Services;
namespace MyWebServiceDemo
{
// Use "Namespace" attribute with an unique name,to make service
uniquely discoverable
[WebService(Namespace = "http://tempuri.org/")]
// To indicate service confirms to "WsiProfiles.BasicProfile1_1"
standard,
// if not, it will throw compile time error.
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To restrict this service from getting added as a custom tool
to toolbox
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using
ASP.NET AJAX
[System.Web.Script.Services.ScriptService]
public class MyService : WebService
{
[WebMethod]
public int SumOfNums(int First, int Second)
{
return First + Second;
}
}
}
C#
Copy
Now, the service is ready to be used, let's compile and test it.
Let's use method overloading of the OOP concept. Add the following WebMethod in
MyService class.
[WebMethod]
public float SumOfNums(float First, float Second)
{
return First + Second;
}
C#
Copy
Hit F5 to run the application, you will get ―Both Single SumOfNums(Single, Single)
and Int32 SumOfNums(Int32, Int32) use the message name 'SumOfNums'. Use the
MessageName property of the WebMethod custom attribute to specify unique
message names for the methods.‖ error message. We just used method overloading
concept, so why this error message? This is because these methods are not unique
for a client application. As the error message suggests let's use the MessageName
property of the WebMethod attribute as shown below:
Copy
Now, compile and run the application. Again it's showing some different error
message ―Service 'MyWebServiceDemo.MyService' does not conform to WS-I Basic
Profile v1.1‖. As, WsiProfiles.BasicProfile1_1 doesn't support method overloading
we are getting this exception. Now, either remove this
―[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]‖ attribute or
make it ―[WebServiceBinding(ConformsTo = WsiProfiles.None)]‖.
using System.Web.Script.Serialization;
using System.Web.Services;
namespace MyWebServiceDemo
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.None)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class MyService : WebService
{
[WebMethod]
public int SumOfNums(int First, int Second)
{
return First + Second;
}
[WebMethod(MessageName = "SumOfFloats")]
public float SumOfNums(float First, float Second)
{
return First + Second;
}
}
}
C#
Copy
Now you can use method overloading in the service.
Concept of COM in C#
Introduction
COM in C#
Assembly
Types of assembly
DLL EXE
1. Open visual studio-->File menu- select new project- select C# class library-name-
location then OK.
2. Coding
Another example
Windows control library
1. Open visual studio -File menu-new project -C#-windows form control library-name--
ok
These core tutorials will help you to learn the fundamentals of .NET.
For an in-depth understanding and practical experience, explore
Online ".NET Training".
Working with .NET Remoting
Ex:-
In order share the Logic, Some Reouree files need to be copied from the
server machine into the client machine.
Step1:- Write an interface with a set of abstract methods and compile into
a DLL file.
Step2:- Write a server program by overriding Interface methods and
Reserve a channel over a PORT.
Step3:- Write a client program to create a connection with server and call
interface methods.
Obs:-
The interface DLL must be copied into both server and client machines.
Add two records as follows Insert into users values(„teja‟, ‟abc‟); Insert
into users values(„Ravu‟, ‟xyz‟);
Save or commit;
Open class Library project with the project name Middle Interface.
Namespace middle Interface { Public interface MI { Bool check user(String a,
String b); }//HI }Middle Inter face
Build solution)
Obs:- Middle interface.dll is created under D:/C194/ Middle
interfaceBinDebug folder
{
TCP channel t= new TCP channel(1600);
Execute the project Then a TCP Server will be created with the
following URL Tcp://Local host:1600/abc
}
Obs:- Remoting configuration. Register well-known service type() takes3
arguments
Org 1) Type of the class, where interface methods are over rided .
enum
In single ton, only one object will be created for all the clients When
number of clients are limited then use single all other wise use single ton
Activator class is used to open a connection with my specified URL 2
Developing an application like yahoo messenger with off line support and
two consecutive messages quid not be same
Open class library project with project name yahoo Interface
Public Interface YI
Obs:-
Project
Add Reference
System. Run time. Remoting
project menu
Add Reference
Browe
Yahoo Interface.DLL
Code in GD
Static string S;
Class y server: Marshal By Ret Object.YI
Return Farm1.s;
}//Get Text
}//4 Server
OBS:-
Then a tcp server will be created with the following URL Tcp://Local
host:4829/yahoo
Place two text boxes, one button, and a timer control with enabled =
false
Project menu
Timer1.Enabled=true;
S1-X.Get Text();
If(s1 !=s2)
Text box1.text=text box1.text+ Environment. new line+s1;
S2=s1;
First, I will discuss XML .NET Framework Library namespace and classes. Then, you
will see how to read and write XML documents. In the end of this article, I will show
you how to take advantage of ADO.NET and XML .NET model to read and write
XML documents from relational databases and vice versa.
The System.Xml namespace contains major XML classes. This namespace contains
many classes to read and write XML documents. In this article, we are going to
concentrate on reader and write class. These reader and writer classes are used to
read and write XML documents. These classes are - XmlReader, XmlTextReader,
XmlValidatingReader, XmlNodeReader, XmlWriter, and XmlTextWriter. As you can
see there are four reader and two writer classes.
The XmlReader class is an abstract bases class and contains methods and
properties to read a document. The Read method reads a node in the stream.
Besides reading functionality, this class also contains methods to navigate through a
document nodes. Some of these methods are MoveToAttribute,
MoveToFirstAttribute, MoveToContent, MoveToFirstContent, MoveToElement and
MoveToNextAttribute. ReadString, ReadInnerXml, ReadOuterXml, and
ReadStartElement are more read methods. This class also has a method Skip to
skip current node and move to next one. We'll see these methods in our sample
example.
The XmlWrite class contains functionality to write data to XML documents. This class
provides many write method to write XML document items. This class is base class
for XmlTextWriter class, which we'll be using in our sample example.
The XmlNode class plays an important role. Although, this class represents a single
node of XML but that could be the root node of an XML document and could
represent the entire file. This class is an abstract base class for many useful classes
for inserting, removing, and replacing nodes, navigating through the document. It
also contains properties to get a parent or child, name, last child, node type and
more. Three major classes derived from XmlNode are XmlDocument,
XmlDataDocument and XmlDocumentFragment. XmlDocument class represents an
XML document and provides methods and properties to load and save a document.
It also provides functionality to add XML items such as attributes, comments,
spaces, elements, and new nodes. The Load and LoadXml methods can be used to
load XML documents and Save method to save a document respectively.
XmlDocumentFragment class represents a document fragment, which can be used
to add to a document. The XmlDataDocument class provides methods and
properties to work with ADO.NET data set objects.
List 1 reads a document and displays a node information using these properties.
In this sample example, I read an XML file using XmlTextReader and call Read
method to read its node one by one until end of file and display the contents to the
console output.
Sample Example 1.
using System;
using System.Xml;
namespace ReadXml1 {
class Class1 {
static void Main(string[] args) {
// Create an isntance of XmlTextReader and call Read
method to read the file
XmlTextReader textReader = new
XmlTextReader("C:\\books.xml");
textReader.Read();
// If the node has value
while (textReader.Read()) {
// Move to fist element
textReader.MoveToElement();
Console.WriteLine("XmlTextReader Properties Test");
Console.WriteLine("===================");
// Read this element's properties and display them
on console
Console.WriteLine("Name:" + textReader.Name);
Console.WriteLine("Base URI:" + textReader.BaseURI);
Console.WriteLine("Local Name:" +
textReader.LocalName);
Console.WriteLine("Attribute Count:" +
textReader.AttributeCount.ToString());
Console.WriteLine("Depth:" +
textReader.Depth.ToString());
Console.WriteLine("Line Number:" +
textReader.LineNumber.ToString());
Console.WriteLine("Node Type:" +
textReader.NodeType.ToString());
Console.WriteLine("Attribute Count:" +
textReader.Value.ToString());
}
}
}
}
C#
Copy
The NodeType property of XmlTextReader is important when you want to know the
content type of a document. The XmlNodeType enumeration has a member for each
type of XML item such as Attribute, CDATA, Element, Comment, Document,
DocumentType, Entity, ProcessInstruction, WhiteSpace and so on.
List 2 code sample reads an XML document, finds a node type and writes
information at the end with how many node types a document has.
Highly Recommended
I have published a free book on XML programming using C#. Get your free copy
here.
Still hungry for more XML programming with C# and .NET? Here is a dedicated
section with hundreds of articles and code samples on XML programming using C#
and .NET.
XML Programming in C#
About Sample Example 2
In this sample example, I read an XML file using XmlTextReader and call Read
method to read its node one by one until end of the file. After reading a node, I check
its NodeType property to find the node and write node contents to the console and
keep track of number of particular type of nodes. In the end, I display total number of
different types of nodes in the document.
SHORT QUESTIONS
LONG QUESTIONS
UNIT-4
Background
C# console application is the simplest app to create to test our database connectivity. In this
article, I'll create a console application, use ADO.NET SQL data provider classes to connect to a
SQL Server database using C#, and access, update and execute SQL commands using
ADO.NET.
You can use the same code in your Windows Forms or WPF application.
SQL data provider of ADO.NET is defined in the System.Data.SqlClient namespace. We'll also
use the System.Data and System.Data.Sql namespace that provide additional database
functionality.
System.Data.SqlClient
This assembly (namespace) of .NET Framework contains all of the classes required to connect
to a SQL Server database and read, write, and update. The namespace provides classes to
create a database connection, adapters, and SQL commands that provide the functionality to
execute SQL queries.
The SqlError class is used for error and the success report returned after query execution.
In this article, we will work with the SQL Server database only.
Connecting to a database
Connection to a database requires a connection string. This string has the information about the
server you're going to connect to, the database you will require, and the credentials that you can
use to connect. Each database has its own properties including the server name and type.
In my case, the authentication was Windows, so I need to write the Trusted_Connection part
inside the string. If you're using the database authentication then you will provide the username
and word fields in the string.
Connection pools
Connecting to a database, as already said, is a long process of opening the connection, closing
the connection, and so on. To repeat this process for every single user in the application is not a
good approach and will slow down the processes of code execution. So, in program executions,
many such connections would be opened and closed and again opened that are identical. These
processes are time-consuming and are the opposite of a good UX.
In the .NET Framework, ADO.NET plays a part in this and minimizes the opening and closing
process to make the program execution a bit faster by creating, what we call, a Connection Pool.
This technique reduces the number of times the connection is opened, by saving the instance of
the connection. For every new connection, it just looks for a connection already opened, and
then if the connection exists, doesn't attempt to create a new connection, otherwise, it opens a
new connection based on the connection string.
It must be remembered that only the connections with the same configuration can be pooled. Any
connection with even a single dissimilarity would require a new pool for itself. Generally, it is
based on the ConnectionString of the connection. You can learn how that would differ by
changing the values in the connection string.
We could have done it using the simple line to line code like:
Once the code would step out of this block. The resources would be closed and disposed of on
their own. The framework would take care of in the best way.
SQL has the basic syntax for the commands and in my opinion, has the simple syntax of
commands and nearly human-understandable commands in the programming world. In the
namespace the class, SqlCommand does this job for us. An example of a command would be
like:
Each and every command on the SQL Server would be executed like this. The first parameter is
the command and the second one is the connection on which the command would execute. You
can any command into it and the underlying code would convert it back to the command that
would execute on the server where the data is present and then will return the result to you,
whether an error or a success report.
Sometimes you might want to use the command of the INSERT INTO clause. To work that out,
you will need to add parameters to the command, so that your database is safe from SQL
Injections. Using parameters would reduce the chances of your database being attacked, by
throwing an error if the user tries to add some commands (using the form) into the database
server.
In the preceding code, the variable added is 0 and the value to it is ed. You can use any variable
but it must start with a @ sign. Once that has been done, you can then add the parameters to
that name. In this case, the value 1 has been hardcoded and you can add a variable value here
too.
Remember, the connection must be opened in order to run this code, you can use conn.Open()
to open the connection if asked.
As explained in the code, I have used the parameter as a number (0) that can also be a name.
For example, you can also write the code as:
This way, it will be easier for you to keep them in mind. I am better at working with numbers and
indexes like in an array so I used 0, you can use a name, a combination of alphanumeric
characters, and so on. Just the name in the SqlParameter object and you'll be good to go!
The following code would get the results from the command once executed:
1. // Create a new SqlDataReader object and read data from the command.
2. using(SqlDataReader reader = command.ExecuteReader()) {
3. while there is another record present
4. while (reader.Read()) {
5. // write the data on to the screen
6. Console.WriteLine(String.Format("{0} \t | {1} \t | {2} \t | {3}",
This is the same code, it will execute, and once done executing it will let the framework handle
the job and close the resources depending on the best method.
You can then use the SqlParameter objects to add the values to the parameters. This way, when
the command is executed the data would be added to the table that you've specified.
For this to work, we will a command that we know will throw an error.
Now we know that this is faulty, but this won't generate any error, untill we execute it. To do so,
we will try to execute it like this:
1. errorCommand.ExecuteNonQuery();
Once this is executed, SQL Server would complain, saying there is no such table present. To
catch it you can simply use the try-catch block with the SqlException in the catch block to be
caught. For a working code, you can see the following code block in the live example of my
article. That explains the usage of the try-catch block with the SqlException here.
Working example
In the article, there is an associated example for you to download if you want to work it out. You
must use a SQL Server, database, and the relevant tables to ensure the program works. If the
server name does not match the database name or the tables then the program won't run. There
was no way for me to attach a database in the example. Since the databases require a SQL
Server database that will be always available using a connection, I won't use this database
again, so I have not provided the database connection string.
Database table
The database table in my system was like the following,
We can at the same time add a few more parameters to the SELECT query so that only the data
we want would be extracted from the database. For example, if we add a WHERE clause to the
SELECT query, the following result would be generated.
You can also run a transform over data that was loaded into the DataSet from SQL
Server. Another option is to bind .NET Framework classes-style-managed WinForm
and WebForm controls to a DataSet that was populated from an XML input stream.
The following illustration shows the different associations that XML data has with
the DataSet and XmlDataDocument:
The illustration shows that XML data can be loaded directly into a DataSet, which
allows direct manipulation with XML in the relational manner. Or, the XML can be
loaded into a derived class of the DOM, which is the XmlDataDocument, and
subsequently loaded and synchronized with the DataSet. Because
the DataSet and XmlDataDocument are synchronized over a single set of data,
changes made to the data in one store are reflected in the other store.
The XmlDataDocument inherits all the editing and navigational features from
the XmlDocument. There are times when using the XmlDataDocument and its
inherited features, synchronized with a DataSet, is a more appropriate option than
loading XML directly into the DataSet. The following table shows the items to be
considered when choosing which method to use to load the DataSet.
Queries of data in the DataSet are easier using SQL than XPath queries are needed over data in
XPath. the DataSet.
Preservation of element ordering in the source XML is not Preservation of element ordering in the
critical. source XML is critical.
White space between elements and formatting does not White space and formatting preservation in
need to be preserved in the source XML. the source XML is critical.
If loading and writing XML directly into and out of a DataSet addresses your needs,
see Loading a DataSet from XML and Writing a DataSet as XML Data.
In This Section
DiffGrams
Provides details on the DiffGram, an XML format used to read and write the contents
of a DataSet.
Nesting DataRelations
Discusses the importance of nested DataRelation objects when representing the
contents of a DataSet as XML data, and describes how to create them.
Related Sections
ADO.NET Overview
Describes the ADO.NET architecture and components, and how to use them to
access existing data sources as well as to manage application data.
See also
DataSets, DataTables, and DataViews
ADO.NET Overview
Recommended content
Read XML data into a dataset - Visual Studio (Windows)
Read XML data into a dataset. In this walkthrough, you create a Windows application
that loads XML data into a dataset.
Writing DataSet Contents as XML Data - ADO.NET
Save a dataset as XML. Access the XML data in a dataset by calling the available XML
methods on the dataset, such as GetXml or WriteXml.
Loading a DataSet from XML - ADO.NET
Learn how to add contents to an ADO.NET DataSet from XML. The .NET Framework
offers flexibility for what to load and the structure of the DataSet.
Show more
Emgu CV is an open source library that uses the OpenCV library as a basis for its image
processing features. It works by allowing OpenCV core functions and functionalities to be called
by any .NET language (including C#). It’s written in C# and is highly portable — it’s supported on
Windows, Mac, and Linux operating systems.
Application hosting on Azure - Azure can host your entire application stack from web
applications and APIs to databases to storage services. Azure supports a variety of
hosting models from fully managed services to containers to virtual machines. When
using fully managed Azure services, your applications can take advantage of the
scalability, high-availability, and security built in to Azure.
Consuming cloud services from applications - Existing apps can incorporate Azure
services to extend their capabilities. This could include adding full-text searching
capability with Azure Cognitive Search, securely storing application secrets in Azure
Key Vault or adding vision, speech and language understanding capabilities with Azure
Cognitive Services. These services are fully managed by Azure and can be easily added
to your application without changing your current application architecture or
deployment model.
Modern serverless architectures - Azure Functions simplify building solutions to
handle event-driven workflows, whether responding to HTTP requests, handling file
uploads in Blob storage, or processing events in a queue. You write only the code
necessary to handle your event without worrying about servers or framework code.
Further, you can take advantage of over 250 connectors to other Azure and third-party
services to tackle your toughest integration problems.
Recommended content
Key Azure Services for .NET developers
Azure has over 100 services, but this article focuses on the ~8 or so services used by .NET
developers most frequently
.NET Development on Azure Configuration Checklist
Provides a quick summary of all the tools you should have installed to do .net development
with Azure
Configure Visual Studio for Azure Development with .NET
This article helps you configure Visual Studio for Azure development including getting the
right workloads installed and connecting Visual Studio to your Azure account.
Azure SDK for .NET Overview
Provides an overview of what the Azure SDK for .NET is and the basic steps to use the SDK
in a .NET application
Show more
SHORT QUESTIONS
5.Define graphics?
LONG QUESTIONS
UNIT-5
Creating Web Sites with
ASP.NET 2.0
“Web application development has come a long way in a fairly short period of time.” A quote
like that surely won‟t send anyone into shock anytime soon because it‟s accepted as fact.
From basic, static HTML pages to totally data-driven and data-centric Web applications, the
demands on a Web developer are much more complex and demanding than they were just a
few years ago. The advent of social networking sites like MySpace, which is written in
ASP.NET 2.0, interactive mapping sites, and sites streaming full motion video has required
the Web developer to adapt and change with the times. One of the best tools to use to build
these types of Web applications is Microsoft‟s ASP.NET 2.0. In this article I am going to
delve into some of the more interesting features of ASP.NET 2.0 and show you how you can
begin using ASP.NET 2.0 on your next Web project.
ASP.NET 2.0 offers features that every ASP.NET developer will find useful, including:
The Web Application project is an implementation of the type of Web project available in
Visual Studio 2003 and consists of a solution (.sln) and project files (.vbproj). It is the result
of Microsoft listening to the ASP.NET 2.0 developer community and responding to the needs
of the community. It provides the benefit of generating a single assembly in the local /bin
folder ready for deployment. This model also makes it easier to incrementally deploy changes
made to your site. If you are converting a Web application from Visual Studio 2003, this is
the project model you are going to want to adopt. I use this model with most of the Web
applications I develop.
Advertisement
To create a Web site with the Web Application project model, launch Visual Studio 2005 and
from the File menu option choose New Project… and the New Project dialog box will
appear (Figure 1). Choose ASP.NET Web Application, the name of the project, the
location, and the name of the solution if you select to have one created or specify if you want
the new project added to the current solution. Click OK and Visual Studio will create the
solution (.sln), the project (.vbproj since I selected Visual Basic), a default.aspx page, and a
Web.config file.
Figure 1: The New Project dialog box specifies the name, location, and language for your Web
Application.
To create a Web site with the Web Site project model, launch Visual Studio 2005 and from
the File menu option choose New Web Site and the New Web Site dialog box will
appear (Figure 2). Choose ASP.NET Web Site, the location of the Web site, the language
used, and lastly, the name of the Web site.
Figure 2: The New Web Site dialog box specifies the name, location, and language for your Web site.
I don‟t need to explain the name of the Web site and the language you want to use but I‟ll
discuss other options. The location dropdown offers three options: File System, HTTP, and
FTP. Creating a File System Web site is the simplest approach because your Web site can
reside in any directory on your hard drive or shared network drive. The advantage of a File
System Web site is that you can run it using Visual Studio 2005‟s built in development Web
server. You don‟t need IIS though you can use IIS to run a File System Web site by creating a
virtual directory for the directory you are storing the Web site in.
The second option, choosing HTTP as the location, will direct Visual Studio 2005 to
automatically create a Web site in an IIS virtual directory. This saves you the step of creating
the virtual directory in IIS but obviously you need to have access to an IIS server.
Choosing FTP as the location allows you to actually store and even code your application on
a remote Web server somewhere. If you‟ve selected this option, click the Browse button to
display the Choose Location dialog box and then select a directory, an IIS virtual directory,
and then enter the FTP parameters required to log on to an FTP location (Figure 3).
Figure 3: Site location can be FTP folder on a distant server.
Once you have decided on the name, location, and language for your new Web site,
click OK to create the site. Visual Studio will create a Default.aspx page, Web.config file,
and an App_Data folder. One primary difference between the Web Site project model and the
Web Application project model is that in the Web Site model settings are stored in a
Web.config file as opposed to project file.
Throughout this article I‟ll make references to smart tags, which you can think of as a list of
the most commonly used properties or tasks for a control. You access the smart tags for a
control by clicking the glyph (small black triangle) in the upper right-hand corner of the
control.
System-Defined Folders
Table 1 illustrates some special system-defined folders.
You store all of your non-page classes such as utility classes, business objects, or any other
classes you may have created in the App_Code folder. To add an App_Code folder to your
project, right-click on the project name and select Add ASP.NET Folder and then
select App_Code. ASP.NET monitors the folder and whenever you change a class in the
App_Code folder, ASP.NET will dynamically recompile it and automatically make it
available to the entire site. You can even place classes coded in different languages in
subdirectories under the App_Code directory. Each subdirectory needs to be registered with a
particular language in Web.config.
The App_Data folder makes database integration easy. The App_Data folder holds file-based
data stores including SQL Server Express 2005 database files (.mdf files), Access database
files (.mdb files), Excel worksheets, XML files, and so on. The primary advantage of using
App_Data is that files placed there are not downloadable if a request is made for the file over
the wire.
ASP.NET‟s compilation model offers a number of benefits including the ability to run the
current form each time you run the site. A project‟s Start Options, available on the project‟s
Property Pages dialog box, specifies, among other options, the ability to launch the current
page or a specific page each time the site is launched (Figure 6). See the article by Rick
Strahl referred to in the sidebar, Compilation and Deployment.
Figure 6: You can specify the launch the current page or a specific page start page in the Start
Options.
The ASP.NET Web Site Administration Tool page (Figure 7) makes it fairly easy to
administer your Web site. You can launch it by selecting the ASP.NET Administration icon
on the top of the Solution Explorer (Figure 8). You can manage all aspects of your site with
this tool including security, application settings, and providers. The security features include
being able to add and delete users, assign folder permissions, add and delete user roles, and
assign users to specific roles. The application settings include being able to add and remove
application variables, configure e-mail settings, take the site offline, configure the debugging
and tracing options, and specify which page to use as the default error.
Figure 7: The ASP.NET Web Site Administration Tool provides site configuration features.
BulletedList Control
The BulletedList control provides a quick and easy way to develop both bulleted and
numbered lists. You can manually enter a list (Figure 9) or you can use data binding to
populate the items in the list. The BulletStyle property offers a number of options for
bulleted and numbered lists.
Figure 9: The
BulletedList control makes creating manually maintained and data bound lists easy.
HiddenField Control
Storing data in hidden fields on a page is nothing new and is in fact a very common technique
to save state data across posts back to the server. ASP.NET 2.0‟s HiddenField control
provides the ability to create a hidden field on a page and use it to store data to be sent back
to the server on a post back.
FileUpload Control
Many Web sites provide the ability for users to upload files. For example, an employment
recruiting firm may allow people to upload their resume or a printing company might allow
customers to upload their print jobs. Microsoft‟s ASP.NET team designed
the FileUpload control to make this an easy feature to add to your site. The
FileUpload control is comprised of a textbox to allow the user to type the file information
and a Browse button that allows the user to go search for the file. To get the file uploaded you
must add a separate button that results in a postback and executes the code to upload the
file (Listing 1). In this code, the FilePath variable is going to contain where the file will be
uploaded to. If there is a value in the textbox portion of the FileUpload control, indicated by
the HasFile property, then the file name is combined with the file upload path. Next,
the SaveAs method for the control is executed thereby actually uploading the file.
MultiView
As the name implies, a MultiView control is a container control hosting a number
of View controls. Each View control is an independent section which in turn hosts its own
controls (Figure 10). Use MulitView controls to replace multiple forms related to a specific
function, such as you‟d find in an online shopping cart. Instead of having multiple forms for
each action in a shopping cart, you could use a single MultiView control and simply control
which views a page displays at specific times. The ActiveViewIndex property holds the
index of the currently active view. Assigning ActiveViewIndex to 0 displays the first view in
the control. Programmatically assigning a value to the ActiveViewIndex property, or calling
the SetActiveView method and passing a view object reference, is one technique for
displaying a specific View control.
You can also specify which view to display using a technique that doesn‟t require writing any
code at all. For example, you can add a CommandButton and set
its CommandName property to NextView or PrevView thereby causing
the MultiView control to automatically switch views when a user clicks the button (Figure
11). If you prefer jumping to a specific view instead of moving forward or backward one
view at a time, you can set the CommandButton‟s CommandName property
to SwitchViewByIndex and its CommandAgrument property to the index of the view to
switch to. To switch to a view by its ID instead of index position you can set the
CommandButton‟s CommandName property to SwitchViewByID and
its CommandArguement property to the ID of the view.
Controls are small building blocks of the graphical user interface, which include text
boxes, buttons, check boxes, list boxes, labels, and numerous other tools. Using
these tools, the users can enter data, make selections and indicate their
preferences.
Controls are also used for structural jobs, like validation, data access, security,
creating master pages, and data manipulation.
ASP.NET uses five types of web controls, which are:
HTML controls
HTML Server controls
ASP.NET Server controls
ASP.NET Ajax Server controls
User controls and custom controls
ASP.NET server controls are the primary controls used in ASP.NET. These controls
can be grouped into the following categories:
Validation controls - These are used to validate user input and they work by
running client-side script.
Data source controls - These controls provides data binding to different data
sources.
Data view controls - These are various lists and tables, which can bind to
data from data sources for displaying.
Personalization controls - These are used for personalization of a page
according to the user preferences, based on user information.
Login and security controls - These controls provide user authentication.
Master pages - These controls provide consistent layout and interface
throughout the application.
Navigation controls - These controls help in navigation. For example, menus,
tree view etc.
Rich controls - These controls implement special features. For example,
AdRotator, FileUpload, and Calendar control.
The syntax for using server controls is:
<asp:controlType ID ="ControlID" runat="server" Property1=value1 [Property2=value2] />
In addition, visual studio has the following features, to help produce in error-free
coding:
AccessKey Pressing this key with the Alt key moves focus to the control.
DisabledCssClass Gets or sets the CSS class to apply to the rendered HTML
element when the control is disabled.
Font Font.
RenderingCompatibility It specifies the ASP.NET version that the rendered HTML will
be compatible with.
Site The container that hosts the current control when rendered on
a design surface.
TabIndex Gets or sets the tab index of the Web server control.
TemplateSourceDirectory Gets the virtual directory of the page or control containing this
control.
ToolTip Gets or sets the text displayed when the mouse pointer
hovers over the web server control.
Method Description
CreateControlStyle Creates the style object that is used to implement all style
related properties.
DataBind Binds a data source to the server control and all its child
controls.
DataBind(Boolean) Binds a data source to the server control and all its child
controls with an option to raise the DataBinding event.
HTML server controls added from the Toolbox to a page in Visual Studio are simply HTML
elements with certain attributes already set. You can also create HTML elements in Source
view by typing markup.
By default, HTML elements on a Web Forms page are not available to the server; they are
treated as markup that is passed through to the browser. However, if you add an id attribute
and the attribute runat="server", ASP.NET recognizes the element as a control on the page
and you can program it with server-based code.
Unlike other HTML elements, if you convert an HTML INPUT element to an ASP.NET
server control, it is not created as an instance of the HtmlInputControl class. You cannot
create an instance of the HtmlInputControl class directly. Instead, this class is inherited by the
classes listed in the table below.
The following table lists the type that is used to instantiate INPUT elements as ASP.NET
server controls if the markup contains the attribute runat="server" and an id attribute.
For more information, see ASP.NET Web Server Controls Overview. For a list of HTML
controls, see HTML Server Controls.
Security Note:
User input in a Web Forms page can include potentially malicious client script. By default, the
Web Forms page validates that user input does not include script or HTML elements. For more
information, see Script Exploits Overview and How to: Protect Against Script Exploits in a Web
Application by Applying HTML Encoding to Strings.
Every ASP.NET web form control inherits the DataBind method from its parent
Control class, which gives it an inherent capability to bind data to at least one of its
properties. This is known as simple data binding or inline data binding.
Simple data binding involves attaching any collection (item collection) which
implements the IEnumerable interface, or the DataSet and DataTable classes to the
DataSource property of the control.
On the other hand, some controls can bind records, lists, or columns of data into
their structure through a DataSource control. These controls derive from the
BaseDataBoundControl class. This is called declarative data binding.
The data source controls help the data-bound controls implement functionalities such
as, sorting, paging, and editing data collections.
The BaseDataBoundControl is an abstract class, which is inherited by two more
abstract classes:
DataBoundControl
HierarchicalDataBoundControl
The abstract class DataBoundControl is again inherited by two more abstract
classes:
ListControl
CompositeDataBoundControl
The controls capable of simple data binding are derived from the ListControl abstract
class and these controls are:
BulletedList
CheckBoxList
DropDownList
ListBox
RadioButtonList
The controls capable of declarative data binding (a more complex data binding) are
derived from the abstract class CompositeDataBoundControl. These controls are:
DetailsView
FormView
GridView
RecordList
Example
Let us take the following steps:
Step (1) : Create a new website. Add a class named booklist by right clicking on the
solution name in the Solution Explorer and choosing the item 'Class' from the 'Add
Item' dialog box. Name it as booklist.cs.
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace databinding
{
public class booklist
{
protected String bookname;
protected String authorname;
public booklist(String bname, String aname)
{
this.bookname = bname;
this.authorname = aname;
<tr>
<td style="width: 228px; height: 40px;">
<asp:Label ID="lbllistbox" runat="server"></asp:Label>
</td>
<tr>
<td style="width: 228px; height: 21px">
</td>
<tr>
<td style="width: 228px; height: 21px">
<asp:RadioButtonList ID="RadioButtonList1" runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
</asp:RadioButtonList>
</td>
<tr>
<td style="width: 228px; height: 21px">
<asp:Label ID="lblrdlist" runat="server">
</asp:Label>
</td>
</div>
</form>
Step (3) : Finally, write the following code behind routines of the application:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
IList bklist = createbooklist();
if (!this.IsPostBack)
{
this.ListBox1.DataSource = bklist;
this.ListBox1.DataTextField = "Book";
this.ListBox1.DataValueField = "Author";
this.DropDownList1.DataSource = bklist;
this.DropDownList1.DataTextField = "Book";
this.DropDownList1.DataValueField = "Author";
this.RadioButtonList1.DataSource = bklist;
this.RadioButtonList1.DataTextField = "Book";
this.RadioButtonList1.DataValueField = "Author";
this.CheckBoxList1.DataSource = bklist;
this.CheckBoxList1.DataTextField = "Book";
this.CheckBoxList1.DataValueField = "Author";
this.DataBind();
}
}
return allbooks;
}
SHORT QUESTIONS
1.Define features of asp.net 2.o?
LONG QUESTIONS
Internal Examinations-1
Section-A
Answer any five of the following Questions. 5*2=10m
5.Define multithreading?
Unit-1
Unit-2
Internal Examinations-2
Section-A
Answer any five of the following Questions. 5*2=10m
5.What is Multithreading?
Unit-1
Unit-2
Semester Paper
MASTER OF COMPUTER APLLICATIONS DEGREE
EXAMINATION
FOURTH SEMESTER
PAPER MCA 401B: Dot Net Technologies
(Under C.B.S.C Revised Regulations w.e.f.2021-2023)
(Common paper to University and all Affliated Colleges)
Time:3 hours Max.Marks:70
PART-A
Answer any five of the following questions each question
carries 2 marks(5*2=10)
1.a) define features of .NET?
b).What is Multithreading?
PART-B
Unit-1
(or)
Unit-2
(or)
(or)
Unit-4
(or)
Unit-5
(or)