Você está na página 1de 39

Solutions to Chapter One Questions

1. What is .NET Framework? Ans. The .NET Framework is the foundation on which you can design, develop, and deploy applications. It is the core of the .NET infrastructure. It exists as a layer between the .NET applications and the underlying operating system. The .NET Framework encapsulates much of the basic functionality, such as debugging and security services, which was earlier built into various programming languages. 2. What does .NET Framework consists of? Ans. The .NET Framework consists of Web forms, Windows forms, and console applications that pertain to the presentation layer of an application. Web forms are used in Web-based applications, whereas Windows Forms are used in Windows-based applications for providing an interactive user interface. In addition, you can create character-based console applications that can be executed from the command line. Besides these three components, the .NET Framework consists of two other components, the .NET Framework Base Classes and the Common Language Runtime (CLR). 3. Write a note on: a. Programming methodologies Ans. The Visual Studio .NET programming methodology allows for mixed-language programming. This is established through a Common Type System (CTS) that is defined for all the languages that .NET Framework supports. All these languages compile into an intermediate language before they compile in native code. Therefore, the .NET developer has the independence to code one module of an application in one language and the other module of the same application in another language. b. Platform technologies Ans. The .NET Framework includes platform technologies like ADO.NET, ASP.NET, and VB.NET. ADO.NET allows .NET applications to communicate with a database for retrieving, accessing, and updating data. ASP.NET is a framework for building enterprise-class Web applications. VB.NET is an object-oriented language that provides features such as abstraction, encapsulation, and polymorphism. By using these technologies, you can easily develop robust Web applications, Windows applications, and XML Web services. c. Code execution Ans. The code execution process involves the conversion of Intermediate Language into native or CPU-specific code. The CLR is completely architecture-neutral. All the .NET languages get compiled into the IL. This intermediate language gets compiled by Just-in-Time (JIT) compiler into the native machine code. After translating the IL into native code, the converted code is sent to the .NET runtime manager. The .NET runtime manager executes the code. While executing the code, a security check is performed to ensure that the code has the appropriate permissions for accessing the available resources. 4. Which are the platform technologies supported by .NET Framework? Ans. Some of the platform technologies supported by .NET Framework are: ADO.NET

NIIT

Coordinator Guide Basics of .NET 1

ASP.NET VB.NET

5. List the advantages of .NET Framework. Ans. The .NET Framework offers the following advantages: Consistent programming model: The base classes of the .NET class library provide standard functionality such as, input/output, remoting, thread management, string manipulation, user interface design, and security management. The ADO.NET classes allow developers to access data in the form of XML. XML classes enable developers to read, write, manipulate, and transform XML files. The ASP.NET classes support the development of Web-based applications and Web services. The Windows forms classes support the development of desktop-based applications. Together, the .NET class library provides a common functionality to all .NET languages resulting in a consistent object model regardless of the programming language used by the developer. Language independence: The .NET developer has the independence to code one module of an application in one language and the other module of the same application in another language. This language interoperability can help in code reuse, and improve the efficiency of the development process. Ease of application deployment: The .NET Framework manages the details of locating and loading the components required by an application, even if several versions of the same application exist on the computer. The .NET Framework ensures that all the components on which the application depends are available on the computer before the application begins to run. Visual Studio 2005 includes a new application deployment technology known as ClickOnce, which allows you to easily deploy a Windows forms application. ClickOnce enables you to create desktop applications that are deployed with a secure and systemcontrolled installation. Improved security: The .NET Framework provides several mechanisms for protecting resources and code from unauthorized users:

Code Access Security (CAS) uses permissions to control the code accessing protected resources and operations. Role-based security provides information needed to make decisions about user permissions. Support for Web services: With the advent of .NET technology, Web services provide many built-in BCL facilities that allow different applications from different sources to communicate with each other. Web services do not provide the user with a GUI. Web services instead share business logic, data and processes through a programmatic interface across a network. Ease of creating dynamic Web content: Dynamic Web content is easier to create with .NET. ASP. NET 2.0 includes various features that enable you to easily develop Web applications having a consistent layout and appearance. Visual Studio .NET: Visual Studio .NET is the Microsoft application and interface for programming in .NET. Visual Studio .NET provides all the programming advantages mentioned so far. This development environment has an extensive set of ready-to use-controls, good debugging facilities, easy and simple programming features, and a vast set of .NET base classes. All these features enable you to develop high performance applications in a short period of time. 6. What is backward compatibility? Ans. Backward compatibility refers to the ability of a technology to work with its previous versions or with other earlier technologies. For example, the Active Directory structure of Windows 2000 is backward compatible with Windows NT 3.51 and 4.0. Similarly, the .NET Framework supports backward compatibility. For example, you can compile and run applications created in Visual Basic 6.0 in Visual Studio 2005.

2 Coordinator Guide Basics of .NET

NIIT

7. Does .NET platform support backward compatibility? Explain. Ans. The .NET platform supports backward compatibility. It is possible for an application compiled in one version of the .NET Framework to run on a different version of the .NET Framework. For example, you can run applications developed in Visual Studio 2002/2003 on Visual Studio 2005. In addition to the above example, the .NET platform supports backward compatibility in the following ways: The .NET Framework 2.0 BCL supports backward compatibility with the earlier versions. .NET supports C++ because of backward compatibility. To run a C++ code on .Net Framework, you need to include the following line at the beginning of the code:
#using <mscorlib.dll>

VB applications can work on VB.NET and ASP applications can run on ASP.NET because of backward compatibility. You can easily reference COM components in.NET applications.

Solutions to Chapter Two Questions


1. With a neat diagram, explain the .NET Framework architecture. Ans. The .NET Framework is the foundation on which you design, develop, and deploy applications. The .NET Framework consists of ASP.NET Web Forms, Windows Forms, and Console applications that pertain to the presentation layer of an application. Web Forms are used in Web-based applications, whereas Windows Forms are used in Windows-based applications for providing an interactive user interface. In addition, you can create character-based console applications that can be executed from the command line. Besides these three components, the .NET Framework consists of two other components, the .NET Framework Base Classes and the CLR. Refer to page 14 of the SG for a diagram on the .NET Framework architecture. 2. List out the objectives of the .NET Framework. Ans. The objectives of .NET Framework are: To provide an object-oriented programming environment and to determine whether object code is stored and executed locally, or executed remotely. To provide a code-execution environment that minimizes software deployment and versioning conflicts. To provide a code-execution environment that guarantees safe execution of code, including code created by an unknown or semi-trusted third party. To provide a code-execution environment that eliminates the performance problems of scripted or interpreted environments. To ensure consistency across varying types of applications, such as Windows-based applications and Web-based applications. To build all communication on industry standards to ensure that code based on the .NET Framework can integrate with any other code. 3. How is Windows Programming different from .NET Programming. Ans.

NIIT

Coordinator Guide Basics of .NET 3

In Windows Programming, the application programs call Windows API function directly. The applications run in the Windows environment, that is, the operating system itself. These types of applications are called unmanaged or unsafe applications. In .NET Programming, the application calls the .NET BCL functions which communicate with the operating system. The applications run in .NET Runtime environment. These types of applications are called managed or safe applications. The .NET Runtime starts code execution, manages threads, provides services, and manages memory. 4. Define the following: Ans. The CLR loads and executes the code. Code management is a fundamental principle of the runtime. It also provides services such as memory management, thread management, remoting, type safety, code security, and robustness. Ans. The code that is developed with a language compiler that targets the CLR is called managed code. Managed code is designed to run on .Net environment. Ans. In the .NET framework, all the .NET languages get compiled into the MSIL or simply the Intermediate Language (IL). The intermediate language is analogous to the byte code of Java. The significant difference is that the byte code is interpreted while the IL is compiled by JIT compilation to native machine code. Ans. The CTS is a standardized set of basic data types. This system provides a way to language interoperability. An object implemented in one .NET supported language can call an object implemented in another .NET supported language. Ans. .NET Base Classes is a library consisting of an extensive set of functions for all services supported by the Framework. This class library provides classes that can be used in the code to accomplish a range of common programming tasks such as string management, data collection, database connectivity, and file access. Ans. Assembly is the unit in which compiled managed code is stored. An assembly contains IL and metadata. Metadata gives details of the assembly, properties and methods stored in it, and security information. Ans. Common Language Specification (CLS) is a set of rules for basic language features that have been defined to enhance and ensure language interoperability. Ans. Reflection is the process of obtaining information about assemblies and the types defined within them as metadata at runtime. JIT compilation Reflection CLS Assemblies .NET Base Classes CTS Intermediate language Managed code CLR

4 Coordinator Guide Basics of .NET

NIIT

Ans. JIT compilation converts IL into its native machine code. The name JIT is because it compiles portion of code as and when required at runtime. Ans. Manifest is the area of the assembly where metadata is stored. Ans. Application domain is the boundary that the CLR establishes around objects created within the same application. Application domain allows different code to run in the same process space. Ans. The garbage collection feature relieves the programmer from the responsibility of freeing memory when no longer required. The CLR calls the garbage collector to handle memory efficiently. 5. What are the functionalities of CLR? Give the steps involved in the managed execution process. Ans. The CLR has the following functionalities: The CLR uses metadata to locate and load classes, lay out instances in memory, resolve method invocations, generate native code, enforce security, and set runtime context boundaries. The CLR automatically handles object layout and manages references to objects, releasing them when they are no longer being used. Automatic memory management eliminates memory leaks as well as some other common programming errors. The CLR makes it easy to design components and applications whose objects interact across languages. Objects written in different languages can communicate with each other, and their behaviors can be tightly integrated. The managed execution process includes the following steps: 1. Choosing an appropriate language compiler. 2. Compiling your code to MSIL or simply IL: Compiling translates your source code into IL and generates the required metadata. 3. Compiling IL to native code: At execution time, a JIT compiler translates the IL into the native machine code. During this compilation, the code must pass a verification process that examines the IL and metadata to find out whether the code can be determined to be type safe. 4. Executing code: The CLR provides the environment that enables execution as well as a variety of services that can be used during execution. 6. What are assemblies? What are static and dynamic assemblies? Ans. Assembly is a basic element of packaging in .NET. An assembly consists of IL code, metadata that describes what is in the assembly, and any other files or information that the application needs to run, such as graphics and sound files. Assemblies can be static or dynamic. Static assemblies can include .NET types (interfaces and classes), as well as required resources for the assembly (bitmaps, JPEG files, resource files, and so on). Static assemblies are stored on disk in Portable Executable (PE) files. Dynamic assemblies are the ones that run directly from the memory, and are not saved on disk before execution. They can be saved on the disk after they have been executed. 7. How does the .NET execution environment with application domain differ from the traditional way of execution? Garbage collection Application domain Manifest

NIIT

Coordinator Guide Basics of .NET 5

Ans. In the case of .NET Framework, application domains provide a secure and versatile unit of processing that the CLR can use to provide isolation between applications. Several application domains can be run in a single process with the same level of isolation that would exist as separate processes, but without incurring the additional overhead of making IPC calls or switching between processes. Traditionally, the process boundaries have been used to isolate applications running on the same computer. Each application is loaded into a separate process, which isolates one application from another applications running on the same computer. The applications are isolated to provide process security. As a result, the process cannot make direct calls to another process. Instead, IPC techniques have to be used to have communication between the processes. Each application is a separate process. 8. What is the function of CTS? Explain the classification of types in CTS with the help of a diagram. Ans. The CTS defines how types are declared, used, and managed in the runtime. It is important for language interoperability. The CTS performs the following functions: Establishes a common framework that enables cross-language integration, type safety, and high performance code execution. Provides an object-oriented model. Defines rules that languages must follow, so that different languages can interact with each other.

CTS can be classified into: Value types Reference types

The following diagram illustrates type classification.

Type

Value Types Built-In-Value Types User-Defined Value Types Enumerations Self Describing Types Class Types User-Defined Classes

Reference Types Pointer Types Arrays Boxed Value Types Interface Types

Delegates

Type Classification

Value types directly store data in the variable. Value types can be built-in type, user-defined types, or enumerations. Reference types store a reference to the data's memory address. Reference types can be self-describing types, pointer types, or interface types. Self-describing types are further split into arrays and class types. The class types are user-defined classes, boxed value types, and delegates. All types derive from the System.Object base type. 9. Write a note on metadata.

6 Coordinator Guide Basics of .NET

NIIT

Ans. An assembly stores all the information about itself. This information is called metadata and includes the name and version number of the assembly, security information, information about the dependencies, and a list of the files that constitute an assembly. Metadata is the binary information describing the program. When we compile our code into a PE file, the metadata is inserted into one portion of the PE file, while the code is converted to IL and inserted into another portion of the PE file. Every type member that are defined or referenced in a module is described within metadata. When code is executed, the runtime loads metadata into memory and refers it to get information about the code's classes, members, inheritance, and so on. Metadata allows .NET languages to describe themselves in a language-neutral manner. It gives required information to the CLR to perform much of its functionalities. The presence of metadata makes the assembly selfdescribing file. The CLR modules or components or other assemblies which want to communicate with each other use this information stored in metadata to perform their tasks. 10. It is told that if we learn any one .NET language, then working with other .NET languages will be easy. How? Explain with an appropriate example. Ans. It can be told that if you have learned any one .NET language, then working with other .NET languages will be easy. This is because all the .NET languages rely on the same managed classes of BCL for the same services. The same classes, methods, parameters, and types are used for all the system services regardless of any .NET language. Let us look at the following code that writes to and then reads from a file: // Program in C#
using System; using System.IO; static public void Main() { StreamWriter sw1=new StreamWriter("temp.txt", true); string tempstring="Hi, this is Gopal"; sw1.WriteLine(tempstring); sw1.Close(); StreamReader sr1=new StreamReader("temp.txt"); string filestring=sr1.ReadToEnd(); sr1.Close(); Console.WriteLine(filestring); }

// Program in VB.NET
shared public sub Main() dim sw1 as StreamWriter=new StreamWriter("temp.txt", true) dim tempstring as string= "Hi, this is Gopal" sw1.WriteLine(tempstring) sw.Close() dim sr1 as StreamReader=new StreamReader("temp.txt") dim filestring as string=sr1.ReadToEnd() sr1.Close() Console.WriteLine(filestring) end sub

If we see, both versions of the above program are nearly identical. The syntax and use of StreamReader, StreamWriter, and the Console class are identical, same methods, and identical parameters.

Solutions to Chapter Three Questions


1. List out the important features of C#. Ans. The features of C# are as follows:

NIIT

Coordinator Guide Basics of .NET 7

C# is an elegant, simple, type-safe, object-oriented language. C# has the capability to build durable system-level components due to the following features:

Full COM/platform support for existing code integration Robustness through garbage collection and type safety Security provided through good design Full support of extensible metadata concepts C# supports language interoperability and platform independence.

2. Write a program in C# to display Welcome to the world of C Sharp. Explain the program. Ans. The C# program is as follows:
using System; namespace ConsoleApplication1 { class Welcome { static void Main() { System.Console.WriteLine("Welcome to the world of C Sharp"); Console.Read(); } } }

The important points to be noted in this program are: Main method: Program execution begins with the Main method. Input and output: The WriteLine function displays the string on the standard output device. Compilation and execution: To compile the program, enter the following command:

csc Welcome.cs

To execute the program, enter the following command:


Welcome

3. Explain the general structure of a C# program. Ans. C# program can consist of one or more files. Each file can contain one or more namespaces. A namespace contains group of related types such as classes, structs, interfaces, enumerations, and delegates. Namespaces may be nested. The following is the structure of a C# program that contains all of these elements:
using System; //Using the System Namespace namespace Namespace1 //Defining a namespace { class Class1 //Defining a class { } struct Struct1 // Defining a structure { } interface Interface1 //Defining an interface { } delegate int Delegate1(); enum Enum1 //Defining an enumeration { } namespace Namespace2 //Defining a namespace

8 Coordinator Guide Basics of .NET

NIIT

{ } class Class2 //Defining a class { public static void Main(string[] args) //Program execution begins //from here { } } }

4. How do namespaces and types in C# have unique names? Give an example. Ans. Namespaces and types always have unique names. If there are two classes with the same name but present in different namespaces, then both the objects will have unique fully qualified names. Consider the following code snippet:
namespace ABC { class Class1 { } } // ABC // ABC.Class1

namespace XYZ // XYZ { class Class1 // XYZ.Class1 { } }

Here the ABC.Class1 and XYZ.Class1 are two different types, even if the class name is same. 5. List out the difference between C# and C++. Ans. The differences between C# and C++ are as follows. C# C# is a purely object-oriented language. The long data type is of 64 bits. C# supports ref and out parameters, which are used instead of pointers in passing parameters by reference. Pointers are allowed in C# but only in the unsafe mode. C++ C++ supports object-oriented programming. The long data type is of 32 bits. C++ supports pointers in passing parameters by reference.

C# Vs. C++

Solutions to Chapter Four Questions


1. Which are the two different categories of types in C#? Ans. In C# language, the types are divided into two categories: Value types: Variables of the value types directly contain their data. With value types, the variables have their own copy of the data.

NIIT

Coordinator Guide Basics of .NET 9

Reference types: Variables of the reference types store address of their data. With reference types, it is possible for two variables to reference the same object. 2. What are variables? How many categories of variables are there in C#? Define each. Ans. Variables represent storage locations. Every variable has a type that determines what kind of data can be stored in the variable. There are seven categories of variables: Static variables: A variable declared with the static modifier is called a static variable. There will be only one copy of the variable, regardless of how many instances of class (in which static variable exists) are created. Instance variables: A variable declared without the static modifier is an instance variable. Array elements: The array is a container that has a list of storage locations for a specified type. The elements for a specified type of an array come into existence when an array instance is created and exists until there are no references to that array instance. Value parameters: Parameters are arguments passed to the function. A parameter declared without a ref or out modifier is a value parameter. A value parameter comes into existence when the function is invoked and is initialized with the value of the argument passed. A value parameter exists until the function returns. Reference parameters: A parameter declared with a ref modifier is a reference parameter. A reference parameter does not create a new instance, it points to the same storage location of the parameter passed as an argument. Output parameters: A parameter declared with an out modifier is an output parameter. The value of an out argument is not passed to the out parameter. Local variables: A local variable is declared within a block, like a for-statement, a switch-statement, or a using-statement. A local variable is not automatically initialized and thus has no default value. 3. What is the importance of automatic memory management? Explain with example. Ans. Manual memory management requires developers to manage the allocation and de-allocation of blocks of memory. Manual memory management can be both time consuming and difficult. In C#, automatic memory management is provided so that developers are freed from this manual task. Automatic memory management increases code quality and enhances developer productivity without negative impact on either expressiveness or performance. Consider the following example:
using System; public class Stack { private Node first = null; public bool Empty { get { return (first == null); } } public object Pop() { if (first == null) Console.Write("Can't Pop from an empty Stack."); else { object temp = first.Value; first = first.Next; return temp; }

10 Coordinator Guide Basics of .NET

NIIT

} public void Push(object o) { first = new Node(o, first); } class Node { public Node Next; public object Value; public Node(object value): this(value, null) {} public Node(object value, Node next) { Next = next; Value = value; } } }

In the above example, a Stack class is implemented as a linked list of Node instances. These node instances are created in the Push method and are deallocated when no longer in use. 4. Write a note on expressions and operators in C#. Ans. An expression is a sequence of operators and operands that specifies computation and assigns the result to a variable. Expressions are constructed from operands and operators. The operators of an expression indicate which operations to perform. Examples for operators are +, -, *, /, etc. Examples for operands are literals, variables, and expressions. There are three kinds of operators: Unary operators: The unary operators operate on only one operand. For example, --x, x++. Binary operators: The binary operators operate on two operands. For example, x + y.

Ternary operator: The ternary operator operates on three operands. For example, condition? true_exp: false_exp. There is only one ternary operator, ?:. The order of evaluation of operators in an expression is determined by the precedence and associability of the operators. When an expression contains multiple operators, the precedence of the operators controls the order in which the individual operators are evaluated. For example, the expression x + y * z is evaluated as x + (y * z) because the * operator has a higher precedence than the + operator. 5. What are empty statement and labeled statements? Why are they used? Ans. An empty statement (;) is used when there are no operations to perform. Execution of an empty statement simply transfers control to the end point of the statement. For example, an empty statement can be used when writing a while statement with a null body:
while (WaitForAnEvent()) ;

An empty statement can also be used to declare a label just before the closing } of a block:
void Func() { ... if (true) goto exit; ... exit: ; }

A labeled statement is prefixed by a label of a character string. Labeled statements are permitted in blocks. A label is a name given by the identifier. The scope of a label is the block in which the label is declared. If two labels have the same name, you get a compile time error.

NIIT

Coordinator Guide Basics of .NET 11

A label can be referenced from goto statements within the scope of the label. Labels and other identifiers can have the same name. Consider the following example:
int Func(int abc) { if (abc >= 0) goto abc; abc = -abc; abc: return abc; }

The above example uses the name abc as both a parameter and a label. 6. What is an iterative statement? Explain foreach statement with example. Ans. Iteration statements repeatedly execute a block of statements. The number of iterations depends on the condition represented by the boolean expression. The block of code will be iterated until the condition is true. Consider the following code:
using System; class TestForeach { static void Main() { int[] array1 = new int[] {1,2,3,4,5}; foreach (int i in array1) Console.WriteLine(Value is {0}, i); } }

In the above example, the foreach statement iterates through the elements of array1. 7. List the different jump statements supported by C#. Ans. The different jump statements supported by C# are: break statement continue statement goto statement return statement throw statement

8. What are checked and unchecked statements? Give an example. Ans. The checked and unchecked statements are used to control the overflow checking for integer type arithmetic operations and conversions. The checked statement causes all expressions in the checked block to be evaluated in a checked context, and the unchecked statement causes all expressions in the unchecked block to be evaluated in an unchecked context. Checked allows you to raise an exception whenever stack overflow (or underflow) occurs due to type conversion issues. Unchecked will allow you to ignore these exceptions when the C# project is set to raise these types of exceptions. Consider the following example:
static void Main() { int x = Int32.MaxValue;

12 Coordinator Guide Basics of .NET

NIIT

Console.WriteLine(x + 1); // Overflow checked { Console.WriteLine(x + 1); // Exception } unchecked { Console.WriteLine(x + 1); // Overflow } }

In the above example, the checked keyword allows you to report the overflow at runtime. 9. Give an example of lock and using statements. Ans. Example of lock statement:
static void Main() { A a = ...; lock(a) { a.P = a.P + 1; } }

In the above code snippet, a block of code obtains a mutual-exclusion lock. Example of using statement:
static void Main() { using (Resource r = new Resource()) { r.Func(); } }

In the above code snippet, resources are obtained with the using statement. 10. How are structures different from classes in C#? Ans. Structures are value types and classes are reference type. A variable of a structure type directly contains the data of the structure, whereas a variable of a class type contains a reference to the object. You can inherit classes but you cannot inherit structures. 11. What are interfaces? Give an example. Ans. Interfaces are used to define a contract; a class or struct that implements the interface must obey to this contract. Interfaces can contain methods, properties, indexers, and events as members. They cannot contain constants, fields (private data members), constructors, and destructors, or any type of static member. All the members of an interface are public by definition. Consider the following example:
interface IExample { string this[int index] { get; set; } event EventHandler E; void Func(int value); string P { get; set; } } public delegate void EventHandler(object sender, EventArgs e);

The above example shows an interface that contains an indexer, an event E, a method Func, and a property P.

NIIT

Coordinator Guide Basics of .NET 13

12. What is a delegate? What is the use of it? Give an example. Delegates are objects that you use to call the methods of other objects. Delegates are said to be object-oriented function pointers since they allow a function to be invoked indirectly by using a reference to the function. A delegate declaration defines a class that is derived from the class System.Delegate. A delegate instance encapsulates one or more methods, each of which is referred to as a callable entity. For instance methods, a callable entity consists of an instance and a method on that instance. For static methods, a callable entity consists of just a method. Given a delegate instance and an appropriate set of arguments, one can invoke all instance methods of that delegate with that set of arguments. Consider the following example of a delegate:
class Test { static void F() { System.Console.WriteLine("Test.F"); } static void Main() { SimpleDelegate dele = new SimpleDelegate(F); dele(); } }

The above example creates a SimpleDelegate instance, dele, and then immediately calls it. This program displays Test.F. 13. Write a program to demonstrate the usage of enums in C#. Ans. The following program illustrates the use of enums.
enum Color { Red, Blue, Green } class Shape { public void Fill(Color color) { switch(color) { case Color.Red: Console.WriteLine(RED); break; case Color.Blue: Console.WriteLine(BLUE); break; case Color.Green: Console.WriteLine(GREEN); break; default: break; } Console.Read(); } }

14 Coordinator Guide Basics of .NET

NIIT

The above program shows a color enum and a method that uses this enum. 14. Write a note on namespaces in C#. Ans. C# programs are organized by using namespaces. Namespaces are used both as an internal organization system for a program, and as an external organization system. This is a way of writing program elements that are exposed to other programs. A namespace declaration consists of the keyword namespace, followed by a namespace name and body:
namespace NamespaceName { ... // namespace body }

Classes actually contain data and Namespaces are used to logically arrange classes. Namespaces can also contain many other Namespaces and classes. C# classes are organized by using namespaces. Namespaces provide a way to group classes by providing an extra level of naming beyond the class name. Namespaces are implicitly public and the declaration of a namespace does not include any access modifiers. The identifier or name of a namespace may be a single identifier or a sequence of identifiers separated by . tokens. The latter form permits a program to define a nested namespace. Consider the following code snippet:
namespace Example.Namespace1 { public class NmEx { public string Display() { return "Namespace example"; } } }

Namespaces are hierarchical, and the name Example.Namespace1 is an easier and convenient way for defining a namespace named Example that contains a namespace named Namespace1, as in:
namespace Example { namespace Namespace1 { } }

15. What is the use of attributes in C# programs? Ans. C# is an imperative language, but like all imperative languages it does have some declarative elements. For example, the accessibility of a method in a class is specified by declaring it public, protected, internal, protected internal, or private. C# generalizes this capability, so that programmers can invent new kinds of declarative information, attach this declarative information to various program entities, and retrieve this declarative information at runtime. Programs specify this additional declarative information by defining and using attributes.

Solutions to Chapter Five Questions


1. Write a note on classes in C#.

NIIT

Coordinator Guide Basics of .NET 15

Ans. A class is a collection of variables and methods. The class defines all the common properties of the different objects that belong to it. Class declarations are reference types. A class can inherit from another class and can implement interfaces. Class members can include constants, fields, methods, properties, events, indexers, operators, instance constructors, destructors, static constructors, and nested type declarations. Each member has an associated accessibility, which controls the portion of the program code that is able to access the member. There are five forms of accessibility. These are as follows: Public, which is selected by including a public modifier in the member declaration. The intuitive meaning of public is access not limited. Protected internal (meaning protected or internal), which is selected by including both a protected and an internal modifier in the member declaration. The intuitive meaning of protected internal is access limited to this program or types derived from the containing class. Protected, which is selected by including a protected modifier in the member declaration. The intuitive meaning of protected is access limited to the containing class or types derived from the containing class. Internal, which is selected by including an internal modifier in the member declaration. The intuitive meaning of internal is access limited to the program. Private, which is selected by including a private modifier in the member declaration. The intuitive meaning of private is access limited to the containing type. 2. What are constant members? Give an example. Ans. A constant is a class member that represents a constant value. Constant members are initialized at the time of their declaration. Consider the following example:
class Constants { public const int A = 1; public const int B = A + 1; }

The above example shows a class named Constants that has two public constants. 3. Give an example of field member. Ans. Consider the following code, which displays a class and its field members:
class Color { internal ushort redPart; internal ushort bluePart; internal ushort greenPart; public Color(ushort red, ushort blue, ushort green) { redPart = red; bluePart = blue; greenPart = green; } public static readonly Color Red = new Color(0xFF, 0, 0); public static readonly Color Blue = new Color(0, 0xFF, 0); public static readonly Color Green = new Color(0, 0, 0xFF); public static readonly Color White = new Color(0xFF, 0xFF, 0xFF); }

In the above example, the Color class has the fields: redPart, bluePart, greenPart, Red, Blue, Green, and White. 4. With appropriate examples, explain parameter passing in C#.

16 Coordinator Guide Basics of .NET

NIIT

Ans. Parameters can be passed by value or by reference. These are explained as follows: Passing by value: The parameter modifiers 'ref' and 'out' relate to how the parameter is passed into the method. By default, parameters are passed by value. In this case, when the method is called, the value given is copied to the variable specified in the method declaration. The following example illustrates this point; note that the change made to variable b in the body of the 'change' method does not result in a change to the variable a used to invoke the method. Consider the following code snippet:
public static void Main() { int a = 0; change(a); Console.WriteLine(a); //Line 2 } public static void change(int b) { b = 5; Console.WriteLine(b); //Line 1 } In the above example, the value of a is initialized to 0. When the change method is called, the value of a is changed to 5. Therefore, Line1 displays 5. However, the parameter a is passed by value. Therefore the original value of a does not change. Therefore, Line2 would display 0.

Passing by reference: In C#, you can pass variables into methods 'by reference'. When a variable is passed by reference, the 'ref' modifier must be used both in the method definition argument list and the method invocation. Consider the following example:
public static void Main() { int a = 0; change(ref a); Console.WriteLine(a); //Line2 } public static void change (ref int b) { b = 5; Console.WriteLine(b); //Line1 }

In the above example, the value of a is initialized to 0. When the change method is called, the value of a is changed to 5. Therefore, Line1 displays 5. Here, the parameter a is passed by reference. Therefore the original value of a changes. Therefore, Line2 would display 5. 5. What is the use of property member in a class? Ans. A property is a member that provides access to a characteristic of an object or a class. Examples of properties include the length of a string, the size of a font, the caption of a Window, the name of a customer, and so on. Properties are a natural extension of fields. Both are named members with associated types, and the syntax for accessing fields and properties is the same. However, unlike fields, properties do not denote storage locations. Instead, properties have accessors that specify the block of statements to be executed when their values are read or written. 6. What are events? Give an example to demonstrate its usage. Ans. An event is a set of actions that is triggered to call a function or to start an operation. A class defines an event by providing an event declaration and an optional set of event accessors. The declaration resembles a field declaration, with an added event keyword. The type of this declaration must be a delegate type.

NIIT

Coordinator Guide Basics of .NET 17

Consider the following example:


void Button1_Click(object sender, EventArgs e) { MessageBox.Show("Button1 was clicked!"); }

In the above example, a click event is raised when Button1 is clicked. 7. With an example, explain indexers. Ans. An indexer enables an object to be indexed in the same way as an array. Whereas properties enable field-like access, indexers enable array-like access. Indexer declarations are similar to property declarations, with the main differences being that indexers are nameless and that indexers include indexing parameters. The indexing parameters are provided between square brackets. Consider the following example:
using System; public class Stack { private Node GetNode(int index) { Node temp = first; while (index > 0) { temp = temp.Next; index--; } return temp; } public object this[int index] { get { if (!ValidIndex(index)) throw new Exception("Index out of range."); else return GetNode(index).Value; } set { if (!ValidIndex(index)) throw new Exception("Index out of range."); else GetNode(index).Value = value; } } ... } class Test { static void Main() { Stack s = new Stack(); s.Push(1); s.Push(2); s.Push(3); s[0] = 33; // Changes the top item from 3 to 33 s[1] = 22; // Changes the middle item from 2 to 22 s[2] = 11; // Changes the bottom item from 1 to 11 } }

The above example shows an indexer for the Stack class.

18 Coordinator Guide Basics of .NET

NIIT

8. Explain each of the following with an example: a. Instance constructors Ans. An instance constructor is a member that implements the actions required to initialize an instance of a class. Consider the following example:
using System; class Point { public double x, y; // Instance constructor public Point() { this.x = 0; this.y = 0; } //Parameterized Instance constructor public Point(double x, double y) { this.x = x; this.y = y; } public static double Distance(Point a, Point b) { double xdiff = a.x - b.x; double ydiff = a.y - b.y; return Math.Sqrt(xdiff * xdiff + ydiff * ydiff); } public override string ToString() { return string.Format("({0}, {1})", x, y); } } class Test { static void Main() { Point a = new Point(); Point b = new Point(3, 4); double d = Point.Distance(a, b); Console.WriteLine("Distance from {0} to {1} is {2}", a, b, d); } }

The above example shows a Point class provides two public instance constructors, one of which takes no arguments, while the other takes two arguments. b. Destructor Ans. A destructor is a member that implements the actions required to destroy an instance of a class. Destructors cannot have parameters, they cannot have accessibility modifiers, and they cannot be called explicitly. The destructor of an instance is called automatically during garbage collection. Consider the example:
using System; class Point

NIIT

Coordinator Guide Basics of .NET 19

{ public double x, y; public Point(double x, double y) { this.x = x; this.y = y; } ~Point() { Console.WriteLine("Destructed {0}", this); } public override string ToString() { return string.Format("({0}, {1})", x, y); } }

The above example shows a Point class with a destructor. c. Static constructor Ans. A static constructor is a member that implements the actions required to initialize a class. Static constructors cannot have parameters, they cannot have accessibility modifiers, and they cannot be called explicitly. The static constructor for a class is called automatically. Consider the following code snippet:
class Employee { private static DataSet ds; static Employee() { ds = new DataSet(...); } public string Name; public decimal Salary; ... }

The above example shows an Employee class with a static constructor that initializes a static field. 9. How does C# support inheritance? Ans. C# classes support inheritance by using the : operator. Consider the following example:
using System; class A { public void F() { Console.WriteLine("Inside A.F"); } } class B: A { public void G() { Console.WriteLine("Inside B.G"); } } class Test { static void Main() { B b = new B(); b.F(); // Inherited from A

20 Coordinator Guide Basics of .NET

NIIT

b.G(); A a = b; a.F(); } }

// Introduced in B // Treat a B as an A

The output will be: Inside A.F Inside B.G Inside A.F The above program shows a class B that derives from A. The class B inherits A's F method, and introduces a G method of its own. 10. What is method overloading? Give an example. Ans. Method overloading refers to the methods with the same name but different signatures doing different tasks. Consider the following example:
using System; class PolymorphismEx { public static int add(int a, int b) { int sum=a+b; Console.WriteLine(sum); } public static int add(int a, int b, int c) { int sum=a+b+c; Console.WriteLine(sum); } static void main() { add(3,4); add(3,4,5); add(5,6); } }

In the above example, the add function is overloaded as the two add functions have different signatures. The output of the above program is: 7 12 11 11. What is operator overloading? Give an example. Ans. Operator overloading refers to loading an operator to perform different operations on different data types on different contexts. To overload an operator in a class, one defines a method by using the 'operator' keyword. The following program uses operator overloading to create a complex number class ComplexAdd that defines complex addition. The program displays the imaginary and the real parts of the numbers and the addition result using an override of the ToString method.
// complexAdd.cs

NIIT

Coordinator Guide Basics of .NET 21

using System; public struct ComplexAdd { public int r; public int img; public Complex(int r, int img) { this.r = r; this.img = img; } // Declare which operator to overload public static ComplexAdd operator +(ComplexAdd c1, ComplexAdd c2) { return new ComplexAdd(c1.r + c2.r, c1.img + c2.img); } // Override the ToString method to display a complex number in a required format: public override string ToString() { return(String.Format("{0} + {1}i", r, img)); } public static void Main() { ComplexAdd var1 = new ComplexAdd(5,3); Complex var2 = new Complex(6,2); // Add two Complex objects (var1 and var2) through the // overloaded plus operator: ComplexAdd total = var1 + var2; // Print the numbers and the sum using the overridden ToString method: Console.WriteLine("First complex number: {0}",var1); Console.WriteLine("Second complex number: {0}",var2); Console.WriteLine("The sum of the two numbers: {0}",total); } }

Output First complex number: 5 + 3i Second complex number: 6 + 2i The sum of the two numbers: 11 + 5i

Solutions to Chapter Six Questions


1. What is a preprocessor? Explain the purpose of the following directives: #if #else #elif #endif #define #undef #warning #error #line

Ans.

22 Coordinator Guide Basics of .NET

NIIT

A preprocessor manipulates the source code. It breaks up the source code into modules. Preprocessor directives instruct the preprocessor to perform specific tasks. Some of the preprocessor directives are explained below. #if: It begins a conditional directive for testing a symbol, to see if they evaluate to true. If true, the compiler evaluates all the code between the #if and the next corresponding directive. #else: It evaluates if none of the expressions in the preceding #if or #elif directives evaluate to true. #elif: It evaluates if neither the preceding #if nor any preceding #elif directive expressions evaluate to true. #endif: It specifies the end of an #if directive. #define: It defines a symbol, which can be passed to the #if directive to evaluate the expression as true. Consider the following code, which illustrates the use of #if, #else, #elif, #endif, and #define:
#define DEBUG #define VC_V6 using System; public class IfClass { public static void Main() { #if (DEBUG && !VC_V6) Console.WriteLine("DEBUG #elif (!DEBUG && VC_V6) Console.WriteLine("VC_V6 #elif (DEBUG && VC_V6) Console.WriteLine("DEBUG #else Console.WriteLine("DEBUG #endif } } has been defined"); has been defined"); and VC_V6 has been defined"); and VC_V6 has not been defined");

Output DEBUG and VC_V6 has been defined. #undef: It undefines a symbol. Consider the following code:
#undef DEBUG using System; public class Test { public static void Main() { #if DEBUG Console.WriteLine("DEBUG has been defined"); #else Console.WriteLine("DEBUG has not been defined"); #endif } }

Output DEBUG has not been defined. #warning: It generates a Level 1 warning from a specific location in the code. Consider the following code snippet:
#define DEBUG public class Test { public static void Main() { #if DEBUG

NIIT

Coordinator Guide Basics of .NET 23

#warning DEBUG defined #endif } }

#error: It generates an error from a specific location in the code. Consider the following code snippet:
#define DEBUG public class Test { public static void Main() { #if DEBUG #error DEBUG defined #endif } }

#line: It changes the compiler's line number and the file name. Consider the following code snippet:
public class Test { public static void Main() { #line 100 int i; // error or warning will be: CS0168 on line 100 #line 10 char c; // error or warning will be: CS0168 on line 10 } }

2. What is an exception? How are exceptions handled in C#? Ans. An exception is any error condition or unexpected behavior encountered by a program in execution. Exceptions can be raised because of: Fault in the code or in shared library. Unavailability of operating system resources. Unexpected conditions encountered by the CLR encounters.

Exceptions are handled by a try statement. When an exception occurs, the system searches for the nearest catch block that can handle the exception. Once a matching catch block is found, the control is transferred to the first statement of the catch block and the catch block executes. If no matching catch block or finally block is found, then the execution of the thread is terminated. Note: If the application does not handle these exceptions, then the application terminates (default behavior). 3. What is an unsafe code? Explain. Ans. Unsafe code refers to the code that is processed with low security levels. There are situations where access to pointer types becomes a necessity. For example, interfacing with the underlying operating system, accessing a memory-mapped device, or implementing a time-critical algorithm may not be possible without access to pointers. To address this need, C# provides the ability to write unsafe code. In unsafe code, it is possible to declare and operate on pointers, to perform conversions between pointers and integral types, to take the address of variables, and so forth. In a sense, it is like writing C code within a C# program. Unsafe code must be clearly marked with the modifier unsafe, so developers cannot possibly use unsafe features accidentally. When CLR finds this unsafe modifier, the execution engine works to ensure that the unsafe code cannot be executed in an untrusted environment.

24 Coordinator Guide Basics of .NET

NIIT

4. What is threading? List out the advantages and disadvantages of multiple threads. Ans. Threads are the basic unit to which an operating system allocates processor time, and more than one thread can run inside that process. Each thread maintains exception handlers, a scheduling priority, and a set of structures the system uses to save the thread context until it is scheduled. The thread context includes all of the information the thread needs to resume execution, including the set of CPU registers and stack, in the address space of the thread's host process. Multithreading offers the following advantages: Improved responsiveness: If the application is performing operations that take a perceivably long time to complete, these operations can be put into a separate thread which will allow the application to continue to be responsive to the user. Faster application: Multiple threads can lead to improved application performance. For example, if there are a number of calculations to be performed, then there the application can be made faster by performing multiple operations at the same time. Prioritization: Threads can be assigned a priority which would allow higher priority tasks to take precedence over lower priority tasks. Programming and debugging is more complex: With multithreaded applications the programmer must ensure deadlock avoidance. Threads add overhead to the system: In order for the operating system to track a large number of threads it is going to consume processor time. If there are too many threads then each thread may not be given enough time to execute during its time slice.

Multithreading has the following disadvantages:

5. Write a note on library base classes. Ans. The .NET Framework base classes include classes, interfaces, and value types that provide access to system functionality. To facilitate interoperability between languages, the .NET Framework base classes are CLS compliant and therefore can be used from any programming language. The .NET Framework library base classes are the foundation on which .NET applications, components, and controls are built. These also include types that perform the following functions: Represent base data types and exceptions Encapsulate data structures Perform I/O operations Access information of data types Perform .NET Framework security checks Provide data access, GUI, and Web services

6. What is the role of System.Object, System.String, System.Array and System.Collections Classes? Ans. The roles of the various classes and namespaces are as follows: The System.Object class provides classes and methods that allow you to build generic routines, provides Type System Unification, and enables working with groups collections. The System.String class provides methods that allow you to perform various string operations. The System.Array class provides methods for creating, traversing, manipulating, sorting, and searching arrays. The System.Collections namespace contains interfaces and classes that allow you to define various collections of objects, such as lists, queues, bit arrays, hash tables, and dictionaries.

NIIT

Coordinator Guide Basics of .NET 25

7. What are the different methods supported by System.Object class? Give an example for each. Ans. The methods are: Equals: This method of the object class provides a default implementation that compares two reference type objects for reference equality. The following code snippet illustrates the use of the Equals method:
public static void Main() { string str1= Mark; string str2= Adam; str3= Mark; Console.WriteLine(Object.Equals(str1,str2)); //Displays False Console.WriteLine(Object.Equals(str1,str3)); //Displays True }

ReferenceEquals: This method compares object instances. The following code snippet illustrates the use of the ReferenceEquals method:
public static void Main() { object obj1= null; object obj2= null; Console.WriteLine(Object.ReferenceEquals(obj1,obj2)); True }

//Displays

ToString: This method returns a string representation of a type. The following code snippet illustrates the use of the ToString method:
public class Example { void StrConvert() { Object obj= new Object(); Console.WriteLine(obj.ToString()); //Displays System.Object } }

GetType: This method returns a Type object, describing the object it was called on. The following code snippet illustrates the use of the GetType method:
public static void Main() { Class1 obj= new Class1(); Console.WriteLine(obj.GetType()); //Displays Class1 }

GetHashCode: This method makes any object usable in a hash table or any hashing algorithm. The following code snippet illustrates the use of the GetHashCode method:
public struct Int32 { public int val; public override int GetHashCode()

26 Coordinator Guide Basics of .NET

NIIT

{ return val; //Returns an integer value } }

MemberwiseClone: This method is used to create a bitwise copy of the type. The following code snippet illustrates the use of the MemberwiseClone method:
public static void Main() { Class1 obj1= new Class1(); obj1.name= Stephen; Class1 obj2 = (Class1)obj1.MemberwiseClone; }

Finalize: This method is used as a destructor. The Finalize destructor is called after the last reference to an object is released from the memory. The .NET Framework automatically runs the Finalize destructor to destroy objects in the memory. The following code snippet illustrates how to override the Finalize method:
~Object();

8. What is boxing and unboxing? Explain with an example. Ans. Boxing refers to the conversion of value types to object types. Consider the following code snippet:
public static void Main() { int var= 21; object obj=var; //Boxing }

In the memory, var and obj are represented in the following manner. Stack Heap
21

var

obj
int 21 Representation of var and obj in Memory

Unboxing refers to the conversion of object types to value types. Consider the following code snippet:
public static void Main() { int var= 21; object obj=var; //Boxing int var2= (int)obj; }

In the memory, var, obj, and var2 are represented in the following manner.

NIIT

Coordinator Guide Basics of .NET 27

Stack

Heap
21

var

obj
int 21

var2
21 Representation of var, obj, and var2 in Memory

9. Write a program to replace all r by R in the string rose is a rose. Ans. This program is given below:
using System; namespace ConsoleApplication1 { class Change { static void Main() { string errString = "rose is a rose"; string correctString = errString.Replace("r", "R"); Console.WriteLine(correctString); Console.ReadLine(); } } }

10. Write a note on the following: a. Single-dimensional arrays Ans. Single-dimension array is defined as an array having only one dimension. We can declare a single-dimension array of five integers in the following way:
int[] arr = new int [5];

This array contains the elements from arr[0] to arr[4]. The new operator is used to create the array and initialize the array elements to their default values. In this case, all the array elements are initialized to zero. An array that stores string elements can be declared in the same way. For example:
string[] myStringArray = new string[6]; b. Multidimensional arrays

Ans. Multidimensional array is defined as an array having more than one dimension. For example, the following declaration creates a two-dimensional array of four rows and two columns:
int[,] arr = new int[4,2];

The following code creates an array of three dimensions, 4, 2, and 3, as shown below:

28 Coordinator Guide Basics of .NET

NIIT

int[,,] arr = new int [4,2,3];

c. Jagged arrays Ans. A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions. The following is a declaration of an array that has three elements, each of which is a single-dimensional array of integers:
int[][] myJaggedArr = new int[3][];

Before we can use myJaggedArr, its elements must be initialized. We can initialize the elements like:
myJaggedArr [0] = new int[5]; myJaggedArr [1] = new int[4]; myJaggedArr [2] = new int[2];

Each of the elements is a single-dimensional array of integers. The first element is an array of 5 integers, the second is an array of 4 integers, and the third is an array of 2 integers. It is also possible to use initializers to fill the array elements with values, in which case we do not need the array size. For example:
myJaggedArr [0] = new int[] {1,3,4,7,9}; myJaggedArr [1] = new int[] {0,2,9,6}; myJaggedArr [2] = new int[] {18,22};

A jagged array can be initialized in the following manner as well:


int[][] myJaggedArr = new int [][] { new int[] {1,3,5,7,9}, new int[] {0,2,4,6}, new int[] {11,22} };

d. Passing arrays by using ref and out Ans. The ref and out parameters allow you to retain the change in the value of a variable when control passes back to the calling procedure. Without these keywords, the variable would not retain the modified value once the control passes back to the calling procedure. A ref parameter of an array type must be assigned by the caller. Therefore, there is no need to be definitely assigned by the callee. A ref parameter of an array type may be altered as a result of the call. For example, the array can be assigned the null value or can be initialized to a different array. For example:
public static void MyMethod(ref int[] arr) { arr = new int[10]; // arr initialized to a different array }

An out parameter of an array type must be assigned before it is used; that is, it must be assigned by the callee. For example:
public static void MyMethod(out int[] arr) { arr = new int[10]; // definite assignment of arr }

11. What is the use of System.Collections namespace? Ans.

NIIT

Coordinator Guide Basics of .NET 29

The System.Collections namespace contains interfaces and classes that are used to define various collections of objects, such as lists, queues, bit arrays, hashtables and dictionaries.

Solutions to Chapter Seven Questions


1. Give the overall concept of ADO.NET with the help of figures. Ans. ActiveX Data Objects for the .NET Framework (ADO.NET) is a set of classes that provide data access services to the .NET programmer. ADO.NET provides a rich set of components for creating distributed, data-sharing applications. It is an integral part of the .NET Framework, providing access to relational database, XML, and application data. ADO.NET supports a variety of development needs, including the creation of front end database clients and middle tier business objects used by applications, tools, languages, or Internet browsers. ADO.NET provides consistent access to data sources such as Microsoft SQL Server, or data sources exposed via OLE DB and XML. Data sharing applications can use ADO.NET to connect to these data sources and retrieve, manipulate, and update data. The data residing in a database is retrieved through data provider. Different components of the data provider retrieve data from the database, provide the data to the Visual Basic .NET application, and update the database with the changes made in the application. An application can access data either through a dataset or through a DataReader object: Using a dataset: In this case, the data is cached in a dataset and the application accesses the data from the dataset. Using a data reader: In this method, a DataReader object, which is a component of the data provider, uses the Connection object to connect to the database, uses the Command object to retrieve data, and provides data to the application in a read-only and forward-only mode.

Refer to pages 120-123 of the SG for diagrams on the ADO.NET architecture. 2. Explain in detail the ADO.NET architecture. Ans. The ADO.NET components have been designed for easy access and manipulation of data. There are two central components of ADO.NET, DataSet and .NET Data Provider. The ADO.NET DataSet is the core component of the disconnected architecture of ADO.NET. The DataSet is explicitly designed for data access independent of any data source. It can be used with multiple and different data sources, used with XML data, or used to manage data local to the application. The DataSet contains a collection of one or more DataTable objects. The other core element of the ADO.NET architecture is the .NET Data Provider, whose components (Connection, Command, DataReader, and DataAdapter) are explicitly designed for data manipulation. The Connection object provides connectivity to a data source. The Command object enables access to database commands to return data, modify data, run stored procedures, and so on. The DataReader provides a high-performance stream of data from the data source. Finally, the DataAdapter provides the bridge between the DataSet object and the data source. The DataAdapter uses Command objects to execute SQL commands at the data source to both load the DataSet with data, and to update changes made to the data in the DataSet back to the data source. 3. What is a data provider? Explain. Ans. A data provider is used for connecting to a database, retrieving data, storing the data in a dataset, reading the retrieved data, and updating the database. There are two types of data providers:

30 Coordinator Guide Basics of .NET

NIIT

OLE DB data provider: This type of data provider works with all the OLE DB providers, such as SQL OLE DB provider, Oracle OLE DB provider, and Jet OLE DB provider. The OLE DB Data provider classes are present in the System.Data.OleDb namespace. SQL Server data provider: This type of data provider is used to work specifically with Microsoft SQL Server. A SQL Server data provider is recommended for working with a Microsoft SQL Server data source, because a SQL Server data provider allows fast access to a data source without going through an OLE DB or ODBC layer. The SQL Server data provider classes are present in the System.Data.SqlClient namespace.

NIIT

Coordinator Guide Basics of .NET 31

4. What is a dataset? Explain. Ans. A dataset is a cached set of database records. ADO.NET is based on a disconnected data structure, therefore it is not possible for the application to interact with the database for processing each record. Therefore, the data is retrieved and stored in datasets. A dataset is the most common method of accessing data as it implements a disconnected architecture. You can work with the records stored in a dataset as you work with real data; the only difference being that the dataset is independent of data source and you remain disconnected from the data source. ADO.NET supports scalability by working with datasets. Database operations are performed on the dataset instead of on the database. As a result, resources are saved, and the database can meet the increasing demands of users more efficiently. The dataset acts like a virtual database containing tables, rows, and columns. An application works with the database records stored in the dataset. 5. Write a program to show the demonstration of ADO.NET. Ans. The following program demonstrates the use of ADO.NET. Write the following code in the Click event of a button named Delete:
Private Sub Delete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim result As Integer Dim conn As New OleDb.OleDbConnection("Provider=SQLOLEDB;User ID=sa;Password=;Trusted_Connection=yes;Initial Catalog=CallCenter11;data source=localhost") conn.Open() Dim deleteEMP As OleDb.OleDbCommand = New OleDb.OleDbCommand("delete from Employees where EmpID='E003'", conn) result = deleteEMP.ExecuteNonQuery() End Sub

In the code given for the Click event of the Delete button, a connection object conn is created by providing the information about the provider, the data source server, database name that is to be accessed, and the ID and password for connecting to the data source. Then, the connection with the database is opened and a DataCommand object deleteEMP is created from the OleDbCommand class. The DataCommand object deleteEMP is initialized by setting the SQL statement to be executed using the Connection object conn. Then, the command is executed and the number of rows affected by the execution of the command is stored in an integer result.

Solutions to Chapter Eight Questions


1. What is a Web service? Explain its working. Ans. Web service refers to a platform on which you can build distributed applications. A Web service exposes a number of methods that provide functionality that can be used by one or more applications, regardless of the programming languages, operating systems, and hardware platforms used to develop them. In other words, a Web service ensures interoperability. Consider the following figure.

32 Coordinator Guide Basics of .NET

NIIT

Request

Client Application Response

Web Service

Communication Between Client Application and Web Service

The functionality exposed by a Web service can be accessed by applications by using Internet standards, such as Simple Object Access Protocol (SOAP). SOAP is a protocol that uses extensible Markup Language (XML) to describe data and HyperText Transfer Protocol (HTTP) to transmit application data. An application that uses a Web service is called a Web service client. The client sends a request to the Web service. The cloud in the figure refers to the Internet. If the Web service calls some other service to get the answer or response, the Web service can take a while to respond. While it is waiting for the response, the client can perform other operations. 2. How is a Web service different from a Web page? Ans. The differences between a Web service and a Web page are listed in the following table. Web Services No User Interface Interacts with application Works with any type of client Web Page Has a User Interface Interacts with the user Works with web browser client
Web Services Vs. Web Page

3. With a neat diagram, explain the event handling process of Web forms. Ans. Consider a Web form with a button. If a user clicks the button control, an event Click is raised for the button on the client computer. However, the browser does not process the event. Instead, the browser raises a postback event so that the Web server is alerted about the Click event being raised. Next, the event handler written for the Click event is processed on the Web server and the output is sent to the client computer. 4. What is ASP.NET? Ans. ASP.NET is a framework for developing high performance Web applications. It is a compiled, .NET-based environment. You can write applications in any .NET compatible language, including VB.NET, C#, and JScript .NET. Additionally, the entire .NET Framework is available to any ASP.NET application

NIIT

Coordinator Guide Basics of .NET 33

5. What is the use of ASP.NET? Ans. ASP.NET provides a new programming model and infrastructure for more secure, scalable, and stable applications. You can write applications in any .NET compatible language, including VB.NET, C#, and JScript .NET. Developers can easily use the benefits of these technologies, which include the managed CLR environment, type safety, inheritance, and so on. ASP.NET has been designed to work seamlessly with What You See Is What You Get (WYSIWYG) HTML editors and other programming tools, including Microsoft Visual Studio .NET. Not only it makes Web development easier, but it also provides all the benefits that tools offer, including a GUI that developers can use to drop server controls onto a Web page and fully integrated debugging support. 6. Write a program to display Welcome to ASP.NET 8 times in increasing order of their font size by using ASP.NET. Ans. The following program displays Welcome to ASP.NET eight times in increasing order of their font size. In the following code, the Web application name WebApplication9 is application specific:
<%@ Page language="c#" Codebehind="WebForm1.aspx.cs" AutoEventWireup="false" Inherits="WebApplication9.WebForm1" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" > <html> <head> <title>WebForm1</title> <meta name="GENERATOR" Content="Microsoft Visual Studio .NET 7.1"> <meta name="CODE_LANGUAGE" Content="C#"> <meta name=vs_defaultClientScript content="JavaScript"> <meta name=vs_targetSchema content="http://schemas.microsoft.com/intellisense/ie5"> </head> <body MS_POSITIONING="GridLayout"> <form id="Form2" method="post" runat="server"> <%for(int i=0;i<8;i++){%> <font size="<%=i%>">Welcome to ASP.NET ASHISH</font><br/></font> <%}%> </form> </body> </html>

7. What is the role of System.Web? Ans. The System.Web namespace supplies classes and interfaces that enable browser and server communication. This namespace includes the HttpRequest class that provides extensive information about the current HTTP request, the HttpResponse class that manages HTTP output to the client, and the HttpServerUtility class that provides access to server-side utilities and processes. System.Web also includes classes for cookie manipulation, file transfer, exception information, and output cache control. 8. Write a program to demonstrate handling of server control events. Ans. 1. 2. Select StartProgramsMicrosoft Visual Studio .NET 2003Microsoft Visual Studio .NET 2003 to open the Start Page of Visual Studio .NET IDE. Select FileNewProject to open the New Project dialog box.

34 Coordinator Guide Basics of .NET

NIIT

3. 4. 5.

Select Visual C# Projects from the Project Types pane and ASP.NET Web Application from the Templates pane. Click the OK button. Select ViewToolbox from the main menu. The Toolbox window is displayed in the left pane. Using the Web Forms tab of Toolbox, add the following controls to WebForm1.aspx and change the properties of the controls, as shown in the following table. Control Type Text First Name lblfname txtfname Last Name lbllname txtlname User Name lbluname txtuname Password lblpassword txtpassword Confirm Password lblcpassword txtcpassword Address lbladdress txtaddress City lblcity txtcity State lblstate txtstate Postal Code lblpcode txtpcode Country lblcountry ddlcountry Telephone no. lbltelno txttelno E-mail Id lblemail txtemail lblmessage Submit btnsubmit ID

Label TextBox Label TextBox Label TextBox Label TextBox Label TextBox Label TextBox Label TextBox Label TextBox Label TextBox Label DropDownList Label TextBox Label TextBox Label Button

Description of the Controls to be Added in the Web Form

NIIT

Coordinator Guide Basics of .NET 35

6. 7. 8. 9.

The text boxes for Password and Confirm Password fields need to display asterisks (*) when a user enters a value. To enable this, set the TextMode property of these two text boxes to Password in the Properties window. Add three RequiredFieldValidator controls to the WebForm1.aspx form by using the Web Forms tab of the Toolbox. Add one CompareValidator control to the WebForm1.aspx form by using the Web Forms tab of the Toolbox. Double-click the WebForm1.aspx form to open the code-behind file with a .cs extension. In the Load event of the page, enter the following lines of code:
ddlcountry.Items.Add("Bangladesh"); ddlcountry.Items.Add("Bhutan"); ddlcountry.Items.Add("India"); ddlcountry.Items.Add("Nepal"); ddlcountry.Items.Add("Pakistan"); ddlcountry.Items.Add("Sri Lanka"); CompareValidator1.ControlToValidate="txtcpassword"; CompareValidator1.ControlToCompare="txtpassword"; CompareValidator1.Text="The values of Password and Confirm Password fields does not match"; RequiredFieldValidator1.ControlToValidate="txtuname"; RequiredFieldValidator1.Text="Please enter a user name"; RequiredFieldValidator2.ControlToValidate="txtpassword"; RequiredFieldValidator2.Text="Please enter a password"; RequiredFieldValidator3.ControlToValidate="txtcpassword"; RequiredFieldValidator3.Text="Please re-enter the password";

10. In the Click event of btnsubmit, enter the following code:


if(IsValid) { lblmessage.Text="Welcome "+ txtfname.Text +" "+txtlname.Text + ".You have successfully registered."; }

11. Execute the application.

Solutions to Chapter Nine Questions


1. What is .NET Remoting? Ans. Remoting is the process of communication between different processes, regardless of whether they are on the same or different computers. The .NET remoting system is an architecture designed to simplify communication between objects existing in different application domains whether or not on the same computer. It also simplifies communication between different contexts whether or not in the same application domain. 2. How is .NET Remoting different from Web services and DCOM? Ans. The differences between .NET Remoting and Web services are listed as follows: ASP.NET based Web services can only be accessed over HTTP, whereas the .NET Remoting can be used across any protocol. Web services work in a stateless environment where each request results in a new object created to service the request. .NET Remoting supports state management options and can identify multiple calls from the same client. Web services serialize objects through XML contained in the SOAP messages and can thus only handle items that can be fully expressed in XML. .NET Remoting relies on the existence of the metadata within assemblies that contain information about data types. This limited metadata information is passed about an object, when it is passed by reference.

36 Coordinator Guide Basics of .NET

NIIT

Web services support interoperability across platforms and are good for heterogeneous environments. .NET Remoting requires the clients to be by built using .NET, which means a homogeneous environment.

The difference between .NET Remoting and DCOM is listed as follows: DCOM relies on a proprietary binary protocol that not all object models support. It also wants to communicate over a range of ports that are typically blocked by firewalls. However, .NET Remoting supports different transport protocol formats and communication protocols. This allows .NET Remoting to be adaptable to the network environment in which it is being used.

3. Explain remoting architecture. Ans. The remoting architecture consists of the remote component, server, client, and a transportation medium that enables communication between the client and the server. These components are explained below. The remote component is the object that provides services to the client. The server creates and register a channel, which is a transportation medium, to listen at a specified port. The server also registers the remote object. A channel is a transportation medium through which communication between a server and a client takes place. The client requests for the services of a remote object. A client can choose the registered channels on the server to communicate with the remote object. Note: The process by which the interaction takes place between these components is explained in the following answer. 4. With a neat diagram explain the remoting process. Ans. The primary function of remoting is to communicate between server and client by using objects. After the client is configured properly, a new instance of the remote object is created. Proxy objects are used by the remoting system. Proxies are those objects that present themselves as some other objects. The infrastructure of remoting creates proxy objects when a user generates an instance of remote types. To the user, this proxy object will look exactly similar to the remote objects. In this proxy object, the user calls a method and the call is received by the remoting system. The method is then routed to the server and it invokes the server object. After invoking the server object, a value is returned that is sent back to the client proxy. This will provide the results to the user. The communication between server and client is done by using a channel. A channel carries the data stream, makes a package related to a particular protocol, and sends the package to a different computer. In remoting architecture, the process of remoting is designed considering the security factor. The remoting process is illustrated in the following figure.

Remoting System

Remoting System
Proxy

Server Object

Client Object

NIIT

Channel Coordinator Guide Basics of .NET 37 Carries a stream of data, makes a package related to a particular protocol, and sends the package to a different computer.

Remoting Process 5. Explain the steps or phases involved in implementing .NET remoting applications. Ans. The phases involved in implementing .NET remoting applications are: 1. 2. 3. Create a remotable object: A remotable object is an object that inherits from MarshalByRefObject. Create a server to expose the remote object: A server object acts as a listener to accept remote object requests. Create a client to use the remote object: A client object will connect to the server, create an instance of the object using the server, and then execute the remote methods.

6. Write a program to demonstrate .NET remoting. Ans. The steps involved in implementing .NET remoting applications are: 1. Create a remotable object. Add the following code in the code window of a Class Library:
using System; namespace RemoteTest { public class TestLoader : System.MarshalByRefObject { public TestLoader() { System.Console.WriteLine("Hello World"); } public string Test () { string stc="Client"; return stc; } } }

Build the code. 2. Create a server to expose the remote object. Add the following code in the code window of a Console Application:
using using using using using using using System; System.Runtime; System.Runtime.Remoting; System.Runtime.Remoting.Channels; System.Runtime.Remoting.Channels.Tcp; System.IO; RemoteTest;

namespace Server { class ClassServer { static void Main(String[] args) {

38 Coordinator Guide Basics of .NET

NIIT

TcpServerChannel channel = new TcpServerChannel(9932); ChannelServices.RegisterChannel(channel); RemotingConfiguration.RegisterWellKnownServiceType(typeof(TestLoader), "TestLoader", WellKnownObjectMode.SingleCall); System.Console.WriteLine("Hello From Server"); System.Console.ReadLine(); } } }

Set a reference to RemoteTest.dll file and System.Runtime.Remoting. The RemoteTest.dll file will be located in RemoteTest /bin/Debug. Build the server code. 3. Create a client to use the remote object. Add the following code in the code window of a Console Application:
using using using using using System; System.Runtime.Remoting; System.Runtime.Remoting.Channels; System.Runtime.Remoting.Channels.Tcp; RemoteTest;

namespace Client { class ClassClient { static void Main(string[] args) { try { ChannelServices.RegisterChannel(new TcpClientChannel()); TestLoader loader = (TestLoader)Activator.GetObject( typeof(RemoteTest.TestLoader), "tcp://localhost:9932/TestLoader"); string res = loader.Test(); Console.WriteLine("Hello From "+ res); } catch(Exception e) { Console.WriteLine("Unable to get remote reference" + e); } System.Console.ReadLine(); } } }

Set a reference to RemoteTest.dll file and System.Runtime.Remoting. The RemoteTest.dll file will be located in RemoteTest /bin/Debug. Build the client program. Execute the server program followed by the client program.

NIIT

Coordinator Guide Basics of .NET 39

Você também pode gostar