Documente Academic
Documente Profesional
Documente Cultură
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
18. Syntax:
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
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
Page | 5
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
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
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
Page | 11
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]
Page | 13
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
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
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
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
Page | 19
Page | 20
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
Page | 22
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
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
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
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
Page | 27
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
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
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
Syntax: type name { get; set; } EG: public int UserCount { get; set; }
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
Page | 33
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
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
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
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(){ /* ... */ }
Page | 37
Base class:
//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
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
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
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
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
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
Page | 43
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
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
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
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
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
1.
Page | 51
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
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
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
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
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
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
Page | 61
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
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
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
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
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
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
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
//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
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
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
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
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
//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
Page | 78
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
Page | 80
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
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
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
Page | 84
Need to Write
Page | 85
Page | 86
Page | 87
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.
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
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.
By setting the EnableViewStateMac to true in the @Page directive. This attribute checks the encoded and encrypted viewstate for tampering.
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 configuration files to be accessed remotely by unauthorized users?
Page | 89
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.
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?
As quoted by Scott Hanselman, the short answer is that the latter gives you String.Formatstyle output and the former doesn't.
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
Yes. To change a master page, set the MasterPageFile property to point to the .master page during the PreInit page event.
Eg: <configuration>
<system.web>
</system.web>
</configuration>
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 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.
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
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.
_________________
Page | 93
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.
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
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.
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
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.
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
A set of resources.
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.
A dynamic assembly is created dynamically at run time when an application requires the types within these assemblies.
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
gacutil -i abc.dll
The caspol tool grants and modifies permissions to code groups at the user policy, machine policy, and enterprise policy levels.
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.
Page | 98
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.
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.
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.
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 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.
Page | 100
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.
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 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 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
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 logging?
Logging is the process of persisting information about the status of an application.
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 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 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 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
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
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
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
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
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
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
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
What are the levels at which filters can be applied in an asp.net mvc application? 1. Action Method 2. Controller
Page | 112
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 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
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
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.
Page | 116
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.
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.
By adding the WebGetAttribute, we can define a service as REST based service that can be accessible using HTTP GET operation.
Page | 118
<system.serviceModel> <client> <endpoint name = "MyEndpoint" address = "http://localhost:8000/MyService/" binding = "wsHttpBinding" contract = "IMyContract" /> </client> </system.serviceModel>
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.
<system.serviceModel> <services> <service name = "MyService"> <endpoint address = "net.tcp://localhost:8888/MyService" binding = "netTcpBinding" bindingConfiguration = "ReliableCommunication" contract = "IMyContract" /> </service> </services>
Page | 120
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> <bindings> <wsHttpBinding> <binding name = "LongTimeout" sendTimeout = "00:04:00"/> </wsHttpBinding> </bindings>
Page | 121
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
Page | 123