Professional Documents
Culture Documents
com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)
Introduction
Getting started
using System;
class Hello
Console.WriteLine("hello, world");
The source code for a C# program is typically stored in one or more text files with a file
extension of .cs, as in hello.cs. Using the command-line compiler provided with Visual
Studio .NET, such a program can be compiled with the command-line directive
csc hello.cs
hello, world
For C and C++ developers, it is interesting to note a few things that do not appear in the
"hello, world" program.
The program does not use a global method for Main. Methods and variables are
not supported at the global level; such elements are always contained within type
declarations (e.g., class and struct declarations).
The program does not use either "::" or "->" operators. The "::" is not an operator
at all, and the "->" operator is used in only a small fraction of programs — those
that employ unsafe code (Section A). The separator "." is used in compound
names such asConsole.WriteLine.
The program does not contain forward declarations. Forward declarations are
never needed, as declaration order is not significant.
The program does not use #include to import program text. Dependencies
among programs are handled symbolically rather than textually. This approach
eliminates barriers between applications written using multiple languages. For
example, the Console class need not be written in C#.
sample code
using System;
namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
/* my first program in C# */
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}
C# was developed by Anders Hejlsberg and his team during the development of .Net
Framework.
Although C# constructs closely follow traditional high-level languages, C and C++ and
being an object-oriented programming language. It has strong resemblance with Java,
it has numerous strong programming features that make it endearing to a number of
programmers worldwide.
Boolean Conditions
Automatic Garbage Collection
Standard Library
Assembly Versioning
Properties and Events
Delegates and Events Management
Easy-to-use Generics
Indexers
Conditional Compilation
Simple Multithreading
LINQ and Lambda Expressions
Integration with Windows
The constants refer to fixed values that the program may not alter during its execution.
These fixed values are also called literals. Constants can be of any of the basic data
types like an integer constant, a floating constant, a character constant, or a string
literal. There are also enumeration constants as well.
The constants are treated just like regular variables except that their values cannot be
modified after their definition.
Integer Literals
An integer literal can also have a suffix that is a combination of U and L, for unsigned
and long, respectively. The suffix can be uppercase or lowercase and can be in any
order.
212 /* Legal */
215u /* Legal */
0xFeeL /* Legal */
078 /* Illegal: 8 is not an octal digit */
032UU /* Illegal: cannot repeat a suffix */
85 /* decimal */
0213 /* octal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */
Floating-point Literals
A floating-point literal has an integer part, a decimal point, a fractional part, and an
exponent part. You can represent floating point literals either in decimal form or
exponential form.
3.14159 /* Legal */
314159E-5L /* Legal */
510E /* Illegal: incomplete exponent */
210f /* Illegal: no decimal or exponent */
.e55 /* Illegal: missing integer or fraction */
While representing in decimal form, you must include the decimal point, the exponent,
or both; and while representing using exponential form you must include the integer
part, the fractional part, or both. The signed exponent is introduced by e or E.
Character Constants
Character literals are enclosed in single quotes. For example, 'x' and can be stored in a
simple variable of char type. A character literal can be a plain character (such as 'x'),
an escape sequence (such as '\t'), or a universal character (such as '\u02C0').
There are certain characters in C# when they are preceded by a backslash. The have
special meaning and they are used to represent like newline (\n) or tab (\t). Here, is a
list of some of such escape sequence codes:
\\ \ character
\? ? character
\a Alert or bell
\b Backspace
\f Form feed
\n Newline
\r Carriage return
\t Horizontal tab
\v Vertical tab
using System;
namespace EscapeChar
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello\tWorld\n\n");
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
Hello World
String Literals
String literals or constants are enclosed in double quotes "" or with @"". A string
contains characters that are similar to character literals: plain characters, escape
sequences, and universal characters.
You can break a long line into multiple lines using string literals and separating the
parts using whitespaces.
Here are some examples of string literals. All the three forms are identical strings.
"hello, dear"
"hello, \
dear"
"hello, " "d" "ear"
@"hello dear"
Defining Constants
Constants are defined using the const keyword. Syntax for defining a constant is:
The following program demonstrates defining and using a constant in your program:
using System;
namespace DeclaringConstants
{
class Program
{
static void Main(string[] args)
{
const double pi = 3.14159;
// constant declaration
double r;
Console.WriteLine("Enter Radius: ");
r = Convert.ToDouble(Console.ReadLine());
double areaCircle = pi * r * r;
Console.WriteLine("Radius: {0}, Area: {1}", r, areaCircle);
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
Enter Radius:
C# - Variables
A variable is nothing but a name given to a storage area that our programs can
manipulate. Each variable in C# has a specific type, which determines the size and
layout of the variable's memory the range of values that can be stored within that
memory and the set of operations that can be applied to the variable.
Type Example
C# also allows defining other value types of variable such as enum and reference
types of variables such as class, which we will cover in subsequent chapters.
Defining Variables
<data_type> <variable_list>;
Here, data_type must be a valid C# data type including char, int, float, double, or any
user-defined data type, and variable_list may consist of one or more identifier names
separated by commas.
int i, j, k;
char c, ch;
float f, salary;
double d;
int i = 100;
Initializing Variables
Variables are initialized (assigned a value) with an equal sign followed by a constant
expression. The general form of initialization is:
variable_name = value;
Variables can be initialized in their declaration. The initializer consists of an equal sign
followed by a constant expression as:
using System;
namespace VariableDefinition
{
class Program
{
static void Main(string[] args)
{
short a;
int b ;
double c;
/* actual initialization */
a = 10;
b = 20;
c = a + b;
Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
a = 10, b = 20, c = 30
For example,
int num;
num = Convert.ToInt32(Console.ReadLine());
The function Convert.ToInt32() converts the data entered by the user to int data type,
because Console.ReadLine() accepts the data in string format.
Variables are lvalues and hence they may appear on the left-hand side of an
assignment. Numeric literals are rvalues and hence they may not be assigned and can
not appear on the left-hand side. Following is a valid C# statement:
int g = 20;
But following is not a valid statement and would generate compile-time error:
10 = 20;
C# - Data Types
Value types
Reference types
Pointer types
Value Type
Value type variables can be assigned a value directly. They are derived from the
class System.ValueType.
The value types directly contain data. Some examples are int, char, and float, which
stores numbers, alphabets, and floating point numbers, respectively. When you declare
an int type, the system allocates memory to store the value.
decimal 128-bit precise decimal (-7.9 x 1028 to 7.9 x 1028) / 100 to 28 0.0M
values with 28-29
significant digits
To get the exact size of a type or a variable on a particular platform, you can use
the sizeof method. The expression sizeof(type) yields the storage size of the object or
type in bytes. Following is an example to get the size of int type on any machine:
using System;
namespace DataTypeApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Size of int: {0}", sizeof(int));
Console.ReadLine();
}
}
}
When the above code is compiled and executed, it produces the following result:
Size of int: 4
Reference Type
The reference types do not contain the actual data stored in a variable, but they
contain a reference to the variables.
In other words, they refer to a memory location. Using multiple variables, the reference
types can refer to a memory location. If the data in the memory location is changed by
one of the variables, the other variable automatically reflects this change in value.
Example of built-in reference types are: object,dynamic, and string.
Object Type
The Object Type is the ultimate base class for all data types in C# Common Type
System (CTS). Object is an alias for System.Object class. The object types can be
assigned values of any other types, value types, reference types, predefined or user-
defined types. However, before assigning values, it needs type conversion.
When a value type is converted to object type, it is called boxing and on the other
hand, when an object type is converted to a value type, it is calledunboxing.
object obj;
Dynamic Type
You can store any type of value in the dynamic data type variable. Type checking for
these types of variables takes place at run-time.
For example,
dynamic d = 20;
Dynamic types are similar to object types except that type checking for object type
variables takes place at compile time, whereas that for the dynamic type variables
takes place at run time.
String Type
The String Type allows you to assign any string values to a variable. The string type is
an alias for the System.String class. It is derived from object type. The value for a
string type can be assigned using string literals in two forms: quoted and @quoted.
For example,
@"Tutorials Point";
The user-defined reference types are: class, interface, or delegate. We will discuss
these types in later chapter.
Pointer Type
Pointer type variables store the memory address of another type. Pointers in C# have
the same capabilities as the pointers in C or C++.
type* identifier;
For example,
char* cptr;
int* iptr;
C# - Operators
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Misc Operators
This tutorial explains the arithmetic, relational, logical, bitwise, assignment, and other
operators one by one.
Arithmetic Operators
Following table shows all the arithmetic operators supported by C#. Assume
variable A holds 10 and variable B holds 20 then:
Show Examples
Relational Operators
Following table shows all the relational operators supported by C#. Assume
variable A holds 10 and variable B holds 20, then:
Show Examples
> Checks if the value of left operand is greater than the value (A > B) is
of right operand, if yes then condition becomes true. not true.
< Checks if the value of left operand is less than the value of (A < B) is
right operand, if yes then condition becomes true. true.
>= Checks if the value of left operand is greater than or equal to (A >= B) is
the value of right operand, if yes then condition becomes not true.
true.
<= Checks if the value of left operand is less than or equal to the (A <= B) is
value of right operand, if yes then condition becomes true. true.
Logical Operators
Following table shows all the logical operators supported by C#. Assume
variable A holds Boolean value true and variable B holds Boolean value false, then:
Show Examples
&& Called Logical AND operator. If both the operands are non (A && B) is
zero then condition becomes true. false.
! Called Logical NOT Operator. Use to reverses the logical !(A && B)
state of its operand. If a condition is true then Logical NOT is true.
operator will make false.
Bitwise Operators
Bitwise operator works on bits and perform bit by bit operation. The truth tables for &, |,
and ^ are as follows:
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; then in the binary format they are as follows:
A = 0011 1100
B = 0000 1101
-----------------
~A = 1100 0011
The Bitwise operators supported by C# are listed in the following table. Assume
variable A holds 60 and variable B holds 13, then:
Show Examples
& Binary AND Operator copies a bit to the result if it exists (A & B) = 12,
in both operands. which is 0000
1100
~ Binary Ones Complement Operator is unary and has the (~A ) = 61,
<< Binary Left Shift Operator. The left operands value is A << 2 = 240,
moved left by the number of bits specified by the right which is 1111
operand. 0000
>> Binary Right Shift Operator. The left operands value is A >> 2 = 15,
moved right by the number of bits specified by the right which is 0000
operand. 1111
Assignment Operators
Show Examples
Miscellaneous Operators
There are few other important operators including sizeof, typeof and ? :supported by
C#.
Show Examples
StringReader r = obj as
StringReader;
Operator Precedence in C#
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so the first evaluation takes place for 3*2 and then 7 is added into
it.
Here, operators with the highest precedence appear at the top of the table, those with
the lowest appear at the bottom. Within an expression, higher precedence operators
are evaluated first.
Show Examples
The checked and unchecked operators are used to control the overflow checking
context for integral-type arithmetic operations and conversions.
checked-expression:
checked ( expression )
unchecked-expression:
unchecked ( expression )
The checked operator evaluates the contained expression in a checked context, and
the unchecked operator evaluates the contained expression in an unchecked context. A
checked-expression or unchecked-expression corresponds exactly to a parenthesized-
expression , except that the contained expression is evaluated in the given overflow
checking context.
The following operations are affected by the overflow checking context established by
the checked and unchecked operators and statements:
The predefined ++ and -- unary operators and, when the operand is of an integral
type.
The predefined - unary operator, when the operand is of an integral type.
The predefined +, -, *, and / binary operators, when both operands are of integral
types.
Explicit numeric conversions from one integral type to another integral type, or
from float or double to an integral type.
When one of the above operations produce a result that is too large to represent in the
destination type, the context in which the operation is performed controls the resulting
behavior:
For non-constant expressions (expressions that are evaluated at run-time) that are not
enclosed by any checked or unchecked operators or statements, the default overflow
checking context is unchecked unless external factors (such as compiler switches and
execution environment configuration) call for checked evaluation.
For constant expressions (expressions that can be fully evaluated at compile-time), the
default overflow checking context is always checked. Unless a constant expression is
explicitly placed in an unchecked context, overflows that occur during the compile-time
evaluation of the expression always cause compile-time errors.
In the example
class Test
no compile-time errors are reported since neither of the expressions can be evaluated
at compile-time. At run-time, the F method throws aSystem.OverflowException, and
the G method returns –727379968 (the lower 32 bits of the out-of-range result). The
behavior of the Hmethod depends on the default overflow checking context for the
compilation, but it is either the same as F or the same as G.
In the example
class Test
the overflows that occur when evaluating the constant expressions in F and H cause
compile-time errors to be reported because the expressions are evaluated in
a checked context. An overflow also occurs when evaluating the constant expression
in G, but since the evaluation takes place in an unchecked context, the overflow is not
reported.
The checked and unchecked operators only affect the overflow checking context for
those operations that are textually contained within the "(" and ")" tokens. The operators
have no effect on function members that are invoked as a result of evaluating the
contained expression. In the example
class Test
return x * y;
The unchecked operator is convenient when writing constants of the signed integral
types in hexadecimal notation. For example:
class Test
Both of the hexadecimal constants above are of type uint. Because the constants are
outside the int range, without the unchecked operator, the casts to int would produce
compile-time errors.
The checked and unchecked operators and statements allow programmers to control
certain aspects of some numeric calculations. However, the behavior of some numeric
operators depends on their operands' data types. For example, multiplying two decimals
always results in an exception on overflow even within an
explicitly unchecked construct. Similarly, multiplying two floats never results in an
exception on overflow even within an explicitly checked construct. In addition, other
operators are never affected by the mode of checking, whether default or explicit.
An expression is a sequence of one or more operands and zero or more operators that
can be evaluated to a single value, object, method, or namespace. Expressions can
consist of a literal value, a method invocation, an operator and its operands, or a simple
name. Simple names can be the name of a variable, type member, method parameter,
namespace or type.
Expressions can use operators that in turn use other expressions as parameters, or
method calls whose parameters are in turn other method calls, so expressions can
range from simple to very complex. Following are two examples of expressions:
((x < 10) && ( x > 5)) || ((x > 20) && (x < 25))
System.Convert.ToInt32("35")
Expression Values
In most of the contexts in which expressions are used, for example in statements or
method parameters, the expression is expected to evaluate to some value. If x and y
are integers, the expression x + y evaluates to a numeric value. The expression new
MyClass() evaluates to a reference to a new instance of a MyClass object. The
expression myClass.ToString() evaluates to a string because that is the return type of
the method. However, although a namespace name is classified as an expression, it
does not evaluate to a value and therefore can never be the final result of any
expression. You cannot pass a namespace name to a method parameter, or use it in a
new expression, or assign it to a variable. You can only use it as a sub-expression in a
larger expression. The same is true for types (as distinct from System.Type objects),
method group names (as distinct from specific methods), and
event add and remove accessors.
Every value has an associated type. For example, if x and y are both variables of
type int, the value of the expression x + y is also typed as int. If the value is assigned to
a variable of a different type, or if x and y are different types, the rules of type
conversion are applied. For more information about how such conversions work,
see Casting and Type Conversions (C# Programming Guide).
Overflows
Numeric expressions may cause overflows if the value is larger than the maximum
value of the value's type. For more information, see Checked and Unchecked (C#
Reference) and Explicit Numeric Conversions Table (C# Reference).
Certainly you are familiar with if, switch, while, return and goto statements. These are
famous Branching and Looping statements in many programming languages for
selecting code paths conditionally, looping and jumping to another part of your
application unconditionally. In this article we will discuss what C# offers to us from these
statements. As you will see, the common programming errors that existed in C++ were
eliminated with C# statements.
The if Statement
The if statement gives you the ability to test an expression, then select a statement or a
group of statements to be executed if the expression evaluates to true. If you have the
else part of the statement, you can execute another statement (or statements) if the
expression evaluates to false. The syntax of if statement is as follows:
if(bool expression)
statement 1;
As we will see shortly, the expression must evaluate to bool value (true or false). If you
have more than one statement, you must put the statements in a block using curly
braces:
if(bool expression)
{
statement 1;
statement 2;
statement 3;
}
The same applies to the else statement, so if you have only one statement to execute
with the else statement, you can write it like this:
if(bool expression)
statement 1;
else
statement 1;
But if you have multiple statements in your else part, you can write it as:
if(bool expression)
{
statement 1;
statement 2;
statement 3;
}
else
{
statement 1;
statement 2;
statement 3;
}
For consistency, use the curly braces even if you have only one statement with the if
statement or with the else statement. Most programmers prefer this usage.
int x = 10;
if(x)
{
Console.WriteLine(x);
}
In C# you will get a compile time error that states “Can’t implicitly convert type ‘int’ to
‘bool'”. You need to write this block as follows:
int x = 10;
if(x > 5)
{
Console.WriteLine(x);
}
This will compile in C# because now it’s a Boolean expression. Let’s look at
an example. The following example takes an input number from the user, tests to see if
it’s an even or odd number (using the module operator), and prints a line in each case.
using System;
namespace MyCompany
{
public class IfStatement
{
static void Main(string[] args)
{
Console.WriteLine(“Please type a number”);
int x = Convert.ToInt32(Console.ReadLine());
if(x % 2 == 0)
{
Console.WriteLine(“this is an EVEN number”);
}
else
{
Console.WriteLine(“this is an ODD number”);
}
Console.ReadLine();
}
}
}
{mospagebreak title=Nesting}
Of course you can nest if statements as much as you want. Let’s take a look:
using System;
namespace MyCompany
{
public class IfStatement
{
static void Main(string[] args)
{
Console.WriteLine(“Please type a number”);
int x = Convert.ToInt32(Console.ReadLine());
if(x % 2 == 0)
{
if(x < 1000)
{
Console.WriteLine(“this is an EVEN number”);
}
else
{
Console.WriteLine(“this is a big EVEN number”);
}
}
else
{
if(x < 1000)
{
Console.WriteLine(“this is an ODD number”);
}
else
{
You can combine else with if in one statement to execute more than one test on the
expression. As you already know, if tests the expression, and if it evaluates to false, the
else block will be executed. Sometimes this is not what we need, however. We may
need to be very specific with the else part. For example, take a look at the following
code:
int x = 5;
if(x != 0)
{
Console.WriteLine(“x != 0″);
}
else
{
Console.WriteLine(“x = 0″);
}
There is nothing special about this code; but notice that with the if statement we test to
see if the x is not equal to zero, and if so, it will execute the if block, and else it will
execute the else block. Now let’s look at the following code:
using System;
namespace MyCompany
{
public class IfStatement
{
static void Main(string[] args)
{
int x = 5;
if(x == 0)
{
Console.WriteLine(“x != 0″);
}
else if(x == 4)
{
Console.WriteLine(“x == 4″);
}
else if(x == 5)
{
Console.WriteLine(“x == 5″);
}
else
{
Console.WriteLine(“x = 0″);
}
Console.ReadLine();
}
}
}
if you compile and run the application, you will get the following in the console window:
C# features the combination of else with if to further test the Boolean expression (only
when the if statement evaluates to false), so if the if Boolean expression evaluated to
true, the else if statements will never be tested. I will rewrite the above code as follows:
using System;
namespace MyCompany
{
public class IfStatement
{
static void Main(string[] args)
{
int x = 5;
if(x != 0)
{
Console.WriteLine(“x != 0″);
}
else if(x == 4)
{
Console.WriteLine(“x == 4″);
}
else if(x == 5)
{
Console.WriteLine(“x == 5″);
}
else
{
Console.WriteLine(“x = 0″);
}
Console.ReadLine();
}
}
}
The switch statement is similar to multiple else if statements, but it accepts only
expressions that will evaluate to constant values. The if/else structure is appropriate for
small groups of Boolean expressions, but it would be very ugly to write 20 else if
statements to test for some values: else if(x ==5) do something else if(x == 6) do
another thing, and so on. This is the syntax of a switch statement:
switch(expression)
{
case constant-value:
statement 1;
statement 2;
jump statement
case constant-value:
statement 1;
statement 2;
jump statement
default:
statement 1;
statement 2;
jump statement
}
There are more than three keywords you can use with the switch statement: first, the
switch keyword which, followed by an expression that returns an integral value of type
sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or an Enumeration value.
The switch expression’s value can be returned from a method call, too.
After the switch expression is evaluated, the value will be compared to each case label,
and when the value is found, control is transferred to the first statement in the this case
statement. Each case statement must be ended with a jump statement (unlike C and
C++), such as break or goto. The case keyword is used to define a constant value
(called case label) that will be compared to the value returns from the switch
expression. The constant value of the case label must have a compatible value with the
switch block. This makes sense, because you can’t define an int case label while the
switch expression returns a string value. We will talk about jump statements later in the
article.
The default keyword declares the default statement, which will be executed if none of
the case labels match the switch expression. There can be only one default statement
for each switch statement, and you can write your switch statement without a default
statement, too. Let’s take a look at an example of a switch statement with our famous
Employee class example:
using System;
namespace MyCompany
{
public enum Jobs
{
Programmer = 1,
NetworkAdmin = 2,
Designer = 3,
COMDeveloper = 4
}
// class constructor
This is a very simple example. The Employee class constructor accepts a value of type
Positions, and defines a switch case block to print the Employee job title. One very
important issue to notice is that, with the if/else structure you can write as many else if
statements, each with different conditional expressions, as you want — but you can’t do
that with the switch/case structure. Here the case statements just test for the value of
the switch expression, and if the comparison succeeds, the block get executed. If you
have a statement that will be executed with more than one case label, you can combine
case labels in the following way:
switch(EP)
{
case Positions.Programmer:
case Positions.NetworkAdmin:
case Positions.Designer:
Console.WriteLine(“You are an IT Employee”);
break;
default:
Console.WriteLine(“You are an employee”);
break;
}
You simply write a case statement followed by the next, until you write them all; then
write the statement you want to be executed, then a jump statement. In C# you must
use jump statements between case statements, because the designers of C# eliminated
the fall though that has been in C and C++. You can still explicitly state that you need
the functionality of fall though by using the goto jump keyword:
switch(EP)
{
case Positions.Programmer:
goto case Positions.Designer;
case Positions.NetworkAdmin:
goto case Positions.Designer;
case Positions.Designer:
Console.WriteLine(“You are an IT Employee”);
break;
default:
Console.WriteLine(“You are an employee”);
break;
}
This is an explicit fall through that is clear for every programmer and in fact this
technique eliminates the common problems associated with fall through.
This is the famous for loop structure that many of you have been using to write your
own algorithms. The for loop is used when the number of loops is known (unlike the
while loop, as we will see later). The syntax of the for loop is:
As you can see, the initialization, the expression that controls the loop, and the stepping
parts are all defined in the top of the statement and in one location. The parts are also
separated by semicolons, and you begin the looped statements, or the statements that
will be executed in the loop, using a block ( { } ). The first part of the for statement is the
initialization part; use this part to initialize the variables that will be used in the algorithm
of the for loop. Note that these variables are allocated on the stack, and this part will be
executed only one time, because it doesn’t make any sense to declare and initialize the
same variable with the same value each time in the loop.
The next part is the conditional expression, which determines whether the loop will be
executed again or not. If the condition (something like i < myArray.Length) evaluated to
false, control passes to the first statement after the for statement block. If the condition
evaluated to true, the body of the for block (the controlled statements) will be executed.
The last part is the stepping part. Usually it will be a counter that will increment the
variable that the conditional expression uses, because at some point we need the
conditional expression to evaluate to false and terminate the execution of the for loop.
Note that the stepping part executes after the controlled statements. That is, first the
initialization part executes (one time only) and the variables allocate space on the stack;
second, the conditional expression is evaluated, and if true, the controlled statements
execute, followed by the stepping part execution, and again the conditional expression
is evaluated and the process iterates.
Note that any of the three parts that make the for statement can be empty; although it’s
not common, it can happen. Take a look:
Compile the method into a class and run the application; you will get the following result:
As you can see, we omit the initialization part and we just put in the semicolon. Also
note that the counter can increment or decrement, and it’s up to you to define the
algorithm.
The for loop can be used to define very complex algorithms; this happens as a result of
nesting the for loops. Let’s take a very simple example which extends the above loop
example. It will simply write the same numbers, but this time with a little difference.
Compile the class and run it, and you will get the following result:
I have used a nest for loop to print all the numbers between two iterations from the outer
for loop. The ability to use for loops actually makes great programmers
C# - Methods
Defining Methods in C#
When you define a method, you basically declare the elements of its structure. The
syntax for defining a method in C# is as follows:
Method Body
Example
Following code snippet shows a function FindMax that takes two integer values and
returns the larger of the two. It has public access specifier, so it can be accessed from
outside the class using an instance of the class.
class NumberManipulator
{
public int FindMax(int num1, int num2)
{
/* local variable declaration */
int result;
return result;
}
...
}
Calling Methods in C#
You can call a method using the name of the method. The following example illustrates
this:
using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public int FindMax(int num1, int num2)
{
/* local variable declaration */
int result;
When the above code is compiled and executed, it produces the following result:
You can also call public method from other classes by using the instance of the class.
For example, the method FindMax belongs to the NumberManipulatorclass, you can
call it from another class Test.
using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public int FindMax(int num1, int num2)
{
/* local variable declaration */
int result;
return result;
}
}
class Test
{
static void Main(string[] args)
{
/* local variable definition */
int a = 100;
int b = 200;
int ret;
When the above code is compiled and executed, it produces the following result:
A method can call itself. This is known as recursion. Following is an example that
calculates factorial for a given number using a recursive function:
using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public int factorial(int num)
{
/* local variable declaration */
int result;
if (num == 1)
{
return 1;
}
else
{
result = factorial(num - 1) * num;
return result;
}
}
When the above code is compiled and executed, it produces the following result:
When method with parameters is called, you need to pass the parameters to the
method. There are three ways that parameters can be passed to a method:
Mechanism Description
Value parameters This method copies the actual value of an argument into the
formal parameter of the function. In this case, changes
made to the parameter inside the function have no effect on
the argument.
Output parameters This method helps in returning more than one value.
C#
int i;
However, you might sometimes need to copy a value into a variable or method
parameter of another type. For example, you might have an integer variable that you
need to pass to a method whose parameter is typed as double. Or you might need to
assign a class variable to a variable of an interface type. These kinds of operations are
called type conversions. In C#, you can perform the following kinds of conversions:
Implicit Conversions
For built-in numeric types, an implicit conversion can be made when the value to be
stored can fit into the variable without being truncated or rounded off. For example, a
variable of type long (8 byte integer) can store any value that an int (4 bytes on a 32-bit
computer) can store. In the following example, the compiler implicitly converts the value
on the right to a type long before assigning it to bigNum.
C#
For a complete list of all implicit numeric conversions, see Implicit Numeric Conversions
Table (C# Reference).
For reference types, an implicit conversion always exists from a class to any one of its
direct or indirect base classes or interfaces. No special syntax is necessary because a
derived class always contains all the members of a base class.
Explicit Conversions
class Test
{
static void Main()
{
double x = 1234.7;
int a;
// Cast double to int.
a = (int)x;
System.Console.WriteLine(a);
}
}
// Output: 1234
For a list of the explicit numeric conversions that are allowed, see Explicit Numeric
Conversions Table (C# Reference).
For reference types, an explicit cast is required if you need to convert from a base type
to a derived type:
C#
Animal a = g;
Giraffe g2 = (Giraffe) a;
A cast operation between reference types does not change the run-time type of the
underlying object; it only changes the type of the value that is being used as a reference
to that object. For more information, see Polymorphism (C# Programming Guide).
In some reference type conversions, the compiler cannot determine whether a cast will
be valid. It is possible for a cast operation that compiles correctly to fail at run time. As
shown in the following example, a type cast that fails at run time will cause
an InvalidCastException to be thrown.
using System;
class Animal
{
public void Eat() { Console.WriteLine("Eating."); }
public override string ToString()
{
return "I am an animal.";
}
}
class Reptile : Animal { }
class Mammal : Animal { }
class UnSafeCast
{
static void Main()
{
Test(new Mammal());
C# - Arrays
All arrays consist of contiguous memory locations. The lowest address corresponds to
the first element and the highest address to the last element.
Declaring Arrays
datatype[] arrayName;
where,
For example,
double[] balance;
Initializing an Array
Declaring an array does not initialize the array in the memory. When the array variable
is initialized, you can assign values to the array.
Array is a reference type, so you need to use the new keyword to create an instance of
the array. For example,
You can assign values to individual array elements, by using the index number, like:
balance[0] = 4500.0;
You can assign values to the array at the time of declaration, as shown:
You can copy an array variable into another target array variable. In such case, both
the target and source point to the same memory location:
When you create an array, C# compiler implicitly initializes each array element to a
default value depending on the array type. For example, for an int array all elements
are initialized to 0.
An element is accessed by indexing the array name. This is done by placing the index
of the element within square brackets after the name of the array. For example,
using System;
namespace ArrayApplication
{
class MyArray
{
static void Main(string[] args)
{
int [] n = new int[10]; /* n is an array of 10 integers */
int i,j;
When the above code is compiled and executed, it produces the following result:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
UsingtheforeachLoop
In the previous example, we used a for loop for accessing each array element. You can
also use a foreach statement to iterate through an array.
using System;
namespace ArrayApplication
{
class MyArray
{
static void Main(string[] args)
{
int [] n = new int[10]; /* n is an array of 10 integers */
When the above code is compiled and executed, it produces the following result:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
C#Arrays
There are following few important concepts related to array which should be clear to a
C# programmer:
Concept Description
parameters to a function.
C# - Array Class
The Array class is the base class for all the arrays in C#. It is defined in the System
namespace. The Array class provides various properties and methods to work with
arrays.
The following table describes some of the most commonly used properties of the Array
class:
Sr.No Property
1 IsFixedSize
Gets a value indicating whether the Array has a fixed size.
2 IsReadOnly
Gets a value indicating whether the Array is read-only.
3 Length
Gets a 32-bit integer that represents the total number of elements in all the
dimensions of the Array.
4 LongLength
Gets a 64-bit integer that represents the total number of elements in all the
dimensions of the Array.
5 Rank
Gets the rank (number of dimensions) of the Array.
Methodsof theArrayClass
The following table describes some of the most commonly used methods of the Array
class:
Sr.No Methods
1 Clear
Sets a range of elements in the Array to zero, to false, or to null, depending
on the element type.
3 CopyTo(Array, Int32)
Copies all the elements of the current one-dimensional Array to the specified
one-dimensional Array starting at the specified destination Array index. The
index is specified as a 32-bit integer.
4 GetLength
Gets a 32-bit integer that represents the number of elements in the specified
dimension of the Array.
5 GetLongLength
Gets a 64-bit integer that represents the number of elements in the specified
dimension of the Array.
6 GetLowerBound
Gets the lower bound of the specified dimension in the Array.
7 GetType
Gets the Type of the current instance. (Inherited from Object.)
8 GetUpperBound
Gets the upper bound of the specified dimension in the Array.
9 GetValue(Int32)
Gets the value at the specified position in the one-dimensional Array. The
index is specified as a 32-bit integer.
10 IndexOf(Array, Object)
Searches for the specified object and returns the index of the first
11 Reverse(Array)
Reverses the sequence of the elements in the entire one-dimensional Array.
12 SetValue(Object, Int32)
Sets a value to the element at the specified position in the one-dimensional
Array. The index is specified as a 32-bit integer.
13 Sort(Array)
Sorts the elements in an entire one-dimensional Array using the
IComparable implementation of each element of the Array.
14 ToStringk
Returns a string that represents the current object. (Inherited from Object.)
For complete list of Array class properties and methods, please consult Microsoft
documentation on C#.
Example
The following program demonstrates use of some of the methods of the Array class:
using System;
namespace ArrayApplication
{
class MyArray
{
static void Main(string[] args)
{
int[] list = { 34, 72, 13, 44, 25, 30, 10 };
int[] temp = list;
Console.Write("Original Array: ");
When the above code is compiled and executed, it produces the following result:
Original Array: 34 72 13 44 25 30 10
Reversed Array: 10 30 25 44 13 72 34
Sorted Array: 10 13 25 30 34 44 72
C# - ArrayList Class
The following table lists some of the commonly used properties of theArrayList class:
Property Description
Capacity Gets or sets the number of elements that the ArrayList can
contain.
IsFixedSize Gets a value indicating whether the ArrayList has a fixed size.
The following table lists some of the commonly used methods of the ArrayListclass:
Sr.No. Methods
Example
using System;
using System.Collections;
namespace CollectionApplication
{
class Program
{
static void Main(string[] args)
{
ArrayList al = new ArrayList();
Console.Write("Content: ");
foreach (int i in al)
{
Console.Write(i + " ");
}
Console.WriteLine();
Console.Write("Sorted Content: ");
al.Sort();
foreach (int i in al)
{
Console.Write(i + " ");
}
Console.WriteLine();
Console.ReadKey();
}
}
}
When the above code is compiled and executed, it produces the following result:
C# - Strings
In C#, you can use strings as array of characters, However, more common practice is
to use the string keyword to declare a string variable. The string keyword is an alias
for the System.String class.
You can create string object using one of the following methods:
using System;
namespace StringApplication
{
class Program
{
static void Main(string[] args)
{
//from string literal and string concatenation
string fname, lname;
fname = "Rowan";
lname = "Atkinson";
When the above code is compiled and executed, it produces the following result:
Sr.No Property
1 Chars
2 Length
Methodsof theStringClass
The String class has numerous methods that help you in working with the string
objects. The following table provides some of the most commonly used methods:
Sr.No Methods
5 public static string Concat(string str0, string str1, string str2, string
str3)
Concatenates four string objects.
You can visit MSDN library for the complete list of methods and String class
constructors.
Examples
Comparing Strings:
using System;
CS6001 C# and .Net programming Page 67
namespace StringApplication
{
class StringProg
{
static void Main(string[] args)
{
string str1 = "This is test";
string str2 = "This is text";
if (String.Compare(str1, str2) == 0)
{
Console.WriteLine(str1 + " and " + str2 + " are equal.");
}
else
{
Console.WriteLine(str1 + " and " + str2 + " are not equal.");
}
Console.ReadKey() ;
}
}
}
When the above code is compiled and executed, it produces the following result:
using System;
namespace StringApplication
{
class StringProg
{
static void Main(string[] args)
{
string str = "This is test";
if (str.Contains("test"))
{
Console.WriteLine("The sequence 'test' was found.");
}
Console.ReadKey() ;
}
}
When the above code is compiled and executed, it produces the following result:
Getting a Substring:
using System;
namespace StringApplication
{
class StringProg
{
static void Main(string[] args)
{
string str = "Last night I dreamt of San Pedro";
Console.WriteLine(str);
string substr = str.Substring(23);
Console.WriteLine(substr);
}
}
}
When the above code is compiled and executed, it produces the following result:
San Pedro
Joining Strings:
using System;
namespace StringApplication
{
class StringProg
{
static void Main(string[] args)
{
string[] starray = new string[]{"Down the way nights are dark",
"And the sun shines daily on the mountain top",
"I took a trip on a sailing ship",
"And when I reached Jamaica",
When the above code is compiled and executed, it produces the following result:
The String object is immutable. Every time you use one of the methods in
the System.String class, you create a new string object in memory, which requires a
new allocation of space for that new object. In situations where you need to perform
repeated modifications to a string, the overhead associated with creating a
new String object can be costly. The System.Text.StringBuilder class can be used when
you want to modify a string without creating a new object. For example, using
the StringBuilder class can boost performance when concatenating many strings
together in a loop.
You can create a new instance of the StringBuilder class by initializing your variable
with one of the overloaded constructor methods, as illustrated in the following example.
Although the StringBuilder is a dynamic object that allows you to expand the number of
characters in the string that it encapsulates, you can specify a value for the maximum
number of characters that it can hold. This value is called the capacity of the object and
should not be confused with the length of the string that the current StringBuilder holds.
For example, you might create a new instance of the StringBuilder class with the string
"Hello", which has a length of 5, and you might specify that the object has a maximum
capacity of 25. When you modify the StringBuilder, it does not reallocate size for itself
until the capacity is reached. When this occurs, the new space is allocated automatically
and the capacity is doubled. You can specify the capacity of the StringBuilder class
using one of the overloaded constructors. The following example specifies that
the MyStringBuilder object can be expanded to a maximum of 25 spaces.
Additionally, you can use the read/write Capacity property to set the maximum length of
your object. The following example uses the Capacityproperty to define the maximum
object length.
MyStringBuilder.Capacity = 25;
The Length property can also be viewed or set. If you set the Length property to a
value that is greater than the Capacity property, theCapacity property is automatically
changed to the same value as the Length property. Setting the Length property to a
value that is less than the length of the string within the current StringBuilder shortens
the string.
The following table lists the methods you can use to modify the contents of
a StringBuilder.
Append
The Append method can be used to add text or a string representation of an object to
the end of a string represented by the currentStringBuilder. The following example
initializes a StringBuilder to "Hello World" and then appends some text to the end of
the object. Space is allocated automatically as needed.
Console.WriteLine(MyStringBuilder);
AppendFormat
Console.WriteLine(MyStringBuilder);
Insert
MyStringBuilder.Insert(6,"Beautiful ");
Console.WriteLine(MyStringBuilder);
Remove
You can use the Remove method to remove a specified number of characters from the
current StringBuilder object, beginning at a specified zero-based index. The following
example uses the Remove method to shorten a StringBuilder object.
MyStringBuilder.Remove(5,7);
Console.WriteLine(MyStringBuilder);
// Hello
Replace
The Replace method can be used to replace characters within the StringBuilder object
with another specified character. The following example uses the Replace method to
search a StringBuilder object for all instances of the exclamation point character (!) and
replace them with the question mark character (?).
MyStringBuilder.Replace('!', '?');
Console.WriteLine(MyStringBuilder);
// Hello World?
You must convert the StringBuilder object to a String object before you can pass the
string represented by the StringBuilder object to a method that has a String parameter
or display it in the user interface. You do this conversion by calling
the StringBuilder.ToString method. The following example calls a number
of StringBuilder methods and then calls the StringBuilder.ToString() method to display
the string.
using System;
using System.Text;
{
public static void Main()
{
StringBuilder sb = new StringBuilder();
bool flag = true;
string[] spellings = { "recieve", "receeve", "receive" };
sb.AppendFormat("Which of the following spellings is {0}:", flag);
sb.AppendLine();
for (int ctr = 0; ctr <= spellings.GetUpperBound(0); ctr++) {
sb.AppendFormat(" {0}. {1}", ctr, spellings[ctr]);
sb.AppendLine();
}
sb.AppendLine();
Console.WriteLine(sb.ToString());
}
}
// The example displays the following output:
// Which of the following spellings is True:
// 0. recieve
// 1. receeve
// 2. receive
C# - Structures
In C#, a structure is a value type data type. It helps you to make a single variable hold
related data of various data types. The struct keyword is used for creating a structure.
Structures are used to represent a record. Suppose you want to keep track of your
books in a library. You might want to track the following attributes about each book:
Title
Author
Subject
Book ID
Defining a Structure
To define a structure, you must use the struct statement. The struct statement defines
a new data type, with more than one member for your program.
For example, here is the way you can declare the Book structure:
struct Books
{
public string title;
public string author;
public string subject;
public int book_id;
};
using System;
struct Books
{
public string title;
public string author;
public string subject;
public int book_id;
};
/* book 1 specification */
Book1.title = "C Programming";
Book1.author = "Nuha Ali";
Book1.subject = "C Programming Tutorial";
Book1.book_id = 6495407;
/* book 2 specification */
Book2.title = "Telecom Billing";
Book2.author = "Zara Ali";
Book2.subject = "Telecom Billing Tutorial";
Book2.book_id = 6495700;
Console.ReadKey();
}
}
When the above code is compiled and executed, it produces the following result:
Features of C# Structures
You have already used a simple structure named Books. Structures in C# are quite
different from that in traditional C or C++. The C# structures have the following
features:
In the light of the above discussions, let us rewrite the previous example:
using System;
struct Books
{
private string title;
private string author;
private string subject;
private int book_id;
public void getValues(string t, string a, string s, int id)
{
title = t;
author = a;
subject = s;
book_id = id;
}
public void display()
{
Console.WriteLine("Title : {0}", title);
Console.WriteLine("Author : {0}", author);
Console.WriteLine("Subject : {0}", subject);
Console.WriteLine("Book_id :{0}", book_id);
}
};
/* book 1 specification */
Book1.getValues("C Programming",
"Nuha Ali", "C Programming Tutorial",6495407);
/* book 2 specification */
Book2.getValues("Telecom Billing",
"Zara Ali", "Telecom Billing Tutorial", 6495700);
/* print Book1 info */
Book1.display();
/* print Book2 info */
Book2.display();
Console.ReadKey();
}
}
When the above code is compiled and executed, it produces the following result:
Title : C Programming
Author : Nuha Ali
Subject : C Programming Tutorial
Book_id : 6495407
Title : Telecom Billing
Author : Zara Ali
Subject : Telecom Billing Tutorial
Book_id : 6495700
C# - Enums
C# enumerations are value data type. In other words, enumeration contains its own
values and cannot inherit or cannot pass inheritance.
enum <enum_name>
enumeration list
};
Where,
Each of the symbols in the enumeration list stands for an integer value, one greater
than the symbol that precedes it. By default, the value of the first enumeration symbol
is 0. For example:
Example
using System;
namespace EnumApplication
{
class EnumProgram
{
enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };
When the above code is compiled and executed, it produces the following result:
Monday: 1
Friday: 5
Boxing is the process of converting a value type to the type object or to any interface
type implemented by this value type. When the CLR boxes a value type, it wraps the
value inside a System.Object and stores it on the managed heap. Unboxing extracts the
value type from the object. Boxing is implicit; unboxing is explicit. The concept of boxing
and unboxing underlies the C# unified view of the type system in which a value of any
type can be treated as an object.
In the following example, the integer variable i is boxed and assigned to object o.
int i = 123;
object o = i;
o = 123;
i = (int)o; // unboxing
// String.Concat example.
// String.Concat has many versions. Rest the mouse pointer on
// Concat in the following statement to verify that the version
// that is used here takes three object arguments. Both 42 and
// true must be boxed.
Console.WriteLine(String.Concat("Answer", 42, true));
// List example.
// Create a list of objects to hold a heterogeneous collection
// of elements.
List<object> mixedList = new List<object>();
// The following loop sums the squares of the first group of boxed
// integers in mixedList. The list elements are objects, and cannot
// be multiplied or added to the sum until they are unboxed. The
// unboxing must be done explicitly.
var sum = 0;
for (var j = 1; j < 5; j++)
{
// The following statement causes a compiler error: Operator
// '*' cannot be applied to operands of type 'object' and
// 'object'.
//sum += mixedList[j] * mixedList[j]);
// Output:
// Answer42True
// First Group:
// 1
// 2
// 3
// 4
// Second Group:
// 5
// 6
// 7
// 8
// 9
// Sum: 30
Performance
Boxing
Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit
conversion of a value type to the type object or to any interface type implemented by
this value type. Boxing a value type allocates an object instance on the heap and copies
the value into the new object.
int i = 123;
The following statement implicitly applies the boxing operation on the variable i:
object o = i;
The result of this statement is creating an object reference o, on the stack, that
references a value of the type int, on the heap. This value is a copy of the value-type
value assigned to the variable i. The difference between the two variables, i and o, is
illustrated in the following figure.
Boxing Conversion
It is also possible to perform the boxing explicitly as in the following example, but explicit
boxing is never required:
int i = 123;
Description
This example converts an integer variable i to an object o by using boxing. Then, the
value stored in the variable i is changed from 123 to 456. The example shows that the
original value type and the boxed object use separate memory locations, and therefore
can store different values.
class TestBoxing
{
static void Main()
{
int i = 123;
Unboxing
Unboxing is an explicit conversion from the type object to a value type or from an
interface type to a value type that implements the interface. An unboxing operation
consists of:
Checking the object instance to make sure that it is a boxed value of the given
value type.
Copying the value from the instance into the value-type variable.
object o = i; // boxing
Unboxing Conversion
For the unboxing of value types to succeed at run time, the item being unboxed must be
a reference to an object that was previously created by boxing an instance of that value
type. Attempting to unbox null causes a NullReferenceException. Attempting to unbox a
reference to an incompatible value type causes an InvalidCastException.
class TestUnboxing
{
static void Main()
{
int i = 123;
object o = i; // implicit boxing
try
{
int j = (short)o; // attempt to unbox
System.Console.WriteLine("Unboxing OK.");
}
catch (System.InvalidCastException e)
{
System.Console.WriteLine("{0} Error: Incorrect unboxing.", e.Message);
}
CS6001 C# and .Net programming Page 86
}
}
int j = (short) o;
to:
int j = (int) o;
the conversion will be performed, and you will get the output:
Unboxing OK.
Ref: http://www.tutorialspoint.com/
https://msdn.microsoft.com
http://www.aspfree.com/c/a/c-sharp/branching-and-looping-in-c-part-1
Unit II
Abstraction
Encapsulation
Polymorphism
Inheritance.
Examples:
Classes
When you define a class, you define a blueprint for a data type. This does
not actually define any data, but it does define what the class name means.
That is, what an object of the class consists of and what operations can be
performed on that object. Objects are instances of a class. The methods
and variables that constitute a class are called members of the class.
Defining a Class
A class definition starts with the keyword class followed by the class name;
and the class body enclosed by a pair of curly braces. Following is the
general form of a class definition:
// member variables
...
// member methods
// method body
// method body
...
// method body
Note:
Access specifiers specify the access rules for the members as well as the class
itself. If not mentioned, then the default access specifier for a class type
is internal. Default access for the members is private.
Data type specifies the type of variable, and return type specifies the data type
of the data the method returns, if any.
To access the class members, you use the dot (.) operator.
The dot operator links the name of an object with the name of a member.
using System;
namespace BoxApplication
class Box
class Boxtester
// box 1 specification
Box1.height = 5.0;
Box1.length = 6.0;
Box1.breadth = 7.0;
// box 2 specification
Box2.height = 10.0;
Box2.length = 12.0;
Box2.breadth = 13.0;
// volume of box 1
// volume of box 2
Console.ReadKey();
When the above code is compiled and executed, it produces the following
result:
Let us put above concepts to set and get the value of different class
members in a class:
using System;
namespace BoxApplication
class Box
length = len;
breadth = bre;
height = hei;
class Boxtester
double volume;
// box 1 specification
Box1.setLength(6.0);
Box1.setBreadth(7.0);
Box1.setHeight(5.0);
// box 2 specification
Box2.setLength(12.0);
Box2.setBreadth(13.0);
Box2.setHeight(10.0);
// volume of box 1
volume = Box1.getVolume();
// volume of box 2
volume = Box2.getVolume();
Console.ReadKey();
When the above code is compiled and executed, it produces the following
result:
C# Constructors
A class constructor is a special member function of a class that is executed
whenever we create new objects of that class.
A constructor has exactly the same name as that of class and it does not
have any return type. Following example explains the concept of
constructor:
using System;
namespace LineApplication
class Line
public Line()
length = len;
return length;
line.setLength(6.0);
Console.ReadKey();
When the above code is compiled and executed, it produces the following
result:
A default constructor does not have any parameter but if you need, a
constructor can have parameters. Such constructors are
called parameterized constructors. This technique helps you to assign
initial value to an object at the time of its creation as shown in the following
example:
using System;
namespace LineApplication
class Line
length = len;
length = len;
return length;
line.setLength(6.0);
Console.ReadKey();
When the above code is compiled and executed, it produces the following
result:
C# Destructors
A destructor is a special member function of a class that is executed
whenever an object of its class goes out of scope. A destructor has exactly
the same name as that of the class with a prefixed tilde (~) and it can
neither return a value nor can it take any parameters.
Destructor can be very useful for releasing memory resources before exiting
the program. Destructors cannot be inherited or overloaded.
using System;
namespace LineApplication
class Line
~Line() //destructor
length = len;
return length;
line.setLength(6.0);
When the above code is compiled and executed, it produces the following
result:
The keyword static implies that only one instance of the member exists for
a class. Static variables are used for defining constants because their values
can be retrieved by invoking the class without creating an instance of it.
Static variables can be initialized outside the member function or class
definition. You can also initialize static variables inside the class definition.
using System;
namespace StaticVarApplication
class StaticVar
num++;
return num;
class StaticTester
s1.count();
s1.count();
s1.count();
s2.count();
s2.count();
s2.count();
Console.ReadKey();
When the above code is compiled and executed, it produces the following
result:
You can also declare a member function as static. Such functions can
access only static variables. The static functions exist even before the
object is created. The following example demonstrates the use of static
functions:
using System;
namespace StaticVarApplication
class StaticVar
num++;
return num;
class StaticTester
s.count();
s.count();
s.count();
Console.ReadKey();
When the above code is compiled and executed, it produces the following
result:
Variable num: 3
C# - Inheritance
One of the most important concepts in object-oriented programming is
inheritance. Inheritance allows us to define a class in terms of another
class, which makes it easier to create and maintain an application. This also
provides an opportunity to reuse the code functionality and speeds up
implementation time.
When creating a class, instead of writing completely new data members and
member functions, the programmer can designate that the new class should
inherit the members of an existing class. This existing class is called
the baseclass, and the new class is referred to as the derived class.
...
...
using System;
namespace InheritanceApplication
class Shape
width = w;
height = h;
// Derived class
class RectangleTester
Rect.setWidth(5);
Rect.setHeight(7);
Console.ReadKey();
When the above code is compiled and executed, it produces the following
result:
Total area: 35
using System;
namespace RectangleApplication
class Rectangle
//member variables
length = l;
width = w;
{ }
double cost;
return cost;
base.Display();
class ExecuteRectangle
t.Display();
Console.ReadLine();
When the above code is compiled and executed, it produces the following
result:
Length: 4.5
Width: 7.5
Area: 33.75
Cost: 2362.5
Multiple Inheritance in C#
C# does not support multiple inheritance. However, you can use
interfaces to implement multiple inheritance. The following program
demonstrates this:
using System;
namespace InheritanceApplication
class Shape
width = w;
height = h;
// Derived class
class RectangleTester
int area;
Rect.setWidth(5);
Rect.setHeight(7);
area = Rect.getArea();
Console.ReadKey();
When the above code is compiled and executed, it produces the following
result:
Total area: 35
Total paint cost: $2450
Understanding Properties in C#
In C#, properties are nothing but natural extension of data fields. They are
Usually inside a class, we declare a data field as private and will provide a
set of public SET and GET methods to access the data fields. This is a good
programming practice, since the data fields are not directly accessible out
side the class. We must use the set/get methods to access the data fields.
//SET/GET methods
//Author: rajeshvs@msn.com
using System;
class MyClass
private int x;
x = i;
return x;
class MyClient
mc.SetX(10);
Console.WriteLine(xVal);//Displays 10
C#, properties are defined using the property declaration syntax. The
get
set
<return_type> can be any valid C# type. Note that the first part of the
syntax looks quite similar to a field declaration and second part consists of a
follows.
class MyClass
private int x;
public int X
get
return x;
set
x = value;
The object of the class MyClass can access the property X as follows.
mc.X = 10; // calls set accessor of the property X, and pass 10 as value of
property X.
//C#: Property
//Author: rajeshvs@msn.com
using System;
class MyClass
private int x;
public int X
get
return x;
set
x = value;
class MyClient
mc.X = 10;
Console.WriteLine(xVal);//Displays 10
Remember that a property should have at least one accessor, either set or
get. The set accessor has a free variable available in it called value, which
We can do very complicated calculations inside the set or get accessor. Even
Since normal data fields and properties are stored in the same memory
space, in C#, it is not possible to declare a field and property with the same
name.
Static Properties
C# also supports static properties, which belongs to the class rather than to
the objects of the class. All the rules applicable to a static member are
//Author: rajeshvs@msn.com
using System;
class MyClass
get
return x;
set
x = value;
class MyClient
MyClass.X = 10;
Console.WriteLine(xVal);//Displays 10
Remember that set/get accessor of static property can access only other
static members of the class. Also static properties are invoking by using the
class name.
//Author: rajeshvs@msn.com
using System;
class Base
public int X
get
Console.Write("Base GET");
return 10;
set
Console.Write("Base SET");
class MyClient
d1.X = 10;
But remember that the modifiers like virtual, override etc are using at
//Author: rajeshvs@msn.com
using System;
class Base
get
Console.Write("Base GET");
return 10;
set
Console.Write("Base SET");
get
Console.Write("Derived GET");
return 10;
set
Console.Write("Derived SET");
class MyClient
b1.X = 10;
Abstract Properties
all. The get/set accessors are simply represented with a semicolon. In the
If the abstract class contains only set accessor, we can implement only set in
//Author: rajeshvs@msn.com
using System;
get;
set;
get
Console.Write(" GET");
return 10;
set
Console.Write(" SET");
class MyClient
c1.X = 10;
The properties are an important features added in language level inside C#.
They are very useful in GUI programming. Remember that the compiler
actually generates the appropriate getter and setter methods when it parses
C# - Indexers
define an indexer for a class, this class behaves similar to a virtual array.
You can then access the instance of this class using the array access
operator ([ ]).
Syntax
A one dimensional indexer has the following syntax:
get
set
Use of Indexers
Declaration of behavior of an indexer is to some extent similar to a
property. similar to the properties, you use get and set accessors for
object instance. In other words, it breaks the instance data into smaller
defined with names, but with the this keyword, which refers to the object
using System;
namespace IndexerApplication
class IndexedNames
public IndexedNames()
get
string tmp;
tmp = namelist[index];
else
tmp = "";
return ( tmp );
set
namelist[index] = value;
names[0] = "Zara";
names[1] = "Riz";
names[2] = "Nuha";
names[3] = "Asif";
names[4] = "Davinder";
names[5] = "Sunil";
names[6] = "Rubic";
Console.WriteLine(names[i]);
Console.ReadKey();
When the above code is compiled and executed, it produces the following
result:
Zara
Riz
Nuha
Asif
Davinder
Sunil
Rubic
N. A.
N. A.
N. A.
Overloaded Indexers
Indexers can be overloaded. Indexers can also be declared with multiple
using System;
namespace IndexerApplication
class IndexedNames
public IndexedNames()
get
string tmp;
tmp = namelist[index];
else
tmp = "";
return ( tmp );
set
namelist[index] = value;
get
int index = 0;
if (namelist[index] == name)
return index;
index++;
return index;
names[0] = "Zara";
names[1] = "Riz";
names[2] = "Nuha";
names[3] = "Asif";
names[4] = "Davinder";
names[5] = "Sunil";
names[6] = "Rubic";
Console.WriteLine(names[i]);
Console.WriteLine(names["Nuha"]);
Console.ReadKey();
When the above code is compiled and executed, it produces the following
result:
Zara
Riz
Nuha
Asif
Davinder
Sunil
Rubic
N. A.
N. A.
N. A.
2
C# - Polymorphism
multiple functions'.
Static Polymorphism
The mechanism of linking a function with an object during compile time is
Function overloading
Operator overloading
Function Overloading
You can have multiple definitions for the same function name in the same
scope. The definition of the function must differ from each other by the
types and/or the number of arguments in the argument list. You cannot
The following example shows using function print() to print different data
types:
using System;
namespace PolymorphismApplication
class Printdata
void print(int i)
void print(double f)
void print(string s)
p.print(5);
p.print(500.263);
p.print("Hello C++");
Console.ReadKey();
When the above code is compiled and executed, it produces the following
result:
Printing int: 5
Printing float: 500.263
Printing string: Hello C++
Dynamic Polymorphism
C# allows you to create abstract classes that are used to provide partial
derived class inherits from it. Abstract classes contain abstract methods,
which are implemented by the derived class. The derived classes have more
specialized functionality.
using System;
CS6001 C# and .Net programming Page 48
namespace PolymorphismApplication
length = a;
width = b;
class RectangleTester
double a = r.area();
Console.WriteLine("Area: {0}",a);
Console.ReadKey();
When the above code is compiled and executed, it produces the following
result:
functions.
using System;
namespace PolymorphismApplication
class Shape
width = a;
height = b;
return 0;
class Caller
int a;
a = sh.area();
class Tester
c.CallArea(r);
c.CallArea(t);
Console.ReadKey();
When the above code is compiled and executed, it produces the following
result:
C# - Interfaces
inheriting the interface should follow. The interface defines the 'what' part
of the syntactical contract and the deriving classes define the 'how' part of
Interfaces define properties, methods, and events, which are the members
follow.
Abstract classes to some extent serve the same purpose, however, they are
mostly used when only few methods are to be declared by the base class
Declaring Interfaces
Interfaces are declared using the interface keyword. It is similar to class
// interface members
void showTransaction();
double getAmount();
Example
The following example demonstrates implementation of the above interface:
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System;
namespace InterfaceApplication
// interface members
void showTransaction();
double getAmount();
public Transaction()
amount = 0.0;
tCode = c;
date = d;
amount = a;
return amount;
class Tester
t1.showTransaction();
CS6001 C# and .Net programming Page 58
t2.showTransaction();
Console.ReadKey();
When the above code is compiled and executed, it produces the following
result:
Transaction: 001
Date: 8/10/2012
Amount: 78900
Transaction: 002
Date: 9/10/2012
Amount: 451900
Abstract classes
namespace AbstractClasses
{
class Program
{
static void Main(string[] args)
{
Dog dog = new Dog();
Console.WriteLine(dog.Describe());
Console.ReadKey();
}
}
}
}
If you compare it with the examples in the chapter about
inheritance, you won't see a big difference. In fact, the abstract
keyword in front of the FourLeggedAnimal definition is the biggest
difference. As you can see, we create a new instance of the Dog
class and then call the inherited Describe() method from the
FourLeggedAnimal class. Now try creating an instance of the
FourLeggedAnimal class instead:
Now, as you can see, we just inherited the Describe() method, but
it isn't very useful in it's current form, for our Dog class. Let's
override it:
}
}
Ref :
http://www.tutorialspoint.com/
http://www.c-sharpcorner.com/UploadFile/tusharkantagarwal/objectorientedcsharp11162005070743AM/objectorientedcsharp.aspx
DOT NET (.NET) has brought new functionalities and tools to the application programming interface (API). These innovations allow
development of applications for both Windows and the web as well as components and services (web services). .NET provides a new
reflective, object-oriented API. .NET is designed to be sufficiently generic so that many different high-level languages can be compiled.
The other two programming models are Web Pages and MVC (Model, View, Controller).
Web Forms is the oldest ASP.NET programming model, with event driven web pages written as a
combination of HTML, server controls, and server code.
Web Forms are compiled and executed on the server, which generates the HTML that displays
the web pages.
Web Forms comes with hundreds of different web controls and web components to build user-
driven web sites with data access.
Visual Studio Express is a development tool tailor made for Web Forms (and MVC).
Extensible Markup Language (XML) strores and transports data. If we use a XML file to store
the data then we can do operations with the XML file directly without using the database.
The XML format is supported for all applications. It is independent of all software
applications and it is accessible by all applications. Here is an example that shows how to
insert the data into the XML file and how to retrieve the data from the XML file; also how to
bind the data into tha DataList using ASP.NET. For this the following procedure can be used.
Step 1: First start Visual Studio 2010 by clicking "File" -> "New" -> "Web Site..." then click
on "ASP.NET Web Site". Now write the following inline code that will design your web page.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.style1
{
width: 40%;
border-style: solid;
border-width: 1px;
background-color:Silver;
height: 152px;
}
.style2
{
width: 295px;
}
.style3
{
width: 754px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table class="style1">
<tr>
<td class="style2">
</td>
<td class="style3">
Employee_Info
rmation</td>
</tr>
<tr>
<td class="style2">
Name:</td>
<td class="style3">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style2">
Emp_Id:</td>
<td class="style3">
<asp:TextBox ID="TextBox2"runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style2">
Qualification:</td>
<td class="style3">
<asp:DropDownList ID="DropDownList1" runat="server" Height="22px" Width
="132px">
<asp:ListItem>--SELECT--</asp:ListItem>
<asp:ListItem>MCA</asp:ListItem>
<asp:ListItem>BCA</asp:ListItem>
<asp:ListItem>MBA</asp:ListItem>
<asp:ListItem>BBA</asp:ListItem>
<asp:ListItem>BTech</asp:ListItem>
<asp:ListItem>MTech</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td class="style2">
</td>
<td class="style3">
<asp:Button ID="Button1" runat="server" Text="Submit" onclick="Button1_Cl
ick"/>
<asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="Sho
w"/>
</td>
</tr>
</table>
<asp:DataList ID="DataList1" runat="server" BackColor="#DEBA84" BorderColor="#D
EBA84"
Name:<%#DataBinder.Eval(Container.DataItem,"name")%><br/>
Emp_id:<%#DataBinder.Eval(Container.DataItem,"Emp_id")%></a><br/>
Qualification:<%#DataBinder.Eval(Container.DataItem,"Qualification")%><br/>
</ItemTemplate>
</asp:DataList>
<br />
</div>
</form>
</body>
</html>
Step 2: Add a XML file by clicking "File" -> "Add new item" then click on "XML file". Name
this XML file Sample.xml. Put the following code in the XML file:
<?xml version="1.0"encoding="utf-8"?>
<EmployeeInformation>
</EmployeeInformation>
Step 3: After that add the following namespaces in the code behind:
using System.Data;
using System.Xml;
Step 4: Now write the following code in the code behind file:
{
//Bind xml data to datalist
BindDatalist();
}
}
private void BindDatalist()
{
XmlTextReader xmlreader =new XmlTextReader(Server.MapPath("Employee.xml"));
DataSet ds = newDataSet();
ds.ReadXml(xmlreader);
xmlreader.Close();
if (ds.Tables.Count != 0)
{
DataList1.DataSource = ds;
DataList1.DataBind();
}
else
{
DataList1.DataSource = null;
DataList1.DataBind();
}
}
}
Step 5: Write the following code in the click event of the submit button, so that the data
that is entered is stored in the XML File:
Step 6: Write the following code in the click event of the show button. Now the data stored
in the XML file can be shown.
xmldoc.DocumentElement.AppendChild(parentelement);
xmldoc.Save(Server.MapPath("Employee.xml"));
BindDatalist();
}
Step 8 : See your sample.xml file, it will include the data that I entered at the run time like
this:
<?xmlversion="1.0"encoding="utf-8"?>
<EmployeeInformation>
<Details>
<Name>Richa</Name>
<Emp_id>1</Emp_id>
<Qualification>MCA</Qualification>
</Details>
</EmployeeInformation>
Summary: In this article I use a XML file so that the data is stored and retrieved in XML
using the Datalist in ASP.NET.
While I was writing .NET test automation that had test case data stored in XML files, I discovered
that the .NET Framework provides powerful new ways of parsing XML. But in conversations with
colleagues, I also discovered that there are a variety of opinions on which way of parsing XML
files is the best.
I set out to determine how many different ways there are to parse XML using .NET and to
understand the pros and cons of each technique. After some experimentation, I learned that
there are five fundamentally different ways to parse XML, and that the "best" method depends
both on the particular development situation you are in and on the style of programming you
prefer.
In the sections that follow, I will demonstrate how to parse a testCases.xml file using five
different techniques. Each technique is based on a different .NET Framework class and its
associated methods:
XmlTextReader
XmlDocument
XPathDocument
XmlSerializer
DataSet
After I explain each technique so you can modify my examples to suit your needs, I will give you
guidance on which technique should be used in which situation. Knowing these five methods for
parsing XML files will be a valuable addition to your .NET skill set. I'm assuming that you're
familiar with C#, VS.NET, the creation and use of class libraries, and have a working knowledge
of XML files.
Let's examine the testCases.xml file that we will use for all five parsing examples. The file
contents are shown in Listing One.
?
1 <?xml version="1.0" encoding="utf-8" ?>
2 <suite>
5 <inputs>
6 <arg1>4</arg1>
7 <arg2>7</arg2>
8 </inputs>
9 <expected>11.00</expected>
10 </testcase>
11
13 <inputs>
14 <arg1>9</arg1>
15 <arg2>6</arg2>
16 </inputs>
17 <expected>15.00</expected>
18 </testcase>
19
21 <inputs>
22
<arg1>5</arg1>
<arg2>8</arg2>
23
</inputs>
24
<expected>13.00</expected>
25
</testcase>
26
<
27
/suite>
28
Note that each of the three test cases has five data items: id, kind, arg1,
arg2, andexpected. Some of the data is stored as XML attributes (id and kind),
and arg1 and arg2are stored as XML elements two levels deep relative to the root node
(suite). Extracting attribute data and dealing with nested elements are key tasks regardless of
which parsing strategy we use.
The goal is to parse our XML test cases file and extract the data into memory in a form that we
can use easily. The memory structure we will use for four of the five parsing methods is shown in
Listing Two. (The method that employs an XmlSerializer object requires a slightly
different memory structure and will be presented later.)
?
1
using System;
2
using System.Collections;
3
4
namespace CommonLib
5
{
6
public class TestCase
7
{
8
public string id;
9
public string kind;
10
public string arg1;
11
public string arg2;
12 public string expected;
13 }
14
19 {
21 {
25 }
26 }
27 } // class Suite
} // ns
Because four of the five techniques will use these definitions, for convenience we can put the
code in a .NET class library named "CommonLib." A TestCase object will hold the five data
parts of each test case, and a Suite object will hold a collection of TestCase objects and
provide a way to display it.
Once the XML data is parsed and stored, the result can be represented as shown in >Figure 1.
The data can now be easily accessed and manipulated.
Of the five ways to parse an XML file, the most traditional technique is to use
theXmlTextReader class. The example code is shown in Listing Three.
?
1 using System;
2 using System.Xml;
3 using CommonLib;
5 namespace Run
6 {
7 class Class1
8 {
9 [STAThread]
11 {
13
18
while (!xtr.EOF) //load loop
19
{
20
if (xtr.Name == "suite" && !xtr.IsStartElement()) break;
21
22
while (xtr.Name != "testcase" || !xtr.IsStartElement() )
23
xtr.Read(); // advance to <testcase> tag
24
25
CommonLib.TestCase tc = new CommonLib.TestCase();
26
tc.id = xtr.GetAttribute("id");
27
tc.kind = xtr.GetAttribute("kind");
28
xtr.Read(); // advance to <inputs> tag
29
xtr.Read(); // advance to <arg1> tag
30
tc.arg1 = xtr.ReadElementString("arg1"); // consumes the </arg1> tag
31
tc.arg2 = xtr.ReadElementString("arg2"); // consumes the </arg2> tag
39
xtr.Close();
40
s.Display(); // show the suite of TestCases
41
42
} // Main()
43
} // class Class1
44
} // ns Run
After creating a new C# Console Application Project in Visual Studio .NET, we add a Project
Reference to the CommonLib.dll file that contains definitions
for TestCase and Suite classes. We start by creating a Suite object to hold the XML data
and an XmlTextReader object to parse the XML file.
?
1 <?xml version="1.0" ?>
2 <foo>
3 <bar>99</bar>
4 </foo>
has 6 nodes: the XML declaration, <foo>, <bar>, 99, </bar>, and </foo>.
The Read() method advances one node at a time. Unlike many Read() methods in other
classes, the System.XmlTextReader.Read() does not return significant data.
TheReadElementString() method, on the other hand, returns the data between the
begin and end tags of its argument, and advances to the next node after the end tag. Because
XML attributes are not nodes, we have to extract attribute data using
the GetAttribute()method.
Figure 2 shows the output of running this program. You can see that we have successfully parsed
the data from testCases.xml into memory.
The main loop control structure that I used is not elegant but is more readable than the
alternatives:
?
while (!xtr.EOF) //load loop
1
{
2
if (xtr.Name == "suite" && !xtr.IsStartElement())
3
break;
When marching through the XML file, you can either Read() your way one node at a time or
get a bit more sophisticated with code like the following:
?
1 while (xtr.Name != "testcase" || !xtr.IsStartElement() )
Parsing an XML file with XmlTextReader has a traditional, pre-.NET feel. You walk
sequentially through the file using Read(), and extract data
with ReadElementString() andGetAttribute(). Using XmlTextReader is
straightforward and effective and is appropriate when the structure of your XML file is relatively
simple and consistent. Compared to other techniques we will see in this
article, XmlTextReader operates at a lower level of abstraction, meaning it is up to you as a
programmer to keep track of where you are in the XML file andRead() correctly.
The second of five ways to parse an XML file is to use the XmlDocument class.
The example code is shown in Listing Four.
2 using System.Xml;
3 using CommonLib;
5 namespace Run
6 {
7 class Class1
8 {
9 [STAThread]
11 {
13
15 xd.Load("..\\..\\..\\..\\testCases.xml");
16
18
20 {
22
23 tc.id = node.Attributes.GetNamedItem("id").Value;
24 tc.kind = node.Attributes.GetNamedItem("kind").Value;
25
27 tc.arg1 = n.ChildNodes.Item(0).InnerText;
28 tc.arg2 = n.ChildNodes.Item(1).InnerText;
29
30 tc.expected = node.ChildNodes.Item(1).InnerText;
31
32 s.items.Add(tc);
34
35 s.Display();
36
37 } // Main()
38 } // class Class1
39
40 } // ns Run
XmlDocument objects are based on the notion of XML nodes and child nodes.
Instead of sequentially navigating through a file, we select sets of nodes with
the SelectNodes()method or individual nodes with
the SelectSingleNode() method. Notice that because XML attributes are
not nodes, we must get their data with
an Attributes.GetNamedItem()method applied to a node.
After loading the XmlDocument, we fetch all the test case nodes at once with:
?
1 XmlNodeList nodelist = xd.SelectNodes("/suite/testcase");
Then we iterate through this list of nodes and fetch each <input> node with:
?
1 XmlNode n = node.SelectSingleNode("inputs");
and then extract the arg1 (and similarly arg2) value using:
?
1 tc.arg1 = n.ChildNodes.Item(0).InnerText;
The output from running this program is shown in Figure 3. Notice it is identical to
the output from running the XmlTextReader technique and, in fact, all the
other techniques presented in this article.
The XmlDocument class is modeled on the W3C XML Document Object Model
and has a different feel to it than many .NET Framework classes that you are
familiar with. Using theXmlDocument class is appropriate if you need to extract
data in a nonsequential manner, or if you are already
using XmlDocument objects and want to maintain a consistent look and feel to
your application's code.
Let me note that in discussions with my colleagues, there was often some confusion
about the role of the XmlDataDocument class. It is derived from
the XmlDocument class and is intended for use in conjunction
with DataSet objects. So, in this example, you could use
theXmlDataDocument class but would not gain anything.
The third technique to parse an XML file is to use the XPathDocument class.
The example code is shown in Listing Five.
2 using System.Xml.XPath;
3 using CommonLib;
5 namespace Run
6 {
7 class Class1
8 {
9 [STAThread]
11 {
13
17
19 {
23
24 XPathNodeIterator tcChild =
xpi.Current.SelectChildren(XPathNodeType.Element);
25
while (tcChild.MoveNext()) // each part (<inputs> and <expected>) of <testcase>
26
{
27
if (tcChild.Current.Name == "inputs")
28
{
29
XPathNodeIterator tcSubChild =
30 tcChild.Current.SelectChildren(XPathNodeType.Element);
32 {
33 if (tcSubChild.Current.Name == "arg1")
34 tc.arg1 = tcSubChild.Current.Value;
36 tc.arg2 = tcSubChild.Current.Value;
37 }
38 }
40 tc.expected = tcChild.Current.Value;
41 }
42 s.items.Add(tc);
43
45
46 s.Display();
47
48 } // Main()
49 } // class Class1
50
} // ns Run
Using an XPathDocument object to parse XML has a hybrid feel that is part
procedural (as inXmlTextReader) and part functional (as in XmlDocument).
You can select parts of the document using the Select() method of
an XPathNavigator object and also move through the document using
the MoveNext() method of an XPathNodeIterator object.
?
1 XPathNavigator xpn = xpd.CreateNavigator();
?
1 while (xpi.MoveNext())
?
1 while (tcChild.MoveNext())
The XPathDocument class is optimized for XPath data model queries. So using
it is particularly appropriate when the XML file to parse is deeply nested or has a
complex structure. You might also consider using XPathDocument if other parts
of your application code use that class so that you maintain a consistent coding look
and feel.
2 using System.Xml.Serialization;
3 using System.IO;
6 namespace Run
7 {
8 class Class1
9 {
10 [STAThread]
12 {
14 StreamReader sr = new
StreamReader("..\\..\\..\\..\\testCases.xml");
15
SerializerLib.Suite s =
16 (SerializerLib.Suite)xs.Deserialize(sr);
17 sr.Close();
18 s.Display();
19 }
20 } // class Class1
} // ns Run
Using the XmlSerializer class is significantly different from using any of the
other classes because the in-memory data store is different from the
CommonLib.Suite we used for all other examples. In fact, observe that pulling the
XML data into memory is accomplished in a single statement:
?
SerializerLib.Suite s =
1
(SerializerLib.Suite)xs.Deserialize(sr);
Creating the Suite class is done with the help of the xsd.exe command-line tool.
You will find it in your Program Files\Microsoft Visual Studio
.NET\FrameworkSDK\bin folder. I used xsd.exe to generate a Suite class and
then modified it slightly by changing some names and adding
aDisplay() method.
The screen shot in Figure 4 shows how I generated the file testCases.cs, which
contains aSuite definition that you can use directly or modify as I did. Listings
Seven and Eight show the classes generated by XSD and my modified classes in the
SerializerLib library.
4
[System.Xml.Serialization.XmlRootAttribute("suite", Namespace="",
5 IsNullable=false)]
7 [System.Xml.Serialization.XmlElementAttribute("testcase")]
9 }
10
13 [System.Xml.Serialization.XmlElementAttribute("inputs")]
15 [System.Xml.Serialization.XmlAttributeAttribute()]
17 [System.Xml.Serialization.XmlAttributeAttribute()]
19 }
20
24 }
2 using System.Xml.Serialization;
4 namespace SerializerLib
5 {
6 [XmlRootAttribute("suite")]
8 {
9 [XmlElementAttribute("testcase")]
12 {
14 {
21
public class TestCase // changed name from xsd-generated code
22
{
23
[XmlAttributeAttribute()]
24
public string id;
25
[XmlAttributeAttribute()]
26
public string kind;
27
[XmlElementAttribute("inputs")]
28
public Inputs inputs; // change from xsd-generated code: no array
29
public string expected;
30
}
31
32
public class Inputs // changed name from xsd-generated code
33
{
34
public string arg1;
35
public string arg2;
36
}
37
}
Using the XmlSerializer class gives a very elegant solution to the problem of
parsing an XML file. Compared with the other four techniques in this
article, XmlSerializer operates at the highest level of abstraction, meaning
that the algorithmic details are largely hidden from you. But this gives you less
control over the parsing and lends an air of magic to the process.
1. Click Start, point to Programs, click to select Administrative Tools, and then click Internet Services Manager.
2. Expand the server name.
3. In the left pane, right-click Default Web Site, point to New, and then click Virtual Directory.
4. In the first screen of the Virtual Directory Creation Wizard, type an alias, or name, for the virtual directory (such
as MyWebData), and then click Next.
5. In the second screen, click Browse. Locate the content folder that you created to hold the content. Click Next.
6. In the third screen, click to select Read and Run scripts (such as ASP). Make sure that the other check boxes
are cleared. Click Finish to complete the wizard.
7. For ASP content, you may want to confirm that an application was created. To do this, right-click the new virtual
directory, and then click Properties.
8. On the Virtual Directory tab, make sure that the virtual directory name is listed in the Application Name box
under Application Settings. If it is not, click Create. Note that the application name does not have to match
the virtual directory alias.
9. Close the Properties dialog box.
On Windows 7: Open Start -> Control Panel -> System and Security category -> Administrative
Tools -> Internet Information Services (IIS) Manager.
On Windows Server 2008 or Windows Vista: Open Start -> Control Panel -> System and
Maintenance category -> Administrative Tools ->Internet Information Services (IIS) Manager.
2. Expand local computer -> Sites -> right-click on Default Web Site (or other website if you're
running multiple websites on the same computer) and choose Add Virtual Directory...
3. Enter the Virtual Directory Alias. If you want the website to run
as http://localhost/KenticoCMSDemo, enter alias KenticoCMSDemo.
4. Type a path or browse to the physical directory that contains the chosen directory.
5. Click OK.
7.Click Select... and choose the ASP.NET v4.0 application pool from the drop-down menu.
8. Click OK.
Alternatively, you can create an application in one step by right-clicking a web site and
choosing Add Application... and filling the required information in the Add Application dialog as
mentioned above.
You can check and change the assigned application pool by right-clicking an application under local
computer -> Sites -> Default Web Site (or other web site) and selecting Manage Application ->
Advanced Settings...
You can set the Recycling and other options by right-clicking on an application pool under local
computer -> Application Pools and selecting Advanced Settings....
It's highly recommended that you run Kentico in a separate application pool. If you share the pool
with other websites, the system may behave unpredictably.
We do not recommend to run multiple websites in a single pool.
It's recommended that you specify some value in the Recycle worker processes on
the Recycling tab. This value shouldn't be too short (less than60 minutes) or too long (more
than 1440 minutes/1 day). Setting this value ensures that the memory is recycled and the
application is automatically recovered from failures by regular restart. If your website
freezes time to time, you can temporarily set the value to 30 minutes to ensure that the website is
restarted automatically. Short intervals may lead to high server load and slow response since after
each recycling, the application needs to be restarted and data reloaded to the cache.
It's recommended that you do not limit the maximum virtual or used memory. If you need to use
some value, use at least 100 MB. If your website is being restarted too often, it may be caused by
low maximum memory limit. You can check the frequency of application restarts in KenticoEvent log.
The Maximum number of worker processes on the Performance tab must be set to 1. If you set a
higher value, the worker processes will not be synchronized and Kentico website will not work
correctly. This may lead to unexpected caching of content and system objects.
You can configure the user account under which the application runs on the Identity tab. This
information is useful if you need to troubleshoot issues with permissions, such as disk write
permissions.
Kentico does not support Web garden. Therefore, the Maximum number of worker
processes has to be set to 1.
Introduction
In this article we will try to see what are the different ways we can manage
sessions in an ASP.NET application. When should we use which techniques and
what are the pros and cons of using each technique.
Background
The basic stateless nature of web sites and web applications are rather very
confusing to anyone who is starting with web development. ASP.NET provides
various ways of handling the states. The basic overview of all the state
management techniques can be found here.
Better security
Reduced bandwidth
Let us start looking into how we can use the Session state in our application and
see how we can configure it to use various techniques.
//global.asax
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
Session["number"] = 0;
}
// Web forms
Session["number"] = Convert.ToInt32(Session["number"]) + 1;
Label6.Text = Session["number"].ToString();s
Before we proceed, let us see what all session management techniques are
present in the ASP.NET framework.
In-Proc.
SQLServer.
StateServer.
<sessionState mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="Data Source=.\SQLEXPRESS;Trusted_Connection=Yes;"
cookieless="false"
timeout="100"/>
Single server
If we are using In-Proc session handling then all the session information will be
stored in the server memory. This is the default session state in ASP.NET.
This approach works fine as long as we are keeping small session information.
Since the memory location was handled by the ASP.NET worker thread only it
involves a considerable overhead for the worker thread to manage these. Also,
since this is in the memory of server, chances are that large session information
would lead to more memory usage and thus lowering the performance.
<sessionState mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="Data Source=.\SQLEXPRESS;Trusted_Connection=Yes;"
cookieless="false"
timeout="100"/>
The only relevant options for In_proc session mode in this configuration elements
are the mode(which specifies that we are using In_proc sessions), the cookieless(if
true, will use to manage sessions otherwise append session management data in
the URL) and timeout(the time after which the session should expire.
It is advisable to use the In-Proc sessions when we want very small amount of
information in the sessions. Since the session data is stored in the memory of
computer which is directly accessible by ASP.NET worker thread nothing extra
needs to be done.
The problem with In-Proc mode session mode is that if the size of session data
becomes large then it effects performance. Also, since the session data is in
memory of server the application restart(ASP.NET) will effectively flush all the
data.
As we have discussed above the web farm will have a load balancer accepting all
the requests. It will then forward the request to any server based on some criteria.
Lets try to see a scenario which could create problems for us if we are using In-
Proc sessions.
Problem Scenario
1. The request from Computer1 reaches the load balancer and load balancer forwards
it to server1.
2. The In-Proc session led the session data created in the server1's memory.
3. The next request comes from Computer1 and this time load balancer pushes it
to Server2.
4. Since the server1 had this user specific data in its memory server2 will not be able
to recognize this request leading to failure of our application logic.
So what should we do to tackle this situation. The whole problem was because
each server in our web form was keeping the session data in their own memory. If
we could somehow move this data from each server memory to a centralized
location then we will not face this problem. And that is where
the SQLServer and stateServercomes to rescue. using these two approaches we
can easily configure a central repository to store session data.
Note: There could still be some reasons(explained below) which will force you to
use In-Proc sessions in a Web farm scenario. If this is the case then the load
balancer should be configured to maintain connection affinity or sticky
sessions so that the requests coming from a particular client will always be
forwarded to the same server so that the session information can always be
found.
If we use the SqlServer mode of session management then the session data will
be stored in the SqlServer. The benefit of having this scenario is that the data is
stored in a centralized database rather than the server memory. Let us see how
this can be configured from web.config
<sessionState mode="SQLServer"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="Data Source=.\SQLEXPRESS;Trusted_Connection=Yes;"
cookieless="false"
timeout="100"/>
Apart from this the SQLServer also needs to be configured to store the session
data. To do that simply typeaspnet_regsql on Visual studio command prompt and
a configuration wizard will open. Here we can configure the SqlServer to cater
the session data. The demo project has sqlexpress in local machine configured
for this. To run the application, you will have to configure the sqlserver on local
machine and perhaps change the web.config of the website.
Note: I have given cursory step by step guide to configure SqlServer because I
want to keep this article at conceptual level rather than becoming a "How
To" guide.
This way the server memory is not affected by the size of session data. Also, if we
have a web farm then we can don't find any problem in using session data as the
session data is in a central location. lets try to visualize this scenario
Using this mode will only involve the overhead of additional database access to
retrieve the session data. But there is one important aspect to remember when
we are planning to use this technique. We need to send and receive the data to
a SqlServer database, which will be a separate server. To successfully send and
receive the data toSqlServer all the data that is being kept in the Session has to
be serializable. This sometimes becomes a very big issue when an application is
being ported to web farm from a single server. That is where the load balancer's
connection affinity will come in picture with In-Proc sessions.
If we use the StateServer mode of session management then the session data
will be stored in a separate computer(server) and the session data will be handled
by a windows service. The benefit of having this scenario is that the data is stored
in a centralized location i.e. a state server rather than the individual server
memory. Let us see how this can be configured from web.config
<sessionState mode="StateServer"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="Data Source=.\SQLEXPRESS;Trusted_Connection=Yes;"
cookieless="false"
timeout="100"/>
Apart from this the Server that will be used as state server also needs to be
configured to store the session data. To do that simply run the service
named ASP.NET state service to enable the desired Server to cater the session
data. The demo project does the same on local machine configured for this. To
run the application, you will have to run the service on local machine and perhaps
change the web.config of the website.
Note: I have given cursory step by step guide to configure state server on local
machine because I want to keep this article at conceptual level rather than
becoming a "How To" guide.
This way the server memory is not affected by the size of session data. Also, if we
have a web farm then we can don't find any problem in using session data as the
session data is in a central location. lets try to visualize this scenario
Using this mode will only involve the overhead of network latency to retrieve the
session data. But there is one important aspect to remember when we are
planning to use this technique. We need to send and receive the data to a state
server. To successfully send and receive the data to the state server all the data
that is being kept in the Session has to be serializable. This sometimes becomes
a very big issue when an application is being ported to web farm from a single
server. That is where the load balancer's connection affinity will come in picture
with In-Proc sessions.
To run all three websites the Sqlserver on local machine has to be configured to
store session specific data(details above in the respective category) and the
ASP.NET state service should be running on local machine. Also,
the connectionstring will have to be modified accordingly to use the database on
the running computer.
Note: Please refer the web.config of each website to get the subtle difference.
Error behavior.
Security.
ASP.NET - Configuration
The behavior of an ASP.NET application is affected by different settings in
the configuration files:
machine.config
web.config
The machine.config file contains default and the machine-specific value for
all supported settings. The machine settings are controlled by the system
administrator and applications are generally not given access to this file.
If the application contains child directories, it can define a web.config file for
each folder. Scope of each configuration file is determined in a hierarchical
top-down manner.
Any web.config file can locally extend, restrict, or override any settings
defined on the upper level.
The following figure shows the Solution Explorer for the sample example
used in the web services tutorial:
In this application, there are two web.config files for two projects i.e., the
web service and the web site calling the web service.
The web.config file has the configuration element as the root node.
Information inside this element is grouped into two main areas: the
configuration section-handler declaration area, and the configuration section
settings area.
The following code snippet shows the basic syntax of a configuration file:
<configuration>
<configSections>
</configSections>
<section1>
</section1>
<section2>
</section2>
<system.web>
</system.web>
</configuration>
<configSections>
<section />
<sectionGroup />
<remove />
<clear/>
</configSections>
Application Settings
The application settings allow storing application-wide name-value pairs for
read-only access. For example, you can define a custom application setting
as:
<configuration>
<appSettings>
</appSettings>
</configuration>
For example, you can also store the name of a book and its ISBN number:
<configuration>
<appSettings>
</appSettings>
</configuration>
Connection Strings
The connection strings show which database connection strings are
available to the website. For example:
<connectionStrings>
<add name="ASPDotNetStepByStepConnectionString"
connectionString="Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=E:\\projects\datacaching\ /
datacaching\App_Data\ASPDotNetStepByStep.mdb"
providerName="System.Data.OleDb" />
<add name="booksConnectionString"
connectionString="Provider=Microsoft.Jet.OLEDB.4.0;
providerName="System.Data.OleDb" />
</connectionStrings>
System.Web Element
The system.web element specifies the root element for the ASP.NET
configuration section and contains configuration elements that configure
ASP.NET Web applications and control how the applications behave.
<system.web>
<anonymousIdentification>
<authentication>
<authorization>
<browserCaps>
<caching>
<clientTarget>
<compilation>
<customErrors>
<deployment>
<deviceFilters>
<globalization>
<healthMonitoring>
<hostingEnvironment>
<httpCookies>
<httpHandlers>
<httpModules>
<httpRuntime>
<identity>
<machineKey>
<membership>
<mobileControls>
<pages>
<processModel>
<profile>
<roleManager>
<securityPolicy>
<sessionPageState>
<sessionState>
<siteMap>
<trace>
<trust>
<urlMappings>
<webControls>
<webParts>
<webServices>
<xhtmlConformance>
</system.web>
AnonymousIdentification
This is required to identify users who are not authenticated when
authorization is required.
Authentication
It configures the authentication support. The basic syntax is as given:
<authentication mode="[Windows|Forms|Passport|None]">
<forms>...</forms>
<passport/>
</authentication>
Authorization
It configures the authorization support. The basic syntax is as given:
<authorization>
<allow .../>
<deny .../>
</authorization>
Caching
It Configures the cache settings. The basic syntax is as given:
<caching>
<cache>...</cache>
<outputCache>...</outputCache>
<outputCacheSettings>...</outputCacheSettings>
<sqlCacheDependency>...</sqlCacheDependency>
</caching>
CustomErrors
It defines custom error messages. The basic syntax is as given:
<error. . ./>
</customErrors>
Deployment
It defines configuration settings used for deployment. The basic syntax is as
follows:
HostingEnvironment
It defines configuration settings for hosting environment. The basic syntax
is as follows:
<hostingEnvironment idleTimeout="HH:MM:SS"
shadowCopyBinAssemblies="true|false"
Identity
It configures the identity of the application. The basic syntax is as given:
password="<secure password>"/>
MachineKey
It configures keys to use for encryption and decryption of Forms
authentication cookie data.
decryptionKey="AutoGenerate,IsolateApps" [String]
/>
Membership
This configures parameters of managing and authenticating user accounts.
The basic syntax is:
<providers>...</providers>
</membership>
Pages
It provides page-specific configurations. The basic syntax is:
buffer="[True|False]" clientIDMode="[AutoID|Predictable|Static]"
compilationMode="[Always|Auto|Never]"
controlRenderingCompatibilityVersion="[3.5|4.0]"
enableEventValidation="[True|False]"
enableSessionState="[True|False|ReadOnly]"
enableViewState="[True|False]"
enableViewStateMac="[True|False]"
maintainScrollPositionOnPostBack="[True|False]"
masterPageFile="file path"
maxPageStateFieldLength="number"
pageBaseType="typename, assembly"
pageParserFilterType="string"
smartNavigation="[True|False]"
styleSheetTheme="string"
theme="string"
userControlBaseType="typename"
validateRequest="[True|False]"
viewStateEncryptionMode="[Always|Auto|Never]" >
<controls>...</controls>
<namespaces>...</namespaces>
<tagMapping>...</tagMapping>
<ignoreDeviceFilters>...</ignoreDeviceFilters>
</pages>
Profile
It configures user profile parameters. The basic syntax is:
<properties>...</properties>
<providers>...</providers>
</profile>
RoleManager
It configures settings for user roles. The basic syntax is:
cookiePath="/" cookieProtection="All|Encryption|Validation|None"
enabled="true|false"
<providers>...</providers>
</roleManager>
SecurityPolicy
It configures the security policy. The basic syntax is:
<securityPolicy>
<trustLevel />
</securityPolicy>
UrlMappings
It defines mappings to hide the original URL and provide a more user
friendly URL. The basic syntax is:
<urlMappings enabled="true|false">
<add.../>
<clear />
<remove.../>
</urlMappings>
WebControls
It provides the name of shared location for client scripts. The basic syntax
is:
WebServices
This configures the web services.
In this tutorial you will learn what exactly Web Services are and Why and
How to use them.
Audience
This tutorial will be useful for all those readers inclined to learn the basics of
web services and implement them in practice.
Prerequisites
This is an elementary tutorial that introduces the concepts of web services.
It does not require the readers to have a prior knowledge of any technology
in particular, however it would certainly make you comfortable if you have a
basic understanding of XML, HTTP, TCP/IP concepts.
You can build a Java-based web service on Solaris that is accessible from
your Visual Basic program that runs on Windows.
You can also use C# to build new web services on Windows that can be
invoked from your web application that is based on JavaServer Pages (JSP)
and runs on Linux.
Example
Consider a simple account-management and order processing system. The
accounting personnel use a client application built with Visual Basic or JSP
to create new accounts and enter new customer orders.
The processing logic for this system is written in Java and resides on a
Solaris machine, which also interacts with a database to store information.
The web service unpacks the SOAP request and converts it into a
command that the application can understand.
Next, the web service packages the response into another SOAP
message, which it sends back to the client program in response
to its HTTP request.
Interoperability
Web services allow various applications to talk to each other and share data
and services among themselves. Other applications can also use the web
services. For example, a VB or .NET application can talk to Java web
services and vice versa. Web services are used to make the application
platform and technology independent.
Standardized Protocol
Web services use standardized industry standard protocol for the
communication. All the four layers (Service Transport, XML Messaging,
Service Description, and Service Discovery layers) use well-defined
protocols in the web services protocol stack. This standardization of protocol
stack gives the business many advantages such as a wide range of choices,
reduction in the cost due to competition, and increase in the quality.
XML-Based
Web Services uses XML at data representation and data transportation
layers. Using XML eliminates any networking, operating system, or platform
binding. Web Services based applications are highly interoperable
application at their core level.
Loosely Coupled
A consumer of a web service is not tied to that web service directly. The
web service interface can change over time without compromising the
client's ability to interact with the service. A tightly coupled system implies
that the client and server logic are closely tied to one another, implying that
if one interface changes, the other must be updated. Adopting a loosely
coupled architecture tends to make software systems more manageable and
allows simpler integration between different systems.
Coarse-Grained
Object-oriented technologies such as Java expose their services through
individual methods. An individual method is too fine an operation to provide
any useful capability at a corporate level. Building a Java program from
scratch requires the creation of several fine-grained methods that are then
composed into a coarse-grained service that is consumed by either a client
or another service.
Service Provider
This is the provider of the web service. The service provider implements the
service and makes it available on the Internet.
Service Requestor
This is any consumer of the web service. The requestor utilizes an existing
web service by opening a network connection and sending an XML request.
Service Registry
This is a logically centralized directory of services. The registry provides a
central place where developers can publish new services or find existing
ones. It therefore serves as a centralized clearing house for companies and
their services.
Service Transport
This layer is responsible for transporting messages between applications.
Currently, this layer includes Hyper Text Transport Protocol (HTTP), Simple
Mail Transfer Protocol (SMTP), File Transfer Protocol (FTP), and newer
protocols such as Blocks Extensible Exchange Protocol (BEEP).
XML Messaging
This layer is responsible for encoding messages in a common XML format so
that messages can be understood at either end. Currently, this layer
includes XML-RPC and SOAP.
Service Description
This layer is responsible for describing the public interface to a specific web
service. Currently, service description is handled via the Web Service
Description Language (WSDL).
Service Discovery
This layer is responsible for centralizing services into a common registry
and providing easy publish/find functionality. Currently, service discovery is
handled via Universal Description, Discovery, and Integration (UDDI).
SOAP is not tied to any specific transport protocol. In fact, you can use
SOAP via HTTP, SMTP, or FTP. One promising idea is therefore to use SOAP
over BEEP.
XML-RPC
This is the simplest XML-based protocol for exchanging information between
computers.
XML-RPC is platform-independent.
SOAP
SOAP is an XML-based protocol for exchanging information between
computers.
WSDL
WSDL is an XML-based language for describing web services and how to
access them.
UDDI
UDDI is an XML-based standard for describing, publishing, and finding web
services.
We will write and publish a simple web service using .NET SDK.
We will also write two web service requestors: one web-based consumer
(ASP.NET application) and another Windows application-based consumer.
Given below is our first web service example which works as a service
provider and exposes two methods (add and SayHello) as the web services
to be used by applications. This is a standard template for a web service.
.NET web services use the .asmx extension. Note that a method exposed as
a web service has the WebMethod attribute. Save this file as
FirstService.asmx in the IIS virtual directory (as explained in configuring
IIS; for example, c:\MyWebSerces).
FirstService.asmx
using System;
using System.Web.Services;
using System.Xml.Serialization;
[WebService(Namespace="http://localhost/MyWebServices/")]
[WebMethod]
return a + b;
[WebMethod]
Enter the directory path name for the virtual directory. For
example, c:\MyWebServices Click Next.
To test whether the IIS has been configured properly, copy an HTML file
(For example, x.html) in the virtual directory (C:\MyWebServices) created
above. Now, open Internet Explorer and type
http://localhost/MyWebServices/x.html. It should open the x.html file.
Note: If it does not work, try replacing the localhost with the IP address of
your machine. If it still does not work, check whether IIS is running; you
may need to reconfigure the IIS and the Virtual Directory.
To test this web service, copy FirstService.asmx in the IIS virtual directory
created above (C:\MyWebServices). Open the web service in Internet
Explorer (http://localhost/MyWebServices/FirstService.asmx). It should
open your web service page. The page should have links to two methods
This application has two text fields that are used to get numbers from the
user to be added. It has one button, Execute, that when clicked gets the
Add and SayHello web services.
WebApp.axpx
<script runat="server">
Label1.Text = mySvc.SayHello();
Label2.Text = mySvc.Add(Int32.Parse(txtNum1.Text),
Int32.Parse(txtNum2.Text)).ToString();
</script>
<html>
<head> </head>
<body>
<form runat="server">
<p>
</p>
<p>
</p>
<p>
</p>
<p>
</p>
<p>
<em>Add Service</em> :
</p>
<p align="left">
</p>
</form>
</body>
</html>
After the consumer is created, we need to create a proxy for the web
service to be consumed. This work is done automatically by Visual Studio
.NET for us when referencing a web service that has been added. Here are
the steps to be followed:
Put the compiled proxy in the bin directory of the virtual directory
of the Web Service (c:\MyWebServices\bin). Internet Information
Services IIS looks for the proxy in this directory.
WinApp.cs
using System;
using System.IO;
namespace SvcConsumer {
class SvcEater {
Now, the question arises: How can you be sure that this application is
actually calling the web service?
It is simple to test. Stop your Web server so that the Web Service cannot
be contacted. Now, run the WinApp application. It will fire a run-time
exception. Now, start the web server again. It should work.
Ref:
http://www.codeproject.com/Articles/416137/Understanding-Session-Management-Techniques-in-ASP
http://www.tutorialspoint.com/asp.net/asp.net_configuration.htm
https://in.godaddy.com/help/what-is-a-webconfig-file-5445
http://www.tutorialspoint.com/webservices/
https://documentation.progress.com/output/ua/OpenEdge_latest/index.html#page/dvnet/passing-
dataset-and-dataset-handle-parameters.html
.NET Framework
.NET Framework (pronounced dot net) is a software framework developed by Microsoft that runs
primarily on Microsoft Windows. It includes a large class library known as Framework Class
Library (FCL) and provides language interoperability(each language can use code written in other
languages) across several programming languages. Programs written for .NET Framework execute
in a software environment (as contrasted to hardware environment), known as Common Language
Runtime (CLR), an application virtual machine that provides services such as security, memory
management, and exception handling. FCL and CLR together constitute .NET Framework.
FCL provides user interface, data access, database connectivity, cryptography, web
application development, numericalgorithms, and network communications. Programmers produce
software by combining their own source code with .NET Framework and other libraries. .NET
Framework is intended to be used by most new applications created for the Windows platform.
Microsoft also produces an integrated development environment largely for .NET software
called Visual Studio.
.NET Framework started out as a proprietary framework, although the company worked
to standardize the software stack almost immediately, even before its first release. Despite the
standardization efforts, developers—particularly those in the free and open-source
software communities—expressed their uneasiness with the selected terms and the prospects of
any free and open-source implementation, especially with regard to software patents. Since then,
Microsoft has changed .NET development to more closely follow a contemporary model of a
community-developed software project, including issuing an update to its patent that promises to
address the concerns.
.NET Framework family also includes two versions for mobile or embedded device use. A reduced
version of the framework,.NET Compact Framework, is available on Windows CE platforms,
including Windows Mobile devices such as smartphones. Additionally, .NET Micro Framework is
targeted at severely resource-constrained devices.
This article is based on the ideas that Dr.Asad Altimeemy posed in the article he wrote titled: A
Beginners Guide To Dialog Based Applications written in Visual C++. This article covers essentially
the same methods only converted to run in .NET and written in C#. This code is unfortunately based
on Visual Studio .NET Beta 2; please make any comments regarding the changes to the final release
version.
Item Quantity
GroupBox 1
Label 3
ComboBox 1
Textbox 2
Button 3
ListBox 1
Arrange your items onto the form so that they look something like this. I would suggest that you
place the GroupBox on the form first, otherwise you will need to re-drag all item inside the box once
they are on the form. Arrange the items as you see below in Figure 2.
comboBox1.Items.Add("Dr.");
comboBox1.Items.Add("Mr.");
comboBox1.Items.Add("Mrs.");
comboBox1.Items.Add("Ms.");
comboBox1.Focus();
}
We now need to handle what happens when the user hits the OK button after populating the text
boxes. To do this simply click on the Form1.cs[Design]* tab at the top left to switch from code-view
to the form object designer. Double-click on the OK button and add the following code:
When we want to allow the user to clear all fields entered into the listBox, we will need to go back
like we did above to the visual designer and double-click on the Clear List button, this should again
switch to a code view and allow you to add the following code:
And finally we want to allow the user to be able to close the application when they want. To show
you another way to allow the user to close the program aside from that catchy X in the upper right-
hand corner, I have provided a button entitled……Close. I know, you were looking for some complex
name, weren’t you? Anyway, before I get off on a tangent, double-click the Close button and add the
following code below:
Conclusion
Again this small sample application was made to show you how some of the basic components of a
Windows application are controlled in C#. Hopefully, you have a better understanding of how the
new C# language works within a Windows application. Here is a view of what you might see when
running the application.
using System;
using System.Windows.Forms;
public MyForm() {
[STAThread]
// your application will compile and execute, but because it is not in the //
Application.Run(aform);
using System;
using System.ComponentModel;
using System.Windows.Forms;
using System.Resources;
using System.Drawing;
InitializeComponent();
base.Dispose(disposing);
red.Text = "Red";
red.Click +=handler;
Controls.Add(red);
blue.Text = "Blue";
blue.Click += handler;
Controls.Add(blue);
green.Text = "Green";
green.Click += handler;
Controls.Add(green);
// Event handler.
[STAThread]
Application.Run(new MyForm());
Menu Creation
Defining a Property in Windows
Forms Controls
One common aspect of Web sites of any complexity is a
navigational menu. You can use the Menu control in ASP.NET to
easily set up a complex navigational menu without writing code.
The Menu control allows for multiple display options, including a
static display where the menu is fully exposed and a dynamic
display where portions of the menu appear as the mouse pointer
moves over the parent menu item. The control also provides a
combination of static and dynamic display modes that allow a
series of root items that are static, but with child menu items that
appear dynamically.
You can configure the ASP.NET Menu control in the designer with
static links to your pages or you can bind it automatically to a
hierarchical data source such as an XmlDataSource or
a SiteMapDataSource control.
Tasks illustrated in this walkthrough include:
Creating a basic menu and configuring it statically to link to
your pages.
Creating a more complex menu that is bound to a
Walkthrough: Displaying a
Menu on Web Pages
.NET Framework 4
Other Versions
This walkthrough illustrates how to place and configure an ASP.NET Menu control on a Web
page.
One common aspect of Web sites of any complexity is a navigational menu. You can use
the Menu control in ASP.NET to easily set up a complex navigational menu without writing code.
The Menu control allows for multiple display options, including a static display where the menu
is fully exposed and a dynamic display where portions of the menu appear as the mouse pointer
moves over the parent menu item. The control also provides a combination of static and
dynamic display modes that allow a series of root items that are static, but with child menu
items that appear dynamically.
You can configure the ASP.NET Menu control in the designer with static links to your pages or
you can bind it automatically to a hierarchical data source such as an XmlDataSource or
a SiteMapDataSource control.
Tasks illustrated in this walkthrough include:
Creating a basic menu and configuring it statically to link to your pages.
Creating a more complex menu that is bound to a Web.sitemap XML file.
Adjusting the orientation of a menu.
Configuring multiple levels of static display versus dynamic display.
Prerequisites
In order to complete this walkthrough, you will need:
Visual Studio or Visual Web Developer Express installed on your computer.
Note
If you are using Visual Studio, the walkthrough assumes that you selected the Web
Development collection of settings when you started Visual Studio the first time. For
more information, see How to: Select Web Development Environment Settings.
For this example, you will orient the menu horizontally rather than
vertically.
To position the Menu control horizontally
Right-click the Menu control, click Properties, and then
set Orientation to Horizontal.
</siteMap>
5.Save the file.
C#
MDI applications allow multiple document frame windows to be open in the same instance
of an application. An MDI application has a window within which multiple MDI child
windows, which are frame windows themselves, can be opened, each containing a separate
document. In some applications, the child windows can be of different types, such as chart
windows and spreadsheet windows. In that case, the menu bar can change as MDI child
windows of different types are activated.
In the usability community, there has been much debate about whether the multiple
document or single document interface is preferable. Software companies have used both
interfaces with mixed responses. For example, Microsoft changed its Office applications
from SDI to MDI mode and then back to SDI, although the degree of implementation varies
from one component to another. SDI can be more useful in cases where users switch more
often between separate applications than among the windows of one application.
The disadvantage of MDI usually cited is its lack of information about the currently opened
windows: In MDI applications, the application developer must provide a way to switch
between documents or view a list of open windows, and the user might have to use an
application-specific menu ("window list" or something similar) to switch between open
documents. This is in contrast to SDI applications, where the window manager's task
bar or task manager displays the currently opened windows. However, in recent years it has
become increasingly common for MDI applications to use "tabs" to display the currently
opened windows, which has made this criticism somewhat obsolete. An interface in which
tabs are used to manage open documents is referred to as a "tabbed document interface"
(TDI).
Another option is "tiled" panes or windows, which make it easier to prevent content from
overlapping.
Some applications allow the user to switch between these modes at their choosing,
depending on personal preference or the task at hand.
Nearly all graphical user interface toolkits to date provide at least one solution for designing
MDIs, with an exception being Apple's Cocoa API. The Java GUI toolkit, Swing, for
instance, provides the class javax.swing.JDesktopPane which serves as a container for
individual frames (class javax.swing.JInternalFrame ). GTK+ lacks any standardized
support for MDI.
Advantages[edit]
With multiple document interfaces (and also tabbed document interfaces), a single
menu bar and/or toolbar is shared between all child windows, reducing clutter and
increasing efficient use of screen space. This argument is less relevant on an operating
system which uses a common menu bar.
Can be tricky to implement on desktops using multiple monitors as the parent window
may need to span two or more monitors, hiding sections.
Virtual desktops cannot be spanned by children of the MDI. However, in some cases,
this is solveable by initiating another parent window; this is the case
in Opera andChrome, for example, which allows tabs/child windows to be dragged
outside of the parent window to start their own parent window. In other cases, each child
window is also a parent window, forming a new, "virtual" MDI [1].
MDI can make it more difficult to work with several applications at once, by restricting
the ways in which windows from multiple applications can be arranged together without
obscuring each other.
The shared menu might change, which may cause confusion to some users.
MDI child windows behave differently from those in single document
interface applications, requiring users to learn two subtly different windowing concepts.
Similarly, the MDI parent window behaves like the desktop in many respects, but has
enough differences to confuse some users.
Deeply nested, branching hierarchies of child windows can be confusing.
Many window managers have built-in support for manipulating groups of separate
windows, which is typically more flexible than MDI in that windows can be grouped and
ungrouped arbitrarily. A typical policy is to group automatically windows that belong to
the same application. This arguably makes MDI redundant by providing a solution to the
same problem.
Controls and hotkeys learned for the MDI application may not apply to others, whereas
with an advanced Window Manager, more behavior and user preference settings are
shared across client applications on the same system
Without an MDI frame window, floating toolbars from one application can clutter the
workspace of other applications, potentially confusing users with the jumble of
interfaces.
The second form you've just created is called a Modeless form. These are forms than
can be hidden or sent to the taskbar. You can then return to the main form or
programme and do things with it.
A Modal form is sometimes called a dialogue box. And we'll see how to create one of
these now.
Add a second button to your Form1. Change the Name property of the new button
tobtnDialogueBox. Double click the new button and add the following code:
frmDialogue.ShowDialog()
To display a form as a Modal dialogue box, you use the ShowDialog method. If you
use the Show method, the form is displayed as a Modeless form.
Run your programme. Click your new button, and the second form should display. Move
it out the way and try to click a button on Form1. You won't be able to. The second form
has to be dealt with before you can access Form1.
When the form is a Modal dialogue box, you can create OK and Cancel buttons for it.
VB.NET then has a trick up its sleeve for these types of buttons. We'll see that trick
now.
In the design environment, Click the Tab for your frmSecond. When the form is
displayed in the design window, add two buttons to it (Make sure you're adding the
buttons to the second form and NOT Form1). Change the Name property of the first
button to btnOK, and the Name property of the second to btnCancel. Double click your
OK button and add the following code to it:
Me.DialogResult = DialogResult.OK
The Me keyword refers to the current form. When you type a full stop,
select DialogResult from the pop up list that appears. DialogResult is a property of the
Form. It can accept a range of values. As soon as you type a space after the equals
sign, you'll see a list with these values on it (VB NET 2008 only. In VB 2010, you have
to type the DialogResult):
As you can see, one of these values is DialogResult.OK. This indicates that you want to
use this button as an OK button. When the button is clicked, VB.NET will return a result
of OK for this button.
Access the code for your Cancel button and add the following line:
Me.DialogResult = DialogResult.Cancel
For the Cancel button, we're just selecting DialogResult.Cancel from the list. When the
button is clicked, VB.NET will return a result of Cancel for this button.
You can test to see what value is stored in Me.DialogResult. But you do that from the
button that displays the form, Form1 for us.
So access your Form1 code, and locate the lines that display the second form. The two
lines should be these:
frmDialogue.ShowDialog()
End If
To get at the value of the button clicked, you test to see what result
the ShowDialog property is. If theShowDialog property of frmDialogue is OK then you
can execute the code that needs executing. If the Cancel button was clicked, however,
you don't have to do anything: VB.NET will take of closing your Modal dialogue box for
you!
Run your programme and test it out. Click your button to bring up your Modal dialogue
box. Click the OK button, and you should see the message box display. Bring the Modal
dialogue box up a second time and then click the Cancel button. The form will just close
down.
Some applications require various dialog boxes to complete their functionality. When in
case, you may need to call one dialog box from another and display it as modal. Here is
an example:
The Date and Time dialog box of WordPad is modal: when it is displaying, the user cannot
use any other part of WordPad unless he or she closes th
is object first
After creating a dialog used as an addition to an existing form or an existing dialog box, to
call it as modal, use the ShowDialog() method.
Here is an example:
The Find (and the Replace) dialog box of WordPad (also the Find and the Replace dialog
boxes of most applications) is an example of a modeless dialog box. If it is opened, the
user does not have to close it in order to use the application or the document in the
background.
Since the modeless dialog box does not display its button on the task bar, the user should
know that the dialog box is opened. To make the presence of a modeless dialog box
obvious to the user, it typically displays on top of its host application until the user closes
it.
A modeless dialog box is created from a form but it should look like a regular dialog box
or a tool window. Therefore, to create a modeless dialog box, set
the FormBorderStyle property to an appropriate value such
as FixedSingle, FixedToolWindow, Sizable or SizableToolWindow. Also, set
its ShowInTaskbar property to False.
After creating the dialog box, to display it as modeless, call the Show() method. The
fundamental difference between the ShowDialog() and the Show() methods is that the
former displays a modal dialog box, which makes sure that the called dialog box cannot
go in the background of the main application. By contrast, the Show() method only calls
the dialog box every time it is requested. For this reason, it is up to you to make sure that
the modeless dialog box always remains on top of the application. This is easily taken care
of by setting the BooleanTopMost property of the form to True.
There are two main ways a normal modeless dialog box can be dismissed:
If the user has finished using it, he or she can close it and recall it at will
When the form or application that owns the modeless dialog box is closed, the form
or application closes the modeless dialog if it is opened; this means that you don't
need to find out whether a modeless dialog box is still opened when the application
is being destroyed: either the user or the application itself will take care of closing it
If you visually add two (or more) forms to your application, you
may need to link them, allow one to call the other. To do this,
in the top section of the file, type #include followed by the
name of the header file in which the form was defined. In the
section where you want to access the form, declare a handle to
the class of the form and use the new operator to allocate
memory for it. To display the other form, you can call
its Show() method.
if (dlgEditor.ShowDialog() == DialogResult.OK)
{
ListViewItem lvi = lvwProperties.Items.Add(
rnd.Next(100000, 999999).ToString());
lvi.SubItems.Add(dlgEditor.txtPropertyType.Text);
lvi.SubItems.Add(dlgEditor.txtBedrooms.Text);
lvi.SubItems.Add(dlgEditor.txtBathrooms.Text);
lvi.SubItems.Add(dlgEditor.txtMonthlyRent.Text);
}
}
3. Execute the application and click the New Property... button
4. Create a property
5. Press Enter
6. Create a few more properties and press Enter each time
ADO.NET
Introduction
This article aims at understanding the various concepts and classes available for data access in
ADO.NET. This article is meant for absolute beginners and discusses various techniques of data
access using ADO.NET.
Background
ADO.NET is a set of classes that comes with the Microsoft .NET framework to facilitate data access
from managed languages. ADO.NET has been in existence for a long time and it provides a
comprehensive and complete set of libraries for data access. The strength of ADO.NET is firstly that it
lets applications access various types of data using the same methodology. If I know how to use
ADO.NET to access a SQL Server database then the same methodology can be used to access any
other type of database (like Oracle or MS Access) by just using a different set of classes. Secondly,
ADO.NET provides two models for data access: a connected model where I can keep the connection
with the database and perform data access, and another way is to get all the data in ADO.NET
objects that let us perform data access on disconnected objects.
Note: Many developers and development houses are now using ORMs to perform data access
instead of using ADO.NET. ORMs provide a lot of data access functionality out of the box and
relieves users from writing mundane data access code again and again. Still, I think that knowing and
understanding ADO.NET is crucial as a .NET developer as it gives a better understanding of the data
access methodologies. Also, there are many development houses that are still using ADO.NET.
Let us try to visualize ADO.NET data access using the following diagram:
The diagram above shows that ADO.NET can be used with any kind of application, i.e., it can be used
from a Windows Forms application, an ASP.NET application, or from a WPF and/or Silverlight
application. Also, the data store underneath can be any data store, SQL Server, Access, or Oracle. It is
just a matter of using the right set of classes specific to that data store and the methodology will
remain the same.
Before jumping into the code, we will have to understand some of the important objects of
ADO.NET. In a typical scenario requiring data access, we need to perform four major tasks:
So now we need to understand how we can achieve these functionalities using ADO.NET.
The Connection
The ADO.NET Connection class is used to establish a connection to the database. The Connection
class uses a ConnectionString to identify the database server location, authentication parameters,
and other information to connect to the database. This ConnectionString is typically stored in
the web.config.
<connectionStrings>
<add name="MyConnectionString"
connectionString ="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\PUBS.MDF;
Integrated Security=True;User Instance=True" />
</connectionStrings>
Let us see how we can use the SqlConnection class to establish a connection with a database.
Now we have a connection ready with our database. Whenever we want to retrieve data, we just
need to open the connection, perform the operation, and close the connection.
Before we can jump to understanding how we can execute commands on a database, we first need
to understand how we can store the results and these results can be displayed to the user. To get the
hang of how we can store the results, we need to understand a few ADO.NET objects.
DataReader - A DataReader is an object that can be used to access the results sequentially from a
database. The DataReader is used to get forward only sequential results as the query executes. This
is used with the Command object (we will see the usage shortly).
Dataset - The Dataset can be thought of as an in-memory representation of a database.
A DataSet is a disconnected data access object. The result of the query can be stored in a Dataset.
The DataSet containsDataTables. The DataTables contain DataRow and DataColumns.
A DataSet or a DataTable can be used with a Command and a DataAdapter object to store
query results.
DataAdapter - A DataAdapter object is used to fill a DataSet/DataTable with query results. This
can be thought of as the adapter between the connected and disconnected data models. A
Command object will be used to execute the query and a DataAdapter will use this Command
object and fill the query results coming from the database into a DataSet/DataTable.
Note:
1. There are more objects that can/are used to store results but we will mainly be using these in this
article.
2. The usage and implentation of these objects are in the next section, as understanding the Command
object is required before that.
The Command
Once we have the connection ready, the next step would be to tell the database about what
operation we need to perform on the database. This can be done using the Command object. We will
be using SqlCommand to tell the database about the operation we need to perform. The typical
commands on a database will be:
Note: We are only talking about data manipulation commands in this article.
All these commands expect SQL syntax. This SQL can either be passed from the application or can be
written in the form of Stored Procedures and executed using a SqlCommand.
If we want to use a Stored Procedure with a Command object then we need to specify it as:
cmd = con.CreateCommand();
// This will specify that we are passing the stored procedures name
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = CommandName; // This will be the stored procedures name
If the Stored Procedure is expecting some parameters then we can pass these parameters by
creating instances ofSqlParameter objects as:
If we want to pass a SQL query from our application then we can use the SqlCommand as:
There is one important thing to understand here and that is SqlParameters. Many a times we will
need to pass parameters in our SQL query. This can be done in two ways: we can create a query
using string concatenation like:
This is not recommended as this approach is error prone and is vulnerable to SQL Injection attacks.
So whenever we need to pass parameters to a query the preferred way is using SqlParameters. The
same query can be written as:
Using SqlParameters gives a cleaner, less error prone and SQL injection safe (comparative) code.
Now let us see how we can retrieve the result of a Select command in the form of a DataTable.
cmd = con.CreateCommand();
cmd.CommandType = cmdType;
cmd.CommandText = CommandName;
try
{
con.Open();
SqlDataAdapter da = null;
using (da = new SqlDataAdapter(cmd))
{
da.Fill(table);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd.Dispose();
cmd = null;
con.Close();
}
return table;
}
cmd = con.CreateCommand();
cmd.CommandType = cmdType;
cmd.CommandText = CommandName;
cmd.Parameters.AddRange(param);
try
{
con.Open();
SqlDataAdapter da = null;
using (da = new SqlDataAdapter(cmd))
{
da.Fill(table);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd.Dispose();
cmd = null;
con.Close();
}
return table;
}
Commands like insert, update, delete are executed by calling the ExecuteNonQuery method
of SqlCommand. Let us see how we can write a simple function that will execute these commands.
These commands can be used by passing a query from the application or by invoking Stored
Procedures (same as we saw above).
cmd = con.CreateCommand();
cmd.CommandType = cmdType;
cmd.CommandText = CommandName;
cmd.Parameters.AddRange(pars);
try
{
con.Open();
res = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd.Dispose();
cmd = null;
con.Close();
}
if (res >= 1)
{
return true;
}
return false;
}
The first thing to notice in the application is that it contains a class that is responsible for all the
ADO.NET logic. The class DataAccess (file: DataAccess.cs) contains all the ADO.NET classes and
methods. All the pages use this class. This class can be reused in any application with some minor
application specific changes. The class diagram for the class is:
Authors.aspx
Titles.aspx
AddAuthors.aspx
AddTitles.aspx
The author pages, i.e., Authors.aspx and AddAuthors.aspx, use Stored Procedures to perform the
operations whereas the title pages pass all the queries from the application to the database. We have
mainly implemented Select and Insert commands but Update and Delete can be implemented on the
same lines as Insert.
This should in no way be treated as a design reference for the data access layer. This is only to
demonstrate ADO.NET logic.
The code is written in such a way as to provide a clear understanding from a beginner's perspective,
i.e., experienced programmers will find a lot of possible optimizations in the code.
No client side or server side validations have been provided as that was not the scope of this article.
There is no design (architecture wise and look wise) in this application.
DataSet
Keyword Array Dictionary List String Sub ArrayList Cast
Class Console Dates DataTable DateTime Enum File For Form
at If IndexOf Lambda LINQ Nothing Parse Process Property R
egex Replace Select Sort Split StringBuilder Substring
DataSet stores many DataTables in VB.NET programs. A DataSet is
conceptually a set of DataTables and other information about those
tables. It is an abstraction that makes programs simpler to develop.
Module Module1
Sub Main()
' Two DataTables.
Dim table1 As DataTable = New DataTable("patients")
table1.Columns.Add("name")
table1.Columns.Add("id")
table1.Rows.Add("sam", 1)
table1.Rows.Add("mark", 2)
Output
<office>
<patients>
<name>sam</name>
<id>1</id>
</patients>
<patients>
<name>mark</name>
<id>2</id>
</patients>
<medications>
<id>1</id>
<medication>atenolol</medication>
</medications>
<medications>
<id>2</id>
<medication>amoxicillin</medication>
</medications>
</office>
Using. The Using resource acquisition statement can be used
with the DataSet. This sometimes alleviates memory usage
problems in programs. The following example demonstrates
the correct syntax for the Using statement and a DataSet
instance.
VB.NET program that shows Using statement with DataSet
Module Module1
Sub Main()
Using set1 As DataSet = New DataSet("office")
' Use set1 here.
End Using
End Sub
End Module
Namespace, Prefix. One of the uses of DataSet is that it
allows you to get XML data for its contents. This can
generate complete XML files. With the Namespace and Prefix
properties, you can form correct XML for your specific
application's requirements.
Module Module1
Sub Main()
' Create DataTable.
Output
<x:office xmlns:x="y">
<patients xmlns="y">
<name>sam</name>
<id>1</id>
</patients>
</x:office>
DataSetName. It is possible to change the name of your
DataSet. When you call the DataSet constructor with a String
argument, that sets the initial name. You can also modify or
read the name by using the DataSetName String property.
VB.NET program that uses DataSetName
Module Module1
Sub Main()
' Initialize DataSet.
Dim set1 As DataSet = New DataSet("office")
End Module
Output
office
unknown
Copy, Clear. The DataSet provides ways for you to copy the
entire contents of it into another object. You can use the
Copy function for this purpose. We also show the Clear
subroutine here, which scrubs the contents of the enclosed
DataTables.
Module Module1
Sub Main()
Dim table1 = New DataTable("patients")
table1.Columns.Add("name")
table1.Columns.Add("id")
table1.Rows.Add("sam", 1)
' Copy.
Dim copy As DataSet = set1.Copy()
Output
Module Module1
Sub Main()
Dim table1 As DataTable = New DataTable("patients")
table1.Columns.Add("name")
table1.Columns.Add("id")
table1.Rows.Add("sam", 1)
table2.Rows.Add(1, "atenolol")
table2.Rows.Add(6, "trifluoperazine")
Output
0: patients
1: medications
x: patients
y: 2
Let us look into a small example which explain the Typed DataSet,
1. Using DataSet:
//Create DataAdapter
SqlDataAdapter daEmp = new SqlDataAdapter("SELECT empno,empname,empaddress
FROM EMPLOYEE",conn);
//Create a DataSet Object
DataSet dsEmp = new DataSet();
//Fill the DataSet
daEmp.Fill(dsEmp,"EMPLOYEE");
//Let us print first row and first column of the table
Console.Write(dsEmp.Tables["EMPLOYEE"].Rows[0][0].ToString());
//Assign a value to the first column
dsEmp.Tables["EMPLOYEE"].Rows[0][0] = "12345";//This will generate runtime error as
empno column is integer
If we observe above code we will get a runtime error when this code gets
executed as the value assigned to the column (empno) does not take string
value. Also any misspell of the column will generate a runtime error. And
also we need to go thro the hierarchy to get the final value.
//Create DataAdapter
SqlDataAdapter daEmp = new SqlDataAdapter("SELECT empno,empname,empaddress
FROM EMPLOYEE",conn);
//Create a DataSet Object
EmployeeDS dsEmp = new EmployeeDS ();
//Fill the DataSet
daEmp.Fill(dsEmp,"EMPLOYEE");
//Let us print first row and first column of the table
Console.Write(dsEmp.EMPLOYEE[0].empno.ToString());
//Assign a value to the first column
dsEmp.EMPLOYEE[0].empno = "12345";//This will generate compile time error.
1. Open VS .Net IDE and Click on File -> New -> Project and Select Console
Application.
2. Enter name for the project. Say TypedDataSetTest.
3. Right click on the solution and click on Add-> Add New Item will show a
dialog box.
Select DataSet from templates pane, give the name (Say TypedDs.xsd) and
click on Open. This will add file by name TypedDs.xsd to the solution.
4. Click on the Server Explorer browse to the database and drop the table on
the TypedDs.xsd file.
If we check the xml file for the same then we can see the schema for the
table.
This dataset can be used in the same manner as the normal dataset to get
the data.
C# ADO.NET DataAdapter
DataAdapter is a part of the ADO.NET Data Provider. DataAdapter
provides the communication between the Datasetand the
Datasource. We can use the DataAdapter in combination with the
DataSet Object. DataAdapter provides this combination by mapping
Fill method, which changes the data in the DataSet to match the
data in the data source, and Update, which changes the data in the
data source to match the data in the DataSet. That is, these two
objects combine to enable both data access and data manipulation
capabilities.
C# ADO.NET SqlDataAdapter
CS6001 C# AND .NET PROGRAMMING Unit III
Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]
adapter.Fill(ds);
using System;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
C# ADO.NET OleDbDataAdapter
The OleDbDataAdapter is a part of the C# ADO.NET Data Provider
and it resides in the System.Data.OleDb namespace. The
OleDbDataAdapter provides the communication between the
Dataset and the OleDb Data Sources. We can use
OleDbDataAdapter Object in combination with Dataset Object.
DataAdapter provides this combination by mapping Fill method,
which changes the data in the DataSet to match the data in the
data source, and Update, which changes the data in the data source
to match the data in the DataSet.
OleDbDataAdapter oledbAdapter = new OleDbDataAdapter(sql, oledbCnn);
oledbAdapter.Fill(ds);
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=Your mdb filename;";
sql = "Your SQL Statement Here like Select * from product";
2. Functions can have only input parameters for it, whereas procedures can
have input/output parameters.
Note: Sometimes we face a question, why we can't execute stored procedure inside
a function?
Answer:
So executing function inside stored procedure will never break rule 1, but executing
stored procedure inside function may break rule 2.
So ultimately strict rule is made that we can't execute stored procedures inside
function.
Now we can call stored procedure from our code like the following for Insert
operation.
We can call stored procedure from our code like the following for Delete operation.
We can call stored procedure from our code like the following for Update operation.
connetionString="Data Source=ServerName;
Initial Catalog=DatabaseName;User ID=UserName;Password=Password"
If you have a named instance of SQL Server, you'll need to add that
as well.
"Server=localhost\sqlexpress"
cnn.Close();
using System;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn ;
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show ("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}
connetionString="Data Source=IP_ADDRESS,PORT;
Network Library=DBMSSOCN;Initial Catalog=DatabaseName;
User ID=UserName;Password=Password"
connetionString="Data Source=ServerName;
Initial Catalog=DatabaseName;Integrated Security=SSPI;
User ID=myDomain\UserName;Password=Password;
using System;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection ;
SqlCommand command ;
string sql = null;
SqlDataReader dataReader ;
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Your SQL Statement Here , like Select * from product";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
MessageBox.Show(dataReader.GetValue(0) + " - " +
dataReader.GetValue(1) + " - " + dataReader.GetValue(2));
}
dataReader.Close();
command.Dispose();
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
C# OLEDB Connection
The C# OleDbConnection instance takes Connection String as
argument and pass the value to the Constructor statement. An
instance of the C# OleDbConnection class is supported theOLEDB
Data Provider .
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=yourdatabasename.mdb;";
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
C# ODBC Connection
An instance of the OdbcConnection Class in C# is supported the
ODBC Data Provider. The OdbcConnection instance takes
Connection String as argument and pass the value to the
Constructor statement. When the connection is established between
C# application and the Data Source the SQL Commands will execute
with the help of the Connection Object and retrieve or manipulate
data in the database.
connetionString = "Driver={Microsoft Access Driver (*.mdb)};
DBQ=yourdatabasename.mdb;";
The Close method rolls back any pending transactions and releases
the Connection from the Database connected by theODBC Data
Provider .
using System;
using System.Windows.Forms;
using System.Data.Odbc;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
C# ADO.NET Command
The Command Object in ADO.NET executes SQL statements and
Stored Procedures against the data source specified in the C#
Connection Object. The Command Object requires an instance of a
C# Connection Object for executing the SQL statements .
Click the following links to see some important built in methods uses
in the Command Object to execute the SQL statements.
C# ExecuteNonQuery
C# ExecuteReader
C# ExecuteScalar
C# ADO.NET SqlCommand -
ExecuteNonQuery
The ExecuteNonQuery() is one of the most frequently used
method in SqlCommand Object, and is used for executing
statements that do not return result sets (ie. statements like insert
data , update data etc.) .
Command.ExecuteNonQuery();
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
try
{
cnn.Open();
cmd = new SqlCommand(sql, cnn);
cmd.ExecuteNonQuery();
cmd.Dispose();
cnn.Close();
MessageBox.Show (" ExecuteNonQuery in SqlCommand executed
!!");
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}
The Data Definition tasks like creating Stored Procedures, Views etc.
perform by the ExecuteNonQuery() . Also Data Manipulation tasks
like Insert , Update , Delete etc. perform by the
ExecuteNonQuery().
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
connetionString =
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;"
sql = "Your SQL Statement Here"
If the Result Set contains more than one columns or rows , it will
take only the value of first column of the first row, and all other
values will ignore. If the Result Set is empty it will return
a NULLreference.
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
using System;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Try: A Try block identifies a block of code for which particular exceptions
will be activated. It's followed by one or more Catch blocks.
Syntax
Assuming a block will raise an exception, a method catches an exception
using a combination of the Try and Catch keywords. A Try/Catch block is
placed around the code that might generate an exception. Code within a
Try/Catch block is referred to as protected code, and the syntax for using
Try/Catch looks like the following:
Try
[ tryStatements ]
[ Exit Try ]
[ catchStatements ]
[ Exit Try ] ]
[ Catch ... ]
[ Finally
[ finallyStatements ] ]
End Try
You can list down multiple catch statements to catch different type of
exceptions in case your try block raises more than one exception in
different situations.
Handling Exceptions
VB.Net provides a structured solution to the exception handling problems in
the form of try and catch blocks. Using these blocks the core program
statements are separated from the error-handling statements.
Module exceptionProg
Try
Catch e As DivideByZeroException
Finally
End Try
End Sub
Sub Main()
division(25, 0)
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following
result:
at ...
Result: 0
Module exceptionProg
MyBase.New(message)
End Sub
End Class
Sub showTemp()
If (temperature = 0) Then
Else
End If
End Sub
End Class
Sub Main()
Try
temp.showTemp()
Catch e As TempIsZeroException
End Try
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following
result:
Throwing Objects
You can throw an object if it is either directly or indirectly derived from the
System.Exception class.
You can use a throw statement in the catch block to throw the present
object as:
Throw [ expression ]
Module exceptionProg
Sub Main()
Try
Catch e As Exception
Console.WriteLine(e.Message)
Finally
End Try
Console.ReadKey()
End Sub
End Module
When the above code is compiled and executed, it produces the following
result:
ASP.NET - Validators
ASP.NET validation controls validate the user input data to ensure that
useless, unauthenticated, or contradictory data don't get stored.
RequiredFieldValidator
RangeValidator
CompareValidator
RegularExpressionValidator
CustomValidator
ValidationSummary
BaseValidator Class
The validation control classes are inherited from the BaseValidator class
hence they inherit its properties and methods. Therefore, it would help to
take a look at the properties and the methods of this base class, which are
common for all the validation controls:
Members Description
RequiredFieldValidator Control
The RequiredFieldValidator control ensures that the required field is not
empty. It is generally tied to a text box to force input into the text box.
<asp:RequiredFieldValidator ID="rfvcandidate"
</asp:RequiredFieldValidator>
RangeValidator Control
The RangeValidator control verifies that the input value falls within a
predetermined range.
Properties Description
Type It defines the type of the data. The available values are:
Currency, Date, Double, Integer, and String.
MinimumValue="6" Type="Integer">
</asp:RangeValidator>
CompareValidator Control
The CompareValidator control compares a value in one control with a fixed
value or a value in another control.
Properties Description
ErrorMessage="CompareValidator">
</asp:CompareValidator>
RegularExpressionValidator
The RegularExpressionValidator allows validating the input text by matching
against a pattern of a regular expression. The regular expression is set in
the ValidationExpression property.
The following table summarizes the commonly used syntax constructs for
regular expressions:
\b Matches a backspace.
\t Matches a tab.
\ Escape character.
Metacharacters Description
Quantifier Description
{N} N matches.
ValidationExpression="string" ValidationGroup="string">
</asp:RegularExpressionValidator>
CustomValidator
The CustomValidator control allows writing application specific custom
validation routines for both the client side and the server side validation.
The server side validation routine must be called from the control's
ServerValidate event handler. The server side validation routine should be
written in any .Net language, like C# or VB.Net.
ClientValidationFunction=.cvf_func. ErrorMessage="CustomValidator">
</asp:CustomValidator>
ValidationSummary
The ValidationSummary control does not perform any validation but shows
a summary of all errors in the page. The summary displays the values of
the ErrorMessage property of all validation controls that failed validation.
The following two mutually inclusive properties list out the error message:
Validation Groups
Complex pages have different groups of information provided in different
panels. In such situation, a need might arise for performing validation
separately for separate group. This kind of situation is handled using
validation groups.
To create a validation group, you should put the input controls and the
validation controls into the same logical group by setting
their ValidationGroupproperty.
Example
The following example describes a form to be filled up by all the students of
a school, divided into four houses, for electing the school president. Here,
we use the validation controls to validate the user input.
<tr>
<asp:Label ID="lblmsg"
runat="server" />
</td>
</tr>
<tr>
<td class="style3">
Candidate:
</td>
<td class="style2">
<asp:ListItem>M H Kabir</asp:ListItem>
<asp:ListItem>Steve Taylor</asp:ListItem>
<asp:ListItem>John Abraham</asp:ListItem>
<asp:ListItem>Venus Williams</asp:ListItem>
</asp:DropDownList>
</td>
<td>
<asp:RequiredFieldValidator ID="rfvcandidate"
</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td class="style3">
House:
</td>
<td class="style2">
<asp:ListItem>Red</asp:ListItem>
<asp:ListItem>Blue</asp:ListItem>
<asp:ListItem>Yellow</asp:ListItem>
<asp:ListItem>Green</asp:ListItem>
</asp:RadioButtonList>
</td>
<td>
</asp:RequiredFieldValidator>
<br />
</td>
</tr>
<tr>
<td class="style3">
Class:
</td>
<td class="style2">
</td>
<td>
<asp:RangeValidator ID="rvclass"
runat="server" ControlToValidate="txtclass"
MinimumValue="6" Type="Integer">
</asp:RangeValidator>
</td>
</tr>
<tr>
<td class="style3">
Email:
</td>
<td class="style2">
</asp:TextBox>
</td>
<td>
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
</td>
</tr>
</table>
</form>
if (Page.IsValid)
else
3) Add your settings into this file using the following as a template
<configuration>
<appSettings>
<add key="setting1" value="key"/>
</appSettings>
<connectionStrings>
<add name="prod" connectionString="YourConnectionString"/>
</connectionStrings>
</configuration>
4)Retrieve them like this :
private void Form1_Load(object sender, EventArgs e)
{
string setting = ConfigurationManager.AppSettings["setting1"];
string conn =
ConfigurationManager.ConnectionStrings["prod"].ConnectionString;
}
5) When built, your output folder will contain a file called
<assemblyname>.exe.config This will be a copy of the App.Config file. No further
work should need to be done by the developer to create this file.
Ref :
https://msdn.microsoft.com/libr
ary
https://en.wikipedia.org
http://www.functionx.com/vcsharp2008/form/dialogboxes3.htm
http://www.dotnetperls.com/dataset-vbnet
http://www.c-
sharpcorner.com/UploadFile/rupadhyaya/TypedDataSets12032005021013AM/TypedDataSets.aspx
http://www.c-sharpcorner.com/blogs/insert-delete-and-update-using-stored-procedure-in-asp-net1