Sunteți pe pagina 1din 123

C# 3.

0: A Beginners Guide [Notes]

Chapter 1: C# Fundamentals

1. To create, compile, and run a C# program, We will need a copy of Microsofts Visual C# which is the compiler that supports C# 3.0. 2. Using Visual C#, there are two general approaches we can take to creating, compiling, and running a C# program. First, we can use the Visual Studio IDE. Second, we can use the command-line compiler, csc.exe. 3. Using Visual Studio IDE:-A. Create a new, empty C# project by selecting File | New Project. Next, Web then select Empty Project. B. Add CodeFile as a Add New Item, Write the Code C. Compile the program by selecting Build Solution from the Build menu. D. Run the program by selecting Start without Debugging from the Debug menu 4. Using csc.exe, the C# Command-Line Compiler:-A. Enter the program using a text editor. B. Compile the program using csc.exe. Syntax: C:\>csc FileName.cs C. Run the program. Syntax: C:\>FileName 5. The csc compiler creates a file called Example.exe that contains the MSIL version of the program. Although MSIL is not executable code, it is still contained in an exe file. The Common Language Runtime automatically invokes the JIT compiler when you attempt to execute Example.exe. 6. Be aware, however, that if you try to execute Example.exe (or any other exe file that contains MSIL) on a computer for which the .NET Framework is not installed, the program will not execute, because the CLR will be missing. 7. C# supports three styles of comments:-A. Multiline comment. B. Single line comment Page | 1

C# 3.0: A Beginners Guide [Notes]


C. XML comment or documentation comment:i. It uses XML tags to help you create self-documenting code. 8. C# compiler will compile classes that do not contain a Main() method, there is no way to use one as an entry point for executing your program. 9. All C# applications begin execution by calling Main(). C# is case-sensitive. 10. If you had mistyped Main, the compiler would still compile your program. However, you would also see an error message that states that Example.exe does not have an entry point defined. 11. A variable is a named memory location that can be assigned a value. It is called a variable because its value can be changed during the execution of a program. Syntax: type var-name; Eg: int length, width; 12. All variables must be declared before they are used. 13. Implicitly typed variables are variables whose type is automatically determined by the compiler. It still needs to be declared. Instead of using a type name, such as int, an implicitly typed variable is declared using the var keyword. 14. The Write() method is just like WriteLine(), except that it does not output a new line after each call. 15. C# defines two floating-point types: float and double, which represent single- and doubleprecision values, respectively. [Need to work] 16. Why arent all numeric values just the same type? A. Faster in calculations [No need to incur the overhead] B. Amount of memory 17. Syntax: if(condition) statement; Here, condition is a Boolean (that is, true or false) expression. If condition is true, then the statement is executed. If condition is false, then the statement is bypassed. EG: if(10 < 11) Console.WriteLine("10 is less than 11"); Page | 2

C# 3.0: A Beginners Guide [Notes]

18. Syntax:

for(initialization; condition; iteration) statement;

19. A code block is a grouping of statements. A code block is created by enclosing the statements between opening and closing curly braces. a block can be a target for if and for statements. Code blocks do not add any overhead whatsoever. 20. In C#, an identifier is a name assigned to a method, a variable, or any other user-defined item. 21. Variable names may start with any letter of the alphabet or with an underscore. You cant start an identifier with a digit. Although you cannot use any of the C# keywords as identifiers, C# does allow you to precede a keyword with an @, allowing it to be a legal identifier. EG: @for is a valid identifier. In this case, the identifier is actually for and the @ is ignored. 22. C# defines two general types of keywords: reserved and contextual. A. The reserved keywords cannot be used as names for variables, classes, or methods. There are currently 77 reserved keywords B. C# 3.0 defines 13 contextual keywords that have a special meaning in certain contexts. In those contexts, they act as keywords. Outside their context, they can be used as names for other program elements, such as variable names. 23. The C# environment relies on the .NET Framework class library to provide support for such things as I/O, string handling, networking, and GUIs. Thus, C# as a totality is a combination of the C# language itself, plus the .NET standard classes. 24. Formula for C to F: C = 5/9 * (F 32) 25. Object-Oriented Programming:-In an object-oriented language, you define the data and the routines that are permitted to act on that data. Object-oriented programming took the best ideas of structured programming and combined them with several new concepts. The result was better way of organizing a program. A. Encapsulation: Putting same type of data together. B. Polymorphism: Ability to present in more than one form. C. Abstraction: Process of hiding the complexity of a program a different and

Page | 3

C# 3.0: A Beginners Guide [Notes]


D. Inheritance: Process by which one object can acquire the properties of another object.

26. The Evolution of C#:27. How C# Relates to the .NET Framework? Although C# is a computer language that can be studied on its own, it has a special relationship to its runtime environment, the .NET Framework. The reason for this is twofold. First, C# was initially designed by Microsoft to create code for the .NET Framework. Second, the libraries used by C# are the ones defined by the .NET Framework. Thus, even though it is separate the C# language from the .NET environment, the two are closely linked. 28. What is the .NET Framework? In a sentence, the .NET Framework defines an environment that supports the development and execution of highly distributed, component-based applications. It enables different computer languages to work together and provides for security, program portability, and a common programming model for the Windows platform. Common Language Runtime: This is the system that manages the execution of your program. Along with other benefits, the Common Language Runtime is the part of the .NET Framework that enables programs to be portable, supports mixed-language programming, and provides for security. The second entity is the .NET class library. This library gives your program access to the runtime environment. 29. How the Common Language Runtime Works? When you compile a C# program, the output of the compiler is not executable code. Instead, it is a file that contains a special type of pseudo code called Microsoft Intermediate Language, or MSIL for short. MSIL defines a set of portable instructions that are independent of any specific CPU. In essence, MSIL defines a portable assembly language. One other point: Although MSIL is similar in concept to Javas bytecode, the two are not the same. It is the job of the CLR to translate the intermediate code into executable code when a program is run. Thus, any program compiled to MSIL can be run in any environment for which the CLR is implemented. This is part of how the .NET Framework achieves portability. Microsoft Intermediate Language is turned into executable code using a JIT compiler. JIT stands for just in time. The process works like this: When a .NET program is executed, the CLR activates the JIT compiler. The JIT compiler converts MSIL into native code on a demand basis, as each part of your program is needed. Thus, your C# program actually executes as native code, even though it was initially compiled into MSIL. possible to

30. Managed vs. Unmanaged Code Page | 4

C# 3.0: A Beginners Guide [Notes]


A. A. In general, when you write a C# program, you are creating what is called managed code. Managed code is executed under the control of the Common Language Runtime, as just described B. The opposite of managed code is unmanaged code. Unmanaged code does not execute under the Common Language Runtime. 31. The Common Language Specification If your code will be used by other programs written in different languages, for maximum usability, it should adhere to the Common Language Specification (CLS). The CLS describes a set of features, such as data types, that different languages have in common.

Page | 5

C# 3.0: A Beginners Guide [Notes]


Chapter 2: Introducing Data Types and Operators:

1. C# contains two general categories of built-in data types: value types and reference types. A. For a value type, a variable holds an actual value, such 101 or 98.6. B. For a reference type, a variable holds a reference to the value. The most commonly used reference type is the class. 2. At the core of C# are the 13 value types. Collectively, these are referred to as the simple types. They are called simple types because they consist of a single value. Table: Integer Types int short long uint ushort ulong byte sbyte char Floating-Point Types double float Others bool decimal Represents true/false values Numeric type for financial calculations 128 Double-precision floating point Single-precision floating point 32 64 Integer Short integer Long integer Unsigned integer Unsigned short integer Unsigned long integer 8-bit unsigned integer 8-bit signed integer Character is an unsigned Meaning 32 16 64 32 16 64 8 8 16 Width in Bits

Page | 6

C# 3.0: A Beginners Guide [Notes]


3. In addition to the simple types, C# defines three other categories of value types. These are A. enumerations, B. structures, and C. nullable types 4. The difference between signed and unsigned integers is in the way the high-order bit of the integer is interpreted. 5. If a signed integer is specified, the C# compiler will generate code that assumes the highorder bit of an integer is to be used as a sign flag. If the sign flag is 0, the number is positive; if it is 1, the number is negative but they have only half the absolute magnitude of their unsigned relatives. 6. Of the two, double is the most commonly used. One reason for this is that many of the math functions in C#s class library (which is the .NET Framework library) use double values. EG: the Sqrt() method (which is defined by the System.Math class) returns a double value that is the square root of its double argument. 7. Normal floating-point arithmetic is subject to a variety of rounding errors when it is applied to decimal values. The decimal type eliminates these errors and can accurately represent up to 28 decimal places (or 29 places, in some cases). Useful for computations that involve money. 8. decimal values must be followed by an m or M. Syntax: decimal balance= 1000.10m; 9. In C#, characters are not 8-bit quantities like they are in many other computer languages, such as C++. Instead, C# uses Unicode. Unicode defines a character set that can represent all of the characters found in all human languages. Thus, in C#, char is an unsigned 16-bit type having a range of 0 to 65,535. Syntax: char ch = 'X'; 10. Some Output Options: Syntax: {argnum, width: format} A. Console.WriteLine("Here is 10/3: " + 10.0/3.0); B. Console.WriteLine("February has {0} or {1} days.", 28, 29); C. Console.WriteLine("Here is 10/3: {0:#.##}", 10.0/3.0); D. decimal balance= 12323.09m; Console.WriteLine("Current balance is {0:C}", balance); E. Console.WriteLine("February has {0,10} or {1,5} days.", 28, 29); Page | 7

C# 3.0: A Beginners Guide [Notes]

Output: A. Here is 10/3: 3.33333333333333 B. February has 28 or 29 days. C. Here is 10/3: 3.33 Note: However, that WriteLine( ) will display more than one digit to the left of the decimal point D. Current balance is $12,323.09 E. February has 28 or 29 days. 11. literals refer to fixed values that are represented in their human-readable form. For example, the number 100 is a literal. C# literals can be of any of the value types. The way each literal is represented depends upon its type. As explained earlier, character literals are enclosed between single quotes. For example a and % are both character literals. 12. What is the type of a numeric literal? A. An integer literal is of type int, uint, long, or ulong, depending upon its value. B. Floating-point literals are of type double. C. To specify a long literal, append an l or an L. For example, 12 is an int, but 12L is a long. D. To specify an unsigned integer value, append a u or U. Thus, 100 is an int, but 100U is a uint. E. To specify an unsigned, long integer, use ul or UL. For example, 984375UL is of type ulong. F. To specify a float literal, append an F or f. For example, 10.19F is of type float. Although redundant, you can specify a double literal by appending a D or d. (As just mentioned, floating-point literals are double by default.) G. Although integer literals create an int, uint, long, or ulong value by default, they can still be assigned to variables of type byte, sbyte, short, or ushort as long as the value being assigned can be represented by the target type. 13. Hexadecimal Literals:-count = 0xFF; // 255 in decimal incr = 0x1a; // 26 in decimal [F=15, (15*16^1)+(25*16^0)=255] [A=10, (1*16^1)+(10*16^0)=26]

Page | 8

C# 3.0: A Beginners Guide [Notes]


14. String Literals:--"this is a test". 15. C# allows integer literals to be specified only in decimal or hexadecimal form. 16. A verbatim string literal begins with an @, which is followed by a quoted string. The contents of the quoted string are accepted without modification. 17. C# defines several different kinds of variables. The kinds that we have been using are called local variables because they are declared within a method. 18. Is k the same as k? No 19. C# allows variables to be initialized dynamically, using any expression valid at the point at which the variable is declared. 20. It is possible to let the compiler determine the type of a variable based on the value used to initialize it. This is called an implicitly typed variable. An implicitly typed variable is declared using the keyword var, and it must be initialized. var radius=10; //radius is of type int radius = 12.2; // Error! 21. One last point: Only one implicitly typed variable can be declared at any one time. Therefore, the following declaration var count = 10, max = 20; // Error! 22. A block defines a scope. when you declare a variable within a scope, you are preventing it from being accessed or modified by code outside the scope. Indeed, the scope rules provide the foundation for encapsulation. 23. Although blocks can be nested, no variable declared within an inner scope can have the same name as a variable declared by an enclosing scope. 24. p ^ q[xor]=same false 25. Short-Circuit Logical Operators, && and || The only difference between the normal and short-circuit versions is that the normal operands will always evaluate each operand, but short-circuit versions will evaluate the second operand only when necessary. if(false & (++i < 100)){} if(false && (++i < 100)){} i is incremented i is not incremented Page | 9

C# 3.0: A Beginners Guide [Notes]

26. Compound assignment:x += 10; which means: x = x + 10; 27. Type Conversion: assign a value of one type to a variable of another type. 28. When one type of data is assigned to another type of variable, an implicit type conversion will take place automatically, if: A. The two types are compatible. B. The destination type is larger than the source type 29. When these two conditions are met, a widening conversion takes place. 30. There are no implicit conversions between decimal and float or double, or from the numeric types to char or bool. Also, char and bool are not compatible with each other. 31. Casting Incompatible Types:--A cast is an instruction to the compiler to convert an expression into a specified type. Thus, it requests an explicit type conversion. Syntax: (target-type) expression EG: double x, y; // ... (int) (x / y) Note: A. The parentheses surrounding x / y are necessary. Otherwise, the cast to int would apply only to the x, and not to the outcome of the division B. When a cast involves a narrowing conversion, information might be lost. 32. Cast required between incompatible types. EG: byte b = 88; // ASCII code for X ch = (char) b; 33. When the attempt is made to assign byte b the value 257, information loss occurs because 257 exceed a bytes range. This results in b having the value 1 because only the 1 bit is set in the low-order 8 bits of the binary representation of 257 34. C#s type promotion rules:

Page | 10

C# 3.0: A Beginners Guide [Notes]


IF one operand is decimal, THEN the other operand is promoted to decimal (Unless it is of type float or double, in which case an error results). ELSE IF one of the operands is double, the second is promoted to double. ELSE IF one operand is a float operand, the second is promoted to float. ELSE IF one operand is a ulong, the second is promoted to ulong (unless it is of type sbyte, short, int, or long, in which case an error results). ELSE IF one operand is a long, the second is promoted to long. ELSE IF one operand is a uint and the second is of type sbyte, short, or int, both are promoted to long. ELSE IF one operand is a uint, the second is promoted to uint. ELSE both operands are promoted to int. EG: byte b = 10; b = (byte) (b * b); Cast needed char ch1 = 'a', ch2 = 'b'; ch1 = (char) (ch1 + ch2);

Page | 11

C# 3.0: A Beginners Guide [Notes]

Chapter 3: Program Control Statements:

1. Inputting Characters from the Keyboard char ch; ch = (char) Console.Read(); This method waits until the user presses a key and then returns the key. The character is returned as an integer, so it must be cast to char to assign it to a char variable. By default, console input is line-buffered, so you must press ENTER before any character that you type will be sent to your program. 2. char ch='P', answer = 'K'; if(ch == answer) 3. The switch Statement-switch(expression) { case constant1: statement sequence break; . . default: statement sequence break; } 4. The switch expression must be an integral type, such as char, byte, short, or int; an enumeration type; or type string. The case constants must be of a type compatible with the expression. 5. In C#, it is an error for the statement sequence associated with one case to continue on into the next case. This is called the no fall-through rule. This is why case sequences end with break. The default sequence must also not fall through, and it, too, usually ends with a break. 6. switch(i) { case 1: case 2: case 3: Console.WriteLine("i is 1, 2 or 3"); break; case 4: Console.WriteLine("i is 4"); Page | 12 [Optional]

C# 3.0: A Beginners Guide [Notes]


break; } If 'Any' break removed, it will show Error: Control cannot 'fall through' from one case label ('case 3:') to another 7. In this fragment, if i has the value 1, 2, or 3, the first WriteLine() statement executes. If it is 4, the second WriteLine() statement executes. The stacking of cases does not violate the no fallthrough rule because the case statements all use the same statement sequence. 8. Under what conditions should I use an if-else-if ladder rather than a switch when coding a multiway branch? A. In general, use an if-else-if ladder when the conditions controlling the selection process do not rely upon a single value. For example, consider the following if-elseif sequence: if(x == 10) // ... else if(ch == 'a') // ... else if(done == true) // ... B. Use when testing floating-point values or when testing other objects that are not of types valid for use in a switch expression C. If you will be testing for some other relationship, such as less than or not equal, you must use an if-else-if ladder. 9. The case constants of the inner and outer switch can contain common values, and no conflicts will arise. 10. for Loop: for(i=0, j=10; i < j; i++, j--) Console.WriteLine("i and j: " + i + " " + j); The output from the program is shown here: i and j: 0 10 i and j: 1 9 i and j: 2 8 i and j: 3 7 i and j: 4 6 11. The condition controlling the for loop can be any valid expression that produces a bool result. It does not need to involve the loop control variable.

Page | 13

C# 3.0: A Beginners Guide [Notes]


12. for(;;) // intentionally infinite loop { //... } 13. for(i = 1; i <= 5; sum += i++) ; valid 14. The while Loop: while(condition) statement;

15. Use a for loop when performing a known number of iterations. Use the do-while when you need a loop that will always perform at least one iteration. The while is best used when the loop will repeat an unknown number of times. 16. The do while Loop: do { statements; } while(condition); 17. // read a letter, but skip cr/lf do { ch = (char) Console.Read(); // get a char } while(ch == '\n' | ch == '\r'); Here is why this loop is needed. As explained earlier, console input is line-bufferedyou have to press ENTER before characters are sent. Pressing ENTER causes a carriage-return and a linefeed character to be generated. These characters are left pending in the input buffer. This loop discards those characters by continuing to read input until neither is present. 18. The given loop wont discard the a carriage-return and a linefeed character static void Main() { char ch; do { Console.Write("Press a key : "); ch = (char)Console.Read(); Console.WriteLine("You pressed: {0}", ch); } while(ch != 'q'); } Press a key : A You pressed: A Press a key : You pressed: Press a key : You pressed: [carriage-return] [linefeed character] Page | 14

C# 3.0: A Beginners Guide [Notes]

Press a key : 19. Use break to Exit a Loop 20. The continue statement forces the next iteration of the loop to take place, skipping any code in between. 21. The break statement in the inner loop causes only the termination of that loop. The outer loop is unaffected. 22. The break that exits a switch statement affects only that switch statement and not any enclosing loops. 23. continue is essentially the complement of break. 24. In while and do-while loops, a continue statement will cause control to go directly to the conditional expression. In the case of the for, the iteration expression of the loop is evaluated and then the conditional expression is executed. 25. goto: The goto is C#s unconditional jump statement. 26. The goto requires a label for operation. A label is a valid C# identifier followed by a colon. Furthermore, the label must be in the same method as the goto that uses it. 27. EG: x = 1; loop1: x++; if(x < 100) goto loop1; 28. The goto does have one important restriction: You cannot jump into a block. Of course, you can jump out of a block 29. The goto can be used to jump to a case or default label within a switch. 30. You cannot jump into the middle of a switch from code outside the switch because a switch defines a block.

Page | 15

C# 3.0: A Beginners Guide [Notes]

Chapter 4: Introducing Classes, Objects, and Methods:

1. A class is a template that defines the form of an object. 2. A class contains data and the code that operates on it 3. A class is a logical abstraction. 4. A class typically contains data member and member methods. 5. Objects are instances of a class. 6. In general terms, data is contained in instance variables defined by the class, and code is contained in methods. 7. It is important to state at the outset, however, that C# defines several specific flavors of members, which include instance variables, static variables, constants, methods, constructors, destructors, indexers, events, operators, and properties. 8. Syntax: class classname { // Declare instance variables. access type var1; // Declare methods. access ret-type method1(parameters) { // body of method } } 9. The access specifier is optional and, if absent, the member is private to the class. 10. A class supports encapsulation. 11. Aside from the access specifier, you declare an instance variable in the same way that you declare local variables. 12. A class declaration is only a type description; it does not create an actual object. 13. To actually create a class object, you will use a statement like the following: Page | 16

C# 3.0: A Beginners Guide [Notes]


ClassName objRefName= new ClassName (); This declaration performs three functions: A. It declares a variable called 'objRefName' of the class type 'ClassName' B. The declaration creates an actual, physical instance of the object. This is done by using the new operator C. It assigns to 'objRefName' a reference to that object. Note: 'objRefName' does not, itself, contain the object. Instead, it contains a reference to the object. 14. To access these members you will use the member access operator, which is a period. Syntax: objName.member 15. CodeFile.cs may contain many related classes. Compiling this CodeFile.cs creates a file called CodeFile.exe. All related classes are automatically part of the executable file. 16. Each time you create an instance of a class, you are creating an object that contains its own copy of each instance variable defined by the class. 17. When you assign one value type variable to another, the situation is straightforward. The variable on the left receives a copy of the value of the variable on the right. 18. When you assign one object reference variable to another, the situation is a bit more complicated because you are causing the variable on the left to refer to the object referred to by the variable on the right. 19. A subsequent assignment to 'objRefName' simply changes what object 'objRefName' refers to. 20. Method: Methods are subroutines that manipulate the data defined by the class and, in many cases, provide access to that data. Syntax: access ret-type name(parameter-list) { // body of method return; //optional in case of void ret-type } 21. void methods: Those that do not return a value. 22. We can use the value returned value from method for other calculations. Page | 17

C# 3.0: A Beginners Guide [Notes]

23. I have heard that C# detects unreachable code. What does this mean? The C# compiler will issue a warning message if you create a method that contains code that no path of execution will ever reach. 24. Constructors: A. Constructors are used to initialize the value of an object. B. Name of Constructor is as same as class name. C. No explicit return Type. D. Two types: Default and Parameterized access class-name(param-list) { // constructor code } 25. All classes have constructors, whether you define one or not, because C# automatically provides a default constructor that causes all member variables to be initialized to their default values. For most value types, the default value is zero. For bool, the default is false. For reference types, the default is null. 26. As a point of interest, it is permitted to use new with the value types, as shown here: int i = new int(); 27. C#s garbage collection system reclaims objects automatically when no references to an object exist. Garbage collection occurs only sporadically during the execution of your program. 28. Destructors: A. It is possible to define a method that will be called just prior to an objects final destruction by the garbage collector. This method is called a destructor. B. It is preceded with a ~ (tilde) Syntax: ~class-name( ) { // destruction code } 29. The this Keyword: When a method is called, it is automatically passed a reference to the invoking object (that is, the object on which the method is called). This reference is called this.

Page | 18

C# 3.0: A Beginners Guide [Notes]


30. C# permits the name of a parameter or a local variable to be the same as the name of an instance variable. When this happens, the local name hides the instance variable. You can gain access to the hidden instance variable by referring to it through this.

Page | 19

C# 3.0: A Beginners Guide [Notes]


Chapter 5: More Data Types and Operators

Page | 20

C# 3.0: A Beginners Guide [Notes]

Chapter 6: A Closer Look at Methods and Classes

1. A public member can be freely accessed by code defined outside of its class. 2. A private member can be accessed only by other methods defined by its class. 3. A protected member can be accessed by other methods defined by its class and method defined by its derived class. 4. The internal modifier applies mostly to the use of an assembly, which in the case of C# means a program, project, or components 5. How Arguments Are Passed: A. The first way is call-by-value. This method copies the value of an argument into the formal parameter of the subroutine. Therefore, changes made to the parameter of the subroutine have no effect on the argument. B. The second way an argument can be passed is call-by-reference. In this method, a reference to an argument (not the value of the argument) is passed to the parameter. Inside the subroutine, this reference is used to access the actual argument specified in the call. This means that changes made to the parameter will affect the argument used to call the subroutine. 6. By default, C# uses call-by-value. 7. When you pass an object reference to a method, the object reference itself is passed by value. Making the parameter refer to a new object will not change the object to which the argument refers. 8. Howeverchanges made to the object being referred to by the parameter will affect the object referred to by the argument because they are one and the same. 9. Using ref and out Parameters: A. ref: In order to pass a value type by reference we can use ref. Method: public void Sqr(ref int i) { i = i * i; Page | 21

C# 3.0: A Beginners Guide [Notes]


} Call: int a = 10; ob.Sqr(ref a); Note: ref parameter must be initialized to a value prior to the call B. out: It can only be used to pass a value out of a method similar to return. Method: public void sqr(int n, out int outParm){ outParm = n * n; } Call: int n = 10; int outParam=12; //No need to initialized ob.Sqr(n, out outParam); Note: inside the method, an out parameter is always considered unassigned and the method must assign the parameter a value prior to the methods termination. Note: Any No. of ref and out can be used as an argument and parameter. 10. We can also use ref and out on reference-type parameters. 11. The params modifier is used to declare an array parameter that will be able to receive zero or more arguments. 12. Using a Variable Number of Arguments: Syntax: public int MinVal(params int[] nums) Case: For example, consider a method that finds the smallest of a set of values 13. Although you can pass a params parameter any number of arguments, they all must be of a type compatible with the array type specified by the parameter. EG: ob.MinVal(1, 2.2); is illegal because there is no implicit conversion from double (2.2) to int. 14. Careful about boundary conditions because a params parameter can accept any number of argumentseven zero.

Page | 22

C# 3.0: A Beginners Guide [Notes]


15. In cases where a method has regular parameters and a params parameter, the params parameter must be the last one in the parameter list. Furthermore, in all situations, there must be only one params parameters. 16. A method can return any type of data, including class types. You can, of course, also return objects of classes that you create. 17. If a method is returning object of some class then there is no need to use new operator. We can just create a reference of that type. EG: ClassName v1 = new ClassName (); //v1 variable to call method ClassReturnedObj v2; new operator v2 = v1.MethodCall(2); //Method which will return object. // v2 hold the reference of returned object. //No

Note: Return statement of Method: return new ClassReturnedObj ();

18. Method Overloading: In C#, two or more methods within the same class can share the same name, as long as their parameter declarations are different. When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading. Method overloading is one of the ways that C# implements polymorphism. 19. The type and/or number of the parameters of each overloaded method must differ. It is not sufficient for two methods to differ only in their return types.

Page | 23

C# 3.0: A Beginners Guide [Notes]

20. Implicit type conversions can affect overloaded method resolution. [Type promotion] EG: We have MyMeth(int) and MyMeth(double), overloaded Methods. Now we are calling through different arguments. i int, d double, b byte, s short, f float. ob.MyMeth(i); // calls ob.MyMeth(int) ob.MyMeth(d); // calls ob.MyMeth(double) ob.MyMeth(b); // calls ob.MyMeth(int) -- type conversion ob.MyMeth(s); // calls ob.MyMeth(int) -- type conversion ob.MyMeth(f); // calls ob.MyMeth(double) -- type conversion 21. The implicit conversions apply only if there is no direct match between the types of a parameter and an argument. 22. Both ref and out participate in overload resolution. // This will compile. public void MyMeth(int x) { // ... public void MyMeth(ref int x) { // ... // This will compile. public void MyMeth(int x) { // ... public void MyMeth(out int x) { // ...

23. Although ref and out participate in overload resolution, the difference between the two alone is not sufficient. // This won't compile. public void MyMeth(out int x) { // ... public void MyMeth(ref int x) { // ... 24. A signature is the name of a method plus its parameter list. Notice that a signature does not include the return type, since it is not used by C# for overload resolution. 25. Overloading Constructors: By overloading a class constructor, you give the user of your class flexibility in the way objects are constructed. public MyClass() {//.. public MyClass(int i) {//.. public MyClass(double d) {//..

Page | 24

C# 3.0: A Beginners Guide [Notes]


26. One of the most common reasons that constructors are overloaded is to allow one object to initialize another. EG: MyClass s1 = new MyClass (5); MyClass s2 = new MyClass (s1);

27. Invoking an Overloaded Constructor through this: Syntax: constructor-name(parameter-list1) : this(parameter-list2) { // ... body of constructor, which may be empty } EG: public MyClass (int i, int j) {//.. public MyClass () : this(0, 0) { public MyClass(MyClass obj) : this(obj.x, obj.y) {//.. 28. The Main( ) Method: Returning Values from Main( ): Notice that instead of being declared void, this version of Main( ) has a return type of int. Usually, the return value from Main( ) indicates whether the program ended normally or due to some abnormal condition. By convention, a return value of 0 usually indicates normal termination. All other values indicate that some type of error occurred. Passing Arguments to Main( ): Many programs accept what are called command-line arguments. A command-line argument is the information that directly follows the programs name on the command line when it is executed. For C# programs, these arguments are then passed to the Main( ) method. To receive the arguments, you must use one of these forms of Main( ): EG: static void Main(string[ ] args) static int Main(string[ ] args) While running the program: c:/> CodeFileName one two three 29. Recursion: In C#, a method can call itself. This process is called recursion. EG: Factorial: FactR(n-1) * n 30. Understanding static: Page | 25

C# 3.0: A Beginners Guide [Notes]

A. A static constructor is called automatically when the class is first loaded, before any objects are created and before any instance constructors are called. Thus, the primary use for a static constructor is to initialize features that apply to the class as a whole, rather than to an instance of the class. A static constructor cannot have access modifiers and cannot be called directly by your program. B. A static class has two important features. First, no object of a static class can be created. Second, a static class must contain only static members. C. A static method does not have a this reference. This is because a static method does not execute relative to any object. D. A static method can directly call only other static methods of its class. It cannot directly call an instance method of its class. The reason is that instance methods operate on specific objects, but a static method is not called on an object. Thus, on what object would the instance method operate? E. A similar restriction applies to static data. A static method can directly access only other static data of its class. It cannot operate on an instance variable of its class because there is no object to operate on. F. A static variable is initialized before its class is used. If no explicit initializer is specified, it is initialized to zero for numeric types, null in the case of reference types, or false for variables of type bool. Thus, a static variable always has a value. G. Variables declared as static are, essentially, global variables. When objects of its class are declared, no copy of a static variable is made. Instead, all instances of the class share the same static variable. H. Outside the class, to use a static member, you must specify the name of its class, followed by the dot operator. No object needs to be created. In fact, a static member cannot be accessed through an object instance. It must be accessed through its class name. I. It is important to understand that although a static method cannot directly call instance methods or access instance variables of its class, it can call an instance method or access an instance variable if it does so through an object of its class. Case1: public static void StaticMeth() { NonStaticMeth(); // won't compile Page | 26

C# 3.0: A Beginners Guide [Notes]


} Case2: public static void StaticMeth(MyClass ob) { ob.NonStaticMeth(); // this is OK } Case3: public int Denom = 3; // a normal instance variable public static int Val = 1024; // a static variable public static int ValDivDenom() { return Val/Denom; // won't compile! }

Page | 27

C# 3.0: A Beginners Guide [Notes]

Chapter 7: Operator Overloading, Indexers, and Properties

1. C# allows you to define the meaning of an operator relative to a class that you create. This process is called operator overloading. By overloading an operator, you expand its usage to your class. When an operator is overloaded, none of its original meaning is lost. It is simply that a new operation, relative to a specific class, is added. 2. For example, a class that defines a linked list might use the + operator to add an object to the list. A class that implements a stack might use the + to push an object onto the stack. Another class might use the + operator in an entirely different way. 3. Operator overloading is closely related to method overloading. To overload an operator, use the operator keyword to define an operator method, which defines the action of the operator. 4. The General Forms of an Operator Method There are two forms of operator methods: one for unary operators and one for binary operators. The general form for each is shown here: // General form for overloading a unary operator. public static ret-type operator op(param-type operand) { // operations } // General form for overloading a binary operator. public static ret-type operator op(param-type1 operand1, param-type2 operand2) { // operations } 5. For unary operators, the operand must be of the same type as the class for which the operator is being defined. 6. For binary operators, at least one of the operands must be of the same type as the class. 7. Thus, you cannot overload any C# operators for objects that you have not created. For example, you cant redefine + for int or string. One other point: Operator parameters must not use the ref or out modifier. Page | 28

C# 3.0: A Beginners Guide [Notes]

8. Although return-type can be of any type you choose, the return value is often of the same type as the class for which the operator is being overloaded. public static ThreeD operator +(ThreeD op1, ThreeD op2){//

9. For any given class and operator, an operator method can, itself, be overloaded. public static ThreeD operator +(ThreeD op1, int op2){ ThreeD result = new ThreeD(); result.x = op1.x + op2; return result; } public static ThreeD operator +(int op1, ThreeD op2){// ThreeD result = new ThreeD(); result.x = op1+ op2.x ; return result; } 10. Overloading the Relational Operators: The relational operators, such as = = or <, can also be overloaded, and the process is straightforward. Usually, an overloaded relational operator returns a true or false value. EG: public static bool operator <(ThreeD op1, ThreeD op2) { if(Math.Sqrt(op1.x * op1.x + op1.y * op1.y + op1.z * op1.z) < Math.Sqrt(op2.x * op2.x + op2.y * op2.y + op2.z * op2.z)) return true; else return false; }

11. Restriction: if you overload <, you must also overload >, and vice versa. if you overload <=, you must also overload >=, and if you overload = =, you must also overload !=. 12. You cannot alter the precedence of any operator. 13. You cannot alter the number of operands required by the operator, although your operator method could choose to ignore an operand.. 14. Perhaps most significantly, you cannot overload any assignment operator, including the compound assignments, such as +=. Page | 29

C# 3.0: A Beginners Guide [Notes]

15. The keywords true and false can also be used as unary operators for the purposes of overloading. They are overloaded relative to a class to determine whether an object is true or false. Once these are overloaded for a class, you can use objects of that class to control an if statement, for example. 16. Since I cant overload operators such as +=, what happens if I try to use += with an object of a class for which I have defined +, for example? your overloaded operator method is invoked. Thus, += automatically uses your version of operator+( ). ThreeD a = new ThreeD(1, 2, 3); ThreeD b = new ThreeD(10, 10, 10); b += a; // add a and b together ThreeDs operator+( ) is automatically invoked, and b will contain the coordinates 11, 12, 13. 17. Indexers: As you know, array indexing is performed using the [ ] operator. It is possible to overload the [ ] operator for classes that you create, but you dont use an operator method. Instead, you create an indexer. An indexer allows an object to be indexed like an array. 18. Can indexers be overloaded? Yes. The version executed will be the one that has the closest type-match between its parameter(s) and the argument(s) used as an index. 19. One-dimensional indexers have this general form: element-type this[int index] { // The get accessor. get { // return the value specified by index } } // The set accessor. set { // set the value specified by index } } 20. The main use of indexers is to support the creation of specialized arrays that are subject to one or more constraints.

Page | 30

C# 3.0: A Beginners Guide [Notes]


21. Each element accessed by the indexer will be of type element-type. It corresponds to the element type of an array. The parameter index receives the index of the element being accessed. Technically, this parameter does not have to be of type int, but since indexers are typically used to provide array indexing, an integral type is customary. 22. It is not necessary for an indexer to provide both get and set. 23. It is important to understand that there is no requirement that an indexer actually operate on an array. It simply must provide functionality that appears array-like to the user of the indexer. 24. An indexer cannot be declared static. 25. An indexer does not define a storage location, a value produced by an indexer cannot be passed as a ref or out parameter to a method. 26. Multi-dimensional indexers have this general form: element-type this[int r, int c] { // The get accessor. get { // return the value specified by index } } // The set accessor. set { // set the value specified by index } } 27. Properties: a property combines a field with the methods that access it. it helps in order to maintain control over what operations are allowed on that field. 28. Properties are similar to indexers. A property consists of a name, along with get and set accessors. The accessors are used to get and set the value of a variable. 29. The key benefit of a property is that its name can be used in expressions and assignments like a normal variable, but in actuality, the get and set accessors are automatically invoked. This is similar to the way that an indexers get and set accessors are automatically used. Syntax: type name { get { Page | 31

C# 3.0: A Beginners Guide [Notes]


// get accessor code } set { // set accessor code } } EG: //Field int prop; //Property public int MyProp { get { return prop; } set { if(value >= 0) prop = value; } } 30. Properties do not define storage locations. Instead, a property typically manages access to a field defined elsewhere. The property itself does not provide this field. Thus, a field must be specified independently of the property. 31. Auto-Implemented Properties: it is possible to implement very simple properties without having to explicitly define the variable managed by the property. Instead, you can let the compiler automatically supply the underlying variable. This is called an auto-implemented property.

Syntax: type name { get; set; } EG: public int UserCount { get; set; }

//This syntax tells the compiler to automatically create a

storage location (sometimes referred to as a backing field) that holds the value.

Notice that no variable is explicitly declared. 32. Both the get and set must be specified in all cases for Auto-Implemented Properties. However, you can approximate the same effect by declaring either get or set as private 33. Property Restrictions: First, because a property does not define a storage location, it cannot be passed as a ref or out parameter to a method. Page | 32

C# 3.0: A Beginners Guide [Notes]


Second, you cannot overload a property. Finally, a property should not alter the state of the underlying variable when the get accessor is called. Although this rule is not enforced by the compiler, such an alteration is semantically wrong. 34. It is possible, however, to give set or get its own access modifier, such as private. In all cases, the access modifier for an accessor must be more restrictive than the access specification of its property or indexer. EG: class MyClass { int maximum; // ... public int Max { get { return maximum; } private set { // the set accessor is private if(value < 0) maximum = -value; else maximum = value; } } // ... } 35. Perhaps the most important use of restricting an accessors access is found when working with auto-implemented properties. Syntax: public int Length { get; private set; } How to access property outside the class (inside no need to use obj ): obj.Length = 10; // it will call set accessor automatically obj.Length; //it will call get accessor automatically

Page | 33

C# 3.0: A Beginners Guide [Notes]


Chapter 8: Inheritance

1. Inheritance is foundational principles of object-oriented programming by which one class can acquire the properties of another class. 2. A class that is inherited is called a base class. The class that does the inheriting is called a

derived class.
3. It inherits all of the variables, methods, properties, and indexers defined by the base class and add its own, unique elements. Syntax: class BaseClass {// class DerivedClass : BaseClass {// 4. C# does not support the inheritance of multiple base classes into a single derived class. 5. Even though a derived class includes all of the members of its base class, it cannot access those members of the base class that are private. 6. As explained in the previous chapter, a property allows you to manage access to an instance variable. 7. By using protected, you can create class members that are private to their class but that can still be inherited and accessed by a derived class. 8. The constructor for the base class constructs the base class portion of the object, and the constructor for the derived class constructs the derived class part. 9. We can make variable as private if constructor is used to set its value. 10. When both the base class and the derived class define constructors, the process is a bit more complicated because both the base class and derived class constructors must be executed. 11. In this case, you must use another of C#s keywords: base, which has two uses. The first calls a base class constructor. The second is used to access a member of the base class that has been hidden by a member of a derived class. Here, we will look at its first use. Syntax: derived-constructor(parameter-list) : base(arg-list) { // body of constructor Page | 34

C# 3.0: A Beginners Guide [Notes]


} 12. A default constructor of derived class automatically invokes the default constructor of base class. 13. If no base clause is present, then the base class default constructor is called automatically. 14. Inheritance and Name Hiding: It is possible for a derived class to define a member that has the same name as a member in its base class. When this happens, the member in the base class is hidden within the derived class. In such case, the derived class member must be preceded by the new keyword. EG:
class A { public int i = 0; } // Create a derived class. class B : A { new int i; // this i hides the i in A public B(int b) { i = b; // i in B } public void Show() { Console.WriteLine("i in derived class: " + i); } }

15. Use base to access a Hidden Name. Syntax: base.member 16. A reference variable for one class type cannot normally refer to an object of another class type. X x = new X(10); X x2; Y y = new Y(5); x2 = x; // OK, both of same type x2 = y; // Error, not of same type 17. However, an important exception to C#s strict type enforcement . A reference variable of a base class can be assigned a reference to an object of any class derived from that base class.

Page | 35

C# 3.0: A Beginners Guide [Notes]


18. When a reference to a derived class object is assigned to a base class reference variable, you will have access only to those parts of the object defined by the base class. X: Base Class Y: Derived Class X x= new X( ); Y y = new Y( ); X x = new Y( ); Y y= new X( ); //x can call class X method //y can call class Y method // x can call class X method //Error Compile Time

19. Notice that the Triangle constructor receives an object of type Triangle, and it passes that object through base) to the TwoDShape constructor. The key point is that TwoDShape( ) is expecting a TwoDShape object. However, Triangle( ) passes it a Triangle object. As explained, the reason this works is because a base class reference can refer to a derived class object. class TwoDShape { // ... // Construct a copy of a TwoDShape object. public TwoDShape(TwoDShape ob) { Width = ob.Width; Height = ob.Height; } // ... class Triangle : TwoDShape { // ... // Construct a copy of a Triangle object. public Triangle(Triangle ob) : base(ob) { Style = ob.Style; } // ... 20. Virtual Methods and Overriding: A virtual method is a method that is declared as virtual in a base class. The defining characteristic of a virtual method is that it can be redefined in one or more derived classes. 21. Virtual methods are interesting because of what happens when one is called through a base class reference. In this situation, C# determines which version of the method to call based upon the type of the object referred to by the referenceand this determination is made at runtime. 22. When a virtual method is redefined by a derived class, the override modifier is used. Thus, the process of redefining a virtual method inside a derived class is called method overriding.

Page | 36

C# 3.0: A Beginners Guide [Notes]


23. When overriding a method, the name, return type, and signature of the overriding method must be the same as the virtual method that is being overridden. 24. Also, a virtual method cannot be specified as static or abstract (discussed later in this chapter). 25. X: Base Class Y: Derived Class X x= new X( ); Y y = new Y( ); X x = new Y( ); //x can call class X method //y can call class Y method // x can call class X method

Note: if method is virtual in X and if Y override s the virtual method then method of Y will get executed. Y y= new X( ); //Error Compile Time

27. An abstract method contains no body and is, therefore, not implemented by the base class. Thus, a derived class must override it. Note: virtual method contains implementation (Body) and abstract method doesnt. A derived class may override virtual method but A derived class must override the abstract method and if doesnt then the derived class must also be specified as abstract. 28. A class that contains one or more abstract methods must also be declared as abstract by preceding its class declaration with the abstract specifier. 29. When a derived class inherits an abstract class, it must implement all of the abstract methods in the base class. 30. Using sealed to Prevent Inheritance: sealed keyword it used to prevent a class from being inherited. 31. sealed can also be used on virtual methods to prevent further overrides. In that case sealed keyword is used prior to override method. We cant make a normal method as sealed. An override method can only be sealed. Base class: public virtual void MyMethod(){ /* ... */ }

Derived class: sealed public override void MyMethod() { /* ... */ }

Page | 37

C# 3.0: A Beginners Guide [Notes]

Base class:

sealed public virtual void MyMethod(){ /* ... */ }

//Error compilation

32. The object Class: C# defines one special class called object that is an implicit base class of all other classes and for all other types (including the value types). 33. Boxing is the process of wrapping a value into an object. Unboxing is the process of retrieving a value from that object. object obj = 10; int y = (int) obj; //Boxing //Unboxing

Chapter 9: Inter faces, Structures, and Enumerations

1. Interfaces: Interfaces are syntactically similar to abstract classes. However, in an interface, no method can include a body or we can say all methods are abstract and there is no need to put abstract keyword prior to methods of an Interface. Syntax: interface name {

ret-type method-name(param-list);
} 2. In an interface, methods are implicitly public, and no explicit access specifier is allowed. 3. Interfaces cannot have data members. They cannot define constructors, destructors, or operator methods. Also, no member can be declared as static. 4. Interfaces can declare the signatures for properties, indexers, and events. 5. To implement an interface, the name of the interface is specified after the class name in just the same way that a base class is specified. Syntax: class class-name : interface-name { // class-body } 6. When a class implements an interface, the class must implement the entire interface, including any that are inherited from other interfaces. Since a class cannot create a partial implementation of an interface. 7. A class can inherit a base class and implement one or more interfaces. In this case, the name of the base class must come first in the comma-separated list. Page | 38

C# 3.0: A Beginners Guide [Notes]

8. The methods that implement an interface must be declared public. . 9. To compile ISeriesDemo, you must include the classes ISeries, ByTwos, and ISeriesDemo in the compilation. (EG) 10. An interface reference variable can refer to any object that implements its interface. EG: Interface ob= new Class1 (); ob.GetNext(); ob= new Class2 (); ob.GetNext(); 11. Like methods, properties are specified in an interface without any body. EG: // Use a property in an interface. using System; public interface ISeries { // An interface property. int Next { get; // return the next number in series set; // set next number } } // Implement ISeries. class ByTwos : ISeries { int val; public ByTwos() { val = 0; } // Get or set value. public int Next { get { val += 2; return val; } set { val = value; } } }

Page | 39

C# 3.0: A Beginners Guide [Notes]

12. An indexer declared in an interface has this general form: Syntax: // An interface indexer. int this[int index] { } 13. Interfaces Can Be Inherited. 14. Q: When one interface inherits another, is it possible to declare a member in the derived interface that hides a member defined by the base interface? A: Yes. When a member in a derived interface has the same signature as one in the base interface, the base interface name is hidden. As is the case with class inheritance, this hiding will cause a warning message, unless you specify the derived interface member with new. 15. Explicit Implementations: When implementing a member of an interface, it is possible to fully qualify its name with its interface name. Doing this creates an explicit interface member implementation, or explicit implementation, for short. There are two reasons for doing this: 1. First, it is possible for a class to implement two interfaces, which both declare methods by the same name and type signature. Qualifying the names with their interfaces removes the ambiguity from this situation. 2. Second, when you implement a method using its fully qualified name, you are providing an implementation that cannot be accessed through an object of the class. It can be accessed only through an interface reference. EG: 16. InterfaceName o = this; // Interface reference to invoking object (Here, we can use this as it is a reference to an invoking object inside a method. 17. A structure is similar to a class, but is a value type, rather than a reference type. Syntax: struct name : interfaces { // member declarations } // Declare a read-only indexer get; // return the specified number in series

18. Structures cannot inherit other structures or classes, or be used as a base for other structures or classes. 19. A structure can implement one or more interfaces. These are specified after the structure name using a comma-separated list. Page | 40

C# 3.0: A Beginners Guide [Notes]

20. Like classes, structure members include methods, fields, indexers, properties, operator methods, and events. Structures can also define constructors, but not destructors. 21. You cannot define a default (parameterless) constructor for a structure. 22. A structure object can be created using new in the same way as a class object, but it is not required. When new is used, the specified constructor is called. When new is not used, the object is still created, but it is not initialized. Thus, you will need to perform any initialization manually. EG: Account acc1 = new Account("Tom", 1232.22); // explicit constructor Account acc2 = new Account(); // default constructor that initializes all fields to their default values Account acc3; // no constructor // Must initialize acc3 prior to use. acc3.name = "Mary"; acc3.balance = 99.33; 23. In C#, a struct defines a value type, and a class defines a reference type. 24. An enumeration is a set of named integer constants. Syntax: enum name { enumeration list }; EG: enum Coin { Penny, Nickel, Dime, Quarter, HalfDollar, Dollar}; Note: Each of the symbols stands for an integer value. However, no implicit conversions are defined between an enum type and the built-in integer types, so an explicit cast must be used. Also, a cast is required when converting between two enumeration types. 25. The members of an enumeration are accessed through their type name via the dot operator. For example, this code: Console.WriteLine(Coin.Penny + " " + Coin.Nickel); 26. You can use an enumeration to control a switch statement or as the control variable in a for loop. 27. 1. int i=(int)Coin.Penny; 2. Coin c; Page | 41 //i=0

C# 3.0: A Beginners Guide [Notes]


switch(c) { case Coin.Nickel: Console.WriteLine("A nickel is 5 pennies."); break; }

EG: class EnumDemo { enum Coin { Penny, Nickel, Dime, Quarter, HalfDollar, Dollar }; static void Main() { Coin c; // declare an enum variable // Use c to cycle through the enum by use of a for loop. for(c = Coin.Penny; c <= Coin.Dollar; c++) { Console.WriteLine(c + " has value of " + (int) c); // Use an enumeration value to control a switch. switch(c) { case Coin.Nickel: Console.WriteLine("A nickel is 5 pennies."); break; } } } 28: Initialize an Enumeration: enum Coin { Penny, Nickel, Dime, Quarter=100, HalfDollar, Dollar}; Now, the values of these symbols are: Symbol Penny Nickel Dime Quarter HalfDollar Dollar Value 0 1 2 100 101 102

29. Specifying the Underlying Type of an Enumeration: By default, enumerations are based on type int, but you can create an enumeration of any integral type, except for type char. Page | 42

C# 3.0: A Beginners Guide [Notes]


EG: enum Coin : byte { Penny, Nickel, Dime, Quarter, HalfDollar, Dollar};

Page | 43

C# 3.0: A Beginners Guide [Notes]


Chapter 10: Exception Handling

1. An exception is an error that occurs at runtime. 2. In C#, exceptions are represented by classes. All exceptions are subclasses of System.Exception. 3. One very important subclass of Exception is SystemException. This is the exception class from which all exceptions generated by the C# runtime system (that is, the CLR) are derived. 4. C# exception handling is managed via four keywords: try, catch, throw, and finally. 5. Program statements that you want to monitor for exceptions are contained within a try block. If an exception occurs within the try block, it is thrown. Your code can catch this exception using catch. 6. System-generated exceptions are automatically thrown by the runtime system. 7. To manually throw an exception, use the keyword throw. 8. Any code that absolutely must be executed upon exiting from a try block is put in a finally block. 9. Syntax: try { // block of code to monitor for errors } catch (ExcepType1 exOb) { // handler for ExcepType1 } catch (ExcepType2 exOb) { // handler for ExcepType2 } 10. If the exception type specified by a catch matches that of the exception, then the block of code associated with that catch clause is executed and all other catch clauses are bypassed. 11. When an exception is caught, the exception variable exOb will receive its value. Actually, specifying exOb is optional. If the exception handler does not need access to the exception object (as is often the case), then there is no need to specify exOb.

Page | 44

C# 3.0: A Beginners Guide [Notes]


12. In case of exception control transfer takes place from try to catch block. 13. An exception can be generated by one method and caught by another. EG: class ExcTest { // Generate an exception. public static void GenException() { int[] nums = new int[4]; Console.WriteLine("Before exception is generated."); // Generate an index out-of-bounds exception. nums[7] = 10; Console.WriteLine("this won't be displayed"); } } class ExcDemo2 { static void Main() { try { ExcTest.GenException(); } catch (IndexOutOfRangeException) { // Catch the exception. Console.WriteLine("Index out-of-bounds!"); } Console.WriteLine("After catch block."); } }

14. If your program does not catch an exception, then it will be caught by the runtime system. The trouble is that the runtime system will report an error and terminate the program. 15. Catching All Exceptions: for(int i=0; i < numer.Length; i++) { try { Console.WriteLine(numer[i] + " / " + denom[i] + " is " + numer[i]/denom[i]); } catch { Console.WriteLine("Some exception occurred."); Page | 45

C# 3.0: A Beginners Guide [Notes]


} } 16. Try Blocks Can Be Nested: One try block can be nested within another. An exception generated within the inner try block that is not caught by a catch associated with that try is propagated to the outer try block. EG: int[] numer = { 4, 8, 16, 32, 64, 128, 256, 512 }; int[] denom = { 2, 0, 4, 4, 0, 8 }; try { // outer try for(int i=0; i < numer.Length; i++) { try { // nested try Console.WriteLine(numer[i] + " / " + denom[i] + " is " + numer[i]/denom[i]); } catch (DivideByZeroException) { // catch for inner try Console.WriteLine("Can't divide by Zero!"); } } } catch (IndexOutOfRangeException) { // catch for outer try Console.WriteLine("No matching element found."); Console.WriteLine("Fatal error -- program terminated."); } 17. Throwing an Exception: Syntax: throw exceptOb; Here, exceptOb must be an instance of an exception class derived from Exception. EG: try { Console.WriteLine("Before throw."); throw new DivideByZeroException(); } catch (DivideByZeroException) { Console.WriteLine("Exception caught."); } 18. Rethrowing an Exception: An exception caught by one catch clause can be rethrown so that it can be caught by an outer catch. Page | 46

C# 3.0: A Beginners Guide [Notes]


Syntax: throw ; EG: Inner: catch (IndexOutOfRangeException) { Console.WriteLine("No matching element found."); throw; // rethrow the exception } Outer: catch(IndexOutOfRangeException) { // recatch exception Console.WriteLine("Fatal error -- program terminated."); } 19. The finally block will be executed whenever execution leaves a try/catch block, no matter what conditions cause it. 20. Exception defines several properties. All are read-only. 1. Message is a string that describes the nature of the error. 2. StackTrace is a string that contains the stack of calls that lead to the exception. 3. TargetSite returns an object that specifies the method that generated the exception. 21. Exception also defines several methods. The one that you will most often use is ToString( ), which returns a string that describes the exception. ToString( ) is automatically called when an exception is displayed via WriteLine( ). EG: catch (IndexOutOfRangeException exc) { Console.WriteLine("Standard message is: "); Console.WriteLine(exc); Console.WriteLine("Stack trace: " + exc.StackTrace); Console.WriteLine("Message: " + exc.Message); Console.WriteLine("TargetSite: " + exc.TargetSite); } 22. Exception defines the following four constructors: I. II. III. IV. public Exception( ) public Exception(string str) public Exception(string str, Exception inner) protected Exception(System.Runtime.Serialization.SerializationInfo si, System.Runtime.Serialization.StreamingContext sc) Page | 47 // calls ToString()

C# 3.0: A Beginners Guide [Notes]

Note: The first is the default constructor. The second specifies the string associated with the Message property associated with the exception. The third specifies what is called an inner

exception. It is used when one exception gives rise to another. In this case, inner specifies
the first exception, which will be null if no inner exception exists. (The inner exception, if it exists, can be obtained from the InnerException property defined by Exception.) The last constructor handles exceptions that occur remotely and require deserialization. EG: class NonIntResultException : Exception { public NonIntResultException() : base() { } public NonIntResultException(string str) : base(str) { } public NonIntResultException(string str, Exception inner) : base(str, inner) { } protected NonIntResultException( System.Runtime.Serialization.SerializationInfo si, System.Runtime.Serialization.StreamingContext sc) : base(si, sc) { } // Override ToString for NonIntResultException. public override string ToString() { return Message; } } //Demo Class try { if((numer[i] % denom[i]) != 0) throw new NonIntResultException("Outcome of " + numer[i] + " / " + denom[i] + " is not even."); Console.WriteLine(numer[i] + " / " + denom[i] + " is " + numer[i]/denom[i]); } catch (IndexOutOfRangeException) { Console.WriteLine("No matching element found."); } catch (NonIntResultException exc) { Console.WriteLine(exc); } 23. The System namespace defines several standard, built-in exceptions. All are derived from SystemException since they are generated by the CLR when runtime errors occur. Several of the more commonly used standard exceptions are given below:

Page | 48

C# 3.0: A Beginners Guide [Notes]

24. If you want to catch exceptions of both a base class type and a derived class type, put the derived class first in the catch sequence. This is necessary because a base class catch will also catch all derived classes. Fortunately, this rule is self-enforcing because putting the base class first causes a compile-time error. 25. Using checked and unchecked: An arithmetic computation can cause an overflow. EG: byte a, b, result; a = 127; b = 127; result = (byte)(a * b); Here, the product of a and b exceeds the range of a byte value. Thus, the result overflows the type of the result. 26. C# allows you to specify whether your code will raise an exception when overflow occurs using the keywords checked and unchecked. 27. To specify that an expression be checked for overflow, used checked. To specify that overflow be ignored, use unchecked. In this case, the result is truncated to fit into the target type of the expression. 28. The checked keyword has these two general forms. One checks a specific expression and is called the operator form of checked. The other checks a block of statements and is called the

statement form. Syntax:


Page | 49

C# 3.0: A Beginners Guide [Notes]


checked (expr) checked { // statements to be checked } Here, expr is the expression being checked. If a checked expression overflows, then an OverflowException is thrown. 29. The unchecked keyword also has two general forms. The first is the operator form, which ignores overflow for a specific expression. The other ignores overflow for a block of statements.

Syntax:
unchecked (expr) unchecked { // statements for which overflow is ignored } Here, expr is the expression that is not being checked for overflow. If an unchecked expression overflows, then truncation will occur. EG: byte result = unchecked((byte)(a * b)); byte result = checked((byte)(a * b)); //truncation //exception

30. In general, there are two ways errors can be reported: return values and exceptions. When is one approach better than the other? Simply put, in C#, exception handling should be the norm.

Page | 50

C# 3.0: A Beginners Guide [Notes]


Chapter 11: Using I/O

1.

Page | 51

C# 3.0: A Beginners Guide [Notes]

Chapter XX: ADO.NET

ADO stands for ActiveX Data Objects. ADO.NET is an object-oriented set of libraries that allows you to interact with data sources. These libraries are called Data Providers and are usually named for the protocol or data source type they allow you to interact with. Before you can use the classes from the SqlClient namespaces in your components and pages, you need to import the System.Data.SqlClient namespace. ADO.NET Objects: ADO.NET includes many objects you can use to work with data.

The Connection Object: Enables you to represent a connection to a data source. A connection object is used by command objects so they will know which database to execute the command on. The connection helps identify the database server, the database name, user name, password, and other parameters that are required for connecting to the data base. DbConnection: The base class for all Connection classes. The Command Object: Enables you to execute a command against a data source. Page | 52

C# 3.0: A Beginners Guide [Notes]


A command object is used to send SQL statements to the database. A command object uses a connection object to figure out which database to communicate with. DbCommand: The base class for all Command classes.

The DataReader Object: Enables you to represent data retrieved from a data source. The data reader object allows you to obtain the results of a SELECT statement from a command object. This is good for speed, but if you need to manipulate data, then a DataSet is a better object to work with. DbDataReader: The base class for all DataReader classes. The DataSet Object: DataSet objects are in-memory representations of data. DataSet provides a disconnected representation of result sets from the Data Source, and it is completely independent from the Data Source. DataSet provides much greater flexibility when dealing with related Result Sets.

Dataset has a collection of Data Table object within the Tables collection that you can relate to each other with DataRelation objects. Each Data Table object contains a collection of Data Row objects and a collection of Data Column objects. Constraint collection: collections for the primary keys, constraints, and default values used in this table. Finally, there is a Default View object for each table. This is used to create a Data View object based on the table, so that the data can be searched, filtered, or otherwise manipulated while displaying the data. Page | 53

C# 3.0: A Beginners Guide [Notes]

DataTable: Represents an in-memory database table. You can add rows to a DataTable with a SqlDataAdapter, with a SqlDataReader, with an XML file, or programmatically. EG: public void CreateDataTable() { // Create the DataTable columns DataTable dataTable = new DataTable(); dataTable.Columns.Add("Id", typeof(int)); dataTable.Columns.Add("ProductName", typeof(string)); dataTable.Columns.Add("ProductPrice", typeof(decimal)); // Mark the Id column as an autoincrement column dataTable.Columns["Id"].AutoIncrement = true; // Add some data rows for (int i = 1; i < 11; i++) { DataRow row = dataTable.NewRow(); row["ProductName"] = "Product " + i.ToString(); row["ProductPrice"] = 12.34m; dataTable.Rows.Add(row); } Selecting DataRows: You can retrieve particular rows from a DataTable by using the DataTable objects Select method. The Select method accepts a filter parameter. You can use just about anything that you would use in a SQL WHERE clause with the filter parameter. When you retrieve an array of rows with the Select method, you can also specify a sort order for the rows. When specifying a sort order, you can use any expression that you would use with a SQL ORDER BY clause. EG: static void DataTableSelect() { // Create the DataTable columns DataTable dataTable = new DataTable("DataTable"); dataTable.Columns.Add("Id", typeof(int)); dataTable.Columns.Add("ProductName", typeof(string)); dataTable.Columns.Add("ProductPrice", typeof(decimal)); // Mark the Id column as an autoincrement column dataTable.Columns["Id"].AutoIncrement = true; // Add some data rows for (int i = 0; i <= 10; i = i + 2) { DataRow row = dataTable.NewRow(); row["ProductName"] = "Product " + i.ToString(); row["ProductPrice"] = 12.34m; dataTable.Rows.Add(row); } for (int i = 1; i <= 11; i=i+2) { DataRow row = dataTable.NewRow(); Page | 54

C# 3.0: A Beginners Guide [Notes]


row["ProductName"] = "Goods " + i.ToString(); row["ProductPrice"] = 12.39m; dataTable.Rows.Add(row); } String filter = String.Format("ProductName LIKE '{0}%'", "Prod"); DataRow[] rows= dataTable.Select(filter, "ProductName"); DataTable filteredDataTable = new DataTable("FilteredDataTable"); filteredDataTable.Columns.Add("Id", typeof(int)); filteredDataTable.Columns.Add("ProductName", typeof(string)); filteredDataTable.Columns.Add("ProductPrice", typeof(decimal)); for (int i = 0; i < rows.Length; i++) { DataRow row = filteredDataTable.NewRow(); row["ProductName"] = rows[i].ItemArray[1]; row["ProductPrice"] = rows[i].ItemArray[2]; row["Id"] = rows[i].ItemArray[0]; filteredDataTable.Rows.Add(row); } }

DataRow States and DataRow Versions: A DataTable maintains both the original and modified version of each row. Each row in a DataTable can have more than one version. Each version is represented by one of the following values of the DataRowVersion enumeration: Current: The current version of the row. Default: The default version of the row. Original: The original version of the row. Proposed: The version of a row that exists during editing. You can use the DataTable.AcceptChanges() method to copy the current versions of all the rows to the original versions of all the rows. And you can use the DataTable.RejectChanges() method to copy the original versions of all the rows to the current versions of all the rows. EG: public void RejectChanges() { DataTable movies = (DataTable)HttpContext.Current.Session["MoviestoEdit"]; movies.RejectChanges(); } public void AcceptChanges() { DataTable movies = (DataTable)HttpContext.Current.Session["MoviestoEdit"]; dad.Update(movies); //updating changes in database movies.AcceptChanges(); //Accepting changes for all the rows in datatable. }

Page | 55

C# 3.0: A Beginners Guide [Notes]

Each row in a DataTable has a particular RowState that has one of the following values: Unchanged: The row has not been changed. Added: The row has been added. Modified: The row has been modified. Deleted: The row has been deleted. Detached: The row has been created but not added to the DataTable. EG: <asp:GridView id="grdMovies" DataSourceID="srcMovies" //datasource DataKeyNames="SAVEID" //primary key AutoGenerateEditButton="true" Runat="server"> <Columns> <asp:TemplateField> <ItemTemplate> <%# ((DataRowView)Container.DataItem).Row.RowState %> </ItemTemplate> </asp:TemplateField> </Columns> // this will add rowstate column </asp:GridView> DataView: The DataView object represents an in-memory database view. You can use a

DataView object to create a sortable, filterable view of a DataTable. The DataView object supports three important properties: Sort: Enables you to sort the rows represented by the DataView. RowFilter: Enables you to filter the rows represented by the DataView. RowStateFilter: Enables you to filter the rows represented by the DataView The easiest way to create a new DataView is to use the DefaultView property exposed by the DataTable class like this: DataView dataView = dataTable.DefaultView; The DefaultView property returns an unsorted, unfiltered view of the data contained in a DataTable. DataView dataView = new DataView(dataTable, "ProductName LIKE 'Prod%'", //RowFilter "ProductName ASC ", //Sort DataViewRowState.CurrentRows); //RowStateFilter //Or We can give param like this: dataView.Sort = "ID"; DataSet: Represents an in-memory database.

Page | 56

C# 3.0: A Beginners Guide [Notes]


The DataSet object represents an in-memory database. A single DataSet can contain one or many DataTable objects. You can define parent/child relationships between the DataTable objects contained in a DataSet. The DataSet contains DataTableCollection and their DataRelationCollection. The DataTableCollection contains zero or more DataTable objects. The SqlDataAdapter object allows us to populate DataTables in a DataSet. We can use Fill method in the SqlDataAdapter Object for populating data in a Dataset. ADO.NET enables you to create DataTable objects and add them to an existing DataSet. In a DataSet with multiple DataTable objects, you can use DataRelation objects to relate one table to another, to navigate through the tables, and to return child or parent rows from a related table. We can populate Dataset with more than one table at a time using SqlDataAdapter object. void BuildTree() { // Create Connection string connectionString = WebConfigurationManager.ConnectionStrings["Movies"].ConnectionString; SqlConnection con = new SqlConnection(connectionString); // Create Movie Categories DataAdapter SqlDataAdapter dadCategories = new SqlDataAdapter("SELECT Id,Name FROM MovieCategories", con); // Create Movies DataAdapter SqlDataAdapter dadMovies = new SqlDataAdapter("SELECT Title,CategoryId FROM Movies", con); // Add the DataTables to the DataSet DataSet dstMovies = new DataSet(); using (con) { con.Open(); dadCategories.Fill(dstMovies, "Categories"); dadMovies.Fill(dstMovies, "Movies"); } // Add a DataRelation dstMovies.Relations.Add("Children", dstMovies.Tables["Categories"].Columns["Id"], dstMovies.Tables["Movies"].Columns["CategoryId"]); // Add the Movie Category nodes foreach (DataRow categoryRow in dstMovies.Tables["Categories"].Rows) { string name = (string)categoryRow["Name"]; TreeNode catNode = new TreeNode(name); TreeView1.Nodes.Add(catNode); // Get matching movies DataRow[] movieRows = categoryRow.GetChildRows("Children"); foreach (DataRow movieRow in movieRows) { string title = (string)movieRow["Title"]; TreeNode movieNode = new TreeNode(title); Page | 57

C# 3.0: A Beginners Guide [Notes]


catNode.ChildNodes.Add(movieNode); } } } The DataAdapter Object: Enables you to transfer data from the physical database to the in-memory database and back again. The DataAdapter acts as the bridge between an in-memory database table and a physical database table. You use the DataAdapter to retrieve data from a database and populate a DataTable. You also use a DataAdapter to push changes that you have made to a DataTable back to the physical database. EG: public DataTable GetAll() { // Initialize the DataAdapter SqlDataAdapter adaptor = new SqlDataAdapter("SELECT Title,Director FROM Movies", _connectionString); // Create a DataTable DataTable dtblMovies = new DataTable(); // Populate the DataTable adaptor.Fill(dtblMovies); // Return results return dtblMovies; } When you call the SqlDataAdapter objects Fill method, the SqlDataAdapter automatically creates and opens a connection. After the data is fetched from the database, the Fill method automatically closes the connection. You dont need to wrap the call to the Fill method within a Using or Try...Catch statement. Internally, the SqlDataAdapter uses a Try...Catch statement to ensure that its connection gets closed. Note: 1. If a SqlConnection is already open when you call the Fill method, it doesnt close it. In other words, the Fill method maintains the state of the connection. 2. Opening and closing a database connection is a slow operation. If you know that you will need to perform another database operation after using the SqlDataAdapter, you should explicitly create a SqlConnection EG: public DataTable GetAll() { SqlConnection con = new SqlConnection(_connectionString); // Initialize the DataAdapter Page | 58

C# 3.0: A Beginners Guide [Notes]


SqlDataAdapter adaptor = new SqlDataAdapter("SELECT Title,Director FROM Movies", con); // Create a DataTable DataTable dtblMovies = new DataTable(); using (con) { con.Open(); // Populate the DataTable adaptor.Fill(dtblMovies); //Perform other database operations with connection ... } // Return results return dtblMovies; } [SQLCommandBuilder] The data adapter contains command object references for SELECT, INSERT, UPDATE, and DELETE operations on the data. Executing Asynchronous Database Commands: Normally, when you execute a database command, the thread executing the command must wait until the command finishes before executing any additional code. You can use the current thread to execute yet another database command by using Asynchronous Database Commands. There are two reasons that you might want to use asynchronous database commands when building an ASP.NET page. First, executing multiple database commands simultaneously can significantly improve your applications performance. Second, the ASP.NET Framework uses a limited thread pool to service page requests. When ASP.NET Framework receives a request for a page, it assigns a thread to handle the request. If ASP.NET Framework runs out of threads, the request is queued until a thread becomes available. If too many threads are queued, the framework rejects the page request with a 503 Server Too Busy response code. Note: You can configure the ASP.NET thread pool with the httpRuntime element in the web configuration file. You can modify the appRequestQueueLimit, minFreeThreads, and minLocalRequestFreeThreads attributes to control how many requests ASP.NET Framework queues before giving up and sending an error. There are two parts to this task undertaken in this section. A data access component that supports asynchronous ADO.NET methods must be created and an ASP.NET page that executes asynchronously. [Both Required] Page | 59

C# 3.0: A Beginners Guide [Notes]

Using Asynchronous ADO.NET Methods: There are asynchronous versions of several ADO.NET methods. These methods come in pairs: a Begin and End method. For example, the SqlCommand object supports the following asynchronous methods: I. II. III. IV. V. VI. BeginExecuteNonQuery() EndExecuteNonQuery() BeginExecuteReader() EndExecuteReader() BeginExecuteXmlReader() EndExecuteXmlReader()

The idea is that when you execute the Begin method, the asynchronous task is started on a separate thread. To use these asynchronous methods, you must use a special attribute in your connection string: the Asynchronous Processing=true attribute.

Page | 60

C# 3.0: A Beginners Guide [Notes]


EG: public class AsyncDataLayer { private static readonly string _connectionString; private SqlCommand _cmdMovies; public IAsyncResult BeginGetMovies(AsyncCallback callback, Object state) { SqlConnection con = new SqlConnection(_connectionString); _cmdMovies = new SqlCommand("WAITFOR DELAY '0:0:3';SELECT SAVEID,USERID FROM MRSAVE", con); con.Open(); return _cmdMovies.BeginExecuteReader(callback, state, CommandBehavior.CloseConnection); } public List<AsyncDataLayer.Movie> EndGetMovies(IAsyncResult result) { List<AsyncDataLayer.Movie> results = new List<AsyncDataLayer.Movie>(); SqlDataReader reader = _cmdMovies.EndExecuteReader(result); while (reader.Read()) { AsyncDataLayer.Movie newMovie = new AsyncDataLayer.Movie(); newMovie.Title = (int)reader["SAVEID"]; newMovie.Director = (string)reader["USERID"]; results.Add(newMovie); } return results; } static AsyncDataLayer() { _connectionString = WebConfigurationManager.ConnectionStrings["JNJGLRADCRP1_GIS_DW"].ConnectionSt ring; _connectionString = _connectionString + ";Asynchronous Processing=true"; } public class Movie { private int _title; private string _director; public int Title { get { return _title; } set { _title = value; } } public string Director { get { return _director; } set { _director = value; } } } }

Page | 61

C# 3.0: A Beginners Guide [Notes]

Using Asynchronous ASP.NET Pages: When you take advantage of asynchronous ADO.NET methods, you must also enable asynchronous ASP.NET page execution. You enable an asynchronous ASP.NET page by adding the following two attributes to a page directive: <%@ Page Language="C#" Async="true" AsyncTimeout="5" Trace="true" AutoEventWireup="true" CodeFile="ViewPage.aspx.cs" Inherits=" ViewPage" %> The first attribute enables asynchronous page execution. The second attribute specifies a timeout value in seconds. The timeout value specifies the amount of time that the page gives a set of asynchronous tasks to complete before the page continues execution. After you enable asynchronous page execution, you must set up the asynchronous tasks and register the tasks with the page. You represent each asynchronous task with an instance of the PageAsyncTask object. You register an asynchronous task for a page by calling the Page.RegisterAsyncTask method. EG [Remaining]: ASPX: <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Untitled Page</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label id="lblError" Runat="server" /> <asp:GridView id="grdMovies" Runat="server" /> </div> </form> </body> CODEFILE: using System.Threading; public partial class ViewPage : System.Web.UI.Page { private AsyncDataLayer dataLayer = new AsyncDataLayer(); void Page_Load() { // Setup asynchronous data execution PageAsyncTask task = new PageAsyncTask(BeginGetData, EndGetData, TimeoutData, null, true); Page.RegisterAsyncTask(task); // Fire off asynchronous tasks Page | 62

C# 3.0: A Beginners Guide [Notes]


Page.ExecuteRegisteredAsyncTasks(); } IAsyncResult BeginGetData(object sender, EventArgs e, AsyncCallback callback, object state) { // Show Page Thread ID Trace.Warn("BeginGetData: " + Thread.CurrentThread.GetHashCode()); // Execute asynchronous command return dataLayer.BeginGetMovies(callback, state); } void EndGetData(IAsyncResult ar) { // Show Page Thread ID Trace.Warn("EndGetData: " + Thread.CurrentThread.GetHashCode()); // Bind results grdMovies.DataSource = dataLayer.EndGetMovies(ar); grdMovies.DataBind(); } void TimeoutData(IAsyncResult ar) { // Display error message lblError.Text = "Could not retrieve data!"; } }

The constructor for the PageAsyncTask object accepts the following parameters: I. II. III. IV. V. beginHandler: The method that executes when the asynchronous task begins. endHandler: The method that executes when the asynchronous task ends. timoutHandler: The method that executes when the asynchronous task runs out of time according to the Page directives AsyncTimeout attribute. state: An arbitrary object that represents state information. executeInParallel: A Boolean value that indicates whether multiple asynchronous tasks should execute at the same time or execute in sequence. You can create multiple PageAsyncTask objects and register them for the same page. When you call the ExecuteRegisteredAsyncTasks method, all the registered tasks are executed. It is important to understand that the asynchronous task continues to execute even when the task executes longer than the interval of time specified by the AsyncTimeout attribute. The AsyncTimeout attribute specifies the amount of time that a page is willing to wait before continuing execution. An asynchronous task is not canceled if takes too long.

Page | 63

C# 3.0: A Beginners Guide [Notes]

1. How can we force the connection object to close after my datareader is closed? Ans: //using CommandBehavior.CloseConnection public SqlDataReader GetAll() { SqlConnection con = new SqlConnection(_connectionString); SqlCommand cmd = new SqlCommand("SELECT Title,Director FROM Movies", con); con.Open(); return cmd.ExecuteReader(CommandBehavior.CloseConnection); }

The CommandBehavior.CloseConnection parameter enables you to: 1. Return a SqlDataReader from a method. CommandBehavior.CloseConnection parameter causes the SqlConnection object associated with the SqlDataReader to close automatically. The big disadvantage of using the CommandBehavior.CloseConnection parameter is that it prevents you from adding any exception handling code. A Using statement or Try...Catch statement would force the SqlConnection to close before the SqlDataReader is returned from the method. 2. I want to force the data reader to return only schema of the data store rather than data. Ans: SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.SchemaOnly); 2. When all the records are read from the SqlDataReader, the

3. What is difference between dataset and data reader? Ans: S.No. 1. DataReader Data Reader provides forward-only and read-only access to data DateSet Dataset object can hold more than one table (in other words more than one row set) from the same data source as well as the relationships between them. 2. 3. 4. 5. Data Reader cannot persist contents, they are forward only Data Reader is connected architecture Fast Cant move back while reading records Page | 64 Dataset is a disconnected architecture Slow Can move back while reading records Dataset can persist contents

C# 3.0: A Beginners Guide [Notes]


6. Always try to use Data Reader wherever possible, as it is meant especially for speed performance When application needs to access data from more than one table Dataset forms the best choice.

4. Methods provided by command object: ExecuteNonQuery: Executes the command defined in the Command Text property against the connection defined in the Connection property. Returns an Integer indicating the number of rows affected by the query. Used for a query that does not return any row (an UPDATE, DELETE, or INSERT). ExecuteReader: Executes the command defined in the Command Text property against the connection defined in the Connection property. Returns a "reader" object that is connected to the resulting row set within the database, allowing the rows to be retrieved. If you want to retrieve the value of the Title column for the current row represented by a DataReader, you can use any of the following methods: string title = (string)reader["Title"]; //By Column name //As an Object string title = (string)reader[0]; //By Column position //As an Object string title = reader.GetString(0); //By Column position //As a String SqlString title = reader.GetSqlString(0); //By Column position //As a SqlString Note: Retrieving a column by its position rather than its name is faster. A SqlString represents the value using the specialized data types defined in the System.Data.SqlTypes namespace.

ExecuteScalar: Executes the command defined in the Command Text property against the connection defined in the Connection property. Returns only single value (effectively the first column of the first row of the resulting row set any other returned columns and rows are discarded). It is fast and efficient when only a "singleton" value is required The ExecuteScalar method returns a value of type Object. This means that you must cast the value returned from ExecuteScalar to a particular type before you do anything with the value. There is no real difference in performance between using the ExecuteScalar method with a stored procedure and using an output parameter.

Page | 65

C# 3.0: A Beginners Guide [Notes]


5. What are basic methods of Data adapter? Fill: Executes the Select Command to fill the Dataset object with data from the data source. It is also be used to update (refresh) an existing table in a Dataset with changes made to the data in the original data source if there is a primary key in the table in the Dataset. FillSchema: Uses the Select Command to extract just the schema for a table from the data source, and creates an empty table in the DataSet object with all the corresponding constraints. Update: Calls the respective Insert Command, Update Command, or Delete Command for each inserted, updated, or deleted row in the DataSet so as to update the original data source with the changes made to the content of the DataSet. 6. How can we save all data from dataset? Dataset has Accept Changes method, which commits all the changes since last time Accept changes has been executed. 7. DataSet Methods: AcceptChanges: Commits all the changes made to this DataSet since it was loaded or since the last time AcceptChanges was called. Clone: Copies the structure of the DataSet, including all DataTable schemas, relations, and constraints. It does not copy any data. Copy: Copies both the structure and data for this DataSet. GetChanges: Gets a copy of the DataSet that contains all changes made to it since it was loaded or since AcceptChanges was last called. GetXml: Returns the XML representation of the data stored in the DataSet. ReadXML: Reads a XML document in to Dataset. Writexml: This writes a XML data to disk. HasChanges: Gets a value indicating whether the DataSet has changes, including new, deleted, or modified rows. RejectChanges: Rolls back all the changes made to the DataSet since it was created, or since the last time DataSet.AcceptChanges was called. Page | 66

C# 3.0: A Beginners Guide [Notes]

8. How can we add/remove row is in Data Table object of Dataset? Data table provides NewRow method to add new row to Data Table. Data Table has DataRowCollection object that has all rows in a Data Table object NewRow: Creates a new DataRow with the same schema as the table.

9. DataTableCollection Methods: Add(DataTable): Adds the specified DataTable to the collection. Add(String): Creates a DataTable object by using the specified name and adds it to the collection. IndexOf(DataTable): Gets the index of the specified DataTable object. Remove(DataTable): Removes the specified DataTable object from the collection. Remove(String): Removes the DataTable object with the specified name from the collection. RemoveAt: Removes the DataTable object at the specified index from the collection. 10. Data View represents a complete table or can be small section of rows depending on some criteria. It is best used for sorting and finding data within data table. Data view has the following methods:Find: It takes an array of values and returns the index of the row. Find Row: This also takes array of values but returns a collection of Data Row. If we want to manipulate data of Data Table object create Data View (Using the Default View we can create Data View object) of the Data Table object and use the following functionalities:Add New: Adds a new row to the Data View object. Delete: Deletes the specified row from Data View object. 11. What is the use of Command Builder? Command Builder builds Parameter objects automatically.

Page | 67

C# 3.0: A Beginners Guide [Notes]

12. Connection pooling? When connection pooling is enabled, if we request a connection object by passing connection string then an object is created in the connection pool. If we request another connection object by passing same connection string then this request will share the previously created connection object. If the connection string is different, then a new connection object will be created. When connection pooling is enabled, closing a connection does not really close the connection to the database server. Instead, closing the connection releases the database connection back into the pool. By default, the ADO.NET Framework keeps a maximum of 100 connections opened in a connection pool. 13. Maximum Pool Size in ADO.NET Connection String? Maximum pool size decides the maximum number of connection objects to be pooled. If the maximum pool size is reached and there is no usable connection available the request is queued until connections are released back in to pool. To disable connection pooling set Pooling=false in connection string if it is an ADO.NET Connection.

14. Whats difference between Optimistic and Pessimistic locking? Pessimistic: In this, when user wants to update data it locks the record and till then no one can update data. Optimistic: In optimistic locking multiple users can open the same record for updating, thus increase maximum concurrency. Record is only locked when updating the record.

15. How can we load multiple tables in a Dataset? EG: SqlDataAdapter adapter = new SqlDataAdapter( "SELECT * FROM dbo.table1; SELECT * FROM dbo.table2", connection); adapter.TableMappings.Add("Table", "TableName1"); adapter.TableMappings.Add("Table1", "TableName2"); DataSet dataSet = new DataSet(); adapter.Fill(dataSet); OR SqlDataAdapter adapter = new SqlDataAdapter( Page | 68

C# 3.0: A Beginners Guide [Notes]


"SELECT * FROM dbo.table1; SELECT * FROM dbo.table2", connection); DataSet dataSet = new DataSet(); adapter.Fill(dataSet); dataSet.Tables[0].TableName = "TableName1"; dataSet.Tables[1].TableName = "TableName2";

OR SqlCommand command = new SqlCommand("SELECT * FROM dbo.table1", connection); SqlDataAdapter adapter = new SqlDataAdapter(); adapter.SelectCommand = command; DataSet dataSet = new DataSet(); adapter.Fill(dataSet, "TableName1"); adapter.SelectCommand.CommandText = "SELECT * FROM dbo.table2"; adapter.Fill(dataSet, "TableName2"); There are a couple of problems with doing it this way: The DataTables don't have the same name as the tables in the database, you have to set them yourself You can't update/save the tables to the database; to do that you must use a separate DataAdapter for each table. OR SqlDataAdapter dataAdapter1 = new SqlDataAdapter( "SELECT * FROM dbo.table1", connection); SqlDataAdapter dataAdapter2 = new SqlDataAdapter( "SELECT * FROM dbo.table2", connection); DataSet dataSet = new DataSet(); dataAdapter1.Fill(dataSet, "TableName1"); dataAdapter2.Fill(dataSet, "TableName2");

In the above codes, it will show how to load multiple tables in single DataSet. dataSet.Tables("TableName1").DefaultView; dataSet.Tables("TableName2").DefaultView; OR //retrieve first table data for (i = 0; i <= dataSet.Tables[0].Rows.Count - 1; i++) { MessageBox.Show(dataSet.Tables[0].Rows[i].ItemArray[0] + " -- " + dataSet.Tables[0].Rows[i].ItemArray[1]); } Page | 69

C# 3.0: A Beginners Guide [Notes]

//retrieve second table data for (i = 0; i <= dataSet.Tables[1].Rows.Count - 1; i++) { MessageBox.Show(dataSet.Tables[1].Rows[i].ItemArray[0] + " -- " + dataSet.Tables[1].Rows[i].ItemArray[1]); } In order to get table data, use Tables collection of DataSet and the Defaultview object will give you the necessary output 16. Can you explain the difference between an ADO.NET Dataset and an ADO Record set? Properties Data Retrieval ADO.NET Dataset We can retrieve data from two databases like oracle and sql server and merge them in one dataset Representation Transmission XML can be transmitted on HTTP COM cannot be transmitted on HTTP ADO Record set With record set this is not possible

17. How can we perform transactions in .NET? I. II. Open Connection using the Open method of the connection object. Begin Transaction using the Begin Transaction method of the connection object. This method provides us with a transaction object that we will use later to commit or rollback the transaction. Set the Transaction property of the command object to the above mentioned transaction object. III. IV. V. Execute SQL using Command object Commit or Rollback Transaction using the Commit or Rollback method of the transaction object. Close Connection

18. How many ways are there to implement locking in ADO.NET? 19. How can we add relation between tables in a Dataset? Relations can be added between Data Table objects using the Data Relation object. EG: DataSet dst = new DataSet("CustomerOrders"); DataColumn customerColumn, orderColumn; Page | 70

C# 3.0: A Beginners Guide [Notes]


customerColumn = dst.Tables["Customers"].Columns["ID"]; orderColumn = dst.Tables["Orders"].Columns["CustomerID"]; DataRelation dr = new DataRelation("CustOrders", customerColumn, orderColumn); dst.Relations.Add(dr); OR DataSet dst = new DataSet("CustomerOrders"); dst.Relations.Add("CustOrders", dst.Tables["Customers"].Columns["ID"], dst.Tables["Orders"].Columns["CustomerID"]); The example adds a single DataRelation to the Relations collection of the DataSet. The first argument in the example specifies the name of the DataRelation being created. The second argument sets the parent DataColumn and the third argument sets the child DataColumn.

Note: Adding a DataRelation to a DataSet adds, by default, a UniqueConstraint to the parent table and a ForeignKeyConstraint to the child table 20. What is the use of Command Builder? A CommandBuilder object is used to automatically create Update, Delete, and Insert SQL statements for you, based on a Select statement that you supply. You would declare a DataAdapter object, set its SelectCommand.CommandText property to your Select SQL statement. Then when you declare a CommandBuilder object, you include the dataadapter in the CommandBuilder's constructor parameter and it will automatically create the other statements for you when you run a DataAdapter.

EG: string connectionString = ConfigurationManager.ConnectionStrings["JNJGLRADCRP1_GIS_DW"].ConnectionStrin g; //Connection String SqlConnection connection = new SqlConnection(connectionString); //Connection Object string queryString = "SELECT eno, ename FROM MRSAVE"; //Query SqlDataAdapter dataAdapter = new SqlDataAdapter(queryString, connection); //Initialize the SqlCommandBuilder, Create Update, Insert, and Delete commands with SqlCommandBuilder SqlCommandBuilder cd = new SqlComandBuilder(dataAdapter); DataTable dataTable = new DataTable(); dataAdapter.Fill(dataTable);

Page | 71

C# 3.0: A Beginners Guide [Notes]


//Table has 2 columns known as eno and ename DataRow dataRow = dataTable.NewRow(); //create a DataRow dataRow["eno"] = 100; dataRow["ename"] = "king"; //the row is temporarily saved dataTable.Rows.Add(dataRow); //save the Row permanently uses Power of SqlComandBuilder dataAdapter.Update(dataTable);

Note: Be careful while using Derive Parameters method as it needs an extra trip to the Data store, which can be very inefficient DeriveParameters retrieves parameter information from the stored procedure specified in the SqlCommand and populates the Parameters collection of the specified SqlCommand object. DeriveParameters overwrites any existing parameter information for the command object. DeriveParameters requires an additional call to the database to obtain the information. If the parameter information is known in advance, it is more efficient to populate the parameters collection by setting the information explicitly.

21. A context connection enables you to connect to the same database server as the stored procedure without authenticating. Heres how you can initialize a SqlConnection to use a context connection: SqlConnection con = new SqlConnection("context connection=true");

Page | 72

C# 3.0: A Beginners Guide [Notes]


22. The using statement forces the connection to close, regardless of whether an error occurs when a command is executed against the database. The using statement also disposes of the Connection object. (If you need to reuse the Connection, you need to reinitialize it.) Alternatively, you can use a try...catch statement to force a connection to close 23. As an alternative to using the AddWithValue() method, you can create a SqlParameter explicitly and add the SqlParameter to a SqlCommand objects Parameters collection. The advantage of creating a parameter explicitly is that you can specify parameter properties explicitly, such as its name, type, size, precision, scale, and direction. EG: SqlCommand cmd = new SqlCommand("INSERT Titles (Title) VALUES (@Title)", con); SqlParameter paramTitle = new SqlParameter(); paramTitle.ParameterName = "@Title"; paramTitle.SqlDbType = SqlDbType.NVarChar; paramTitle.Size = 50; paramTitle.Value = "ASP.NET 4.0 Unleashed"; cmd.Parameters.Add(paramTitle); OR SqlCommand cmd = new SqlCommand("INSERT Test (Title) VALUES (@Title)", con); cmd.Parameters.Add("@Title", SqlDbType.NVarChar,50).Value = "ASP.NET 4.0 Unleashed";

24. Returning Multiple Resultsets: SELECT * FROM MoviesCategories; SELECT * FROM Movies A semicolon is used to separate the two queries. Executing multiple queries in one shot can result in better performance. When you execute multiple queries with a single command, you dont tie up multiple database connections. EG: using System.Data; using System; using System.Configuration; using System.Data.SqlClient; class DataLayer { private static readonly string _connectionString; static DataLayer() { _connectionString = ConfigurationManager.ConnectionStrings["JNJGLRADCRP1_GIS_DW"].ConnectionStrin g; ; } Page | 73

C# 3.0: A Beginners Guide [Notes]


public class MovieCategory { private int _id; private string _name; public int Id { get { return _id; } set { _id = value; } } public string Name { get { return _name; } set { _name = value; } } } public class Movie { private string _title; private int _categoryId; public string Title { get { return _title; } set { _title = value; } } public int CategoryId { get { return _categoryId; } set { _categoryId = value; } } } public static void GetMovieData(List<DataLayer.MovieCategory> movieCategories, List<DataLayer.Movie> movies) { string commandText = "SELECT Id,Name FROM MovieCategories;SELECT Title,CategoryId FROM Movies"; SqlConnection con = new SqlConnection(_connectionString); SqlCommand cmd = new SqlCommand(commandText, con); using (con) { // Execute command con.Open(); SqlDataReader reader = cmd.ExecuteReader(); // Create movie categories while (reader.Read()) { DataLayer.MovieCategory newCategory = new DataLayer.MovieCategory(); newCategory.Id = (int)reader["Id"]; newCategory.Name = (string)reader["Name"]; movieCategories.Add(newCategory); } // Move to next result set reader.NextResult(); Page | 74

C# 3.0: A Beginners Guide [Notes]


// Create movies while (reader.Read()) { DataLayer.Movie newMovie = new DataLayer.Movie(); newMovie.Title = (string)reader["Title"]; newMovie.CategoryId = (int)reader["CategoryID"]; movies.Add(newMovie); } } } } More Examples: using using using using System.Data; System; System.Configuration; System.Data.SqlClient;

class Movie { private static readonly string _connectionString; static Movie() { _connectionString = ConfigurationManager.ConnectionStrings["JNJGLRADCRP1_GIS_DW"].ConnectionStrin g; } private int _id; private string _title; private string _director; public int Id { get { return _id; } set { _id = value; } } public string Title { get { return _title; } set { _title = value; } } public string Director { get { return _director; } set { _director = value; } } public List<Movie> Select() { List<Movie> results = new List<Movie>(); SqlConnection con = new SqlConnection(_connectionString); Page | 75

C# 3.0: A Beginners Guide [Notes]


SqlCommand cmd = new SqlCommand("SELECT Id,Title,Director FROM Movies", con); using (con) { con.Open(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Movie movie = new Movie(); movie.Id = (int)reader["Id"]; movie.Title = (string)reader["Title"]; movie.Director = (string)reader["Director"]; results.Add(movie); } } return results; } public void Update(int id, string title, string director) { SqlConnection con = new SqlConnection(_connectionString); SqlCommand cmd = new SqlCommand("UPDATE MOVIES SET Title=@Title,Director=@Director WHERE Id=@Id", con); cmd.Parameters.AddWithValue("@Title", title); cmd.Parameters.AddWithValue("@Director", director); cmd.Parameters.AddWithValue("@Id", id); using (con) { con.Open(); cmd.ExecuteNonQuery(); } } public void Delete(int id) { SqlConnection con = new SqlConnection(_connectionString); SqlCommand cmd = new SqlCommand("DELETE MOVIES WHERE Id=@Id", con); cmd.Parameters.AddWithValue("@Id", id); using (con) { con.Open(); cmd.ExecuteNonQuery(); } } //Using Stored Procedure public List<String> GetRandomMovies() { List<String> results = new List<String>(); SqlConnection connection = new SqlConnection(_connectionString); connection.StatisticsEnabled = true; SqlCommand command = new SqlCommand("GetRows", connection); command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue("@rowsToReturn", 5); using (connection) { connection.Open(); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) Page | 76

C# 3.0: A Beginners Guide [Notes]


results.Add((string)reader["Title"]); } IDictionary stats = con.RetrieveStatistics(); long executionTime = (long)stats["ExecutionTime"]; return results; } Stored Procedure: CREATE PROCEDURE dbo.GetRows ( @rowsToReturn int ) AS SELECT TOP(@rowsToReturn )Id, Title, Director FROM Movies

//Reading Return value by SQL private int GetMovieCount() { int result = 0; SqlConnection con = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand("GetMovieCount", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@ReturnVal", SqlDbType.Int).Direction =ParameterDirection.ReturnValue; using (con) { con.Open(); cmd.ExecuteNonQuery(); result = (int)cmd.Parameters["@ReturnVal"].Value; } return result; }

Stored Procedure: CREATE PROCEDURE dbo.GetMovieCount AS RETURN (SELECT COUNT(*) FROM Movies) Note: A stored procedure has only one return value, and it must be an integer value. If you need to return more than one value, or values of a different data type than an integer, you need to use stored procedure output parameters. //Using OUTPUT parameter public List<Movie> GetBoxOffice(out decimal SumBoxOfficeTotals) { List<Movie> results = new List<Movie>(); SqlConnection con = new SqlConnection(_connectionString); SqlCommand cmd = new SqlCommand("GetBoxOfficeTotals", con); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@SumBoxOfficeTotals", SqlDbType.Money).Direction = ParameterDirection.Output; Page | 77

C# 3.0: A Beginners Guide [Notes]


using (con) { con.Open(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Movie movie = new Movie(); movie.Title = (string)reader["Title"]; movie.BoxOfficeTotals = (decimal)reader["BoxOfficeTotals"]; results.Add(movie); } reader.Close(); SumBoxOfficeTotals =(decimal)cmd.Parameters["@SumBoxOfficeTotals"].Value; } return results; } Note: The SqlDataReader is explicitly closed before the output parameter is read. If you do not close the SqlDataReader first, attempting to read the value of the output parameter raises an exception. //Execute Scalar public string GetColllection(string movieName) { SqlConnection con = new SqlConnection(_connectionString); SqlCommand cmd = new SqlCommand("SELECT BoxOfficeTotals FROM Movies WHERE Title=@Title", con); cmd.Parameters.AddWithValue("@Title", movieName); using (con) { con.Open(); Object result = cmd.ExecuteScalar(); if (result != null) return String.Format("{0:c}", result); else return "No match!"; } } Note: The ExecuteScalar() method returns a value of type Object. This means that you must cast the value returned from ExecuteScalar() to a particular type before you do anything with the value. //using CommandBehavior.CloseConnection public SqlDataReader GetAll() { SqlConnection con = new SqlConnection(_connectionString); SqlCommand cmd = new SqlCommand("SELECT Title,Director FROM Movies", con); con.Open(); return cmd.ExecuteReader(CommandBehavior.CloseConnection); } }

Page | 78

C# 3.0: A Beginners Guide [Notes]


Working with Multiple Active Result Sets: If you take advantage of MARS, you can represent multiple resultsets with a single database connection. Using MARS is valuable in scenarios in which you need to iterate through a resultset and perform an additional database operation for each record in the resultset. MARS is disabled by default. To enable MARS, you must include a MultipleActiveResultSets=True attribute in a connection string.

Example: void BuildTree() { // Create MARS connection string _connectionString = ConfigurationManager.ConnectionStrings["JNJGLRADCRP1_GIS_DW"].ConnectionStrin g; SqlConnection con = new SqlConnection("MultipleActiveResultSets=True;" + _connectionString); // Create Movie Categories command string cmdCategoriesText = "SELECT CID,CNAME FROM A_CTable"; SqlCommand cmdCategories = new SqlCommand(cmdCategoriesText, con); // Create Movie command string cmdMoviesText = "SELECT MID,MNAME FROM A_MTable WHERE CID = @CategoryId"; SqlCommand cmdMovies = new SqlCommand(cmdMoviesText, con); cmdMovies.Parameters.Add("@CategoryId", SqlDbType.Int); using (con) { con.Open(); // Iterate through categories SqlDataReader categories = cmdCategories.ExecuteReader(); while (categories.Read()) { // Add category node int id = categories.GetInt32(0); string name = categories.GetString(1); TreeNode catNode = new TreeNode(name); TreeView1.Nodes.Add(catNode); // Iterate through matching movies cmdMovies.Parameters["@CategoryId"].Value = id; SqlDataReader movies = cmdMovies.ExecuteReader(); while (movies.Read()) { // Add movie node string title = movies.GetString(1); TreeNode movieNode = new TreeNode(title); catNode.ChildNodes.Add(movieNode); } movies.Close(); Page | 79

C# 3.0: A Beginners Guide [Notes]


} } } Note: The MultipleActiveResultSets attribute is included in the connection string used to open the database connection. If MARS were not enabled, you couldnt loop through the interior SqlDataReader that represents the matching movies while the containing SqlDataReader that represents the moviecategories is open.

Page | 80

C# 3.0: A Beginners Guide [Notes]


Chapter XXX: WCF

Windows Communication Foundation (Code named Indigo) is a programming platform and runtime system for building, configuring and deploying network-distributed services. It is the latest service oriented technology; Interoperability is the fundamental characteristics of WCF. It is unified programming model provided in .Net Framework 3.0. WCF is a combined features of Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for all .NET communication.

I. II.

WCF is interoperable with other services when compared to .Net Remoting, where the client and service have to be .Net. WCF services provide better reliability and security in compared to ASMX web services.

Difference between WCF and Web service? Web service is a part of WCF. WCF offers much more flexibility and portability to develop a service when comparing to web service. Still we are having more advantages over Web service, following table provides detailed difference between them. Features Hosting Programming Model Web Service It can be hosted in IIS [WebService] attribute has to be added to the class method exposed to client WCF It can be hosted in IIS, windows activation service, Self-hosting, Windows service [ServiceContraact] attribute has to be added to the class the method exposed to client

[WebMethod] attribute represents the [OperationContract] attribute represents One-way, Request- Response are the One-Way, Request-Response, Duplex are

Operation

different operations supported in web different type of operations supported in service WCF System.Runtime.Serialization namespace is used for serialization XML 1.0, MTOM, Binary, Custom Can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P, Custom Page | 81 System.Xml.serialization name space is used for serialization XML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, Custom Can be accessed through HTTP, TCP, Custom

XML

Encoding

Transports

C# 3.0: A Beginners Guide [Notes]


Protocols Security Security, Reliable messaging, Transactions

EndPoint? WCF Service is a program that exposes a collection of Endpoints. Each Endpoint is a portal for communicating with the world. All the WCF communications are take place through end point. End point consists of three components. Address: Basically URL, specifies where this WCF service is hosted .Client will use this url to connect to the service. EG: http://localhost:8090/MyService/SimpleCalculator.svc Binding: Binding will describes how client will communicate with service. There are different protocols available for the WCF to communicate to the Client. A binding has several characteristics, including the following: I. II. Transport -Defines the base protocol to be used like HTTP, Named Pipes, TCP, and MSMQ are some type of protocols. Encoding (Optional) - Three types of encoding are available-Text, Binary, or Message Transmission Optimization Mechanism (MTOM). MTOM is an interoperable message format that allows the effective transmission of attachments or large messages (greater than 64K). III. Protocol(Optional) - Defines information to be used in the binding such as Security, transaction or reliable messaging capability Binding BasicHttpBinding WSHttpBinding WSDualHttpBinding Description Basic Web service communication. No security by default Web services with WS-* support. Supports transactions Web services with duplex contract and transaction support

WSFederationHttpBinding Web services with federated security. Supports transactions MsmqIntegrationBinding NetMsmqBinding Communication directly with MSMQ applications. Supports transactions Communication between WCF applications by using queuing. Page | 82

C# 3.0: A Beginners Guide [Notes]


Supports transactions NetNamedPipeBinding NetPeerTcpBinding NetTcpBinding Communication between WCF applications on same computer. Supports duplex contracts and transactions Communication between computers across peer-to-peer services. Supports duplex contracts Communication between WCF applications across computers. Supports duplex contracts and transactions

Contract: Collection of operation that specifies what the endpoint will communicate with outside world. Usually name of the Interface will be mentioned in the Contract, so the client application will be aware of the operations which are exposed to the client. Each operation is a simple exchange pattern such as one-way, duplex and request/reply.

EG: Endpoints will be mentioned in the web.config file on the created service. <system.serviceModel> <services> <service name="MathService" behaviorConfiguration="MathServiceBehavior"> <endpoint address=http://localhost:8090/MyService/MathService.svc contract="IMathService" binding="wsHttpBinding"/> </service> </services> <behaviors> Page | 83

C# 3.0: A Beginners Guide [Notes]


<serviceBehaviors> <behavior name="MathServiceBehavior"> <serviceMetadata httpGetEnabled="True"/> <serviceDebug includeExceptionDetailInFaults="true" /> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel>

Page | 84

C# 3.0: A Beginners Guide [Notes]

Need to Write

Page | 85

C# 3.0: A Beginners Guide [Notes]


What are the important principles of SOA (Service oriented Architecture)? What are ends, contract, address, and bindings? Which specifications does WCF follow? What are the main components of WCF? Explain how Ends, Contract, Address, and Bindings are done in WCF? What is a service class? What is a service contract, operation contract and Data Contract? What are the various ways of hosting a WCF service? How do we host a WCF service in IIS? What are the advantages of hosting WCF Services in IIS as compared to self-hosting? What are the major differences between services and Web services? What is the difference WCF and Web services? What are different bindings supported by WCF? Which are the various programming approaches for WCF? What is one-way operation? Can you explain duplex contracts in WCF? How can we host a service on two different protocols on a single server? How can we use MSMQ bindings in WCF? Can you explain transactions in WCF? What different transaction isolation levels provided in WCF? Can we do transactions using MSMQ?

Page | 86

C# 3.0: A Beginners Guide [Notes]


Can we have two-way communications in MSMQ? What are Volatile queues? What are Dead letter queues? What is a poison message?

Page | 87

C# 3.0: A Beginners Guide [Notes]

--Binding concept, sessions, https://www.logicsmeet.com/forum/38554-.net-interview-questions-for-3-yearsexperience.aspx

[Interview Question and Answers]

What is XHTML? Are ASP.NET Pages compliant with XHTML?

In simple words, XHTML is a stricter and cleaner version of HTML. XHTML stands for EXtensible Hypertext Markup Language and is a W3C Recommendation.

Yes, ASP.NET 2.0 Pages are XHTML compliant. However the freedom has been given to the user to include the appropriate document type declaration.

More info can be found at http://msdn2.microsoft.com/en-us/library/exc57y7e.aspx

Can I deploy the application without deploying the source code on the server?

Yes. You can obfuscate your code by using a new precompilation process called precompilation for deployment. You can use the aspnet_compiler.exe to precompile a site. This process builds each page in your web application into a single application DLL and some placeholder files. These files can then be deployed to the server.

You can also accomplish the same task using Visual Studio 2005 by using the Build->Publish menu.

Does ViewState affect performance? What is the ideal size of a ViewState? How can you compress a viewstate?

Viewstate stores the state of controls in HTML hidden fields. At times, this information can grow in size. This does affect the overall responsiveness of the page, thereby affecting

Page | 88

C# 3.0: A Beginners Guide [Notes]


performance. The ideal size of a viewstate should be not more than 25-30% of the page size.

Viewstate can be compressed to almost 50% of its size. .NET also provides the GZipStream or DeflateStream to compress viewstate. Another option is explained by Scott Hanselmann over here.

How can you detect if a viewstate has been tampered?

By setting the EnableViewStateMac to true in the @Page directive. This attribute checks the encoded and encrypted viewstate for tampering.

Can I use different programming languages in the same application?

Yes. Each page can be written with a different programming language in the same application. You can create a few pages in C# and a few in VB.NET.

Can the App_Code folder contain source code files in different programming languages?

No. All source code files kept in the root App_Code folder must be in the same programming language.

Update: However, you can create two subfolders inside the App_Code and then add both C# and VB.NET in the respective subfolders. You also have to add configuration settings in the web.config for this to work.

How do you secure your connection string information?

By using the Protected Configuration feature.

How do you secure your configuration files to be accessed remotely by unauthorized users?

Page | 89

C# 3.0: A Beginners Guide [Notes]


ASP.NET configures IIS to deny access to any user that requests access to the Machine.config or Web.config files.

How can I configure ASP.NET applications that are running on a remote machine?

You can use the Web Site Administration Tool to configure remote websites.

How many web.config files can I have in an application?

You can keep multiple web.config files in an application. You can place a Web.config file inside a folder or wherever you need (apart from some exceptions) to override the configuration settings that are inherited from a configuration file located at a higher level in the hierarchy.

I have created a configuration setting in my web.config and have kept it at the root level. How do I prevent it from being overridden by another web.config that appears lower in the hierarchy?

By setting the element's Override attribute to false.

What is the difference between Response.Write and Response.Output.Write?

As quoted by Scott Hanselman, the short answer is that the latter gives you String.Formatstyle output and the former doesn't.

To get a detailed explanation, follow this link

What is Cross Page Posting? How is it done?

By default, ASP.NET submits a form to the same page. In cross-page posting, the form is submitted to a different page. This is done by setting the PostBackUrl property of the button(that causes postback) to the desired page. In the code-behind of the page to which the form has been posted, use the FindControl method of the PreviousPage property to reference the data of the control in the first page.

Page | 90

C# 3.0: A Beginners Guide [Notes]


Can you change a Master Page dynamically at runtime? How?

Yes. To change a master page, set the MasterPageFile property to point to the .master page during the PreInit page event.

How do you apply Themes to an entire application?

By specifying the theme in the web.config file.

Eg: <configuration>

<system.web>

<pages theme=BlueMoon />

</system.web>

</configuration>

How do you exclude an ASP.NET page from using Themes?

To remove themes from your page, use the EnableTheming attribute of the Page directive.

Your client complains that he has a large form that collects user input. He wants to break the form into sections, keeping the information in the forms related. Which control will you use?

The ASP.NET Wizard Control.

To learn more about this control, visit this link. Page | 91

C# 3.0: A Beginners Guide [Notes]


Do webservices support data reader?

No. However it does support a dataset.

What is use of the AutoEventWireup attribute in the Page directive ?

The AutoEventWireUp is a boolean attribute that allows automatic wireup of page events when this attribute is set to true on the page. It is set to True by default for a C# web form whereas it is set as False for VB.NET forms. Pages developed with Visual Studio .NET have this attribute set to false, and page events are individually tied to handlers.

What happens when you change the web.config file at run time?
ASP.NET invalidates the existing cache and assembles a new cache. Then ASP.NET automatically restarts the application to apply the changes.

Can you programmatically access IIS configuration settings?


Yes. You can use ADSI, WMI, or COM interfaces to configure IIS programmatically.

How does Application Pools work in IIS 6.0?


As explained under the IIS documentation, when you run IIS 6.0 in worker process isolation mode, you can separate different Web applications and Web sites into groups known as application pools. An application pool is a group of one or more URLs that are served by a worker process or set of worker processes. Any Web directory or virtual directory can be assigned to an application pool.

Every application within an application pool shares the same worker process. Because each worker process operates as a separate instance of the worker process executable, W3wp.exe, the worker process that services one application pool is separated from the Page | 92

C# 3.0: A Beginners Guide [Notes]


worker process that services another. Each separate worker process provides a process boundary so that when an application is assigned to one application pool, problems in other application pools do not affect the application. This ensures that if a worker process fails, it does not affect the applications running in other application pools.

Use multiple application pools when you want to help ensure that applications and Web sites are confidential and secure. For example, an enterprise organization might place its human resources Web site and its finance Web site on the same server, but in different application pools. Likewise, an ISP that hosts Web sites and applications for competing companies might run each companys Web services on the same server, but in different application pools. Using different application pools to isolate applications helps prevent one customer from accessing, changing, or using confidential information from another customers site.

In HTTP.sys, an application pool is represented by a request queue, from which the usermode worker processes that service an application pool collect the requests. Each pool can manage requests for one or more unique Web applications, which you assign to the application pool based on their URLs. Application pools, then, are essentially worker process configurations that service groups of namespaces.

Multiple application pools can operate at the same time. An application, as defined by its URL, can only be served by one application pool at any time. While one application pool is servicing a request, you cannot route the request to another application pool. However, you can assign applications to another application pool while the server is running.

_________________

What is the Microsoft.NET?

Page | 93

C# 3.0: A Beginners Guide [Notes]


.NET is a set of technologies designed to transform the internet into a full scale distributed platform. It provides new ways of connecting systems, information and devices through a collection of web services. It also provides a language independent, consistent programming model across all tiers of an application.

The goal of the .NET platform is to simplify web development by providing all of the tools and technologies that one needs to build distributed web applications.

What is the .NET Framework?

The .NET Framework is set of technologies that form an integral part of the .NET Platform. It is Microsoft's managed code programming model for building applications that have visually stunning user experiences, seamless and secure communication, and the ability to model a range of business processes.

The .NET Framework has two main components: the common language runtime (CLR) and .NET Framework class library. The CLR is the foundation of the .NET framework and provides a common set of services for projects that act as building blocks to build up applications across all tiers. It simplifies development and provides a robust and simplified environment which provides common services to build application. The .NET framework class library is a collection of reusable types and exposes features of the runtime. It contains of a set of classes that is used to access common functionality.

What is CLR?

The .NET Framework provides a runtime environment called the Common Language Runtime or CLR. The CLR can be compared to the Java Virtual Machine or JVM in Java. CLR handles the execution of code and provides useful services for the implementation of the program. In addition to executing code, CLR provides services such as memory management, thread management, security management, code verification, compilation, and other system services. It enforces rules that in turn provide a robust and secure execution environment for .NET applications.

What is CTS?

Common Type System (CTS) describes the datatypes that can be used by managed code. CTS defines how these types are declared, used and managed in the runtime. It facilitates cross-language integration, type safety, and high performance code execution. The rules defined in CTS can be used to define your own classes and values. Page | 94

C# 3.0: A Beginners Guide [Notes]


What is CLS?

Common Language Specification (CLS) defines the rules and standards to which languages must adhere to in order to be compatible with other .NET languages. This enables C# developers to inherit from classes defined in VB.NET or other .NET compatible languages.

What is managed code?

The .NET Framework provides a run-time environment called the Common Language Runtime, which manages the execution of code and provides services that make the development process easier. Compilers and tools expose the runtime's functionality and enable you to write code that benefits from this managed execution environment. The code that runs within the common language runtime is called managed code.

What is MSIL?

When the code is compiled, the compiler translates your code into Microsoft intermediate language (MSIL). The common language runtime includes a JIT compiler for converting this MSIL then to native code.

MSIL contains metadata that is the key to cross language interoperability. Since this metadata is standardized across all .NET languages, a program written in one language can understand the metadata and execute code, written in a different language. MSIL includes instructions for loading, storing, initializing, and calling methods on objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access, exception handling, and other operations.

What is JIT?

JIT is a compiler that converts MSIL to native code. The native code consists of hardware specific instructions that can be executed by the CPU.

Rather than converting the entire MSIL (in a portable executable[PE]file) to native code, the JIT converts the MSIL as it is needed during execution. This converted native code is stored so that it is accessible for subsequent calls.

Page | 95

C# 3.0: A Beginners Guide [Notes]


What is portable executable (PE)? PE is the file format defining the structure that all executable files (EXE) and Dynamic Link Libraries (DLL) must use to allow them to be loaded and executed by Windows. PE is derived from the Microsoft Common Object File Format (COFF). The EXE and DLL files created using the .NET Framework obey the PE/COFF formats and also add additional header and data sections to the files that are only used by the CLR.

What is an application domain?

Application domain is the boundary within which an application runs. A process can contain multiple application domains. Application domains provide an isolated environment to applications that is similar to the isolation provided by processes. An application running inside one application domain cannot directly access the code running inside another application domain. To access the code running in another application domain, an application needs to use a proxy.

How does an AppDomain get created? AppDomains are usually created by hosts. Examples of hosts are the Windows Shell, ASP.NET and IE. When you run a .NET application from the command-line, the host is the Shell. The Shell creates a new AppDomain for every application. AppDomains can also be explicitly created by .NET applications.

What is an assembly?

An assembly is a collection of one or more .exe or dlls. An assembly is the fundamental unit for application development and deployment in the .NET Framework. An assembly contains a collection of types and resources that are built to work together and form a logical unit of functionality. An assembly provides the CLR with the information it needs to be aware of type implementations.

What are the contents of assembly?

A static assembly can consist of four elements:

Assembly manifest - Contains the assembly metadata. An assembly manifest contains the information about the identity and version of the assembly. It also contains the information required to resolve references to types and resources.

Page | 96

C# 3.0: A Beginners Guide [Notes]


Type metadata - Binary information that describes a program.

Microsoft intermediate language (MSIL) code.

A set of resources.

What are the different types of assembly?

Assemblies can also be private or shared. A private assembly is installed in the installation directory of an application and is accessible to that application only. On the other hand, a shared assembly is shared by multiple applications. A shared assembly has a strong name and is installed in the GAC.

We also have satellite assemblies that are often used to deploy language-specific resources for an application.

What is a dynamic assembly?

A dynamic assembly is created dynamically at run time when an application requires the types within these assemblies.

What is a strong name?

You need to assign a strong name to an assembly to place it in the GAC and make it globally accessible. A strong name consists of a name that consists of an assembly's identity (text name, version number, and culture information), a public key and a digital signature generated over the assembly. The .NET Framework provides a tool called the Strong Name Tool (Sn.exe), which allows verification and key pair and signature generation.

What is GAC? What are the steps to create an assembly and add it to the GAC?

The global assembly cache (GAC) is a machine-wide code cache that stores assemblies specifically designated to be shared by several applications on the computer. You should share assemblies by installing them into the global assembly cache only when you need to.

Page | 97

C# 3.0: A Beginners Guide [Notes]


Steps

- Create a strong name using sn.exe tool eg: sn -k mykey.snk

- in AssemblyInfo.cs, add the strong name eg: [assembly: AssemblyKeyFile("mykey.snk")]

- recompile project, and then install it to GAC in two ways :

drag & drop it to assembly folder (C:\WINDOWS\assembly OR C:\WINNT\assembly) (shfusion.dll tool)

gacutil -i abc.dll

What is the caspol.exe tool used for?

The caspol tool grants and modifies permissions to code groups at the user policy, machine policy, and enterprise policy levels.

What is a garbage collector?

A garbage collector performs periodic checks on the managed heap to identify objects that are no longer required by the program and removes them from memory.

What are generations and how are they used by the garbage collector?

Generations are the division of objects on the managed heap used by the garbage collector. This mechanism allows the garbage collector to perform highly optimized garbage collection. The unreachable objects are placed in generation 0, the reachable objects are placed in generation 1, and the objects that survive the collection process are promoted to higher generations.

What is Ilasm.exe used for?

Page | 98

C# 3.0: A Beginners Guide [Notes]


Ilasm.exe is a tool that generates PE files from MSIL code. You can run the resulting executable to determine whether the MSIL code performs as expected.

What is Ildasm.exe used for?

Ildasm.exe is a tool that takes a PE file containing the MSIL code as a parameter and creates a text file that contains managed code.

What is the ResGen.exe tool used for?

ResGen.exe is a tool that is used to convert resource files in the form of .txt or .resx files to common language runtime binary .resources files that can be compiled into satellite assemblies.

Build HTML5 Mobile Apps with Visual Studio

General .NET Interview Questions


Posted by: Suprotim Agarwal , on 8/12/2007, in Category Interview Questions Views: 288170
retweet

Abstract: The General .NET Interview Questions consists the most frequently asked questions in .NET. This list of 100+ questions guage your familiarity with the .NET platform. The q&a have been collected over a period of time using MSDN and other similar sites.

What is an application server?


As defined in Wikipedia, an application server is a software engine that delivers applications to client computers or devices. The application server runs your server code. Some well known application servers are IIS (Microsoft), WebLogic Server (BEA), JBoss (Red Hat), WebSphere (IBM).

Compare C# and VB.NET


A detailed comparison can be found over here.

What is a base class and derived class?


Page | 99

C# 3.0: A Beginners Guide [Notes]


A class is a template for creating an object. The class from which other classes derive fundamental functionality is called a base class. For e.g. If Class Y derives from Class X, then Class X is a base class.

The class which derives functionality from a base class is called a derived class. If Class Y derives from Class X, then Class Y is a derived class.

What is an extender class?


An extender class allows you to extend the functionality of an existing control. It is used in Windows forms applications to add properties to controls. A demonstration of extender classes can be found over here.

What is inheritance?
Inheritance represents the relationship between two classes where one type derives functionality from a second type and then extends it by adding new methods, properties, events, fields and constants.

C# support two types of inheritance: Implementation inheritance Interface inheritance

What is implementation and interface inheritance?


When a class (type) is derived from another class(type) such that it inherits all the members of the base type it is Implementation Inheritance. When a type (class or a struct) inherits only the signatures of the functions from another type it is Interface Inheritance. In general Classes can be derived from another class, hence support Implementation inheritance. At the same time Classes can also be derived from one or more interfaces. Hence they support Interface inheritance. Source: Exforsys.

What is inheritance hierarchy?


The class which derives functionality from a base class is called a derived class. A derived class can also act as a base class for another class. Thus it is possible to create a tree-like structure that illustrates the relationship between all related classes. This structure is known as the inheritance hierarchy.

Page | 100

C# 3.0: A Beginners Guide [Notes]

How do you prevent a class from being inherited?


In VB.NET you use the NotInheritable modifier to prevent programmers from using the class as a base class. In C#, use the sealed keyword.

When should you use inheritance?


Read this.

Define Overriding?
Overriding is a concept where a method in a derived class uses the same name, return type, and arguments as a method in its base class. In other words, if the derived class contains its own implementation of the method rather than using the method in the base class, the process is called overriding.

Can you use multiple inheritance in .NET?


.NET supports only single inheritance. However the purpose is accomplished using multiple interfaces.

Why dont we have multiple inheritance in .NET?


There are several reasons for this. In simple words, the efforts are more, benefits are less. Different languages have different implementation requirements of multiple inheritance. So in order to implement multiple inheritance, we need to study the implementation aspects of all the languages that are CLR compliant and then implement a common methodology of implementing it. This is too much of efforts. Moreover multiple interface inheritance very much covers the benefits that multiple inheritance has.

What is an Interface?
An interface is a standard or contract that contains only the signatures of methods or events. The implementation is done in the class that inherits from this interface. Interfaces are primarily used to set a common standard or contract.

When should you use abstract class vs interface or What is the difference between an abstract class and interface?
I would suggest you to read this. There is a good comparison given over here.

What are events and delegates?


An event is a message sent by a control to notify the occurrence of an action. However it is not known which object receives the event. For this reason, .NET provides a special type called Delegate which acts as an intermediary between the sender object and receiver object.

What is business logic?


Page | 101

C# 3.0: A Beginners Guide [Notes]


It is the functionality which handles the exchange of information between database and a user interface.

What is a component?
Component is a group of logically related classes and methods. A component is a class that implements the IComponent interface or uses a class that implements IComponent interface.

What is a control?
A control is a component that provides user-interface (UI) capabilities.

What are the differences between a control and a component?


The differences can be studied over here.

What are design patterns?


Design patterns are common solutions to common design problems.

What is a connection pool?


A connection pool is a collection of connections which are shared between the clients requesting one. Once the connection is closed, it returns back to the pool. This allows the connections to be reused.

What is a flat file?


A flat file is the name given to text, which can be read or written only sequentially.

What are functional and non-functional requirements?


Functional requirements defines the behavior of a system whereas non-functional requirements specify how the system should behave; in other words they specify the quality requirements and judge the behavior of a system. E.g. Functional - Display a chart which shows the maximum number of products sold in a region. Non-functional The data presented in the chart must be updated every 5 minutes.

What is the global assembly cache (GAC)?


GAC is a machine-wide cache of assemblies that allows .NET applications to share libraries. GAC solves some of the problems associated with dlls (DLL Hell).

What is a stack? What is a heap? Give the differences between the two?
Stack is a place in the memory where value types are stored. Heap is a place in the memory where the reference types are stored. Page | 102

C# 3.0: A Beginners Guide [Notes]

Check this link for the differences.

What is instrumentation?
It is the ability to monitor an application so that information about the applications progress, performance and status can be captured and reported.

What is code review?


The process of examining the source code generally through a peer, to verify it against best practices.

What is logging?
Logging is the process of persisting information about the status of an application.

What are mock-ups?


Mock-ups are a set of designs in the form of screens, diagrams, snapshots etc., that helps verify the design and acquire feedback about the applications requirements and use cases, at an early stage of the design process.

What is a Form?
A form is a representation of any window displayed in your application. Form can be used to create standard, borderless, floating, modal windows.

What is a multiple-document interface(MDI)?


A user interface container that enables a user to work with more than one document at a time. E.g. Microsoft Excel.

What is a single-document interface (SDI) ?


A user interface that is created to manage graphical user interfaces and controls into single windows. E.g. Microsoft Word

What is BLOB ?
A BLOB (binary large object) is a large item such as an image or an exe represented in binary form.

What is ClickOnce?
ClickOnce is a new deployment technology that allows you to create and publish selfupdating applications that can be installed and run with minimal user interaction.

What is object role modeling (ORM) ?


It is a logical model for designing and querying database models. There are various ORM tools in the market like CaseTalk, Microsoft Visio for Enterprise Architects, Infagon etc. Page | 103

C# 3.0: A Beginners Guide [Notes]

What is a private assembly?


A private assembly is local to the installation directory of an application and is used only by that application.

What is a shared assembly?


A shared assembly is kept in the global assembly cache (GAC) and can be used by one or more applications on a machine.

What is the difference between user and custom controls?


User controls are easier to create whereas custom controls require extra effort. User controls are used when the layout is static whereas custom controls are used in dynamic layouts. A user control cannot be added to the toolbox whereas a custom control can be. A separate copy of a user control is required in every application that uses it whereas since custom controls are stored in the GAC, only a single copy can be used by all applications.

Where do custom controls reside?


In the global assembly cache (GAC).

What is a third-party control ?


A third-party control is one that is not created by the owners of a project. They are usually used to save time and resources and reuse the functionality developed by others (thirdparty).

What is a binary formatter?


Binary formatter is used to serialize and deserialize an object in binary format.

What is Boxing/Unboxing?
Boxing is used to convert value types to object. E.g. int x = 1; object obj = x ; Unboxing is used to convert the object back to the value type. E.g. int y = (int)obj; Boxing/unboxing is quiet an expensive operation.

What is a COM Callable Wrapper (CCW)?


Page | 104

C# 3.0: A Beginners Guide [Notes]


CCW is a wrapper created by the common language runtime(CLR) that enables COM components to access .NET objects.

What is a Runtime Callable Wrapper (RCW)?


RCW is a wrapper created by the common language runtime(CLR) to enable .NET components to call COM components.

What is a digital signature?


A digital signature is an electronic signature used to verify/gurantee the identity of the individual who is sending the message.

What is garbage collection?


Garbage collection is the process of managing the allocation and release of memory in your applications. Read this article for more information.

What is globalization?
Globalization is the process of customizing applications that support multiple cultures and regions.

What is localization?
Localization is the process of customizing applications that support a given culture and regions.

What is MIME?
The definition of MIME or Multipurpose Internet Mail Extensions as stated in MSDN is MIME is a standard that can be used to include content of various types in a single message. MIME extends the Simple Mail Transfer Protocol (SMTP) format of mail messages to include multiple content, both textual and non-textual. Parts of the message may be images, audio, or text in different character sets. The MIME standard derives from RFCs such as 2821 and 2822. What is a garbage collector? Garbage collector is a background process which checks for unused objects in the application and cleans them up. After that answer my guess was the interviewer will not probe more....but fate turned me down , came the bouncer. What are generations in garbage collector? Generation define the age of the object. Well i did not answer the question , i have just written down by searching in google.... How many types of Generations are there in GC garbage collector? Page | 105

C# 3.0: A Beginners Guide [Notes]


There are 3 generations gen 0 , gen 1 and gen 2. Then came a solid tweak questions which i just slipped by saying Yes... Does garbage collector clean unmanaged objects ? No. Then came the terror question...which i never knew... When we define clean up destructor , how does it affect garbage collector? If you define clean up in destructor garbage collector will take more time to clean up the objects and more and more objects are created in Gen 2.. How can we overcome the destructor problem ? By implementing "Idisposable" interface. The above question was tricky , you can search in google for finalize and dispose patterns. Where do we normally put unmanaged code clean up?. In finalize a.k.a destructor. One thing i learnt from this interview experience is one thing but we also should know core concepts in detail to crack Dot net interviews .

What is the difference between DataList and Repeater data binding controls? Answer: The DataList control is similar to the Repeater control. However, it has some additional properties and templates that you can use to display its data in a diverse fashion. The Repeater control does not have any built-in layout or style. We are forced to specify all formatting-related HTML elements and style tags. On the other hand, a DataList control provides more flexibility to display data in a desired layout. It also provides data selection and editing capabilities. How does it do it? Well, in addition to the five templates (Item Template, AlternatingItem Template, Separator Template, Header Template, Footer Template that a repeater has, the DataList control has two more templates: SelectedItemTemplate, and EditItemTemplate. These templates are useful for allowing data selection and data editing functionalities. Furthermore, the RepeatDirection and RepeatColumns properties of a DataList control can be exploited to lay out the data in horizontal or vertical fashions.

We can also load assembly with out adding ref. protected void Page_Load(object sender, EventArgs e) { string vPath = ""; Assembly a = null; a = Assembly.LoadFrom(vPath + "MyAssembly.dll"); Type classType = a.GetType("MyNameSpace.MyClass"); object obj = Activator.CreateInstance(classType); MethodInfo MI = classType.GetMethod("MyMethod"); Page | 106

C# 3.0: A Beginners Guide [Notes]


}

2. about my project,in my project my roles and responsibilities. 3. Screens developed for my project. 4. Which validation you have used for email validation. 5.Session management 6.Session variables are stored in which location? 7.What is the default event for text box? 8.What is dataset? 9.how to bind two tables into dataset? 10.What is the difference between data reader and dataset? 11.What is viewstate? \

MVC

Asp.net real time MVC Interview Quesitons with answers


Labels: ASP.Net Interview Questions, C#.Net Interview Questions, Importent Interview Questions, MVC

What is MVC? MVC is a framework methodology that divides an applications implementation into three component roles: models, views, and controllers. Models in a MVC based application are the components of the application that are responsible for maintaining state. Often this state is persisted inside a database (for example: we might have a Product class that is used to represent order data from the Products table inside SQL). Views in a MVC based application are the components responsible for displaying the applications user interface. Typically this UI is created off of the model data (for example: we might create an Product Edit view that surfaces textboxes, dropdowns and checkboxes based on the current state of a Product object). Controllers in a MVC based application are the components responsible for handling end user interaction, manipulating the model, and ultimately choosing a view to render to display UI. In a MVC application the view is only about displaying information it is the controller that handles and responds to user input and interaction.

Page | 107

C# 3.0: A Beginners Guide [Notes]


What are the 3 main components of an ASP.NET MVC application? 1. M - Model 2. V - View 3. C - Controller In which assembly is the MVC framework defined? System.Web.Mvc Is it possible to combine ASP.NET webforms and ASP.MVC and develop a single web application? Yes, it is possible to combine ASP.NET webforms and ASP.MVC and develop a single web application. What does Model, View and Controller represent in an MVC application? Model: Model represents the application data domain. In short the applications business logic is contained with in the model. View: Views represent the user interface, with which the end users interact. In short the all the user interface logic is contained with in the UI. Controller: Controller is the component that responds to user actions. Based on the user actions, the respective controller, work with the model, and selects a view to render that displays the user interface. The user input logic is contained with in the controller. What is the greatest advantage of using asp.net mvc over asp.net webforms? It is difficult to unit test UI with webforms, where views in mvc can be very easily unit tested. Which approach provides better support for test driven development - ASP.NET MVC or ASP.NET Webforms? ASP.NET MVC What is Razor View Engine? Razor view engine is a new view engine created with ASP.Net MVC model using specially designed Razor parser to render the HTML out of dynamic server side code. It allows us to write Compact, Expressive, Clean and Fluid code with new syntaxes to include server side code in to HTML.

What are the advantages of ASP.NET MVC? 1. Extensive support for TDD. With asp.net MVC, views can also be very easily unit tested. 2. Complex applications can be easily managed
Page | 108

C# 3.0: A Beginners Guide [Notes]


3. Seperation of concerns. Different aspects of the application can be divided into Model, View and Controller. 4. ASP.NET MVC views are light weight, as they donot use viewstate. Is it possible to unit test an MVC application without running the controllers in an ASP.NET process? Yes, all the features in an asp.net MVC application are interface based and hence mocking is much easier. So, we don't have to run the controllers in an ASP.NET process for unit testing. What is namespace of asp.net mvc? ASP.NET MVC namespaces and classes are located in the System.Web.Mvc assembly. System.Web.Mvc namespace Contains classes and interfaces that support the MVC pattern for ASP.NET Web applications. This namespace includes classes that represent controllers, controller factories, action results, views, partial views, and model binders. System.Web.Mvc.Ajax namespace Contains classes that support Ajax scripts in an ASP.NET MVC application. The namespace includes support for Ajax scripts and Ajax option settings. System.Web.Mvc.Async namespace Contains classes and interfaces that support asynchronous actions in an ASP.NET MVC application System.Web.Mvc.Html namespace Contains classes that help render HTML controls in an MVC application. The namespace includes classes that support forms, input controls, links, partial views, and validation.

Is it possible to share a view across multiple controllers? Yes, put the view into the shared folder. This will automatically make the view available across multiple controllers. What is the role of a controller in an MVC application? The controller responds to user interactions, with the application, by selecting the action method to execute and alse selecting the view to render. Where are the routing rules defined in an asp.net MVC application? In Application_Start event in Global.asax Name a few different return types of a controller action method? The following are just a few return types of a controller action method. In general an action method can return an instance of a any class that derives from ActionResult class. Page | 109

C# 3.0: A Beginners Guide [Notes]


1. ViewResult 2. JavaScriptResult 3. RedirectResult 4. ContentResult 5. JsonResult What is the page lifecycle of an ASP.NET MVC?

Following process are performed by ASP.Net MVC page: 1) App initialization 2) Routing 3) Instantiate and execute controller 4) Locate and invoke controller action 5) Instantiate and render view

What is the significance of NonActionAttribute? In general, all public methods of a controller class are treated as action methods. If you want prevent this default behaviour, just decorate the public method with NonActionAttribute. What is the significance of ASP.NET routing? ASP.NET MVC uses ASP.NET routing, to map incoming browser requests to controller action methods. ASP.NET Routing makes use of route table. Route table is created when your web application first starts. The route table is present in the Global.asax file. How route table is created in ASP.NET MVC?

When an MVC application first starts, the Application_Start() method is called. This method, in turn, calls the RegisterRoutes() method. The RegisterRoutes() method creates the route table.

What are the 3 segments of the default route, that is present in an ASP.NET MVC application? 1st Segment - Controller Name 2nd Segment - Action Method Name 3rd Segment - Parameter that is passed to the action method Examplehttp://nareshkamuni.blogspot.in/search/label/MVC Controller Name = search Action Method Name = label Parameter Id = MVC ASP.NET MVC application, makes use of settings at 2 places for routing to work correctly. What are
Page | 110

C# 3.0: A Beginners Guide [Notes]


these 2 places? 1. Web.Config File : ASP.NET routing has to be enabled here. 2. Global.asax File : The Route table is created in the application Start event handler, of the Global.asax file. How do you avoid XSS Vulnerabilities in ASP.NET MVC? Use thesyntax in ASP.NET MVC instead of usingin .net framework 4.0.

What is the adavantage of using ASP.NET routing? In an ASP.NET web application that does not make use of routing, an incoming browser request should map to a physical file. If the file does not exist, we get page not found error. An ASP.NET web application that does make use of routing, makes use of URLs that do not have to map to specific files in a Web site. Because the URL does not have to map to a file, you can use URLs that are descriptive of the user's action and therefore are more easily understood by users. What are the 3 things that are needed to specify a route? 1. URL Pattern - You can include placeholders in a URL pattern so that variable data can be passed to the request handler without requiring a query string. 2. Handler - The handler can be a physical file such as an .aspx file or a controller class. 3. Name for the Route - Name is optional. Is the following route definition a valid route definition? {controller}{action}/{id} No, the above definition is not a valid route definition, because there is no literal value or delimiter between the placeholders. Therefore, routing cannot determine where to separate the value for the controller placeholder from the value for the action placeholder. What is the use of the following default route? {resource}.axd/{*pathInfo} This route definition, prevent requests for the Web resource files such as WebResource.axd or ScriptResource.axd from being passed to a controller. What is the difference between adding routes, to a webforms application and to an mvc application? To add routes to a webforms application, we use MapPageRoute() method of the RouteCollection class, where as to add routes to an MVC application we use MapRoute() method. How do you handle variable number of segments in a route definition? Use a route with a catch-all parameter. An example is shown below. * is referred to as catchPage | 111

C# 3.0: A Beginners Guide [Notes]


all parameter. controller/{action}/{*parametervalues} What are the 2 ways of adding constraints to a route? 1. Use regular expressions 2. Use an object that implements IRouteConstraint interface Give 2 examples for scenarios when routing is not applied? 1. A Physical File is Found that Matches the URL Pattern - This default behaviour can be overriden by setting the RouteExistingFiles property of the RouteCollection object to true. 2. Routing Is Explicitly Disabled for a URL Pattern - Use the RouteCollection.Ignore() method to prevent routing from handling certain requests. What is the use of action filters in an MVC application? Action Filters allow us to add pre-action and post-action behavior to controller action methods. If I have multiple filters impleted, what is the order in which these filters get executed? 1. Authorization filters 2. Action filters 3. Response filters 4. Exception filters What are the different types of filters, in an asp.net mvc application? 1. Authorization filters 2. Action filters 3. Result filters 4. Exception filters Give an example for Authorization filters in an asp.net mvc application? 1. RequireHttpsAttribute 2. AuthorizeAttribute Which filter executes first in an asp.net mvc application? Authorization filter

What are the levels at which filters can be applied in an asp.net mvc application? 1. Action Method 2. Controller
Page | 112

C# 3.0: A Beginners Guide [Notes]


3. Application [b]Is it possible to create a custom filter?[/b] Yes What filters are executed in the end? Exception Filters Is it possible to cancel filter execution? Yes What type of filter does OutputCacheAttribute class represents? Result Filter What are the 2 popular asp.net mvc view engines? 1. Razor 2. .aspx What is difference between Viewbag and Viewdata in ASP.NET MVC? The basic difference between ViewData and ViewBag is that in ViewData instead creating dynamic properties we use properties of Model to transport the Model data in View and in ViewBag we can create dynamic properties without using Model data. What symbol would you use to denote, the start of a code block in razor views? @ What symbol would you use to denote, the start of a code block in aspx views? <%= %> In razor syntax, what is the escape sequence character for @ symbol? The escape sequence character for @ symbol, is another @ symbol When using razor views, do you have to take any special steps to proctect your asp.net mvc application from cross site scripting (XSS) attacks? No, by default content emitted using a @ block is automatically HTML encoded to protect from cross site scripting (XSS) attacks. When using aspx view engine, to have a consistent look and feel, across all pages of the application, we can make use of asp.net master pages. What is asp.net master pages equivalent, when using razor views? To have a consistent look and feel when using razor views, we can make use of layout pages. Layout
Page | 113

C# 3.0: A Beginners Guide [Notes]


pages, reside in the shared folder, and are named as _Layout.cshtml What are sections? Layout pages, can define sections, which can then be overriden by specific views making use of the layout. Defining and overriding sections is optional. What are the file extensions for razor views? 1. .cshtml - If the programming lanugaue is C# 2. .vbhtml - If the programming lanugaue is VB How do you specify comments using razor syntax? Razor syntax makes use of @* to indicate the begining of a comment and *@ to indicate the end. An example is shown below. What is Routing? A route is a URL pattern that is mapped to a handler. The handler can be a physical file, such as an .aspx file in a Web Forms application. Routing module is responsible for mapping incoming browser requests to particular MVC controller actions.

WCF Interview Questions With Answers for 1 year Experience


Labels: ASP.Net Interview Questions, WCF

What is WCF?
Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. WCF provides a runtime environment for services, enabling you to expose CLR types as services, and to consume other services as CLR types. WCF is part of .NET 3.0 and requires .NET 2.0, so it can only run on systems that support it.

What is service and client in perspective of data communication?


A service is a unit of functionality exposed to the world. The client of a service is merely the party consuming the service.

What is address in WCF and how many types of transport schemas are there in WCF?
Address is a way of letting client know that where a service is located. In WCF, every service is associated with a unique address. This contains the location of the service and transport schemas.

Page | 114

C# 3.0: A Beginners Guide [Notes]


WCF supports following transport schemas HTTP TCP Peer network IPC (Inter-Process Communication over named pipes) MSMQ The sample address for above transport schema may look like http://localhost:81 http://localhost:81/MyService net.tcp://localhost:82/MyService net.pipe://localhost/MyPipeService net.msmq://localhost/private/MyMsMqService net.msmq://localhost/MyMsMqService

What are contracts in WCF?


In WCF, all services expose contracts. The contract is a platform-neutral and standard way of describing what the service does. WCF defines four types of contracts.

Service contracts Describe which operations the client can perform on the service. There are two types of Service Contracts. ServiceContract - This attribute is used to define the Interface. OperationContract - This attribute is used to define the method inside Interface.

[ServiceContract]

interface IMyContract { [OperationContract] string MyMethod( ); } class MyService : IMyContract { public string MyMethod( ) { return "Hello World"; } }
Page | 115

C# 3.0: A Beginners Guide [Notes]

Data contracts Define which data types are passed to and from the service. WCF defines implicit contracts for built-in types such as int and string, but we can easily define explicit opt-in data contracts for custom types. There are two types of Data Contracts. DataContract - attribute used to define the class DataMember - attribute used to define the properties.

[DataContract] class Contact { [DataMember] public string FirstName; [DataMember] public string LastName; }

If DataMember attributes are not specified for a properties in the class, that property can't be passed to-from web service. Fault contracts Define which errors are raised by the service, and how the service handles and propagates errors to its clients.

Message contracts Allow the service to interact directly with messages. Message contracts can be typed or untyped, and are useful in interoperability cases and when there is an existing message format we have to comply with.

Where we can host WCF services?


Every WCF services must be hosted somewhere. There are three ways of hosting WCF services. They are 1. IIS 2. Self Hosting 3. WAS (Windows Activation Service)

Page | 116

C# 3.0: A Beginners Guide [Notes]

What is binding and how many types of bindings are there in WCF?
A binding defines how an endpoint communicates to the world. A binding defines the transport (such as HTTP or TCP) and the encoding being used (such as text or binary). A binding can contain binding elements that specify details like the security mechanisms used to secure messages, or the message pattern used by an endpoint. WCF supports nine types of bindings. Basic binding Offered by the BasicHttpBinding class, this is designed to expose a WCF service as a legacy ASMX web service, so that old clients can work with new services. When used by the client, this binding enables new WCF clients to work with old ASMX services. TCP binding Offered by the NetTcpBinding class, this uses TCP for cross-machine communication on the intranet. It supports a variety of features, including reliability, transactions, and security, and is optimized for WCF-to-WCF communication. As a result, it requires both the client and the service to use WCF.

Peer network binding Offered by the NetPeerTcpBinding class, this uses peer networking as a transport. The peer network-enabled client and services all subscribe to the same grid and broadcast messages to it.

IPC binding Offered by the NetNamedPipeBinding class, this uses named pipes as a transport for same-machine communication. It is the most secure binding since it cannot accept calls from outside the machine and it supports a variety of features similar to the TCP binding.

Web Service (WS) binding Offered by the WSHttpBinding class, this uses HTTP or HTTPS for transport, and is designed to offer a variety of features such as reliability, transactions, and security over the Internet.

Federated WS binding Offered by the WSFederationHttpBinding class, this is a specialization of the WS binding, offering support for federated security.

Duplex WS binding Page | 117

C# 3.0: A Beginners Guide [Notes]

Offered by the WSDualHttpBinding class, this is similar to the WS binding except it also supports bidirectional communication from the service to the client.

MSMQ binding Offered by the NetMsmqBinding class, this uses MSMQ for transport and is designed to offer support for disconnected queued calls.

MSMQ integration binding Offered by the MsmqIntegrationBinding class, this converts WCF messages to and from MSMQ messages, and is designed to interoperate with legacy MSMQ clients.

What is endpoint in WCF?


Every service must have Address that defines where the service resides, Contract that defines what the service does and a Binding that defines how to communicate with the service. In WCF the relationship between Address, Contract and Binding is called Endpoint. The Endpoint is the fusion of Address, Contract and Binding.

How to define a service as REST based service in WCF?


WCF 3.5 provides explicit support for RESTful communication using a new binding named WebHttpBinding. The below code shows how to expose a RESTful service

[ServiceContract] interface IStock { [OperationContract] [WebGet] int GetStock(string StockId); }

By adding the WebGetAttribute, we can define a service as REST based service that can be accessible using HTTP GET operation.

What is the address formats of the WCF transport schemas?


Address format of WCF transport schema always follow [transport]://[machine or domain][:optional port] format. for example:

Page | 118

C# 3.0: A Beginners Guide [Notes]


HTTP Address Format http://localhost:8888 the way to read the above url is "Using HTTP, go to the machine called localhost, where on port 8888 someone is waiting" When the port number is not specified, the default port is 80. TCP Address Format net.tcp://localhost:8888/MyService When a port number is not specified, the default port is 808: net.tcp://localhost/MyService NOTE: Two HTTP and TCP addresses from the same host can share a port, even on the same machine. IPC Address Format net.pipe://localhost/MyPipe We can only open a named pipe once per machine, and therefore it is not possible for two named pipe addresses to share a pipe name on the same machine. MSMQ Address Format net.msmq://localhost/private/MyService net.msmq://localhost/MyService

What is Proxy and how to generate proxy for WCF Services?


The proxy is a CLR class that exposes a single CLR interface representing the service contract. The proxy provides the same operations as service's contract, but also has additional methods for managing the proxy life cycle and the connection to the service. The proxy completely encapsulates every aspect of the service: its location, its implementation technology and runtime platform, and the communication transport. The proxy can be generated using Visual Studio by right clicking Reference and clicking on Add Service Reference. This brings up the Add Service Reference dialog box, where you need to supply the base address of the service (or a base address and a MEX URI) and the namespace to contain the proxy. Proxy can also be generated by using SvcUtil.exe command-line utility. We need to provide SvcUtil with the HTTPGET address or the metadata exchange endpoint address and, optionally, with a proxy filename. The default proxy filename is output.cs but you can also use the /out switch to indicate a different name. SvcUtil http://localhost/MyService/MyService.svc /out:Proxy.cs When we are hosting in IIS and selecting a port other than port 80 (such as port 88), we must provide that port number as part of the base address: Page | 119

C# 3.0: A Beginners Guide [Notes]

SvcUtil http://localhost:88/MyService/MyService.svc /out:Proxy.cs

What are different elements of WCF Srevices Client configuration file?


WCF Services client configuration file contains endpoint, address, binding and contract. A sample client config file looks like

<system.serviceModel> <client> <endpoint name = "MyEndpoint" address = "http://localhost:8000/MyService/" binding = "wsHttpBinding" contract = "IMyContract" /> </client> </system.serviceModel>

What is Transport and Message Reliability?

Transport reliability (such as the one offered by TCP) offers point-to-point guaranteed delivery at the network packet level, as well as guarantees the order of the packets. Transport reliability is not resilient to dropping network connections and a variety of other communication problems. Message reliability deals with reliability at the message level independent of how many packets are required to deliver the message. Message reliability provides for end-to-end guaranteed delivery and order of messages, regardless of how many intermediaries are involved, and how many network hops are required to deliver the message from the client to the service.

How to configure Reliability while communicating with WCF Services?


Reliability can be configured in the client config file by adding reliableSession under binding tag.

<system.serviceModel> <services> <service name = "MyService"> <endpoint address = "net.tcp://localhost:8888/MyService" binding = "netTcpBinding" bindingConfiguration = "ReliableCommunication" contract = "IMyContract" /> </service> </services>
Page | 120

C# 3.0: A Beginners Guide [Notes]


<bindings> <netTcpBinding> <binding name = "ReliableCommunication"> <reliableSession enabled = "true"/> </binding> </netTcpBinding> </bindings> </system.serviceModel>
Reliability is supported by following bindings only NetTcpBinding WSHttpBinding WSFederationHttpBinding WSDualHttpBinding

How to set the timeout property for the WCF Service client call?
The timeout property can be set for the WCF Service client call using binding tag.

<client> <endpoint ...

binding = "wsHttpBinding" bindingConfiguration = "LongTimeout" ...

/> </client> <bindings> <wsHttpBinding> <binding name = "LongTimeout" sendTimeout = "00:04:00"/> </wsHttpBinding> </bindings>

If no timeout has been specified, the default is considered as 1 minute.

Page | 121

C# 3.0: A Beginners Guide [Notes]

How to deal with operation overloading while exposing the WCF services?

By default overload operations (methods) are not supported in WSDL based operation. However by using Name property of OperationContract attribute, we can deal with operation overloading scenario.

[ServiceContract] interface ICalculator { [OperationContract(Name = "AddInt")] int Add(int arg1,int arg2); [OperationContract(Name = "AddDouble")] double Add(double arg1,double arg2);

http://nareshkamuni.blogspot.com/p/general.html

Page | 122

C# 3.0: A Beginners Guide [Notes]


Run Command Wordpad = write Windows Media Player = wmplayer Windows Firewall = firewall.cpl Task Manager = taskmgr Shuts Down Windows = shutdown Scheduled Tasks = control schedtasks Services = services.msc System Configuration Editor Paint = pbrush Registry Editor = regedit Network Connections = ncpa.cpl Notepad = notepad Microsoft Paint = mspaint Microsoft Word ( if installed ) = winword Calculator = calc Command Prompt = cmd Bluetooth Transfer Wizard = fsquirt Add/Remove Programs = appwiz.cpl Administrative Tools = control admintools Accessibility Controls = access.cpl = sysedit System Configuration Utility = msconfig

Page | 123

S-ar putea să vă placă și