Docstoc

Basics of .Ne

Document Sample
Basics of .Ne Powered By Docstoc
					                                                                                      Basics of .NET [BSIT-61]

Chapter – 1

1. What is .Net Framework?
Ans: .Net is framework developed by Microsoft.
 It comprises with programming methodologies, platform technologies, and code execution environment.
   All these things combined together in a framework, which is used to provide object-oriented development
   platform.
 It is an environment for the developers.

2. What does .Net Framework comprised off?
Ans: .Net Framework comprised of following things: -
i. Programming Methodologies: - On programming methodology side, an interesting thing about .NET is that
   it allows mixed-programming language for the developer.
 The designers of .NET were able to build a system where the programmer can freely mix modules of the
      program between one language and another.
 By designing from the ground level, a specification that is common to all languages that works in .NET
     framework, design a type system that all languages support, and specifically design an intermediate
     language that all languages compile into; before they compile into native code.

ii. Platform Technologies: - Platform technologies, are mainly – ADO .Net, Internet technologies and User
    Interface designing.
 ADO .Net is the technology that is used to access the databases. .Net has improved that kind of
     programming dramatically from an ease-of-use standpoint, through some features.
         The net effect of ADO .Net for the developer has greatly simplified and enhanced capability of
     programming with databases.
 Internet was the certainly one of the keystone of the development of .Net, as we can understand from the
     name. The particular part of the technology, which deals with Internet is called ASP .Net. The idea for
     developing software for the Internet can be tricky. It become more tricky, if we are trying to have
     reasonable amount of programming logic sitting behind a web page.
 Another place where .Net has innovated is in ‗User Interface Designing‘. It was started in the world of
     Visual Basic.
 In C++, we struggle with hacking code to position our buttons and our text boxes, where as the Visual
     basic user were just dragging them on the screen and putting them where they wanted them.
 That‘s the beauty of the tools that Microsoft has built, that work with those languages.
 The Window programs run under .Net, which are designed visually, are called ―WinForms‖.

iii. Code Execution: - The interesting thing about code execution on .NET framework is, the standardized
     common language infrastructure is completely architecture-neutral.
 The whole purpose of making it standard and putting it in the public domain was so that infrastructure
     could be implemented on any platform. The whole idea is that we are neutral in terms of the architecture.
 Another interesting idea in .NET, is the notion of just-in-time compiling. In the .NET platform, all the
     .NET languages get compiled into the Microsoft Intermediate language or simply called as IL. This
     intermediate language gets compiled by just in time compiler, to the native machine code.

3. Write Short Notes on
a. Programming Methodologies: - On programming methodology side, an interesting thing about .Net is that
   it allows mixed-programming language for the developer.
 The designers of .Net were able to build a system where the programmer can freely mix modules of the
                                                        1
                                                                                        Basics of .NET [BSIT-61]
  program between one language and another.
 By designing from the ground level, a specification that is common to all languages that works in .Net
  framework, design a type system that all languages support, and specifically design an intermediate
  language that all languages compile into; before they compile into native code.

b. Platform Technologies: - Platform technologies, are mainly – ADO .Net, Internet technologies and User
   Interface designing.
 ADO .Net is the technology that is used to access the databases. .Net has improved that kind of
    programming dramatically from an ease-of-use standpoint, through some features.
        The net effect of ADO .Net for the developer has greatly simplified and enhanced capability of
   programming with databases.
 Internet was the certainly one of the keystone of the development of .Net, as we can understand from the
    name. The particular part of the technology, which deals with Internet, is called ASP .Net.
        The idea for developing software for the Internet can be tricky. It becomes trickier, if we are trying to
   have reasonable amount of programming logic sitting behind a web page.
 Another place where .Net has innovated is in ‗User Interface Designing‘. It was started in the world of
    Visual Basic.
 In C++, we struggle with hacking code to position our buttons and our text boxes, where as the Visual
    basic user were just dragging them on the screen and putting them where they wanted them.
 That‘s the beauty of the tools that Microsoft has built, that work with those languages.
 The Window programs run under .Net, which are designed visually, are called ―WinForms‖.

c. Code Execution: - The interesting thing about code execution on .NET framework is, the standardized
   common language infrastructure is completely architecture-neutral.
 The whole purpose of making it standard and putting it in the public domain was so that infrastructure
    could be implemented on any platform. The whole idea is that we are neutral in terms of the architecture.
 Another interesting idea in .NET, is the notion of just-in-time compiling. In the .NET platform, all the
   .NET languages get compiled into the Microsoft Intermediate language or simply called as IL. This
    intermediate language gets compiled by just in time compiler, to the native machine code.

4. Which are the platform technologies supported by .Net framework?
Ans: Platform technologies supported by .Net framework are – ADO .Net, Internet technologies and User
Interface designing.
 ADO .Net is the technology that is used to access the databases. .Net has improved that kind of
    programming dramatically from an ease-of-use standpoint, through some features.
         The net effect of ADO .Net for the developer has greatly simplified and enhanced capability of
   programming with databases.
 Internet was the certainly one of the keystone of the development of .Net, as we can understand from the
    name. The particular part of the technology, which deals with Internet, is called ASP .Net.
         The idea for developing software for the Internet can be tricky. It become more tricky, if we are trying
    to have reasonable amount of programming logic sitting behind a web page.
 Another place where .Net has innovated is in ‗User Interface Designing‘. It was started in the world of
    Visual Basic.
 In C++, we struggle with hacking code to position our buttons and our text boxes, where as the Visual
    basic user were just dragging them on the screen and putting them where they wanted them.
 That‘s the beauty of the tools that Microsoft has built, that work with those languages.
 The Window programs run under .Net, which are designed visually, are called ―WinForms‖.
 .NET supports a concept called data binding that lets that happen completely automatically. The data
    source for this grid is this particular dataset, and that is the end of it. If we change the dataset, the grid
                                                            2
                                                                                     Basics of .NET [BSIT-61]
   updates automatically. If we change the grid programmatically, it updates into the dataset, and then we can
   decide whether to commit those changes to the database. It is a very nice and very powerful concept.

5. List out the advantages of .Net Framework?
Ans: The .NET Framework provides number of advantages to the developers, which are mentioned below –
i. Consistent Programming Model: - Every programming language have different approaches for doing a
   task.
   For example, accessing data with a VB application and a VC++ application is totally different. A developer
   has to know both different techniques to do the task.
 The .NET Class Library provides the functionality to all .NET languages resulting in a consistent object
     model regardless of the programming language used by the developer.

ii. Language Independence: - Language Independence means the developer has the independence to code
    one module of an application in one language and other module of same application in other language.
 This language interoperability can help in code reuse and improve the efficiency of the development
     process.

iii. No versioning Problem: - It makes deployment of applications very easy.
 The .NET ensures that all the components the application depends on are available on the computer before
     the application begins to run.

iv. Improved Security: - The .NET Framework provides several mechanisms for protecting resources and
    code from unauthorized users:
a.) ASP.NET Web Application Security provides a way to control access to a web site by comparing
    authenticated permissions with File System permissions for proper authorization.
b.) Code access security uses permissions to control the code accessing protected resources and operations.
c.) Role-based security provides information needed to make decisions about user‘s permissions.

v. Support for Web Services: - With the advent of .NET technology, web services provide many built in
   Base Class library facilities, which open up a whole new world of information for users.
 Web services can provide everything from basic text news information to vital database or application
   information.

vi. Dynamic Web: - Dynamic web content is easier to create with .NET. ASP.NET and Visual Studio.NET
    allow developers to create dynamic web much easier than IIS and ASP technologies.

vii. Visual Studio .NET: -Visual Studio .NET is the Microsoft application and interface for programming in
     .NET. Visual Studio.
 This development environment has extensive set of ready to use controls, good debugging facilities, easy
     and simple programming features and vast set of .NET Base Classes.

6. What is backward compatibility? (Backward compatibility – self-study topic)
Ans: Backward compatibility is the special case of compatibility in which the new server/application has a
    direct ancestral relationship with the old server/application.

 In technology, irrespective of platform, a product is said to be backward compatible when it is able to take
  the place of an older product, by interoperating with other products that were designed for the older
  product.
 .NET is a fresh start which, supports backward compatibility. It is capable of running applications
                                                       3
                                                                                    Basics of .NET [BSIT-61]
   developed in Visual Studio on Visual Studio .Net.
 For Example - Microsoft is well known for its operating system for home PC. From Windows 3.1
  developed in 1992 to today‘s Windows XP, Microsoft has made many advances in its technologies. With
  the development towards new technology it has to maintain backward compatibility with the existing
  technologies.
 Backward compatibility is the strength of the Windows

7. Does .NET platform support backward compatibility? Explain.
Ans: .Net platform support backward compatibility. It is a fresh start. It is capable of running applications
      developed in Visual Studio on Visual Studio .Net.
 The addable controls and VB.Net has good debugging features.
 .NET is a new framework developed with new set of API. C# is a new language designed from scratch
     with .NET and for .NET platform. .NET platform supports object-oriented programming.
 The .NET framework has Visual Studio .Net, which is the up gradation of Visual Studio.
 In Visual Studio Visual Basic (VB) was very well known for its simplicity and large number of controls
    but did not have good debugging feature. Whereas the VC++ had well built debugging feature, but did not
    had the simplicity and vast controls as in VB.
 The Visual Studio.Net has overcome all these facts. Now VC++.Net has easily Introduction addable
   controls and VB.Net has good debugging features.




                                                      4
                                                                                      Basics of .NET [BSIT-61]

Chapter – 2

1. With a neat diagram, explain the .NET Framework architecture.
Ans:




        The .NET Framework is partitioned into modules, each with its own distinct responsibility. The higher
tiers request services only from the lower tiers, so .NET is hierarchal. The modified architectural layout of the
.NET Framework is following:

→ The .NET Framework is a managed environment.
→ The CLR monitors the execution of .NET applications and provides required services. It manages memory,
  handles exceptions, ensures security, and much more. Language interoperability is one goal of .NET.
→ .NET languages share a Common Language Specification (CLS), Common Type System (CTS) and
  Framework Base Class Library (FCL).
→ Web Services, ADO.NET, Windows or console applications and Remoting execute on CLR. In .NET, the
   programming language like C#, VB.NET, or JScript.NET has similar experience except little differences.
→ .NET abstracts lower-level services, while retaining most of their flexibility. Assemblies, Application
   domains and metadata are brought to CLR environment before they are executed. Once they are brought
   to the execution environment, CLR takes the responsibility of managing and executing it.

2. List out the objectives of .NET framework?
Ans: The objectives of .NET framework are as follows –
 To provide an object-oriented programming environment whether object codes 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
                                                       5
                                                                                     Basics of .NET [BSIT-61]
    interpreted environments.
3. How the Windows Programming is different from .NET Programming?
Ans: Windows Programming is different from .NET Programming in following ways –
Windows Programming: - In Windows Programming, the application programs call windows API function
directly.
 The applications run in the windows environment i.e. operating system itself. These types of applications
    are called unmanaged or unsafe applications.

.NET Programming: - In .NET Programming the application programs call .Net Base Class library functions
which will communicate with operating system.
 The applications run in .Net Runtime environment. These types of applications are called as managed or
  safe applications.
 The .Net Base classes are fully object-oriented. It provides all functionalities of traditional windows API
  along with functionalities in new areas like accessing database, Internet connections and web services.

4. Define the following -
Ans:
a. CLR - Common Language Runtime (CLR) is also known as .NET Runtime. The code management is a
fundamental principle of the runtime. The responsibility of runtime is to load the code, run the code and
provide all kinds of services. The services provided by .NET Runtime are as memory management, thread
management, remoting, strict type safety, ensure code security and robustness.

b. Managed Code - Managed code is one, which is designed to run on .Net environment. The code which runs
in windows environment is unmanaged code.

c. Intermediate Language (IL) - This is also called as Microsoft Intermediate Language (MSIL). The
intermediate language is analogous to the byte code of Java. The significant difference is that the byte code in
interpreted while the IL is compiled by JIT compilation to native machine code. The IL code is not the
machine code. The .Net Runtime calls the Just-in-Time (JIT) compiler to get native machine code from IL
code. This feature makes the .NET platform independent.

d. Common Type System (CTS) - This is a standardized agreed set of basic data types. This system provides
a way for language interoperability. Language Interoperability means that a object implemented in one
language can call a object implemented in another language. In more general way you can say that a
application can be developed in two or more languages supported by .Net framework. To make use of language
interoperability feature, the developers have to follow CTS.

e. .NET Base Classes - .NET Base Classes is a library comprising of extensive set of functions for all services
supported by the framework. This vast collection has well written code for almost all tasks on all services of
.Net framework. The services can be windows creation/displaying or form handling, Internet or web services,
database accessing or file handling.

f. Assemblies - An 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, security information
etc.

g. Common Language Specification (CLS) - The set of rules of basic language features has been defined to
enhance and ensure language interoperability is called the Common Language Specification (CLS). The CLS
rules define a subset of the CTS.

                                                       6
                                                                                     Basics of .NET [BSIT-61]

h. Reflection - The process of obtaining information about assemblies and the types defined within them as
metadata at runtime.

i. Just-in-Time (JIT) Compilation - The compilation converts IL into its native machine code. The name
Just-in-Time is because it compiles portion of code as and when required at run time.

j. Manifest - The area of assembly where metadata is stored is called as manifest.

k. Application Domain - A boundary that the common language runtime establishes around objects created
within the same application is by means of Application Domain. Application domain allows different code to
run in the same process space.

l. Garbage Collection - The Garbage Collector frees the application from the responsibility of freeing memory
when no longer required. CLR calls Garbage collector to handle memory efficiently.

5. What are functionalities of CLR? Give the steps involved in managed execution process.
Ans: The basic functionalities of CLR - To enable the runtime to provide services to managed code; language
compilers must emit metadata that describes the types, members, and references in our code.
 Metadata is stored with the compiled code. Every loadable file contains metadata called as portable
   executable (PE).
 The runtime uses metadata to locate and load classes, lay out instances in memory, resolve method
    invocations, generate native code, enforce security, and set run-time context boundaries.
 The runtime 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.
 This cross-language integration or language interoperability is possible because language compilers and
   tools that target the runtime use CTS defined by the runtime, and they follow the runtime‘s rules for
   defining new types, as well as for creating, using, persisting, and binding to types.
 The runtime uses metadata information to ensure that your component or application has the specified
    versions of everything it needs, which makes your code less likely to break due to some dependency.
 Registration information and state data are no longer stored in the registry where they can be difficult to
   establish and maintain. Rather, information about the types and their dependencies is stored with the code
   as Metadata.

The managed execution process includes the following steps:
 Choosing an appropriate language compiler.
 Compiling code to Microsoft intermediate language (MSIL or simply IL). Compiling translates source
  code into IL and generates the required metadata.
 Compiling IL to native code. At execution time, a just-in-time (JIT) compiler translates the IL into native
  machine code. During this compilation, 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.
 Executing code. The CLR provides the environment that enables execution to take place as well as a
  variety of services that can be used during execution.

                                                       7
                                                                                     Basics of .NET [BSIT-61]

6. What are assemblies? What are static and dynamic assemblies?
Ans: An 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, security information etc.
 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 PE files.
 Dynamic assemblies are one, which run directly from memory and are not saved to disk before execution.
   They can be saved disk after they have executed.

7. How the .NET execution environment with application domain differs from traditional way of execution?
Ans: .NET execution environment differs from traditional way of execution in following ways: -
→ If we are writing application in C#, we need a C# compiler. If we are writing in Visual basic, we need a
   Visual Basic compiler, even for C++, we need a C++ compiler. But in .NET execution environment, the
   approach taken here is that all of those compilers compile into this same intermediate language.
→ The intermediate language is then compiled by Just-In-Time compiler to native machine code.
→ So it really doesn‘t matter that what language we write our code in, it all compiles into same Intermediate
   Language.
→ Just-In-Time compiler only needs to understand one language, not all of them. It only needs to understand
   the Intermediate Language.
→ It compiles it into native code and naturally, that does not take place until run time.
→ This process is completely automatic and independent of how the program is coded.

8. What is the function of CTS? Explain the classification of types in CTS with a diagram.
Ans: The Common Type System (CTS) defines how types are declared, used, and managed in the runtime.
It is an important for Language Interoperability. It 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.

Classifications of types in CTS are as follows: -
1. Value types 2. Reference types




                                                       8
                                                                                         Basics of .NET [BSIT-61]


 Value types directly stores 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 types.

9.Write a note on metadata.
Ans: Metadata: - In earlier days, it was not possible that a software component/module (.exe or .dll) written in
one language could get used in another module, which is written in another language. The solution came in the
form of COM components.
 The .NET Framework makes language interoperation even easier by allowing compilers to put additional
    information into all compiled modules and assemblies. This information is called Metadata.
 Metadata is binary information describing the program. When we compile our code into a PE file,
   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, which 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 codes
   classes, members, inheritance, and so on.
 Metadata allows .NET languages to describe themselves in a language-neutral manner.
 It gives required information to CLR to perform much of its functionalities.
 The presence of metadata makes the assembly Self-describing file.
 The CLR modules or components or other assemblies, which want to communicate with each other uses,
   these information stored in metadata to perform their tasks.
 It stores information like -
    a. Description of the assembly‘s operation.
    b. Assembly Identity (name, version, culture, public key).
    c. Exported types
    d. Other dependent assemblies
    e. Security permissions
    f. Description of types
    g. Members like methods, fields, properties, events, nested types, etc.
    h. Attributes

10. „It is told that if we learn any one .NET language, then working with other .NET languages will be
easy‟. How? Explain with the appropriate example.
Ans:




                                                         9
                                                                                     Basics of .NET [BSIT-61]


Chapter – 3

1. List out the important features of C#?
Ans: Important features of C# are:
 C# is an elegant, simple, type-safe, object-oriented language.
 C# has the capability to build durable system-level components due to 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 due to following features:
 Full interoperability with COM and .NET Framework services, through tight .NET Library Base classes.
 XML support for web-based component interaction.
 Versionability.

2. Write a program in C# to display „Welcome to the world of C Sharp‟. Explain the program.
Ans:

// A ―Welcome to the world of C Sharp‖ program in C#
using System;
class Welcome
{
public static void Main (string[] ar)
{
Console.WriteLine (―Welcome to the world of C Sharp‖);
}
}

Description of the above written program –
Comments: - Comments are used for proper documentation of the code. The compiler does not consider the
comments as the part of code. Compiler ignores the comments during the time of compilation. Comments
make the program more understandable. C# adopts the C++ style of comments.
The first line is a comment:
        // A ―Welcome to the world of C Sharp‖ program in C#

The characters // convert the rest of the line to a comment. You can also comment a block of text by
placing it between the characters /* and */, for example:

The Main Method: - The C# program must contain a Main method, in which control starts and ends. You can
create objects and execute other methods within this Main method. Note that the alphabet ‗M‘ in Main is
uppercase, where as in C and C++ it is lowercase. The Main method is a static method and resides inside a
class. In the ―Welcome to the world of C Sharp‖ example, it resides inside the ‗Welcome‘ class.

Input and Output: - In the above Welcome program there is only one output statement, no input statements.
The statement: System.Console.WriteLine(―Welcome to the world of C Sharp‖); uses the WriteLine method,
of the Console class which resides in the .NET run-time library. This method displays its string parameter on

                                                      10
                                                                                   Basics of .NET [BSIT-61]
the standard output. There are many other Console methods are used for different input and output operations.
If you include the following using statement at the beginning of the program:

Compilation and Execution: - The compile and execution commands given here are for command line
compiler. We are not going into the Visual C# IDE. Follow the below steps to compile and execute a program.
 By using any text editor create a source file and save it as Welcome.cs. The C# source code files should
  have .cs extension.
 To compile the program use the command given below. If there are no compilation errors Welcome.exe is
  created. csc Welcome.cs
 To run the program, enter the command - Welcome
 It will display ―Welcome to the world of C Sharp‖ on the console.

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 skeleton of a C# program that contains all of these elements.
// A skeleton of a C# program
using System;
namespace Namespace1
{
class Class1
{}
struct Struct1
{}
interface Interface1
{}
delegate int Delegate1();
enum Enum1
{}
namespace Namespace2
{}
class Class2
{
public static void Main(string[] args)
{}}}

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

                                                       11
                                                                                       Basics of .NET [BSIT-61]
{}
}
Here the ABC.Class1 and XYZ.Class1 are two different types, even if the class name is same. In the following
code example shows the nested classes and namespaces. Carefully examine the fully qualified names given as
comments.
namespace ABC // ABC
{
class Class1 // ABC.Class1
{
class Class2 // ABC.Class1.Class2
{}
}
namespace XYZ // ABC.XYZ
{
class Class2 // ABC.XYZ.Class2
{}
}
}
From the above code example:
 The namespace ABC is a member of the global namespace. Its fully qualified name is ABC.
 The namespace XYZ is a member of ABC. Its fully qualified name is ABC.XYZ.
 The class Class1 is a member of the ABC. Its fully qualified name is ABC.Class1.
 The class name Class2 is used twice in this code. However, the fully qualified names are unique. The first
   one is declared inside Class1; thus its fully qualified name is: ABC.Class1.Class2.
 The second is declared inside a namespace XYZ; thus, its fully qualified name is ABC.XYZ.Class2.
 Using the preceding code segment, you can add a new class member Class3 to the namespace ABC.XYZ
   as follows:
        namespace ABC.XYZ
        {
        class Class3 // ABC.XYZ.Class3
        {}
        }

5. List out the difference between C# and C++.
Ans: Following are the differences between C# and C++ -
 C# is purely object-oriented language, whereas C++ support object-oriented programming.
 Arrays: The syntax of declaring C# arrays is different from that of C++ arrays. The tokens “[]” appear
   following the array type in C#.
 The bool type in C#: There is no conversion between the bool type and int.
 The long type: In C#, the long data type is 64 bits, while in C++, it is 32 bits.
 The struct type: In C#, classes and structs are semantically different. A struct is a value type, while a class
   is a reference type.
 The switch statement: Unlike the C++ switch statement, C# does not support fall through from one case
    label to another.
 The delegate type: Delegates are roughly similar to function pointers in C++, but they are typesafe and
    secure.
 Preprocessor directives are used for conditional compilation. No header files are used in C#.
 C# operators: C# supports additional operators such as is and type of. It also introduces different
   functionality of some logical operators.
                                                       12
                                                                                       Basics of .NET [BSIT-61]
 The Main method is declared differently from the main function in C++. The usage of the command-line
  arguments are also different.
 Method parameters: 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 unsafe mode.
 Overloading operators is performed differently in C#.
 Strings: C# strings are different from C++ strings.
 The foreach keyword allows you to iterate through arrays and collections.
 No global methods or variables in C#: Methods and variables must be contained within a type declaration.
 No header files or #include directives in C#: The using directive is used to reference types in other
  namespaces without fully qualifying the type names.
 Destructors: In C#, you don’t have control over when a destructor is called because destructors are called
  automatically by the garbage collector.
 Constructors: Unlike C++, if you don’t provide a class constructor in C#, a default constructor is
  automatically generated for you. The default constructor initializes all the fields to their default values.
 C# does not support bit fields.




                                                      13
                                                                                         Basics of .NET [BSIT-61]


Chapter – 4

1. Which are two different categories of type in C#?
Ans: There are two different categories of type in C# are – [i.] Value type [ii.] Reference type.
    i. Value types: - They directly contain data.
       → The variable have their own copy of the data.
       → A variable of a type always stores a data value of that type.
       → Assignment to a value type variable creates a copy of the value being assigned.
       → Some examples of the Value type are – char, int, float.

   ii. Reference types: - The Reference type do not contain data but they contain a reference to the variables,
       which are stored in memory.
        → Using more than one variables, we can use reference types to refer to a memory location.
        → This means that if the value in the memory location is modified by one of the variables, the other
           variables automatically reflect the changed value.
        → In reference type, it is possible for a data to reference an object of other derived type.
        → Assignment to a reference type variable, copies the address of object.
        → Some examples of Reference type are – class, string, interface, array, delegate type.

2. What are variables? How many categories of variables are there in C#? Define each.
Ans: A variable is a location in the memory that has a name and contains a value.
       → The Value could be an integer, decimal, character, string.
       → A variable is associated with a data type that defines the type of data, which can be stored in a
          variable.
       → Variables can be initially assigned or initially not assigned.
    In C# variables are categorized in 7 categories which are mentioned below –

  i. 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 are created.

   ii. Instance variables: - A variables declared without the static modifiers are instance variables.

   iii. 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
        exist until there are no references to that array instance.

   iv. 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 exists until the function returns.

  v. 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.

  vi. Output parameters: - A parameter declared with an out modifier is an output parameter. A reference
      parameter does not create a new instance, it points to the same storage location of the parameter passed
      as an argument. But output parameter must be definitely assigned before the function returns.

  vii. Local variables: - A local variable is declared and exits within a block, for-statement, switch-
                                                        14
                                                                                         Basics of .NET [BSIT-61]
      statement, using statement. A local variable is not automatically initialized, thus has no default
       value.
3. What is the importance of automatic memory management? Explain with example?
Ans: In earlier days, developers need to manage the allocation and de-allocation of blocks of memory, which
     is known as Manual memory management. Manual memory management can be both time-consuming
     and difficult.
→ But in .NET Framework, CLR provides a run-time environment, which manages the execution of code and
   provides essential services like Automatic memory management.
→ Automatic memory management eliminates memory leaks as well as some other common programming
   errors.
→ In C#, automatic memory management is provided so that developers are freed from this burdensome task.
→ Automatic memory management increases code quality and enhances developer productivity without
   negative impact on either expressiveness or performance.

4. Write a note on expression and operators in C#.
Ans: Expression: - 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.

Operators: - Application use operators to process the data entered by a user.
→ Operators like + and – are used to process variables and return a value.
→ An operator is a set of one or more characters that is used for computations or comparisons.
→ Operator can transform one or more data values, called operands, into a new data value.
→ Some examples of Operators are Arithmetic, Arithmetic Assignment, Unary, Comparison, Logical
  operators.

5. What are empty statement and labeled statements? Why are they used?
Ans: Empty statement: - An empty statement (?) simply transfers control to the end point of the statement.
→ It is used when there are no operations to perform, but require an statement.
→ An empty statement can be used when writing a while statement with a null body and can also be used to
   declare a label just before the closing ―}‖ of a block.

Labeled statement: - A labeled statement is prefixed by a label.
→ 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 same name we get compile time error.
→ A label can be referenced from goto statements within the scope of the label.
→ Labels and other identifiers can have same name.

6. What is an iterative statement? Explain foreach statement with example?
Ans: Iterative statements repeatedly execute a block of statements.
→ The number of iterations depends on the condition represented by Boolean expression.
→ The block of code will be iterated until the condition is true.

Foreach statement: – A foreach statement lets us iterate over the elements in arrays and collections.
→ The elements of single-dimensional arrays are traversed in increasing order of index, starting with index 0
  to Length-1.
→ The elements of multi-dimensional arrays elements are traversed such that the indices of the rightmost
                                                     15
                                                                                       Basics of .NET [BSIT-61]
   dimension are incremented first, then the next left dimension, and so on to the left.

→ Following example uses a foreach statement to iterate over the elements of an array –

       using System;
       class ForEachExample
       {
               static void Main ()
               {
               int[] arr =new int[] {1,2,3,4};
               foreach (int i in arr)
               Console.WriteLine (―Value is {0}‖, arr);
               }
       }

7. Which are different jump statements supported by C#?
Ans: Different jump statements supported by C# are: -
       Break Statements: - When there is a need to exit a loop before the loop condition is re-evaluated after
                            iteration. As with the while loop, we can use break statement to exit from the loop.
e.g.: - using System;
        class Ex_Break
        {
               static void Main (string[] ar)
               {
               int i=0;
               while (true)
                        {
                        if (i==ar.Length)
                        break;
                        Console.WriteLine (ar[i++]);
                        }
               }
        }

      Continue Statements: - The continue statement is used to skip all the subsequent instructions and take
                                  the control back to the loop.
e.g.: - using System;
        class Ex_Continue
        {
               static void Main (string[] ar)
               {
               int i=0;
               while (true)
                        {
                        Console.WriteLine (ar[i++]);
                        if (i < ar.Length)
                        continue;
                        break;
                        }
               }
                                                           16
                                                                                        Basics of .NET [BSIT-61]
       }

       Return Statement: - Methods can either return a type or not. A method that does not return a type
                                must give its return type as ‗void‘. A method that does return a type must name
                                the type returned. A method will stop executing and return a value when it
                                reaches a ‗return‘ statement at any point in its execution. The type returned is
                                given at the end of such a return statement; its type must correspond with the
                                type specified in the method declaration. For example, the following piece of
                               code illustrates this point.
       e.g.: - using System;
       class Ex_Return
       {
               static int add (int a, int b)
               {
               return a+b;
               }
                        static void Main ()
                        {
                        Console.WriteLine (add(1,2));
                        return;
                        }
       }

       Throw Statement: - We can throw an object if the object is either directly or indirectly derived from
                        System.Exception. We can use throw statement in the catch block to throw the
                        present object and we can also throw a new exception of a different type. A throw
                        without any expression can only be used in the catch block. Such a throw reverts
                        the exception that is currently being handled.

        Try Statement: - The Try block guards statements that may throw an exception. The block governs
                           statements that are enclosed within it and defines the scope of the exception handlers
                           associated with it. If an exception occurs within the try block, an appropriate
                           exception handler that is associated with the try block handles the exception.
e.g.: - using System:
        class Ex_Throw_Try
        {
               static int F (int a, int b)
               {
               if (b==0)
                        throw new exception (―Divided by Zero‖);
               return a/b;
               }
                    static void Main ()
                   {
                        try
                           {
                             Console.WriteLine (F(5,0));
                            }
                        catch (Exception e)
                            {
                                                           17
                                                                                   Basics of .NET [BSIT-61]
                             Console.WriteLine (―Error‖);
                             }
                    }
        }

8. What are checked and unchecked statements? Give Example.
Ans: Checked Statement: - The Checked statement causes all expressions in the checked block to be
                              evaluated in a checked context.
      Unchecked Statement: - The Unchecked statement causes all expressions in the unchecked block to be
                               evaluated in an unchecked context.
e.g.: - using System;
        class Ex_Check_Uncheck
        {
               static void Main()
               {
                int x = Int32.MaxValue;
                Console.WriteLine(x + 1); // Overflow
                       checked
                       {
                       Console.WriteLine(x + 1); // Exception
                       }
                       unchecked
                       {
                       Console.WriteLine(x + 1); // Overflow
                       }
                }

        }

9. Give an example lock and using statements.
Ans: Lock Statements: - The lock statement obtains the mutual exclusion lock for a given object, executes
                        statements, and then releases the lock. The example is shown below –

e.g.: - static void Main()
         {
         A a = ...;
         lock(a)
         {
         a.P = a.P + 1;
         }
         }

      Using Statements: - The using statement obtains one or more resources, executes statements, and then
                           releases of the resource.
e.g.: - static void Main()
        {
        using (Resource r = new Resource())
       {
        r.Func();
        }
                                                        18
                                                                                      Basics of .NET [BSIT-61]
      }

10. How are structures different from classes in C#?
Ans: Following are the differences between Structures and Classes in C#: -
→ Structures are value types and they get stored in a stack.
→ Structures do not support inheritance.
→ Structures cannot have default constructor.

11. What are interfaces? Give an example.
Ans: Interfaces: - Interface is a syntactical contract that all derived classes should follow. Interface keyword
                   declares a reference type that has abstract members. Interface can contain methods,
                   properties, indexers and events as members. They can contain constants, fields, constructors
                   and destructors or any type of static member. All the members of an interface are public by
                   definition.
e.g.: - interface Example
        {
        String this[int index]
                {
                get; set;
                }
        event EventHandler E;
        void Func (int value);
        string P
                {
                get; set;
                }
        }
        public delegate void EventHandler (object sender, EventArgs);

12. What is delegate? What is the use of it? Give example?
Ans: A Delegate is a reference type variable, which holds the reference to a method.
→ This reference can be changed at runtime, as desired.
→ Delegates in C# allow us to dynamically change the reference to the methods in a class.
→ Delegates are primarily used in C# programming for implementing events and the call-back methods.
→ There are three steps in defining and using delegates: declaration, instantiation and invocation.

e.g.: - First declare a delegate by following syntax –
        delegate void SimpleDelegate(); // Delegate that takes no arguments and returns no result
        using System;
        class Test
        {
                static void F()
                {
                        Console.WriteLine(―Test.F‖);
                }
                static void Main ()
                {
                SimpleDelegate d=new SimpleDelegate(F);
                d();
                }
                                                       19
                                                                                    Basics of .NET [BSIT-61]
       }


13. Write a program to demonstrate the usage of enums in C#?
Ans: using System;
       Namespace EnumYear
       {
             class DisplayYear
            {
             enum year{Jan,Feb,March,April,May,June,July,Aug,Sept,Oct,Nov,Dec};
                static void Main(string[] ar)
                {
                 int First_Month=(int)year.Jan;
                 int Last_Month=(int)year.Dec;
                Console.WriteLine(―Jan ={0}‖, First_Month);
                Console.WriteLine(―Dec ={0}‖,Last_Month);
                }
            }
       }

14. Write a note on namespaces in C#.
Ans: Namespaces: - Namespace provides a way to group classes, by providing an extra level of naming
     beyond the class name.
→ C# programs are organized using namespaces.
→ Namespaces are used both as an ―internal‖ organization system for a program, and as an ―external‖
   organization system.
→ Class actually contain data and namespaces are used to logically arrange classes.
→ Namespaces can also contain many other Namespaces and classes.
→ C# programs are organized using namespaces.
→ Namespaces are implicitly public and the declaration of a namespace does not include any access
   modifiers.
→ Namespaces can be nested. Many namespaces in the base class library are nested.
→ A namespace declaration consist of the keyword namespace, followed by a namespace name and body:

       namespace NamespaceName
       {
         ….// namespace body
       }

15. What is the use of attribute in C# program?
Ans: Attributes are used for adding metadata, such as compiler instructions and other information such as
     comments, description, methods, and classes to a program.
→ Programs specify this additional declarative information by defining and using Attributes.
→ Attributes are applied to different elements of the code.
→ These elements includes assemblies, modules, structs, enums, constructors, properties, fields and delegates.
→ Information about attribute is stored with the metadata of the elements they are associated with.




                                                      20
                                                                                         Basics of .NET [BSIT-61]


Chapter – 5

1. Write a note on classes in C#?
Ans: Class is the collection of Member data and Member functions.
→ Class declarations are reference type.
→ 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 program code that is able to
   access the member.

2. What are constant members? Give an example.
Ans: A constant member is a class member that represents a constant value. Constant members are initialized
       at the time of their declaration.
→ Constants are considered static members.
→ Constant member declaration does not require the static modifier.
e.g.: - class Constant
         {
         public const int A=1;
         public const int B=A+1;
         }

3. Give an example of field member.
Ans: A field is a member that represents a variable associated with an object or class.
→ The fields are initialized at some point before they are used, but after this initialization they can be
   changed.
e.g.: - 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 Color Red = new Color(0xFF, 0, 0);
        public static Color Blue = new Color(0, 0xFF, 0);
        public static Color Green = new Color(0, 0, 0xFF);
        public static Color White = new Color(0xFF, 0xFF, 0xFF);
        }




                                                        21
                                                                                        Basics of .NET [BSIT-61]


4. With appropriate examples explain parameter passing in C#.
Ans: In C#, parameter can be passed either by value or by reference. Passing parameters by reference allows
function members (methods, properties, indexers, operators and constructors) to change the value of the
parameters and have that change persist. To pass a parameter by reference, use the ref or out keyword.

e.g. : - In the following example, it is not the value of myInt that is passed; rather, a reference to myInt is
         passed. The parameter x is not an int; it is a reference to an int. Therefore, when x is squared inside the
         method, what actually gets squared is what x refers to : myInt.
       using System;
       class ParameterPassingValByRef
       {
              static void SquareIt(ref int x)
              // The parameter x is passed by reference.
              // Changes to x will affect the original value of myInt.
              {
                x *= x;
                Console.WriteLine("The value inside the method: {0}", x);
              }
           public static void Main()
           {
             int myInt = 5;
             Console.WriteLine("The value before calling the method: {0}",myInt);
             SquareIt(ref myInt);   // Passing myInt by reference.
             Console.WriteLine("The value after calling the method: {0}",myInt);
           }
       }
Output : - The value before calling the method: 5
           The value inside the method        : 25
           The value after calling the method : 25

5. What is the use of property member in a class?
Ans: Property is a member that provides access to a characteristic of an object or a class.
→ Properties have accessors that is used to specify the block of statement to be executed when their values
  are read or written.
→ Properties that can both read and written, such as caption, include both get and set accessors.
→ The declaration of properties is relatively straightforward , but the real value of properties is seen when
  they are used.

6. What are events? Give an example to demonstrate its usage.
Ans: An event is an action or occurrence, such as clicks, key presses, mouse movements or system generated
       notifications.
→ An event is a member that enables an object or class to provide notifications.
→ A class defines an event by providing an event declaration and an optional set of event accessors.
→ Events are an affective mean of inter-process communication.
→ Events are message sent by the object to indicate the occurrence of the event.
→ Applications can respond to events when they occur.
e.g.: - using System;
         public class Form1
         {
                 public Form1()
                                                       22
                                                                                     Basics of .NET [BSIT-61]
               {
               Button1.Click += new EventHandler(Button1_Click);
               }
               Button Button1=new Button();
               void Button1_Click (object sender, EventArgs e)
               {
               Console.WriteLine(―Button1 was Clicked‖);
               }
               public void disconnect()
               {
               Button1.Click -= new EventHandler(Button1_Click);
               }
       }

7. With an example explain indexers.
Ans: An indexer enables an object to be indexed in the same way as an array.
→ Indexers enable array-like access.
→ Indexers declarations are similar to property declarations, with the main differences being that indexers are
   nameless and that indexers include indexing parameters.
e.g.: - 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;
               }
               }
                                                    23
                                                                                      Basics of .NET [BSIT-61]
       }

       class Test
       {
       static void Main()
               {
               Stack s = new Stack();
               s.Push(1);
               s.Push(2);
               s.Push(3);
               s[0] = 33;
               s[1] = 22;
                s[2] = 11;
               }
       }

8. Explain each with an example
Ans:
a. Instance constructors: - An Instance constructor is called whenever an instance of a class is created.
→ These constructors are used to initialize data members of the class.
e.g.: - using System;
         namespace calc
         {
               class Calculator
               {
               static int num1,num2,total;
                        Calculator()
                        {
                        num1=10;
                        num2=20;
                        }
                        public void AddNumber()
                        {
                        total=num1+num2;
                        }
                        public void DisplayNumber()
                        {
                        Console.WriteLine("The total is {0}",total);
                        }
               public static void Main(string[] ar )
               {
               Calculator c=new Calculator();
               c.AddNumber();
               c.DisplayNumber();
               }
            }
       }

b. Destructor: - A Destructor has the same name as its class but is prefixed with a ~ , which is the symbol of
                 tilde. Destructors cannot be inherited or overloaded.
                                                        24
                                                                                     Basics of .NET [BSIT-61]
e.g.: - using System;
         namespace calc
         {
                class Calculator
                {
                static int num1,num2,total;
                public void AddNumber()
                {
                total=num1+num2;
                Console.WriteLine(―The Total is {0}‖,total);
                }
                Calculator()
                {
                num1=10; num2=20; total=0;
                Console.WriteLine(―Constructor Invoked‖);
                }
                ~Calculator()
                {
                Console.WriteLine(―Destructor Invoked‖);
                }
                public static void Main(string[] ar )
                {
                Calculator c=new Calculator();
                c.AddNumber();
               }
           }
       }
c. Static constructor: - Static constructors are used to initialize the static variables of a class.
→ These variables are created using the static keyword and they store values that can be shared by all the
    instances of a class.
→ The constructors will be invoked only once during the execution of a program.
→ Static Constructors have an implicit private access.
e.g.: - public class Stat_Construct
         {
           static int num1; int num2;
                static Stat_Construct
                {
                num1=10;        //OK. Since num1 is static variable in this class.
                num2=23;        //ERROR. Since num2 is non-static variable in this class.
                }
         }

9. How does C# supports inheritance?
Ans: In C#, Inheritance is the property by which the objects of a derived class possess copies of the data
     members and the member functions of the base class.
→ A class that inherits or derives attributes from another class is called the derived class.
→ The class from which attributes are derived is called the base class.
→ In C#, Inheritance enables the easy maintenance of code. Any change made to the base class automatically
   changes the behavior of its subclasses.

                                                      25
                                                                           Basics of .NET [BSIT-61]


→ The syntax used in C# for creating derived classes is as follows:
      <access_specifier> class <base_class>
      {
      …….
      }
      class <derived_class> : <base_class>
      {
      …….
      }

10. What is method overloading? Give an example.
Ans: Method Overloading is the most common way of implementing polymorphism. We can implement
       Method overloading by defining two or more functions in a class sharing the same name.
e.g.: - using System;
        namespace CalculateMax
        {
               class CalculateMax
               {
               public int Max(int num1, int num2)
               {
                        if (num1>num2)
                        {
                        return num1;
                        }
                        else
                        {
                        return num2;
                        }
               }
               public float Max(float num1, float num2)
               {
                        if(num1>num2)
                        {
                        return num1;
                        }
                        else
                        {
                        return num2;
                        }
               }
        }
        class MaxCalc
        {
               static int Main()
               {
               CalculateMax cal=new CalculateMax();
               Console.WriteLine(―{0}‖,cal.Max(5.4F, 8.6F));
               Console.WriteLine(―{0}‖,cal.Max(19,12));
                                                     26
                                                                                    Basics of .NET [BSIT-61]
              Console.ReadLine();
              return 0; }}
11. What is operator overloading? Give an example.
Ans: Operator overloading allows user-defined types such as structures and classes, to use overloaded
     operators for easy manipulation of their objects. Operator overloading can be achieved by defining the
     static member functions using the operator keyword.
→ The following code is an example showing the usage of operator(+)
       Hour h1;
       Hour h2;
       Hour h3;
       H3=H1+H2;




                                                      27
                                                                                          Basics of .NET [BSIT-61]
Chapter – 6

1. What is a preprocessor? What does the #if, #else, #elif, #endif, #define, #undef, #warning, #error, and
   #line directives do? Give examples for each.
Ans: Preprocessor : - While the compiler does not have a separate preprocessor, the directives are processed
as if there was a preprocessor. These directives are used during conditional compilation. Unlike C and C++
directives, we cannot use these directives to create macros. A preprocessor directive must be the only
instruction on a line.

#if : - #if, begins a conditional directive for testing a symbol, to see if they evaluate to true. If they do evaluate
to true, the compiler evaluates all the code between the #if and the next corresponding directive. The following
operators can also be used to evaluate multiple symbols, like - == (equality symbol), != (inequality symbol)
&& (and symbol), || (or symbol).

e.g. : - #define DEBUG
       #define VC_V7
       using System;
       public class MyClass
       {
            public static void Main()
            {
            #if (DEBUG && !VC_V7)
              Console.WriteLine("DEBUG           is defined");
            #elif (!DEBUG && VC_V7)
              Console.WriteLine("VC_V7           is defined");
            #elif (DEBUG && VC_V7)
              Console.WriteLine("DEBUG           and VC_V7 are defined");
            #else
              Console.WriteLine("DEBUG           and VC_V7 are not defined");
            #endif
          }
       }

#else : - #else lets us create a compound conditional directive, such that, if none of the expression in the
preceding #if or #elif directive did not evaluate to true, the compiler will evaluate all code between #else and
the subsequent #endif.

e.g. : - #define DEBUG
       #define VC_V7
       using System;
       public class MyClass
       {
           public static void Main()
           {
             #if (DEBUG && !VC_V7)
                Console.WriteLine("DEBUG is defined");
             #else
                Console.WriteLine("DEBUG and VC_V7 are not defined");
             #endif
           }
       }

#elif : - #elif let us create a compound conditional directive. The #elif expression will be evaluated if neither
the preceding #if nor any preceding(optional) #elif directive expressions evaluatevto true. If a #elif expression
evaluates to true, the compiler evaluates all the code between the #elif and the next directive.
                                                         28
                                                                                      Basics of .NET [BSIT-61]
e.g. : - #define DEBUG
          #define VC_V7
          using System;
          public class MyClass
          {
              public static void Main()
              {
              #if (DEBUG && !VC_V7)
                    Console.WriteLine("DEBUG is defined");
              #else
                    Console.WriteLine("DEBUG and VC_V7 are not defined");
              #endif
              }
          }

#endif : - #endif specifies the end of a conditional directive, which began with the #if directive. A conditional
directive, beginning with a #if directive, must explicitly be terminated with a #endif directive.
e.g. : - #define DEBUG
          #define VC_V7
          using System;
          public class MyClass
          {
                public static void Main()
                {
                    #if (DEBUG && !VC_V7)
                          Console.WriteLine("DEBUG is defined");
                    #else
                          Console.WriteLine("DEBUG and VC_V7 are not defined");
                    #endif
                }
          }

#define : - #define lets you define a symbol, such that, by using the symbol as the expression passed to the #if
directive, the expression will evaluate to true.

e.g. : - #define DEBUG
          #define VC_V7
          using System;
          public class MyClass
          {
              public static void Main()
            {
            #if (DEBUG && !VC_V7)
              Console.WriteLine("DEBUG is defined");
            #else
              Console.WriteLine("DEBUG and VC_V7 are not defined");
            #endif
            }
      }

#undef : - #undef, undefines a symbol by using the symbol as the expression in a #if directive, the expression
will evaluate to false. The #undef directive must appear in the file before we use any statements that are not
directives.

e.g. : - #undef DEBUG
          using System;


                                                       29
                                                                                     Basics of .NET [BSIT-61]
       public class MyClass
       {
           public static void Main()
           {
             #if DEBUG
                    Console.WriteLine("DEBUG is defined");
             #else
                    Console.WriteLine("DEBUG is not defined");
             #endif
           }
       }

#warning : - #warning, generates a level one warning from a specific location in our code. A common use of
#warning is in a conditional directive.

e.g. : - #define DEBUG
       public class MyClass
       {
           public static void Main()
           {
             #if DEBUG
             #warning DEBUG is defined
             #endif
           }
       }

#error : - #error, generates an error from a specific location in your code. A common use of #error is in a
conditional directive.

e.g. : - #define DEBUG
       public class MyClass
       {
             public static void Main()
             {
             #if DEBUG
             #error DEBUG is defined
             #endif
             }
       }

#line : - #line, modifies the compiler‘s line number and the file name output for errors and warnings. A source
code file may have any number of #line directives.

e.g. : - public class MyClass2
       {
               public static void Main()
               {
               #line 200
                 int i; // error or warning will be: “CS0168 on line 200”
               #line 8
                 char c; // error or warning will be: “CS0168 on line 8”
               }
       }

2. What is an exception? How exceptions are handled in C#?
Ans: An exception is an erroneous situation or unexpected behavior that encountered during program
     execution. Exceptional situations arise when an operation cannot be completed naturally.
                                                      30
                                                                                       Basics of .NET [BSIT-61]
→ Exception Handling in C# provides a structured way of handling both system level and application level
   error conditions.
→ In C#, all exceptions must be represented by an instance of a class type derived from System.Exception.
→ In C#, there are try, catch and finally blocks are present there to handle exceptions. A finally block can be
   used to write termination code which executes in both normal execution and exceptional conditions.
→ In C#, system-level exceptions such as overflow, divide-by-zero and null de-references have well defined
   exception.
e.g.: - // This program shows an exception if a variable is divided by zero: -

       using System;
       namespace System_Exception
       {
              class AddNum
              {
                     public static void add_numbers(int num1,int num2)
                     {
                             try
                             {
                             int res=num1/num2;
                             Console.WriteLine(res);
                             }
                             catch(DivideByZeroException e)
                             {
                             Console.WriteLine(―Exception Occurred{0}‖,e);
                             }
                             Console.WriteLine(―After Handling the Exception‖);
                     }
                     public static void Main()
                     {
                     AddNum.add_numbers(10,0);
                     Console.ReadLine();
                     }
              }
       }

3. What is an unsafe code? Explain.
Ans: Unsafe Code : - Unsafe code are the codes, where 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, writing unsafe code is much like writing C code within a C# program.
→ Unsafe code is in fact a ―safe‖ feature from the perspective of both developers and users.
→ Unsafe code must be clearly marked with the modifier unsafe, so developers can't possibly use unsafe
   features accidentally, and the execution engine works to ensure that unsafe code cannot be executed in an
   untrusted environment.

4. What is threading? List out the advantages and disadvantages of multiple threads.
Ans: Threading is defined as the execution path of a program. Threads are used to run applications that
     perform large and complex computations. Threads are the basic unit to which an operating system
     allocates processor time, and more than one thread can run inside that process.
    Advantages of Multiple Threads: -
       i. Can communicate over a network, to a Web server and to a database.
                                                      31
                                                                                      Basics of .NET [BSIT-61]

       ii. Perform operations that take a large amount of time.

       iii. Distinguish tasks of varying priority. For example, a high-priority thread manages time-critical
            tasks, and a low-priority thread performs other tasks.

       iv. Allow the user interface to remain responsive, while allocating time to background tasks.

  Disadvantages of Multiple Threads: -
      i. Memory requirement for the context information required by processes, Application Domain
         objects and threads. Therefore, the number of processes, Application Domain objects and threads
         which can be created is limited by memory availability.

       ii. Keeping track of a large number of threads consumes significant processor time. If there are too
           many threads, then there will not be any significant advantages of threads.

       iii. Controlling execution of an application with many threads can be a source of many bugs and it is
            very complex.

5. Write a note in 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 provides a rich set of interfaces, abstract and concrete classes.
→ We can use the concrete classes as is or can derive own classes from them.
→ To use the functionality of an interface, we can either create a class that implements the interface or device
   a class from one of the interface of .NET Framework classes.
→ It also follows naming conventions like .NET Framework types use a dot (.) syntax naming scheme that is
   in a hierarchy.
→ These also include types that perform the following functions : -
        a. Represent base data types and exceptions.
        b. Encapsulate data structures.
        c. I/O operations.
        d. Access information of types.
        e. .NET Framework security checks.
        f. Provide data access, GUI and web services.

6. What is the role of System.Object, System.String, System.Array and System.Collections Classes?
Ans:
System.Object: - System.Object class is the ultimate base class that all types directly or indirectly derive
                  from.
System.String: - In C#, a text string is stored in a data type named string, which is an alias to System.String
                  type.
System.Array: - Array types are reference types derived from the abstract base type System.Array.
System.Collections: - The System.Collections namespace contains interfaces and classes that define various
                        collections of objects, such as lists, queues, bit arrays, hashtables and dictionaries.



                                                       32
                                                                                Basics of .NET [BSIT-61]
7. What are the different methods supported by System.Object class? Give an example for each.
Ans: Following are the different methods supported by System.Object : -

   a. The Equals Method: - This is a common operation, especially for searching and sorting in collections,
      it tests two objects for equality. The Equals method of the object class provides a default
      implementation that compares two reference type objects for reference equality. The Equals method is
      virtual, so derived reference types may override it.
               e.g. : - using System;
                    class Employee
                    {
                        string e_name;
                        public Employee(string name)
                        {
                            e_name = name;
                        }
                    }
                  class EqualsDemonstration
                  {
                  static void Main()
                  {
                  EqualsDemonstration eqDemo = new EqualsDemonstration();
                  eqDemo.InstanceEqual();
                  Console.ReadLine();
                  }
                  public void InstanceEqual()
                  {
                  string name = "Nitin";
                  Employee employee1 = new Employee(name);
                  Employee employee2 = new Employee(name);

                  // comparing references of separate instances
                  bool isEqual = employee1.Equals(employee2);
                  Console.WriteLine("employee1 == employee2 - {0}", isEqual);
                  employee2 = employee1;

                  // comparing references of the same instance
                  isEqual = employee1.Equals(employee2);
                  Console.WriteLine("employee1 == employee2 - {0}", isEqual);
                    }
             }

   b. The ReferenceEquals Method: - the Equals and ReferenceEquals methods are semantically
      equivalent, except that the ReferenceEquals works only on object instances. The ReferenceEquals
      method is static.
      e.g. : - using System;
            class Employee
            {
            string e_name;
            public Employee(string name)
            {
            e_name = name;
            }
            }
      class ReferenceEqualsDemo
      {
            static void Main()
            {
              ReferenceEqualsDemo refEqDem = new ReferenceEqualsDemo();
                                                   33
                                                                                 Basics of .NET [BSIT-61]
             refEqDem.InstanceEqual();
             Console.ReadLine();
          }
        public void InstanceEqual()
        {
        string name = "Joe";
        Employee employee1 = new Employee(name);
        Employee employee2 = new Employee(name);

        // comparing separate instances
        bool isEqual = Object.ReferenceEquals(employee1, employee2);
        Console.WriteLine("employee1 == employee2 - {0}", isEqual);
        employee2 = employee1;

        // comparing the same instance
        isEqual = Object.ReferenceEquals(employee1, employee2);
        Console.WriteLine("employee1 == employee2 - {0}", isEqual);
        }
   }
c. The ToString Method: - The purpose of the ToString method is to return a string representation of a
   type. The default implementation in the object class returns a string with the name of the object. The
   ToString method overrides ToString in the object class.
   e.g.: - using System;
         class Employee
         {
             string e_name;
             public Employee(string name)
             {
                 e_name = name;
             }
 // If ToString() is not overridden, the output of this program will be “Employee”.
       public override string ToString()
       {
       return String.Format("[Employee: {0}]", e_name);
       }
     }
   class ToStringDemonstration
   {
       static void Main()
       {
       Employee emp = new Employee("Joe");
       Console.WriteLine(emp.ToString());
       Console.ReadLine();
       }
   }

d. The GetType Method: - GetType is the basis for using reflection in .NET. It returns a Type object,
   describing the object it was called on. It can then be used to extract type member data like methods and
   fields that may subsequently be used for late-bound method invocations. The GetType method is also
   useful if we get an object at runtime and we do not know what its type is.
   e.g.: - using System;
   class Employee
   {
   }
   class GetTypeDemonstration
   {
     static void Main()
     {

                                                  34
                                                                                Basics of .NET [BSIT-61]
       object emp1 = new Employee();
       Employee emp2 = new Employee();
       Console.WriteLine(emp1.GetType());
       Console.WriteLine(emp2.GetType());
       Console.ReadLine();
       }
   }

e. The GetHashCode Method: - The GetHashCode method makes any object usable in a Hashtable or
   any hashing algorithm. Since the default algorithm supplied by the GetHashCode method of the object
   class is not guaranteed to be unique, we should override GetHashCode in our custom types.
   e.g. : - using System;
           class Employee
           {
           string e_name;
           public Employee(string name)
           {
              e_name = name;
           }
             public override int GetHashCode()
           {
              string uniqueString = ToString();
              return uniqueString.GetHashCode();
           }
           public override string ToString()
           {
              return String.Format("[Employee: {0}]", e_name);
           }
           }
           class GetHashCodeDemonstration
           {
                static void Main()
                {
                    Employee emp = new Employee("Joe");
                    Console.WriteLine(emp.GetHashCode());
                    Console.ReadLine();
                }
           }

f. The MemberwiseClone Method: - Whenever we need to create a bitwise copy (shallow copy) of our
   type, the MemberwiseClone method is used. As such, if we perform a MemberwiseClone on our class,
   it will make a copy of the type and all contained value types and references types. However, it will not
   copy the objects that the reference type members in our type refer to. This behavior of only making a
   copy of the first level of our type tells the reason why a MemberwiseClone is called a shallow copy.
   Since the MemberwiseClone method is not virtual, we can not override it in derived classes.
   e.g.: - using System;
           public class Address
           { }
           class Employee
           {
           Address e_address = new Address();
           string e_name;
           public Employee(string name)
           {
           e_name = name;
           }
           public Employee ShallowCopy()
           {
                                                  35
                                                                                      Basics of .NET [BSIT-61]
               return (Employee)MemberwiseClone();
               }
               public Address EmployeeAddress
               {
               get
               {
               return e_address;
               }
               }
               }
               class MemberwiseCloneDemonstration
               {
               static void Main()
               {
               Employee emp1 = new Employee("Joe");
               Employee emp2 = emp1.ShallowCopy();

               // compare Employee references
               bool isEqual = Object.ReferenceEquals(emp1, emp2);
               Console.WriteLine("emp1 == emp2 - {0}", isEqual);
               //compare reference of Address object in each Employee object
             isEqual = Object.ReferenceEquals(emp1.EmployeeAddress,emp2.EmployeeAddress);
           Console.WriteLine("emp1.EmployeeAddress == emp2.EmployeeAddress - {0}", isEqual);
                 Console.ReadLine();
               }
       }
8. What is boxing and unboxing? Explain with an example.
Ans: Boxing : - Boxing is an implicit conversion of a value type object or to any interface type implemented
by this value type. Boxing a value of a value allocates an object instance and copies the value into the new
object.
e.g.: - // Boxing.cs
       // Boxing an integer variable
       using System;
       class TestBoxing
       {
           public static void Main()
           {
               int i = 123;
               object o = i; // Implicit boxing
               i = 456;       // Change the contents of i
               Console.WriteLine("The value-type value = {0}", i);
               Console.WriteLine("The object-type value = {0}", o);
           }
       }
Output : - The value-type=456 and The object-type=123

/* This example converts an integer variable i to an object o via boxing. Then the value stored in the variable i
is changed from 123 to 456. The example shows that the object keeps the original copy of the contents, 123. */
Unboxing :-Unboxing is an explicit conversion from the type object to a value type or from an reference type
to a value type that implements the interface. An unboxing operation consists of: -
       a. Checking the object instance to make sure it is a boxed value of the given value type.
         b. Copying the value from the instance into the value-type variable.
e.g. : - using System;
       public class UnboxingTest
       {
                                                       36
                                                                                  Basics of .NET [BSIT-61]
                  public static void Main()
                  {
                  int intI = 123;
                  // Boxing
                  object o = intI;
                  // Reference to incompatible object produces InvalidCastException
                    try
                    {
                    /* int intJ = (short)o; Display the System.InvalidCastException at
                                        UnboxingTest.Main() Error : Incorrect Unboxing */

                   int intJ = (int)o;// Display the Output without Exception
                          Console.WriteLine("Unboxing OK.");
                   }

                  catch (InvalidCastException e)
                  {
                  Console.WriteLine("{0} Error: Incorrect unboxing.", e);
                  }
              }
          }

Output : - Unboxing OK.

/* The above mentioned example demonstrates a case of invalid unboxing, of how incorrect unboxing leads to
InvalidCastException. By using try and catch, an error message is dispalyed when the error occurs */

9. Write a program to replace all „r‟ by „R‟ in the string “rose is a rose”.
Ans: using System;
          class ChangeCase
          {
            static void Main(string[] args)
            {
                string str = "rose is a rose";
                str=str.Replace("r","R");
                Console.WriteLine(str);
                Console.ReadLine();
            }
     }

10. Write a note on
a. Single-Dimensional Arrays
Ans: This array contains the element from arr[0] to arr[n]. The new operator is used to create the array and
initialize the array elements to their default values. In the following example, all the array elements are
initialized to zero.
e.g. : - using System;
          public class SingleDimensionalArrayClass
          {
          static void PrintArray(string[] w)
          {
            for (int i = 0; i < w.Length; i++)
                Console.Write(w[i] + "{0}", i < w.Length - 1 ? " " : "");
            Console.WriteLine();
          }

          public static void Main()
          {
         // Declare and initialize an array:
                                                       37
                                                                                 Basics of .NET [BSIT-61]
    string[] WeekDays = new string[] { "Sun", "Sat", "Mon", "Tue", "Wed", "Thu", "Fri" };

             // Pass the array as a parameter:
             PrintArray(WeekDays);
         }
         }

b. Multidimensional Arrays
Ans: Arrays can have more than one dimension.
e.g. : - using System;
         public class MultiDimensionalArrayClass
         {
             static void PrintArray(int[,] w)
             {
                 // Display the array elements:
                for (int i = 0; i < 4; i++)
                for (int j = 0; j < 2; j++)
                Console.WriteLine("Element({0},{1})={2}", i, j, w[i, j]);
             }

                public static void Main()
              {
             // Pass the array as a parameter:
             PrintArray(new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 }, { 7, 8 } });
              }
         }

c. Jagged Arrays
Ans: A jagged array is an array whose elements are arrays. The elements of a jagged array can be different
dimension and sizes. A jagged array is sometimes called an ―array-of-arrays‖.
e.g. : - using System;
         public class JaggedArrayTest
         {
           public static void Main()
           {
           // Declare the array of two elements:
           int[][] myArray = new int[2][];

             // Initialize the elements:
             myArray[0] = new int[5] { 1, 3, 5, 7, 9 };
             myArray[1] = new int[4] { 2, 4, 6, 8 };

             // Display the array elements:
             for (int i = 0; i < myArray.Length; i++)
             {
                 Console.Write("Element({0}): ", i);

                 for (int j = 0; j < myArray[i].Length; j++)
                     Console.Write("{0}{1}", myArray[i][j],
                                   j == (myArray[i].Length - 1) ? "" : " ");

                 Console.WriteLine();
             }
     }
}




                                                   38
                                                                                       Basics of .NET [BSIT-61]
d. Passing Arrays Using ref and out
Ans: Like all out parameters, an out parameter of an array type must be assigned before it is used; that is, it
must be assigned by the caller. In case of ref parameters, a ref parameter of an array type must be definitely
assigned by the caller. Therefore, there is no need to be definitely assigned by the caller. 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.
e.g. : -         using System;
               class PassingArrayUsing_Ref_and_Out
               {
                     public static void FillArray(ref int[] arr)
                     {
               // Create the array on demand:
                     if (arr == null)
                     arr = new int[10];
               // Otherwise fill the array:
                       arr[0] = 123;
                       arr[4] = 1024;
                     }
               static public void Main()
               {
                 // Initialize the array:
                 int[] myArray = { 1, 2, 3, 4, 5 };
                 // Pass the array using ref:
                 FillArray(ref myArray);
                 // Display the updated array:
                 Console.WriteLine("Array elements are:");
                 for (int i = 0; i < myArray.Length; i++)
                 Console.WriteLine(myArray[i]);
               }
               }




11. What is the use of System.Collections class?
Ans: System.Collections class is a namespace which contains interfaces and classes that define various
collections of objects, such as lists, queues, bit arrays, hashtables and dictionaries.
→ Each class has a set of methods and properties, which are used on those corresponding class objects.




                                                       39
                                                                                    Basics of .NET [BSIT-61]
Chapter – 7

1. Give the overall concept of ADO.NET with the help of figures. (Hint: Big picture)
Ans:




→ ActiveX Data Objects for the .NET Framework is a set of classes that provide data access services to the
 .NET programmer.
→ It is an integral part of .NET Framework, providing access to relational database, XML and application
  data.
→ It is based on an object model that is based on the standards laid down by World Wide Web Consortium.
→ It provides a rich set of components for creating distributed, data-sharing applications.
→ It 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 MS 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.
→ By using ADO .NET data can be retrieved from one data source and saved in another. For example, data
  can be retrieved from Microsoft Excel and then saved in an XML document.
→ In the ADO .NET object model, the data residing in a database is retrieved through a data provider.
→ The Data Provider is a set of components including the connection, command, data reader and data adapter
  objects.
→ It provides data to the application, and updates the database with the changes made in the application.
→ An application can access data either through a dataset or through a data reader object.
→ ADO .NET also enables to create an XML representation of a dataset.
→ In an XML representation of a dataset, data is written in XML format, and dataset schema is written by
  using the XML Schema definition language (XSD).
→ The two key components of the ADO .NET are: -
        a. Data Provider                     b. Dataset




                                                     40
                                                                                      Basics of .NET [BSIT-61]
→ The four key components of a data provider are: -
      1. Connection                  Establishes a connection to a specified data source.
      2. Command                     Executes a command against a data source.
      3. Data Reader                 Reads a forward-only, read-only stream of data from a data source
      4. Data Adapter                Populates a DataSet and resolves updates with a data source.
→ The key components of Dataset are: -
      1. DataTableCollection : - It contains all the tables retrieved from the Data source.
      2. DataRelationCollection : - It contains relationship and links between tables in a Dataset.
      3. DataTable : - It represents a table in the data table Collection of a dataset.
      4. DataRowCollection : - It contains all the rows in a data table.
      5. DataColumnCollection : - It contains all the columns in a data table.
→ An application can access data either through a dataset or through a data reader 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 data reader 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.

2. Explain in detail ADO.NET architecture.
Ans:



3. What is a data provider? Explain.
Ans: Data Provider : - A Data Provider is used for connecting to a database, retrieving data, storing the data in
a dataset, reading the retrieved data, and updating database.
→ Selecting an appropriate data provider for a client application depends on the type of data sources that is
   being accessed.
→ The four main types of data providers are: -
    a. .NET Framework data provider for SQL Server : - The System.Data.dll assembly implements SQL
        Server .NET Framework data provider in the System.Data.SqlClient namespace and it specifically
        worked with Microsoft SQL Server.
    b. .NET Framework data provider for OLE DB : - This type of data provider works with the OLE DB
        provider, Oracle OLE DB provider, and the Jet OLE DB provider. The System.Data.dll assembly
        implements OLE DB .NET Framework data provider in the System.Data.OleDb namespace.
    c. .NET Framework data provider for ODBC : - To use this type of provider, we must use an ODBC
        driver. The System.Data.ODBC.dll assembly implements ODBC .NET Framework data provider.
    d. .NET Framework data provider for Oracle : - Oracle client software must be installed on the system
        before we use the provider to connect to an Oracle data source. The System.Data.OracleClient.dll
        assembly implements the Oracle .NET Framework data provider in the System.Data.OracleClient
        namespace.

→ The .NET data provider is designed to be lightweight, creating a minimal layer between the data source and
  application code, increasing performance without sacrificing functionality.
→ The four main components of .NET data provider : -

             Object                                        Description
       5. Connection                 Establishes a connection to a specified data source.
       6. Command                    Executes a command against a data source.
       7. Data Reader                Reads a forward-only, read-only stream of data from a data source
                                                      41
                                                                                  Basics of .NET [BSIT-61]
       8. Data Adapter              Populates a DataSet and resolves updates with a data source.

4. What is a data set? Explain
Ans: Dataset : - The Dataset is a memory based relational representation of data. A Dataset is a part of the
disconnected environment.
→ A dataset is a disconnected, cached set of records that are retrieved from a database.
→ A dataset contains a collection of one or more DataTable objects made up of rows and columns of data as
   well as constraint and relation information about data in the DataTable objects.

→ A Dataset is present in the Dataset class in the System.Data namespace. The key components of a Dataset
   are : -
        6. DataTableCollection : - It contains all the tables retrieved from the Datasource.
        7. DataRelationCollection : - It contains relationship and links between tables in a Dataset.
        8. DataTable : - It represents a table in the datatable Collection of a dataset.
        9. DataRowCollection : - It contains all the rows in a datatable.
        10. DataColumnCollection : - It contains all the columns in a datatable.
5. Write a program to show the demonstration of ADO.NET.
Ans: using System;
       using System.Collections.Generic;
       using System.Text;
       using System.Data.SqlClient;

       namespace Demo_ADO_NET
       {
           class Program
           {
             static void Main(string[] args)
             {
               string connectionString = "Data Source=NBMSKN;Initial Catalog=AdventureWorks;
               User id=sa;Password=NBMSKNS";
               string sSQL = "Select * from HumanResources.Employee";
               SqlConnection cn = new SqlConnection(connectionString);
               cn.Open();
               SqlCommand cmd = new SqlCommand(sSQL,cn);
               SqlDataReader dr = cmd.ExecuteReader();
               while (dr.Read())
               {
                   Console.WriteLine(dr[0]+""+dr[1]);
               }
               cn.Close();
               Console.ReadLine();
               }
           }
       }




                                                    42
                                                                                    Basics of .NET [BSIT-61]
Chapter – 8

1. What is a web service? Explain its working.
Ans: Web Service: - A Web service is a very simple idea. It is a application logic, accessible through some
      standard Web protocol.
→ A Web service is just between computer to computer applications.
→ It is like a program on one computer calling a method that exists on another computer and calling it through
   the Internet.
→ A Web service does not have user interface. A Web service is designed to interact with applications.

2. Who does the web service differ from web page?
Ans:

3. With a neat diagram explain the event handling process of win forms/web forms.
Ans:




<%@ Page Language="C#" AutoEventWireup="true"              CodeFile="Default.aspx.cs"
Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
<head>
</head>
<script language="C#" runat="server">
void SubmitBtn_Click(Object sender, EventArgs e)
{
Message.Text = "Hi " + HttpUtility.HtmlEncode(Name.Text) + ", Thanks!!!!! You have
Selected: " + Category.SelectedItem;
}
</script>
<body>
<center>
<form action="Default.aspx" method="post" runat="server">
<h3> Name: <asp:textbox id="Name" runat="server"/>
                                                      43
                                                                                 Basics of .NET [BSIT-61]
Category: <asp:dropdownlist id="Category" runat="server">
<asp:listitem>TOYS</asp:listitem>
<asp:listitem>SPORTS KIT</asp:listitem>
<asp:listitem>FLOWERS</asp:listitem>
</asp:dropdownlist>
</h3>
<asp:button text="Lookup" OnClick="SubmitBtn_Click" runat="server"/>

<asp:label id="Message" runat="server"/>
</form>
</center>
</body>
</html>

→ Each ASP.NET server control is capable of exposing an object model containing properties, methods and
  events. ASP.NET developers can use such object model to cleanly modify and interact with the page.
→ The above mentioned example demonstrates how an ASP.NET page developer can handle the OnClick
  event from the <asp:button runat="server"> control to manipulate the text property of the
  <asp:label runat="server"/> control.
→ In this example, when this web form loads on the web browser, there is two Label, one Textbox, one
  DropDownList, one Button.
→ When the USER select any item present in the DropDownList and click on the Button, it displays a message
  along with the name and the selected item from the dropdownlist.
→ This event occurs due to ASP.NET server controls which handles it.

4. What is ASP.NET?
Ans: ASP.NET is an entirely new paradigm for server-side ASP scripting.
→ ASP.NET is a unified Web development platform that provides the services necessary for us to build
   enterprise Web applications.
→ ASP.NET is largely syntax compatible with Active Server Pages, it also provides a new programming
    model and infrastructure that allow us to create secure, scalable, stable and powerful applications.
→ ASP.NET is a compiled, .NET-based environment; and allows us to take full advantage of the features of
    the CLR, such as type safety, inheritance, language interoperability and versioning.
→ ASP.NET has been designed to work with ―What You See Is What You Get‖ (WYSIWYG) HTML editors
    and other programming tools, including Microsoft Visual Studio .NET.

5. What is the use of ASP.NET?
Ans: ASP.NET is precompiled code so it become very easy to use it in web applications development.
→ We can easily use the benefits of these technologies, which include managed CLR environment, type safety,
    Inheritance, language interoperability and versioning.

6. Write a program to display “Welcome to ASP.NET” 8 times in increasing order of their font size using
   ASP.NET.
Ans: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
       Inherits="_Default" %>
       <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
       <html xmlns="http://www.w3.org/1999/xhtml" >
       <head runat="server"><title>Untitled Page</title></head>
       <body>
       <center>
           <form id="form1" runat="server">
         <div>
           <%for (int i=0; i<8;i++){%>
                                                    44
                                                                                   Basics of .NET [BSIT-61]
           <font size="<%=i%>">Welcome to the ASP .NET</font><br />
           <%}%>
         </div>
       </form>
       </center>
       </body>
       </html>

7. What is the role of System.Web?
Ans: The System.Web namespace supplies classes and interface that enable browser and server
   communication.
→ This namespace includes the HttpRequest classes which provides extensive information about the current
   HTTP request, the HTTP response class which manages HTTP output to the client and HttpServerUtility
   class which 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: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
       Inherits="_Default" %>

       <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

       <html>
       <head>
       </head>
       <script language="C#" runat="server">
       void SubmitBtn_Click(Object sender, EventArgs e)
       {
       Message.Text = "Hi " + HttpUtility.HtmlEncode(Name.Text) + ", Thanks!!!!! You have
       Selected: " + Category.SelectedItem;
       }
       </script>
       <body>
       <center>
       <form action="Default.aspx" method="post" runat="server">
       <h3> Name: <asp:textbox id="Name" runat="server"/>
       Category: <asp:dropdownlist id="Category" runat="server">
       <asp:listitem>TOYS</asp:listitem>
       <asp:listitem>SPORTS KIT</asp:listitem>
       <asp:listitem>FLOWERS</asp:listitem>
       </asp:dropdownlist>
       </h3>
       <asp:button text="Lookup" OnClick="SubmitBtn_Click" runat="server"/>

       <asp:label id="Message" runat="server"/>
       </form>
       </center>
       </body>
       </html>




                                                     45
                                                                                        Basics of .NET [BSIT-61]
Chapter – 9

1. What is a .NET remoting?
Ans: .NET Remoting enables communication between applications.
→ Different applications can communicate with one another, whether those applications reside on the same
   computer, on different computers in the same local area network, or across the world in very different networks
   and even if the computers run different operating systems.
→ The .NET Framework provides a number of services such as activation and lifetime control.
→ It also provides communication channels responsible for transporting messages to and from remote
    applications.
→ It can also use XML encoding when interoperability with other remoting systems is essential.
→ Remoting was designed with security in mind, so we can serialize streams in order to secure them before they
    are transported over the channel.

2. How is .NET remoting different from web services and DCOM?
Ans: .NET Remoting versus Distributed COM (DCOM) –
In the earlier days, Inter-Process communication between applications was handled through Distributed
Component Object Model(DCOM). DCOM works well and the performance is adequate when applications
exist on computers of similar type on the same network.
→ However, DCOM has two major drawbacks –
         a. It relies on a proprietary binary protocol that not all object models support.
         b. It also wants to communicate over a range of ports that are typically blocked by firewalls.
.NET Remoting eliminates the difficulties of DCOM by supporting different transport protocol formats and
communication protocols. This allows .NET Remoting to be adaptable to the network environment in which it
is being used.
.NET Remoting versus Web Services –
Web services fall under the roof of .NET Remoting, but web services have a simplified programming model
and are intended for a wide target audience.
→ Web services involve allowing applications to exchange messages that may be platform independent and
    programming language independent.
→ Web services know nothing about the client that is making the request. The clients communicate by
    transferring messages back and forth in a specific format known as the Simple Object Access Protocol, or
    SOAP The following list gives some of the major differences between .NET Remoting and Web services:
         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.
         Web services support interoperability across platforms and are good for heterogeneous environments.
          .NET Remoting requires the clients be built using .NET, which means a homogeneous environment.

3. Explain remoting architecture.
Ans: The Remoting Architecture, presents to the programmer an even simple procedure. If we configure the
client properly, we need only creates a new instance of the remote object using new.
→ Client receives a reference to the server object, and then call its methods as though the object were in
    process rather than running on a separate computer.
                                                        46
                                                                                       Basics of .NET [BSIT-61]
→ The remoting system uses proxy objects to create the impression that the server object is in the client‘s
  process.
→ Proxies are stand-in objects that present themselves as some other object. When client creates an instance of
  the remote type, the remoting infrastructure creates a proxy object that looks exactly like the remote type.
→ Client calls a method on that proxy, and the remoting system receives the call, routes it to the server
  process, invokes the server object, and returns the return value to the client proxy, which returns the result
  to the client.
→ Remote calls must be conveyed in some way between the client and server process.
→ For building a remoting system, we might start by learning network programming and a wide array of
  protocols and serialization format specifications.
→ .NET remoting system, the combination of underlying technologies required to open a network connection
  and use a particular protocol to send the bytes to the receiving application are represented as a transport
  channel.
→ A channel is a type that takes a stream of data, creates a package according to a particular network protocol,
  and sends the package to another computer.
→ Some channels can only receive information, others can only send information, and still others, such as the
  default TcpChannel and HttpChannel classes, can be used in both directions.

4. With a neat diagram explain the remoting process.
Ans:




        Suppose we have an application running on one computer, and we want to use the functionality that is
stored on another computer. The above mentioned shows the general remoting process.
→ When both the server and client are configured properly, a client creates a new instance of the server class.
→ The remoting system creates a proxy object that represents the class and returns to the client object a
   reference to the proxy.
→ When a client calls a method, the remoting system checks the type information, and sends the call over the
   channel to the server process.
→ A listening channel picks up the request and forwards it to the server remoting system, which locates and
   calls the requested object.
→ The process is then reversed, as the server remoting system bundles the response into a message and the
   server channel sends to the client channel.
→ Finally, the client remoting system returns the result of the call to the client object through the proxy.




                                                      47
                                                                                 Basics of .NET [BSIT-61]
5. Explain the steps or phases involved in implementing .NET remoting applications.
Ans:

6. Write a program to display “Hello World” string to demonstrate .NET remoting.
Ans: using System;
       using System.Runtime.Remoting;
       using System.Runtime.Remoting.Channels;
       using System.Runtime.Remoting.Channels.Tcp;
       namespace Remoting
       {
            // Sample remote object
            public class SampleObject : MarshalByRefObject
            {
                // Constructor
                public SampleObject()
                {
                }
                // Return a Hello world message
                public string HelloWorld()
                {
                return ―Hello World!‖;
                }
          }
   }




                                                   48

				
DOCUMENT INFO
Shared By:
Stats:
views:45
posted:8/1/2011
language:English
pages:48
Description: this file is very user full. every file is write and very easy step ,and fully ansnwer