104
Darshan Institute of Engineering & Technology .Net Introduction 1 .Net Introduction Explain .NET Framework Architecture .NET framework is consisting of several layers as shown below: .NET framework runs on different versions of windows operating system, starting from windows 98 to latest versions of windows 7 and windows 8. Operating system is not a part of .NET framework but generally it is shown as a base layer to indicate that .NET framework runs on operating system. Common Language Runtime (CLR) The CLR is the execution engine for .NET applications and serves as the interface between .NET applications and the operating system. The CLR is the platform on which applications are hosted and executed. The CLR manages memory, Thread execution, Garbage Collection (GC), Exception Handling, Common Type System (CTS), code safety verifications, and other system services. Framework Class Library (FCL) also known as Base Class Library (BCL) The .NET FCL is a collection of reusable types that is integrated with the CLR. The .NET FCL is object oriented It contains more than 7000 classes and data types to read and write files, access databases, process XML, display a graphical user interface, draw graphics, use Web services, etc… C# VB.net J# VC++ Other .net compliant languages Common Language Specifications (CLS) Common Type System (CTS) ASP.net XML Web Services ASP.net Web Forms Windows Forms Data and XML Classes (ADO.net, SQL, XML, etc…) Framework Class Library (FCL) or Base Class Library (BCL) Common Language Runtime (CLR) Operating System (Windows) .NET Framework

Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

  • Upload
    buitram

  • View
    219

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology .Net Introduction

1

.Net Introduction Explain .NET Framework Architecture

.NET framework is consisting of several layers as shown below:

.NET framework runs on different versions of windows operating system, starting from windows 98 to latest versions of windows 7 and windows 8.

Operating system is not a part of .NET framework but generally it is shown as a base layer to indicate that .NET framework runs on operating system.

Common Language Runtime (CLR) The CLR is the execution engine for .NET applications and serves as the interface between .NET

applications and the operating system.

The CLR is the platform on which applications are hosted and executed.

The CLR manages memory, Thread execution, Garbage Collection (GC), Exception Handling, Common Type System (CTS), code safety verifications, and other system services.

Framework Class Library (FCL) also known as Base Class Library (BCL) The .NET FCL is a collection of reusable types that is integrated with the CLR.

The .NET FCL is object oriented

It contains more than 7000 classes and data types to read and write files, access databases, process XML, display a graphical user interface, draw graphics, use Web services, etc…

C# VB.net J# VC++ Other .net compliant languages

Common Language Specifications (CLS) Common Type System (CTS)

ASP.net XML Web Services

ASP.net Web Forms

Windows Forms

Data and XML Classes (ADO.net, SQL, XML, etc…)

Framework Class Library (FCL) or Base Class Library (BCL)

Common Language Runtime (CLR)

Operating System (Windows)

.NET

Fra

mew

ork

Page 2: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology .Net Introduction

2

The .NET FCL wraps much of the large, complex Win32 API into simpler .NET classes that can be used by C# and other .NET programming languages.

Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation.

ADO.NET provides improved support for the disconnected programming model. It also provides rich XML support.

XML classes support various operations on XML data like searching, translations, modifying, etc…

Applications (Windows, Web, Web Services, etc…) Applications are the interface between users and computers that allows .NET to interact with the

outside world.

Commonly used application types are windows (Tally, MS Office, etc…), web (www.gtu.ac.in, www.google.co.in), web services (Internet payment systems), etc…

Common Language Specifications (CLS) CLS is a set of specifications to make languages as .NET compliant languages.

CLS is an agreement among language designers and class library designers to use a common subset of basic language features that all languages have to follow.

This is done in such a way, that programs written in any language (.NET compliant) can interoperate with other languages. This also can take full advantage of inheritance, polymorphism, exceptions, and other features.

CLS makes use of CTS and CLR.

Common Type System (CTS) CTS describes how types are declared, used and managed in the runtime

It facilitates cross-language integration, type safety, and high performance code execution.

Types are the mechanism by which code written in one programming language can talk to code written in a different programming language.

CTS help developers to develop applications in different languages.

The CTS also specifies the rules for type visibility and for access to the members of a type.

.NET compliant languages This is the top most layer, it consists of .NET compliant languages e.g. C#, VB.NET, J#, VC++, F#, etc…

One of the imperative features of the .NET is the facility to program in multiple languages, which allows programmers to use their favorite languages.

Explain Common Language Runtime (CLR) or Write a Short note on CLR.

It works as a layer between operating system and the applications written in .NET languages that matches to the Common Language Specification (CLS).

Page 3: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology .Net Introduction

3

The main function of CLR is to convert the managed code into native code and then execute the code.

The CLR’s Just In Time (JIT) compilation converts Intermediate Language (MSIL) to native code on demand at run time.

During the execution of the program, the CLR manages memory, thread execution, garbage collection (GC), exception handling, CTS, code safety verifications, and other system services.

The CLR defines the CTS which is a standard type system used by all .NET languages. That means all .NET programming languages uses the same representation for common data types, thus CLR is a language-independent runtime environment.

The CLR environment is also referred as a managed environment, because during the execution of a program it also controls the interaction with the Operating System.

Thread Support The .NET Framework provides a number of threading and synchronization facilities to allow you to build high performance, multithreaded code. Your choice of threading approach and synchronization mechanism impacts application concurrency; hence, it also impacts scalability and overall performance.

COM Marshaler COM marshaler allows .NET applications to exchange data with COM applications.

Type Checker Type checker will verify types used in the application with CTS or CLS standards supported by CLR, this provides type safety.

Exception Manager The CLR supports structured exception handling to allow you to build robust, maintainable code. Use language constructs such as try/catch/finally to take advantage of structured exception handling.

Security Engine The .NET Framework provides code access security to ensure that code has the necessary permissions to perform specific types of operations such as accessing the file system, calling unmanaged code, accessing network resources, and accessing the registry.

Base Class Library Support

Thread Support COM Marshaler

Type Checker Exception Manager

Security Engine Debug Engine

MSIL to Native Compilers (JIT)

Garbage Collection

Code Manager

Class Loader

Page 4: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology .Net Introduction

4

Debug Engine Debug Manager Service will activate debugger utility to support line by line execution; the developer can make changes as per requirement without terminating application execution.

MSIL to Native Compilers (JIT) The just-in-time (JIT) compiler converts the Microsoft intermediate language (MSIL) into native machine code at run time. Methods that are never called are not JIT-compiled.

Garbage Collection The garbage collector is responsible for allocating, freeing, and compacting memory. Garbage Collector will release memory of unused objects, this provides automatic memory management.

Code Manager Code manager invokes class loader for execution.

Class Loader The .NET Framework loader is responsible for locating and loading assemblies.

Common Language Specification (CLS) CLS is a set of basic language features that .NET Languages needed to develop Applications and Services,

which are compatible with the .NET Framework.

CLS ensures complete interoperability among applications, regardless of the language used to create the application.

When there is a requirement to communicate objects written in different .NET Complaint languages, those objects must expose the features that are common to all the languages.

CLS defines a subset of Common Type System (CTS) which describes a set of types that can use different .NET languages which ensure that objects written in different languages can interact with each other.

Most of the members defined by types in the .NET Framework Class Library (FCL) are Common Language Specification (CLS) compliant Types. Moreover Common Language Specification (CLS) is standardized by ECMA & Microsoft.

Common Type System (CTS) The common type system defines how types are declared, used, and managed in the runtime, and is also an

important part of the runtime's support for cross-language integration.

The common type system performs the following functions: o To enable cross-language integration, type safety, and high performance code execution. o To provide an object-oriented model that supports the complete implementation of many

programming languages. o To define rules that languages must follow, which helps ensure that objects written in different

languages can interact with each other. o The CTS also defines the rules that ensure that the data types of objects written in various languages

are able to interact with each other.

Page 5: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology .Net Introduction

5

o The CTS also specifies the rules for type visibility and access to the members of a type, i.e. the CTS establishes the rules by which assemblies form scope for a type, and the CLR enforces the visibility rules.

o The CTS defines the rules monitoring type inheritance, virtual methods and object lifetime. o Languages supported by .NET can implement all or some common data types

The common type system supports two general categories of types, each of which is further divided into subcategories

Value types

o Value types directly stores data and variables of value types are either stored on the stack or allocated inline in a structure.

o Value types can be built-in (System.Int32, System.Boolean), user-defined (your own value types which are derived from System.ValueType or System.Enum), or enumerations.

Reference types o Reference types store a reference to the value's memory address and are stored on the heap. o Reference types can be self-describing types, pointer types, or interface types. o The type of a reference type can be determined from values of self-describing types. o Self-describing types are further split into arrays and class types. The class types are user-defined

classes, boxed value types, and delegates.

Type

Value types Reference Type

Built in value types

User-defined value types

Enumerations

System.Int32

System.Byte

System.Boolean

Self-describing type

Pointer types

Interface types

Arrays Class types

User-Defined Classes

Boxed value types Delegates

Page 6: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology .Net Introduction

6

Framework Class Library (FCL) The .NET FCL is a huge collection of reusable classes, interfaces, and value types that provide access to

system functionality.

It is the foundation on which .NET Framework applications, components, and controls are built.

FCL provides the consistent base types that are used across all .NET enabled languages.

The .NET FCL organized in a hierarchical tree structure and it is divided into Namespaces.

Namespaces is a logical grouping of types for the purpose of identification.

The Classes are accessed by namespaces, which reside within Assemblies.

The System Namespace is the root for types in the .NET Framework. The .NET FCL classes are object oriented and easy to use in program developments.

Data and XML Classes (ADO.NET, SQL, XML, etc…)

System.Data

DataSet DataRow

DataTable DataView

System.XML

System.XML.Schema

System.XML.Serialization

Page 7: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology .Net Introduction

7

Namespace

Namespace is a grouping of logically related identifiers, classes, types etc…

Namespace is used to avoid conflicts with the elements of an unrelated code which have the same names.

A namespace acts as a container—like a disk folder—for classes organized into groups usually based on functionality.

All classes and types of .NET FCL are organized in namespaces.

Implementing Namespaces in your own code is a good habit because it is likely to save you from problems later when you want to reuse some of your code.

Namespaces don't correspond to file or directory names.

How to create namespace? Syntax: namespace namespace_name { }

Example:

namespace GTU { class Student { public static void Main() { Console.WriteLine("This is Student class"); } } class Subject { public static void Main() { Console.WriteLine("This is Subject class"); } } }

How to use namespace?

using GTU; using System; class Result { Subject s; //Only class name, no need of namespace as we have used in the beginning System.Windows.Forms.Button b = new System.Windows.Forms.Button (); //Full qualifier name because we have not included namespace.}

Page 8: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology .Net Introduction

8

Alias for namespace:

We can create alias of any namespace. Syntax: using alias-name = namespace; Example:

using Win = System.Windows; class Test { Win.SplashScreen ss = new Win.SplashScreen(); } Nested Namespace

Nested namespace is allowed in .NET. Like System namespace contains System.Web namespace.

Example:

namespace Parent { namespace Child { namespace Grandchild { class Test { public void ShowMessage() { Console.WriteLine("This is a nested namespace!"); } } } }}

Major Namespaces in .NET System: The System namespace contains fundamental classes and base classes that define commonly-used

value and reference data types, events and event handlers, interfaces, attributes, and processing exceptions. It the root of all namespaces containing all other namespaces as subordinates. It also contains the types that we felt to be the most fundamental and frequently use

System.Collections: Includes classes and interfaces that define various collection of objects such as list, queues, hash tables, arrays, etc

System.Data: Includes classes which lets us handle data from data sources

System.Data.OleDb: Includes classes that support the OLEDB .NET provider

System.Data.SqlClient: Includes classes that support the SQL Server .NET provider

System.Diagnostics: Includes classes that allow to debug our application and to step through our code

System.Drawing: Provides access to drawing methods

System.Globalization: Includes classes that specify culture-related information

System.IO: Includes classes for data access with Files

System.NET: Provides interface to protocols used on the internet

Page 9: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology .Net Introduction

9

System.Reflection: Includes classes and interfaces that return information about types, methods and fields

System.Security: Includes classes to support the structure of common language runtime security system

System.Threading: Includes classes and interfaces to support multithreaded applications

System.Web: Includes classes and interfaces that support browser-server communication

System.Web.Services: Includes classes that let us build and use Web Services

System.Windows.Forms: Includes classes for creating Windows based forms

System.XML: Includes classes for XML support

Explain Managed Code & Unmanaged Code in .NET Framework.

Managed code = .NET programs. Unmanaged code = other programs

Managed Code

Code written in any .NET complaint language is managed code.

Code that runs under the control of CLR is called managed code.

If the complete life cycle and execution of code is managed by the .NET CLR then such code is called managed code.

The resources of managed code are within application domain.

Managed code is faster than unmanaged code.

Managed code uses CLR which in turns looks after your applications by managing memory, handling security, allowing cross - language debugging, and so on.

Life cycle of Managed Code

1. Program (Code) is written in any .NET complaint language.

Source Code

MSIL Code

Executable Code

CPU

Code written in any .NET complaint language

Language Specific Compiler

Language independent within .NET framework

JIT (Just-In Time) Compiler

Output

Page 10: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology .Net Introduction

10

2. Language specific compiler converts source code into MSIL Code. MSIL means Microsoft intermediate language. This is intermediate language used to convert the source code to assemblies during compilation. MSIL cannot run directly on machine.

3. MSIL is converted to a native code by a just-in-time (JIT) compiler. Native code is CPU-specific code that runs on the same computer architecture as the JIT compiler. JIT Compiler creates machine specific executable files which then run on computer.

4. CPU executes executable files, generally exe files, and gives output to the user.

Unmanaged Code

The code which is developed outside .NET Framework is known as unmanaged code.

Unmanaged code is executed directly by the operating system outside the CLR environment.

Unmanaged code is written in other languages like old c, c++, vb, cobol, etc…

Background compatibility with code of VB, ASP and COM are examples of unmanaged code.

Unmanaged code may be combination of managed code + COM components or OLE or DLLs

Explain Assembly Structure. Write code for create shared assembly and store assembly in GAC using tool.

An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality.

Assemblies are the building blocks of .NET Framework applications;

.NET assembly is the standard for components developed with the Microsoft.NET.

Assembly physically exists as DLLs or EXEs.

Assembly can include any file types like image files, text files etc. along with DLLs or EXEs.

When you compile your source code, the EXE or DLL is generated and it is actually an assembly.

One assembly may contain one or more files.

Source Code

MSIL Code

CPU

Code written in any .NET complaint language

Native Compiler (Language Specific)

Language independent within .NET framework

JIT (Just-In Time) Compiler

COM, OLE or other DLLs

Output

Executable Code

Page 11: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology .Net Introduction

11

Assembly contains four major parts: 1. Manifest- Additional information regarding assembly 2. Type metadata:-Data about data or structure of classes 3. MSIL code: - Containing business logics – Intermediate version of our program 4. Set of Resource:- Information or resource of other assembly

What is assembly manifest? Every assembly file contains information about itself. This information is called as Assembly Manifest.

Assembly manifest is a data structure which stores information about an assembly.

The information includes version information, list of files packed, definition of types, security permissions, version control, meta-data, deployment and manifest.

Types of Assembly Static Assembly & Dynamic Assembly

Static assemblies can include .NET Framework types (interfaces and classes), as well as resources for the assembly (bitmaps, JPEG files, resource files, and so on).

Static assemblies are first stored on disk in portable executable (PE) files then run.

Dynamic assemblies run directly from memory and are not saved to disk before execution.

You can save dynamic assemblies to disk after they have executed.

Single File Assembly & Multi File Assembly A single file assembly contains all the required information (IL, Metadata, and Manifest) in a single package.

A single file assembly does not implement version checking.

A multi file assembly is spread in multiple files.

A Multi file assembly is generally used for large applications with various types of resources

A Multi file assembly implements version checking.

Note: Multi file assemblies cannot be created with Visual Studio 2005 IDE for C# and VB.NET. You should use command line compilers to create multi-file assemblies. There are various options for grouping resources and code modules in to assemblies.

Private Assembly, Shared Assembly A Private assembly is used only by a single application.

A Private assembly is stored in the application’s directory or sub-directory.

A shared assembly is normally used by more than one application.

A shared assembly is stored in the global assembly cache (GAC) which is a repository of assemblies maintained by .NET runtime.

The .NET Framework library is provided as shared assemblies.

Satellite Assembly A satellite assembly is an assembly that contains language specific resources.

Sometimes, in an application, it is required to support multiple languages. There can be multiple satellite assemblies working side-by-side as they are installed in the language specific folders.

Page 12: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology .Net Introduction

12

Using satellite assemblies, you can place the resources for different languages in different assemblies, and the correct assembly is loaded into memory only if the user selects to view the application in that language.

In general, assemblies should contain culture-neutral resources. If you want to localize your assembly (for example use different strings for different locales) you should use satellite assemblies.

Making a private assembly a global assembly A global assembly is a public assembly that is shared by multiple applications. Unlike private assembly, a

global assembly is not copied to bin directory of each application that references it. Global assembly instead is placed in GAC (Global Assembly Cache) and it can be referenced anywhere within the system. So only one copy is stored, but many applications can use that single copy. In order to convert a private assembly to global assembly, we have to take the following steps.

1. Creating a strong name

Any assembly that is to be placed in GAC must have a strong name. Strong name is a combination of public key and private key. The relationship between public and private keys are such, given one you cannot get the other, but any data that is encrypted with private key can be decrypted only with the corresponding public key.

Take the following steps to invoke SN (Strong Name) tool to create strong name. 1. Go to command prompt using

Programs\Microsoft Visual Studio 2008\Visual Studio Tools\Visual Studio 2008 Command Prompt-> SDK Command prompt Enter the following command.

sn -k HelloWorld.key

2. The above command writes private and public key pair into HelloWorld.key file. Location of HelloWorld.key File: C:\Program Files\Microsoft Visual Studio 9.0\VC

2. Associate strong name with assembly

Once private and public keys are generated using SN tool, use the following procedure to sign Hello World with the key file. 1. Open HelloWorld project. 2. Select project properties using Project -> HelloWorldproperties 3. Select Signing tab in project properties window 4. Check Sign the assembly check box 5. Select HelloWorld.key file using Choose a strong name key file combo box 6. Close properties window 7. Build the solution again using Build->Build Solution

Now, HelloWorld.dll is associated with a public key and also digitally signed with private key.

3. Place assembly in GAC

In order to make an assembly a global assembly, the assembly must be associated with a strong name and then placed in Global Assembly Cache (GAC).

GAC is a folder with name Assembly in windows folder of your system. So, place HelloWorld.dll in GAC using GACUTIL tool as follows.

o Gacutil -i HelloWorld.dll

Page 13: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology .Net Introduction

13

After you install global assembly into GAC, you can see HelloWorld.dll in windows/assembly folder. Once, you place an assembly in GAC, any reference to the assembly will not create a copy of the assembly in

BIN directory of the application. Instead all application that reference the assembly use the same copy that is placed in GAC.

An assembly performs the following functions: It contains code that the CLR executes. MSIL code in a portable executable (PE) file will not be executed if it

does not have an associated assembly manifest.

It forms a security boundary. An assembly is the unit at which permissions are requested and granted.

It forms a type boundary. Every type's identity includes the name of the assembly in which it resides. A type called MyType loaded in the scope of one assembly is not the same as a type called MyType loaded in the scope of another assembly.

It forms a reference scope boundary. The assembly's manifest contains assembly metadata that is used for resolving types and satisfying resource requests. It specifies the types and resources that are exposed outside the assembly.

It forms a version boundary. The assembly is the smallest versionable unit in the CLR; all types and resources in the same assembly are versioned as a unit. The assembly's manifest describes the version dependencies you specify for any dependent assemblies.

It forms a deployment unit. When an application starts, only the assemblies that the application initially calls must be present. Other assemblies, such as localization resources or assemblies containing utility classes can be retrieved on demand. This allows applications to be kept simple and thin when first downloaded.

It is the unit at which side-by-side execution is supported.

Common Language Infrastructure

Page 14: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

14

The Common Language Infrastructure (CLI) is an open specification developed by Microsoft and standardized by ISO and ECMA that describes the executable code and runtime environment that form the core of the Microsoft .NET Framework and the free and open source implementations Mono and Portable.NET.

The specification defines an environment that allows multiple high-level languages to be used on different computer platforms without being rewritten for specific architectures.

The CLI specification describes the following four aspects:- 1. The Common Type System (CTS)

A set of data types and operations that are shared by all CTS-compliant programming languages. 2. Metadata

Information about program structure is language-agnostic, so that it can be referenced between languages and tools, making it easy to work with code written in a language you are not using.

3. Common Language Specification (CLS) A set of base rules to which any language targeting the CLI should conform in order to interoperate with other CLS-compliant languages. The CLS rules define a subset of the Common Type System.

4. Virtual Execution System (VES) The VES loads and executes CLI-compatible programs, using the metadata to combine separately generated pieces of code at runtime.

Page 15: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

15

VB.Net What is VB.Net? Explain? Differentiate VB.Net and C#

VB.Net is a simple, modern, object-oriented computer programming language developed by Microsoft.

It is developed to combine the power of .NET Framework and the common language runtime with the productivity benefits that are the hallmark of Visual Basic.

Everything in VB.NET is an object.

The following reasons make VB.Net a widely used professional language 1. Modern, General Purpose 2. Object Oriented 3. Component Oriented 4. Easy to learn 5. Structured Language 6. It produces efficient programs 7. Part of .Net Framework

Strong Programming Features of the VB.Net 1. Boolean Conditions 2. Automatic Garbage Collection 3. Standard Library 4. Assembly Versioning 5. Properties and Events 6. Delegates and Events Management 7. Easy-to-use Generics 8. Indexers 9. Conditional Compilation 10. Simple Multithreading

Difference between VB.Net and C# Purpose VB.NET C# Declare a named constant Const Const Create a new object New New Function/Method does not return a value Sub Void Overload a function or method Overloads No keyword required for this Refer to the current object Me This Initialize a variable where it declared Dim x as Long = 07; int x=07; Refer to a base class MyBase Base Declare an interface Interface Interface Specify an interface to be implemented Implements

(statement) class C1 : I1 (where C1 is class and I1 is interface name)

Page 16: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

16

Derive a class from a base class Inherits C2 Class C1 : C2 (Where C1 and C2 are classes name)

Override a method Overrides Override Include Namespace Imports Using Declare an array Dim a() as Long int[] a = new int[5]; Initialize an array Dim a() as Long =

{3,6,9}; int[] a = new int[5]{1,5,8,3,2};

Comment Purpose ‘ sign will be used // sign will be used

Explain DataTypes in VB.Net, how to declare variables in VB.Net?

Data Type Storage Allocation Value Range Boolean Depends on implementing

platform True or False

Byte 1 byte 0 through 255 (unsigned) Char 2 bytes 0 through 65535 (unsigned) Date 8 bytes 0:00:00 (midnight) on January 1, 0001 through 11:59:59 PM on

December 31, 9999 Decimal 16 bytes 0 through +/-79,228,162,514,264,337,593,543,950,335 (+/-

7.9...E+28) with no decimal point, 0 through +/-7.9228162514264337593543950335 with 28 places to the right of the decimal

Double 8 bytes -1.79769313486231570E+308 through -4.94065645841246544E-324, for negative values 4.94065645841246544E-324 through 1.79769313486231570E+308, for positive values

Integer 4 bytes -2,147,483,648 through 2,147,483,647 (signed) Long 8 bytes -9,223,372,036,854,775,808 through

9,223,372,036,854,775,807(signed) Object 4 bytes on 32-bit platform

8 bytes on 64-bit platform Any type can be stored in a variable of type Object

SByte 1 byte -128 through 127 (signed) Short 2 bytes -32,768 through 32,767 (signed) Single 4 bytes -3.4028235E+38 through -1.401298E-45 for negative values;

1.401298E-45 through 3.4028235E+38 for positive values String Depends on implementing

platform 0 to approximately 2 billion Unicode characters

UInteger 4 bytes 0 through 4,294,967,295 (unsigned) ULong 8 bytes 0 through 18,446,744,073,709,551,615 (unsigned) User-Defined Depends on implementing

platform Each member of the structure has a range determined by its data type and independent of the ranges of the other members

UShort 2 bytes 0 through 65,535 (unsigned)

Page 17: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

17

Declaring variables Dim number1 As Integer Dim number2 As Integer number1 = 3 number2 = 5

Here's a breakdown of the variable Declaration:

Dim: Short form of Dimension. It's a type of variable. You tell Visual Basic that you are declaring variable.

number1: This is a variable. In other words, our storage area. After the Dim word, Visual Basic is looking for the name of your variable. You can call your variable almost anything you like, but there are a few reserved words that VB won't allow.

As Integer: We're telling Visual Basic that the variable is going to be a number (integer). Well meet alternatives to Integer later.

Number1 = 3: The equals sign is not actually an equals sign. The = sign means assign a value of.

Explain Program Structure of VB.Net with Sample Program.

Let us look at the basic level of the VB.Net Program structure.

A VB.Net Program basically consists of the following parts; 1. Namespace declaration 2. A class or module 3. One to more procedures 4. Variables 5. The main procedure 6. Statements and Expressions 7. Comments

Sample VB.Net program

The first line of the program Imports System is used to include the System namespace in the program.

The next line has a Module declaration, the module Module1. VB.Net is completely object oriented, so every program must contain a module of a class that contains the data and procedures that your program uses.

Classes or Modules generally would contain more than one procedure. Procedures contain the executable code, or in other words, they define the behavior of the class. A procedure could be containing Function, Sub, Operator, Get, Set, AddHandler, Remove Handle, RaiseEvent.

Imports System Module Module1 'This program will display Hello World Sub Main () Console.WriteLine ("Hello World") Console.ReadKey () End Sub End Module

Page 18: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

18

The next line (‘This program) will be ignored by the compiler and it has been put to add additional comments in the program.

The next line defines the Main procedure, which is the entry point for all VB.Net programs. The Main procedure states what the module or class will do when executed.

The Main procedure specifies its behavior with the statement

Console.WriteLine("Hello World")

WriteLine is a method of the Console class defined in the System namespace. This statement causes the message "Hello, World!" to be displayed on the screen.

The last line Console.ReadKey () is for the VS.NET Users. This will prevent the screen from running and closing quickly when the program is launched from Visual Studio .NET.

Control Flow Statements with Examples

Selection Statements

Execute a block of code only when a certain condition or a set of condition are fulfilled , such as if a variable is less than an integer value, say 5.

1. If Statement.

Allows you to test whether or not a certain condition is fulfilled.

If the condition is fulfilled, the program control is transferred to the blocks of code inside the if statements; otherwise the program control is transferred to another block of code.

Syntax is as follows:

If condition [Then] [Statements] End If

With Else keyword:

If condition [Then] [Statements] Else [Else statements] End If

With Else if keyword

If condition [Then] [Statements] ElseIf condition [Then] Else [Else statements] End If

Page 19: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

19

Example:

If (marks>70) Then Console. WriteLine(“Distinction”) Elseif (marks>60 And marks<=70) Then Console. WriteLine(“First Class”) Elseif (marks>50 And marks<=60) Then Console. WriteLine(“Second Class”) Elseif (marks>40 And marks<=50) Then Console. WriteLine(“Pass Class”) Else Console.WriteLine (“Fail”)

2. Select Case.

Allows you to compare an expression with different values.

The Following are the terms used in the syntax of the Select Case Statement:

Select: Specifies a keyword that shows the starting point of the Select Case statement and holds a test expression.

testexpression: Specifies an integral expression defined by using data types, such as Integer and Char.

Case: Specifies a keyword that holds an expression list that fulfills the test expression.

expressionlist: Specifies a constant expression that represents match values that is compared with the value of test expression.

Case Else: Specifies a keyword that executes the code inside the Case Else block when none of the cases within the Select Case statement executes.

Select Case testexpression Case [expression list] [Statements] Case Else [else statements] End Select

Example:

Dim a As Integer a = Console.ReadLine() Console.WriteLine("Press Number between 1 to 4") Select Case (a) Case 1 Console.WriteLine("You have selected 1 ") Case 2 Console.WriteLine("You have selected 2 ") Case 3 Console.WriteLine("You have selected 3 ") Case 4

Page 20: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

20

Console.WriteLine("You have selected 4 ") Case Else Console.WriteLine("Kindly Select valid choice") End Select

Iteration Statements An iteration statement or loop executes a statement or a set of statement in a repeated manner.

1. While

Evaluates the specified condition before executing the loop.

The loop continues to execute as long as the condition is evaluated to True.

The Syntax of While statement is as follows:

While condition [Statements] [Exit While] [Statements] End While

Example:

Dim i As Integer While i < 10 Console.WriteLine("Value of i = " & i) End While

2. Do While

Executes the loop body at least once before evaluating the specified condition ,syntax is as :

Do [Statement] Exit Do [Statements] Loop {While | Until} Condition

Example

Dim n As Integer Dim i As Integer n = Console.ReadLine() Do Console.WriteLine ("Do loop Example") Loop Until (i < n)

Page 21: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

21

3. For Loop

For statement continues to execute the loop body until the condition specified in the loop evaluates to False. The syntax is as follows:

For Counter [As datatype] = start To end [Step step] [Statements] [Exit For] [Statements] Next [counter]

Counter: Defines the numeric control variable for the loop.

Datatype: Defines the data type of the counter, if it’s not declared.

Start: specifies the initial value of the counter.

End: Specifies the final value of counter.

Step: Specifies the value by which counter is increment/decrement.

Statements: specifies statements that executed no. of times.

Exit For: Transfers the control out of For.

Next: Terminates the definition of For Loop

Example:

Dim I as Integer For I=0 to 10 Console.WriteLine (I) Next

4. For Each Loop

The For Each continues to execute the loop body for each element in an array or object collection.

The syntax is :

For Each element [As datatype] in group [Statements] [Continue For] [Exit For] [Statements] Next [elements]

Element: Defines a variable used to iterate through elements of collection or array.

Datatype: Defines data type of the counter.

Group: Specifies the collection or array over which statements are repeated.

Statements: specifies statements that executed no. of times.

Exit For: Transfers the control out of the For Loop.

Next: Terminates the definition of For Loop

Page 22: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

22

Example:

Dim i(2) As integer Dim a As Integer i(0)=1 i(1)=2 For Each a in i Console.WriteLine (a) Next

Explain Array in Vb.net. Also Explain use of ReDim and Preserve keyword.

An array is set of values that are logically related to each other such as marks of students.

An array allows you to refer to these related values by the some name and to use a number called index for identifying individual values.

Dim keyword is used to declare a standard array.

Example :

Dim Arr(30) as Integer Dim Strings (10) As String Dim Two Array (20,40) As Integer Dim a(,) As Integer = {{0, 0}, {1, 2}, {2, 4}, {3, 6}, {4, 8}} Dim threeDIntArray(10, 10, 10) As Integer

Dynamic Array: Dynamic array can be dimensioned or redimensiond again if needed using Redim keyword.

Syntax is : Redim [Preserve] varname (subscript)

The preserve keyword is used to preserve the data in an existing array when you change the dimension of the array.

Dim i as Integer Dim name () as string Redim name (3) Console.WriteLine (“Enter the Student Name”) For i=0 to 2 Console. Write(“Student” &(i+ 1)& “:”) name (i)=Console.Readline() Next i Redim Preserve name (5) For i=3 to 4 Console. Write (“Student” &(i+ 1)& “:”)

Page 23: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

23

name (i)=Console.Readline() Next i Console.WriteLine(“The Students name are”) For i=0 to 4 Console. WriteLine (name (i)) Next i

Here in this program first for loop will read two names.

Than using Redim we have increased size of array.

Also preserve will retain the old values.

Next for loop will print all the five values.

Explain the concept of Class and Object inVB.Net with Example. Also Explain Concept of Inheritance with Example in VB.Net. (Example: Create VB.Net console application to define shape class and derive circle and rectangle from it to demonstrate inheritance)

A class is simply a representation of a type of object. It is the blueprint/ plan/ template that describe the details of an object.

Objects are instances of a class. The methods and variables that constitute a class are called members of the class.

A class definition starts with the keyword Class followed by the class name; and the class body, ended by the EndClass.

accessmodifier defines the access levels of the class, it has values as - Public, Protected, Friend, Protected

Friend and Private. Optional.

[accessmodifier] Class [classname ] Inherits [class_name] Implements [interface_name] [statements] EndClass

Page 24: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

24

Inherits specifies the base class it is inheriting from.

Implements specify the interfaces the class is inheriting from.

Module Module1 Class Test ‘Base Class Public Sub Circle() Console.WriteLine("Circle Method of Test Class") End Sub End Class Class Demo ‘Derived Class Inherits Test Public Sub rectangle() Console.WriteLine("Rectangle Method of Demo Class") End Sub End Class Sub Main() Dim d As Demo = New Demo() d.Circle() d.rectangle() Console.ReadKey() End Sub End Module

As shown in the example we had created one class called “Test” which contains one method/function, its name is “Circle” and we had also created another class called “Demo” which contains one method/function, its name is “rectangle”.

One of the most important concepts in object-oriented programming is that of inheritance.

Inheritance allows us to define a class in terms of another class which makes it easier to create and maintain an application.

When creating a class, instead of writing completely new data members and member functions, the programmer can designate that the new class should inherit the members of an existing class.

This existing class is called the base class (Test Class), and the new class is referred to as the derived class(Demo Class).

In our example Demo class inherits the Test class, now in the main method/function we had created object of the Demo class, now with the help of that object “d” we can called the method of the Test class and Demo class because of the inheritance.

Explain method overloading in VB.Net with Example. (Example: Create VB.Net Console Application to overload area method to find area of circle and rectangle)

Overloading is basically when you have more than one method with the same name but a different number of or different types of parameters.

Page 25: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

25

To overload a method in VB.Net we have to declare that method firstly overridable, so after declaring particular method overridable, we can override that method.

With the help of overloading method, we can define a method with the same name, but different number of arguments, so as we are passing the number of parameters at that time it will be decided which method is going to be called.

Example of the method overloading is as shown below, in that we had created one class Area_Found, which contains method area which is overridable.

Module Module1 Class Area_Found Public Overridable Sub area(ByVal r As Integer) Dim area As Double = r * r * 3.14 Console.WriteLine(area) End Sub Public Sub area(ByVal l As Integer, ByVal b As Integer) Dim area As Double = l * b Console.WriteLine(area) End Sub End Class Sub Main() Dim obj As Area_Found = New Area_Found() obj.area(2) 'It will call the area method of circle obj.area(3, 4) 'It will call the area method of rectangle Console.ReadKey() End Sub End Module

Which method will be called is decided at runtime.

When we are passing one parameter at that time it will call the area method to find the area of the circle, but when we are passing two parameters value then it will call the area method of the rectangle.

Explain Abstract Class. Also show use of Must Overrides and overrides overridable method with example.

Inheritance is a way to extend the functionalities of a class in other classes which are derived from it.

A derived class extends the functionalities of its base by adding new variables and methods inside it.

Page 26: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

26

The class which exposes its members for use by other classes is known as base class.

The class which inherits the functionalities of the base class is known as derived class.

Abstract classes are same like base classes with the difference that the methods declared inside the abstract classes, known as abstract method, do not have method bodies.

The actual implementation of the methods is done in the classes derived from the abstract classes.

Characteristic of Abstract Class:

It cannot be instantiated by its own, it must be inherited first.

It can contain any number of abstract methods.

It can also contain non abstract methods.

It is declared using the MustInherit keyword.

Characteristic of Abstract Method:

It is declared using the MustOverride keyword

It is found only in Abstract classes

It has its declaration in the abstract class i.e name, its return type, its parameters, and the parameters data types.

It must be overridden in the derived class.

MustOverride:

If you declare any method mustoverride in base class, it becomes compulsory to override this method in derived class.

Derived class object will call derived class method that was overrided.

Overridable:

If you declare an overridable method in base class, then it’s not compulsory to override this method in the derived class.

Derived class object will call overridden method if it’s overridden in derived class otherwise it will call base class method.

Overrides

Using Overrides keyword base class method is overridden in derived class and new logic is provided.

Following example shows the use of all these keywords.

Module Module1 MustInherit Class shape Public area As Double Public MustOverride Sub calcarea() Public Overridable Sub display() Console.WriteLine("This is shape class") End Sub End Class Class circle Inherits shape Public radius As Double Public Overrides Sub calcarea() area = 3.14 * radius * radius Console.WriteLine("Area of Circle is " & area)

Page 27: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

27

End Sub Public Overrides Sub display() Console.WriteLine("this is circle class") End Sub End Class Class rectangle Inherits shape Public l As Integer Public b As Integer Public Overrides Sub calcarea() area = l * b Console.WriteLine("Area of Rectangle is " & area) End Sub End Class Sub Main() Dim objcir As New circle() Dim objrec As New rectangle() Console.WriteLine("Enter the value of radius to calculate area of circle") objcir.radius = CDbl(Console.ReadLine()) Console.WriteLine("Enter the value of length and breath to calculate area of rectangle") objrec.l = CInt(Console.ReadLine()) objrec.b = CInt(Console.ReadLine()) objcir.calcarea() objcir.display() objrec.calcarea() objrec.display() Console.ReadLine() End Sub End Module

Here in class circle and rectangle inherits the base class shape which is declared as abstract.

Calcarea() is abstract method.

Here display() is overridden in circle but not in rectangle.

Object of circle will call display method which is overridden in circle, while object of rectangle calls shape’s display method()

Output of above program is as below

Page 28: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

28

Explain the concepts of Garbage Collection

Garbage collection is automatic memory manager for the .Net framework.

When we have a class that represents an object in the runtime that allocates a memory space in the heap memory.

All the behavior of that objects can be done in the allotted memory in the heap. Once the activities related to that object is get finished then it will be there as unused space in

the memory. When a variable defined, its gets a space in the memory and when the program control comes out of that

function the scope of variable get ended, so the garbage collection acts on and memory will releases.

Garbage collection prevents memory leaks during execution of programs.

Garbage Collector is a low-priority process that manages the allocation and deallocation of memory for your application.

Finalization: Finalize provides implicit control by implementing the protected finalize method on an object. The garbage

collector calls this method at some point after there are no longer any valid references to the object.

Module Module1 Public Class Hello Private myname As String Public Sub New (ByVal Name As String) myname = Name Console.WriteLine("Hello {0} !", Name) End Sub Protected Overrides Sub Finalize() Console.WriteLine("Good Bye {0}!", myname) Console.ReadLine() End Sub End Class Sub Main() Dim obj As New Hello("Darshan ") End Sub End Module

Page 29: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

29

Dispose: Dispose is used to explicitly release resources before garbage collector frees the object. If programmer

wants to explicitly release resources, dispose is used.

To provide explicit control, implement Dispose method provided by IDisposable interface.

Programmer calls the Dispose method while Finalize is invoked by the Garbage Collector.

Following example uses dispose method.

Module Module1 Public Class rectangle Implements IDisposable Private ln, wd As Integer Public Sub New(ByVal x As Integer, ByVal y As Integer) ln = x wd = y End Sub Public Sub dispose () Implements IDisposable.Dispose Console.WriteLine("Finalizing rectangle.........") End Sub Public Sub area () Console.WriteLine("Area of rectangle :" & (ln * wd)) End Sub End Class Sub Main() Dim rec As New rectangle(10, 20) rec.area() rec.dispose() Console.ReadKey() End Sub End Module

Output of the above program is as below:

Explain different windows form controls in VB.Net

VB.Net contains a very rich amount of the controls for the windows application.

Every controls have three important elements which are Properties and Events.

Page 30: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

30

Properties means all the controls can resized, customized and moved. A property is a value or characteristics held by the particular control.

An Event means a signal that informs an application that something important has occurred.

Some of the common Properties, Method and Events of all controls are as below.

Common Properties of all controls which are listed below:

Property Name Description Text Display the name of the control on the windows forms Name Contains the name of the controls by which the control can be identified Minimum Size With the help of the this property we can manage the minimum size of the control Maximum Size With the help of the this property we can manage the maximum size of the control Size With the help of the this property we can manage the size of the control Modifier To handle the access level of control public, private, protected or friend Font To set the font style of that control Anchor To set anchor property of the control TabIndex To set the tab index of the particular control Visible Control should be visible or not visible we can set with this property

Common Events of all controls which are listed:

Event Name Description Click When we click on the control and we have to execute any code that code will be

written in this event MouseClick When mouse will be clicked on the control and we have to execute any code that

code will be written in this event DoubleClick When we double click on the control and we have to execute any code that code

will be written in this event DragLeave When we remove the mouse from the control and at that time if any code have to

be executed that code will be written in this event SizeChanged When we changed the size of the control and at that time if any code have to be

executed that code will be written in this event StypeChanged When we changed the style of the control and at that time if any code have to be

executed that code will be written in this event Some of them controls of windows forms are as following;

1. Form Control

The container for all the controls that make up the user interface.

On form control, you can drag and drop controls from the toolbox.

When you run your application form is loaded first.

By default it contains minimize, maximize and close buttons.

Page 31: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

31

Properties:

Property Name Description StartPosition This property determines the initial position of the form when it's first

displayed. MinimizeBox By default, this property is True and you can set it to False to hide the

Minimize button on the title bar. MaximizeBox By default, this property is True and you can set it to False to hide the

Maximize button on the title bar. ControlBox By default, this property is True and you can set it to False to hide the

Minimize, Maximize and close button on the title bar. IsMDIContainer By default, this property is False and you can set it to True for generating

MDI application.

Events:

Event Name Description Load Occurs when the form is loaded for the first time. Closed Occurs before the form is closed. Closing Occurs when the form is closing HelpButtonClicked Occurs when the Help button is clicked.

2. Button Control

It represents a Windows button control.

Properties:

Property Name Description BackColor Gets or sets the background color of the control. DialogResult Gets or sets a value that is returned to the parent form when the button is

clicked. This is used while creating dialog boxes. Image Gets or sets the image that is displayed on a button control. Font Sets the font. Size Sets the size. Enable By default, this property is True and you can set it to False to disable the

working of button.

Page 32: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

32

Events:

Event Name Description GotFocus Occurs when the control receives focus. TextChanged Occurs when the Text property value changes. Validated Occurs when the control is finished validating. Click Occurs when user clicks the Button. FontChange Occurs when font is changed.

3. Label Control

It represents a standard Windows label.

Properties:

Property Name Description Autosize Gets or sets a value specifying if the control should be automatically

resized to display all its contents. BorderStyle Gets or sets the border style for the control. Text Used to Display the text. TextAlign Gets or sets the alignment of text in the label.

Events:

Event Name Description Leave Occurs when the input focus leaves the control. LostFocus Occurs when the control loses focus. TextChanged Occurs when the Text property value changes.

4. TextBox Control

It represents a Windows text box control.

Properties:

Property Name Description CharacterCasing Gets or sets whether the TextBox control modifies the case of characters

as they are typed. Multiline Gets or sets a value indicating whether this is a multiline TextBox control. PasswordChar Gets or sets the character used to mask characters of a password in a

single-line TextBox control. Readonly By default, this property is True and you can set it to False to make the

text Readonly. Visible By default, this property is True and you can set it to False to make the

Textbox invisible.

Page 33: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

33

Events:

Event Name Description TextAlignChanged Occurs when the TextAlign property value changes. TextChanged Occurs when the text in the textbox changes.

5. RadioButton Control

It enables the user to select a single option from a group of choices when paired with other RadioButton controls.

Properties:

Property Name Description CheckAlign Gets or sets the location of the check box portion of the radio button. Checked Gets or sets a value indicating whether the control is checked.

Events:

Event Name Description AppearanceChanged Occurs when the value of the Appearance property of the RadioButton

control is changed. CheckedChanged Occurs when the value of the Checked property of the RadioButton control

is changed.

6. Checkbox Control

It represents windows CheckBox control.

Properties:

Property Name Description CheckAlign Gets or sets the horizontal and vertical alignment of the check mark on the

check box. Checked Gets or sets a value indicating whether the check box is selected. ThreeState Gets or sets a value indicating whether or not a check box should allow three

check states rather than two.

Events:

Event Name Description AppearanceChanged Occurs when the value of the Appearance property of the check box is

changed. CheckedChanged Occurs when the value of the Checked property of the CheckBox control is

Page 34: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

34

changed. CheckStateChanged Occurs when the value of the CheckState property is changed.

7. ComboBox Control

It represents a Windows combo box control.

Properties:

Property Name Description DataBindings Gets the data bindings for the control. DataSource Gets or sets the data source for this ComboBox. DropDownStyle Gets or sets a value specifying the style of the combo box. Items Add the items to be displayed.

Events:

Event Name Description DropDown Occurs when the drop-down portion of a combo box is displayed. DropDownClosed Occurs when the drop-down portion of a combo box is no longer visible. SelectedIndexChanged Occurs when the SelectedIndex property of a ComboBox has changed.

8. ListView Control

It represents a Windows list view control, which displays a collection of items that can be displayed using one of four different views

Properties:

Property Name Description Columns Gets the collection of all column headers that appear in the control. HeaderStyle Gets or sets the column header style. Items Gets a collection containing all items in the control.

Events:

Event Name Description ColumnClick Occurs when a column header is clicked. ItemCheck Occurs when an item in the control is checked or unchecked.

Page 35: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

35

SelectedIndexChanged Occurs when the selected index is changed.

Explain ListBox control of Windows Form with example. Major functionality of Listbox class should be used.

A Windows Forms ListBox control displays a list of choices which the user can select from. List boxes are best used for displaying large number of choices.

Properties.

Property Name Description DataSource Indicates the list that the list box will use to get its

Items. Items The items in the list box. MultiColumn Indicates if values should be displayed in columns

Horizontally. Sorted Controls whether the list is sorted.

Events

Event Name Description ItemCheck Occurs when an item in the control is checked or unchecked. SelectedIndexChanged Occurs when the selected index is changed.

Following example shows functionality of listbox

On respective button Click events write the following code:

Private Sub btn_cnt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_cnt.Click 'counting the numer of items lbl_count.Text = ListBox1.Items.Count End Sub

Page 36: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

36

Private Sub btn_fll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_fll.Click ListBox1.Items.Add("Safety") ListBox1.Items.Add("Security") ListBox1.Items.Add("Governance") ListBox1.Items.Add("Good Music") ListBox1.Items.Add("Good Movies") ListBox1.Items.Add("Good Books") ListBox1.Items.Add("Education") ListBox1.Items.Add("Roads") ListBox1.Items.Add("Health") End Sub Private Sub btn_srt_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_srt.Click 'sorting the list ListBox1.Sorted = True End Sub Private Sub btn_clr_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_clr.Click 'clears the list ListBox1.Items.Clear() End Sub Private Sub btn_rmv_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_rmv.Click 'removing the selected item ListBox1.Items.Remove(ListBox1.SelectedItem.ToString) End Sub Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Me.Text = "listbox example" ' creating multi-column and multiselect list box ListBox1.MultiColumn = True ListBox1.SelectionMode = SelectionMode.MultiExtended End Sub

Clicking on fill the sort button sorts the content, while remove will remove item from listbox.

Page 37: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

37

What is Dialog? Explain different dialogs with its usage. (Font Dialog, Save Dialog, Folder Browser Dialog etc…)

There are many built-in dialog boxes to be used in Windows forms for various tasks like opening and saving files, printing a page, providing choices for colors, fonts, page setup, etc.

All of these dialog box control classes inherit from the CommonDialog class.

The ShowDialog method is used to display all the dialog box controls at run-time.

The values of DialogResult enumeration are:

Abort returnsDialogResult.Abort value, when user clicks an Abort button. Cancel returnsDialogResult.Cancel, when user clicks a Cancel button. Ignore returnsDialogResult.Ignore, when user clicks an Ignore button. No returnsDialogResult.No, when user clicks a No button. None returns nothing and the dialog box continues running. OK returns DialogResult.OK, when user clicks an OK button Retry returns DialogResult.Retry , when user clicks an Retry button Yes returns DialogResult.Yes, when user clicks an Yes button

1. Color Dialog Box

It represents a common dialog box that displays available colors along with controls that enable the user to define custom colors.

some important properties are :

AllowFullOpen Gets or sets a value indicating whether the user can use the dialog box to define custom colors.

AnyColor Gets or sets a value indicating whether the dialog box displays all available colors in the set of basic colors.

CanRaiseEvents Gets a value indicating whether the component can raise an event. Color Gets or sets the color selected by the user. CustomColors Gets or sets the set of custom colors shown in the dialog box. FullOpen Gets or sets a value indicating whether the controls used to create

custom colors are visible when the dialog box is opened

Page 38: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

38

ShowHelp Gets or sets a value indicating whether a Help button appears in the color dialog box.

SolidColorOnly Gets or sets a value indicating whether the dialog box will restrict users to selecting solid colors only.

some important methods are :

Reset Resets all options to their default values, the last selected color to black, and the custom colors to their default values.

RunDialog When overridden in a derived class, specifies a common dialog box. ShowDialog Runs a common dialog box with a default owner.

Drag and drop a label control, a button control and a ColorDialog control on the form.

Set the Text property of the label and the button control to 'Give me a new Color' and 'Change Color', respectively.

Change the font of the label as per your likings.

Double-click the Change Color button and modify the code of the Click event

On Button1 click event write the following code.

Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click If ColorDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then Label1.ForeColor = ColorDialog1.Color End If Label1.Color = ColorDialog1.Font End If End Sub

When you click the button and select the color following output will be generated.

Page 39: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

39

Here color of the text in label is changed to red. 2. Font Dialog Box.

It prompts the user to choose a font from among those installed on the local computer and lets the user select the font, font size, and color.

Properties of Font Dialog Box

Color Gets or sets the selected font color. Font Gets or sets the selected font. ShowApply Gets or sets a value indicating whether the dialog box contains an

Apply button. ShowColor Gets or sets a value indicating whether the dialog box displays the

color choice.

some important methods are :

Reset Resets all options to their default values, the last selected color to black, and the custom colors to their default values.

RunDialog When overridden in a derived class, specifies a common dialog box. ShowDialog Runs a common dialog box with a default owner.

Drag and drop a Label control, a Button control and a FontDialog control on the form and set text property of label to “Change My Font”.

Set the Text property of the button control to 'Change Font'.

Double-click the Change Font button and modify the code of the Click event:

Page 40: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

40

On Click event of button write the following code.

Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click If FontDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then Label1.Font = FontDialog1.Font End If End Sub

On Button click the Font dialog appears, select a font and click the OK button. The font of the label will be changed.

3. OpenFile Dialog Box

It prompts the user to open a file and allows the user to select a file to open.

Some of the important properties

CheckFileExists Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a file name that does not exist.

CheckPathExists Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a path that does not exist.

DefaultExt Gets or sets the default file name extension FileName Gets or sets a string containing the file name selected in the file

dialog box. Filter Gets or sets the current file name filter string, which determines the

choices that appear in the "Save as file type" or "Files of type" box in the dialog box.

Page 41: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

41

Some important methods

OpenFile Opens the file selected by the user, with read-only permission. The file is specified by the FileName property.

Reset Resets all options to their default value.

Drag and drop a PictureBox control, a Button control and a OpenFileDialog control on the form.

Set the Text property of the button control to 'Load Image File'.

Double-click the Load Image File button and modify the code of the Click event:

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click OpenFileDialog1.Filter = "Image Files|*.jpg|*.gif|*.png" If OpenFileDialog1.ShowDialog <> Windows.Forms.DialogResult.Cancel Then PictureBox1.Image = Image.FromFile(OpenFileDialog1.FileName) End If End Sub

The output of the above code will be

4. SaveFileDialog It prompts the user to select a location for saving a file and allows the user to specify the name of the file to save data. Some of the important properties:

Page 42: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

42

CheckFileExists Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a file name that does not exist.

CheckPathExists Gets or sets a value indicating whether the dialog box displays a warning if the user specifies a path that does not exist.

DefaultExt Gets or sets the default file name extension FileName Gets or sets a string containing the file name selected in the file

dialog box. Filter Gets or sets the current file name filter string, which determines the

choices that appear in the "Save as file type" or "Files of type" box in the dialog box.

OverwritePrompt Gets or sets a value indicating whether the Save As dialog box displays a warning if the user specifies a file name that already exists

Some important methods

OpenFile Opens the file selected by the user, with read-only permission. The file is specified by the FileName property.

Reset Resets all options to their default value.

Drag and drop a Label control, a RichTextBox control, a Button control and a SaveFileDialog control on the form.

Set the Text property of the label and the button control to 'We appreciate your comments' and 'Save Comments', respectively.

Double-click the Save Comments button and modify the code of the Click event as shown:

On button click write the following code

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK _ Then My.Computer.FileSystem.WriteAllText _ (SaveFileDialog1.FileName, RichTextBox1.Text, True) End If End Sub

Page 43: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

43

Write some text in the text box and click on the Save Comment button to save the text as a text file in your computer.

5. Print Dialog Box

It lets the user to print documents by selecting a printer and choosing which sections of the document to print from a Windows Forms application.

Some properties of print dialog box

Some important methods of print dialog box.

ShowDialog Runs a common dialog box with a default owner Reset Resets all options to their default value. RunDialog When overridden in a derived class, specifies a common dialog box.

Add a PrintDocument control, a PrintDialog control, button ,and label on the form.

Change the text of the button to 'Print' and label to Print this content Print Dialog.

Double-click the Print button and modify the code of the Click event as shown.

Public Class Form1 Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage Dim fn As New Font("Times New Roman", 24, FontStyle.Italic) e.Graphics.DrawString(Label1.Text, fn, Brushes.Aqua, 10, 100) e.Graphics.PageUnit = GraphicsUnit.Inch End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

AllowSelection Gets or sets a value indicating whether the Selection option button is enabled.

Documents Gets or sets a value indicating the PrintDocument used to obtain PrinterSettings

PrinterSettings Gets or sets the printer settings the dialog box modifies PrintToFile Gets or sets a value indicating whether the Print to file check box is

selected

Page 44: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

44

PrintDialog1.Document = PrintDocument1 If (PrintDialog1.ShowDialog() = DialogResult.OK) Then PrintDocument1.Print () End If End Sub End Class

Click the Print button to make the Print dialog box appears.

6. FolderBrowserDialog

Sometimes we need to prompt users for a folder path, rather than a filename, for such purpose we can use Folderbrowser Dialog box.

Some of the important properties are:

Some important methods are as follows

ShowDialog Opens a FolderBrowser dialog box with a default owner Reset Resets all options to their default value.

Drag and drop the folderbrowser dialog, label control and button control from toolbox on form1.

Change the text property of label to “Print The Path” and of button to “Browse”.

On button click event write the following code

Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click If (FolderBrowserDialog1.ShowDialog() <> Windows.Forms.DialogResult.Cancel) Then

Description Retrieves or sets the descriptive text displayed above the TreeView control in dialog box.

RootFolder Retrieves or sets the root folder where browsing starts. Selected Path Gets or sets the path selected by user. ShowNewFolderButton Gets or sets a value indicating whether or not New Folder button

appears in the folder dialog box.

Page 45: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

45

Label1.Text = FolderBrowserDialog1.SelectedPath End If End Sub End Class

When you run the application and click on button following form is displayed.

Explain MDI Form.

MDI stands for Multiple Document Interface.

The MDI application has an MDI parent and MDI child form, where MDI parent act as a container and every MDI child opens with MDI parent form.

Drag and drop a Menustrip control from toolbox on form1.

Enter Open Child Form as a menu item.

Add another Windows Form is the MDIForms application as Form2.vb

Change the IsMdiContainer property of the Form1 form to True to make this form as MDI parent form.

Double – click the Open Child Form menu item in the Form1 form and add the code below on the click event of the Open Child Form menu item.

Private Sub OpenChildFormToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OpenChildFormToolStripMenuItem.Click Dim NewMDIChild As New Form2 ()

Page 46: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

46

NewMDIChild.MdiParent = Me newMDIChild.Show() End Sub

Following output will occur on open child form click

Explain Structure Error handling in VB.Net with Example.

For Error Handling VB.Net provides Exception Handling, it has a predefined structure n how to use that and when to use exception handling is given below.

Exceptions provide a way to transfer control from one part of a program to another.VB.Net exception handling is built upon four keywords: Try, Catch, Finally and Throw.

Try:A Try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more Catch blocks.

Catch:A program catches an exception with an exception handler at the place in a program where you want to handle the problem.

Finally:The Finally block is used to execute a given set of statements, whether an exception is thrown or not thrown.

Throw:A program throws an exception when a problem shows up. This is done using a Throw keyword.

General structure of these blocks is as follow:

Try [Statements] Catch ex as [Exception Type] [Statements] Catch ex1 as [Exception Type] [Statements] Finally [Finally statements] EndTry

VB.Net provides a structured solution to the exception handling problems in the form of try and catch blocks.

Page 47: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

47

As shown in the example we had created one method which performs division, now it throws an error when user will perform division by 0.

Example of the Error Handling in VB.Net is as shown below,

Module Module1 Sub division(ByVal num1 As Integer, ByVal num2 As Integer) Dim result As Integer Try result = num1 \ num2 Catch e AsDivideByZeroException Console.WriteLine("Exception caught: {0}", e) Finally Console.WriteLine("Result: {0}", result) End Try End Sub Sub Main() division(25, 0) Console.ReadKey() End Sub End Module

We had created one method division which takes two parameters and in that method we had perform exception handling.

While calling method we are passing divider’s values is ‘0’, so error will be handle by the inbuilt error handling function DivideByZeroException.

Finally block will contains the result which we have to display at the end of the error handling.

What do you mean by Thread? State its advantages. Describe Thread priorities. Also give VB. Net code to implement it.

A thread is sequence of instructions that must be executed in a particular order to perform a specific task within a program.

A program in execution is called a process and a thread can be a part of executing program.

Threads share memory with other threads running in same application.

The execution of a process starts with Main() thread, which starts automatically, when a process executes;

Whereas other threads need to be start by passing methods of the Thread Class.

If a process consist more than one thread, it is called multithreading.

Advantages: Multithreaded processing can simultaneously run multiple procedures. For example, a word processor

application can check spelling as a separate task while you continue to work on the document. Because multithreaded applications divide programs into independent tasks, they can substantially improve performance in the following ways:

Page 48: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

48

• Multithreaded techniques can make your program more responsive because the user interface can remain active while other work continues. • Tasks that are not currently busy can yield processor time to other tasks. • Tasks can be stopped at any time. • You can set the priority of individual tasks higher or lower to optimize performance.

Thread Priority

The Priority property of the Thread class specifies the priority of one thread with respect to other. The .Net runtime selects the ready thread with the highest priority.The priorities could be categorized as: o Above normal – The thread with this priority can be scheduled after threads with Highest priority and

before those with Normal priority. o Below normal - The thread with this priority can be scheduled after threads having Normal priority and

before those with lowest priority. o Highest -The thread with this priority can be scheduled before threads with any priority. o Lowest -The thread with this priority can be scheduled after threads with any other priority. o Normal -The thread with this priority can be scheduled after threads having Above Normal priority and

before those with Below Normal priority. Once a thread is created its priority is set using the Priority property of the thread class.

VB.net Implementation is shown below.

Imports System Module Module1 Sub Main() Dim thd1 As New System.Threading.Thread(AddressOf ThreadoneProc) Dim thd2 As New System.Threading.Thread(AddressOf ThreadtwoProc) thd1.Start() thd2.Start() Console.ReadKey() End Sub Public Sub ThreadoneProc() Dim intcount As Integer For intcount = 1 To 200 Console.WriteLine("this is thread one" &intcount) Next End Sub Public Sub ThreadtwoProc() Dim intcount As Integer For intcount = 1 To 20 Console.WriteLine("this is thread two" &intcount) Next End Sub End Module

Page 49: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology VB.Net

49

Here for some interval thread1 will run than thread2 will run.

Page 50: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology ADO.Net

50

ADO.Net Compare classic ADO and ADO.Net. Also explain advantages of ADO.Net compare to classic ADO.

ADO ADO.Net It is a COM based Library It is a CLR based Library. ADO works in the connected mode to access data ADO.Net works in the disconnected mode to access data. Locking features is available Locking features is not available. Data is stored in Binary Format Data is stores in XML XML integration is not possible XML integration is possible. It uses RecordSet to store the data from datasource It uses Dataset to store the data from datasource. Using classic ADO, you can obtain information from one table or set of tables through join. You cannot fetch records from multiple tables independently

Dataset object of ADO.Net includes collection of DataTable wherein each DataTable will contain records fetched from a particular table. Hence multiple table records are maintained independently.

Firewall might prevent execution of Classic ADO ADO.Net has firewall proof and its execution will never be interrupted.

Classic ADO architecture includes client side cursor and server side cursor

ADO.Net architecture doesn’t include such cursors.

You cannot send multiple transaction using a single connection instance

You can send multiple transaction using a single connection instance.

Explain ADO.Net Architecture with figure.

Page 51: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology ADO.Net

51

The ADO.NET architecture has two main parts:

Data provider(connected Objects or Connection oriented objects)

Data Set (Disconnected objects or connectionless objects)

Data Provider The .NET framework Data Provider are components that have been explicitly designed for data

manipulation and fast, forward-only, read-only access to data.

.NET Framework data provider is used for connecting to a database, executing commands, and retrieving results.

The Data Provider has four core objects:

Connection:

The Connection objects provider connectivity to a data source.

Command:

The Command object enables access to database commands to return data, modify data, run stored procedures, and send or retrieve parameter information.

Data Reader The Data Reader provides a high-performance stream of data from the data source.

Data Adapter The Data Adapter provides the bridge between the Data Set object and the data source.

The Data Adapter uses command object to execute SQL commands at the data source to both load the Data Set with data and reconcile changes that were made to the data in the dataset back to the data source.

The following lists the data providers that are included in the .NET framework.

Data Provider Description SQL Server o Provides data access for Microsoft SQL server.

o Uses the System.Data.SqlClient namespace. OLEDB o For data sources exposed by using OLEDB.

o Uses the System.Data.OleDb namespace. ODBC o For data sources exposed by using ODBC.

o Uses the System.Data.Odbc namespace. Oracle o For Oracle data sources.

o Uses the System.Data.OracleClient namespace.

Data Set The dataset object is central to supporting disconnected, distributed data scenarios with ADO.NET.

The dataset is a memory-resident representation of data that provides consistent relational programming model regardless of the data source.

The dataset represents a complete set of data, including related tables, constraints, and relationship among the table.

The dataset has two major objects:

Page 52: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology ADO.Net

52

1. The Data Table Collection:

The Data table collection contains all the data table objects in a dataset.

A Data table is defined in the System.Data namespace and represents a single table of memory-resident data.

It contains a collection of columns represented by a data column collection, and constraints represented by a constraint collection, which together define the schema of the table.

2. The Data Relation Collection:

A relationship represented by the Data relation object, associated rows in one Data table with rows in another Data table.

A relationship is analogous to a join path that might exist between primary and foreign key columns in a relational database.

A data relation identifies matching columns in two tables of a dataset.

The essential element of a data relation are:

The name of the relationship

The name of the tables being related

The related column in each table

Relationship can be built with more than one column per table by specifying an array of Data Column objects as the key columns.

When you add a relationship to the data relation collection, you can optionally add a Unique key constraint to enforce integrity constraints when changes are made to related column values.

Explain different ADO.Net objects with Example.

ADO.Net is designed to help developers work efficiently with multi tier databases, across internet.

ADO.Net object model consists of two key components as follows: 1. Connected Model 2. Disconnected Model

Connected Model:

Connection:

The Connection object is the first component of ADO.NET. The connection object opens a connection to your data source.

Connection object helps in accessing and manipulating a database. Database transactions are also dependent upon the Connection object.

Command: The Command object is used to perform action on the data source. Command object can execute

stored procedures and T-SQL commands.

You can execute SQL queries to return data in a DataSet or a DataReader object. Command object performs the standard Select, Insert, Delete and Update T-SQL operations.

Page 53: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology ADO.Net

53

Data Reader:

The DataReader is built as a way to retrieve and examine the rows returned in response to your query as quickly as possible.

The data returned by a DataReader is always read only. This class was built to be a lightweight forward only, read only, way to run through data quickly

DataReader object works in connected model.

Data Adapter:

The DataAdapter takes the results of a database query from a Command object and pushes them into a DataSet using the DataAdapter.Fill() method.

Additionally the DataAdapter.Update() method will negotiate any changes to a DataSet back to the original data source.

Now as shown in the below example we had created one windows application to get the records of all braches with its branch code.

In our example we had created object of the connection, command, data reader and data adapter.

After click on the button, message box will be pop up and in that message box branch name and branch code will be displayed.

using System; using System.Windows.Forms; using System.Data; using System.Data.SqlClient; namespace WindowsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { stringconnetionString = null; SqlConnectionsqlCnn; SqlCommandsqlCmd ; SqlDataAdapter adapter = new SqlDataAdapter(); DataSet ds = new DataSet(); int i = 0; stringsql = null; connetionString = @"Data Source=MYPC\SQLExpress;Initial Catalog=AddressBook;Integrated Security=True"; sql = "Select * from Branch_Detail"; sqlCnn = new SqlConnection(connetionString); try

Page 54: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology ADO.Net

54

{ sqlCnn.Open(); sqlCmd = new SqlCommand(sql, sqlCnn); adapter.SelectCommand = sqlCmd; adapter.Fill(ds); for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++) { MessageBox.Show(ds.Tables[0].Rows[i].ItemArray[0] + " -- " + ds.Tables[0].Rows[i].ItemArray[1]); } adapter.Dispose(); sqlCmd.Dispose(); sqlCnn.Close(); } catch (Exception ex) { MessageBox.Show("Can not open connection ! "); } } } }

Disconnected Model Dataset

The DataSet Object is the parent object to most of the other objects in the System.Data namespace.

The dataset is a disconnected, in-memory representation of data.

DataSet also contains several methods for reading and writing XML, as well as merging other DataSets, DataTables and DataRows

Datatable

DataTable stores a table of information, typically retrieved from a data source.

DataTable allows you to examine the actual rows of a DataSet through rows and columns collections.

DataTable also stores metatable information such as the primary key and constraints.

DataRows The DataRow class permits you to reference a specific row of data in a DataTable.

This is the class that permits you to edit, accept, or reject changes to individual DataColumns of the row.

DataColumns: DataColumns is the building block of the DataTable. A number of such objects make up a table.

Each DataColumn object has a DataType property that determines the kind of data that the column is holding data table.

using System; usingSystem.Data; usingSystem.Data.SqlClient; namespaceDataTable_Datarow_DataColumn_Example {

Page 55: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology ADO.Net

55

class Program { static void Main(string[] args) { stringstrcon = @"Data Source=ANS-pc\SQLExpress;Initial Catalog=St;Integrated Security=True"; SqlConnection con = new SqlConnection(strcon); con.Open(); stringstrquery = "select * from Faculty"; SqlCommandcmd = new SqlCommand(strquery, con); cmd.CommandType = CommandType.Text; SqlDataAdaptersda = new SqlDataAdapter(cmd); DataTabledt = new DataTable(); sda.Fill(dt); Console.WriteLine("ID Name Initial"); foreach (DataRowdr in dt.Rows) { foreach (DataColumn dc in dt.Columns) { Console.Write(dr[dc]); Console.Write(" "); } Console.WriteLine(); } Console.ReadKey(); } } }

As shown in our example we had created one console application, in that console application we had created object of the datatable, datarow, and datacolumn.

With the help of these objects we can manage all these data easily and can be manipulated easily.

All of these object and its method will be worked in the disconnected model, it will not be worked in the connected model.

Explain Typed Dataset.

A typed dataset is very much similar to a normal dataset. But the only difference is that the schema is already present for the same.

Hence any mismatch in the column will generate compile time errors rather than runtime error as in the case of normal dataset.

Also accessing the column value is much easier than the normal dataset as the column definition will be available in the schema.

The basic program or schema as shown below:

Page 56: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology ADO.Net

56

//Create DataAdapter SqlDataAdapterda Emp = new SqlDataAdapter("SELECT empno,empname,empaddress FROM EMPLOYEE",conn); //Create a DataSet Object EmployeeDS dsEmp = new EmployeeDS (); //Fill the DataSet daEmp.Fill(dsEmp,"EMPLOYEE"); //Let us print first row and first column of the table Console.Write(dsEmp.EMPLOYEE[0].empno.ToString()); //Assign a value to the first column dsEmp.EMPLOYEE[0].empno = "12345";//This will generate compile time error.

How to create a Typed DataSet?? 1. Open VS .Net IDE and Click on File --> New --> Project and Select Console Application. 2. Enter name for the project. Say TypedDataSetTest. 3. Right click on the solution and click on Add--> Add New Item will show a dialog box. 4. Select DataSet from templates pane, give the name (Say TypedDs.xsd) and click on Open. This will add file by

name TypedDs.xsd to the solution. 5. Click on the Server Explorer browse to the database and drop the table on the TypedDs.xsd file. 6. This dataset can be used in the same manner as the normal dataset to get the data.

Page 57: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology C#.Net

57

C#.Net Explain Constructor and Destructors in c#.

A class constructor is a special member function of a class that is executed whenever we create new objects of that class.

A constructor will have exact same name as the class and it does not have any return type.

A default constructor does not have any parameter.

If you need a constructor can have parameters. Such constructors are called parameterized constructors. This technique helps you to assign initial value to an object at the time of its creation.

A destructor is a special member function of a class that is executed whenever an object of its class goes out of scope.

A destructor will have exact same name as the class prefixed with a tilde (~) and it can neither return a value nor can it take any parameters.

Destructor can be very useful for releasing resources before coming out of the program like closing files, releasing memories etc. Destructors cannot be inherited or overloaded.

Using System; Using System.Collections.Generic; Using System.Linq; Using System.Text; namespace Constructor { Class cons { Public cons () { int a = 10; int b = 20; int c = a * b; Console.WriteLine ("No Parameter:s {0}",c); } Public cons (int a, int b) { int c = a * b; Console.WriteLine("With Parameter: {0}",c); } ~cons() { Console.WriteLine("Destructor Called...!!!"); Console.ReadKey(); } } Class Program {

Page 58: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology C#.Net

58

Static void Main (string [] args) { Cons c1 = new cons (); Cons c2 = new cons (3, 4); } } }

As shown in the example we had created two constructor, first constructor with no parameters and the second constructor with two parameters.

Now when object of the class will be destroyed then destructor will be called as shown in example.

Explain function overloading and operator overloading in c#.

The process of creating more than one method in a class with same name is called as method overloading.

In C# no need to use any keyword while overloading a method either in same class or in derived class.

While overloading methods, a rule to follow is the overloaded methods must differ either in number of arguments they take or the data type of at least one argument and return type.

Using System; Using System.Collections.Generic; Using System.Linq; Using System.Text; Namespace Method_Overlaoding { Class Base_Class { Public int sum(int a, int b) { Return a + b; } Public float sum(int a, float b) { return a + b; } } Class Derived_Class :Base_Class { Public int sum(int a, int b, int c) { return a + b + c; } } Class Program { Static void Main (string[] args) { Derived_Classobj = newDerived_Class(); Console.WriteLine (obj.sum (10, 20));

Page 59: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology C#.Net

59

Console.WriteLine (obj.sum(10,30.23f)); Console.WriteLine (obj.sum(10, 20, 30)); Console.ReadKey () } }} As shown in our example we had created two classes Base_Class and Derived_Class, now in our main

method we had created object of the Derived_Class.

Now with the help of that object we are calling method with different number of arguments, while passing the arguments if two methods have same number of arguments but datatype of arguments are different then while passing the values we have to tell the compiler, that which type of the argument you are passing, as shown in our example “10, 30.23f”, here we are telling the compiler that which method have the second parameter as a float that method we have to call.

Operator Overloading: Overloaded operators are functions with special names the keyword operator followed by the symbol for

the operator being defined.

Like any other function, an overloaded operator has a return type and a parameter list.

Example shows implements the addition operator (+) for a user-defined class Box. It adds the attributes of two Box objects and returns the resultant Box object.

Using System; Namespace OperatorOvlApplication { Class Box { Private double length;// Length of a box Private double breadth;// Breadth of a box Private double height;// Height of a box Public double getVolume() { return length * breadth * height;} public void setLength(double len){ length=len;} public void setBreadth(double bre){ breadth=bre;} public void setHeight(double hei){ height=hei;} // Overload + operator to add two Box objects. Public static Box operator+ (Box b, Box c) { Box box=new Box (); box.length=b.length+c.length; box.breadth=b.breadth+c.breadth; box.height=b.height+c.height; return box; } } Class Tester { Static void Main (string[]args) {

Page 60: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology C#.Net

60

BoxBox1=new Box (); // Declare Box1 of type Box BoxBox2=new Box (); // Declare Box2 of type Box BoxBox3=new Box (); // Declare Box3 of type Box double volume =0.0;// Store the volume of a box here // box 1 specification Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0); // box 2 specification Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0); // volume of box 1 volume =Box1.getVolume(); Console.WriteLine ("Volume of Box1 : {0}", volume); // volume of box 2 volume=Box2.getVolume(); Console.WriteLine ("Volume of Box2 : {0}", volume); // Add two object as follows: Box3=Box1+Box2; // volume of box 3 volume=Box3.getVolume(); Console.WriteLine("Volume of Box3 : {0}", volume); Console.ReadKey(); } } }

Explain Array and Array List in .Net with Example. Explain various methods of Array List Array:

An array stores a fixed-size sequential collection of elements of the same type.

An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type.

A specific element in an array is accessed by an index.

Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables.

All arrays consist of contiguous memory locations.

Page 61: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology C#.Net

61

The lowest address corresponds to the first element and the highest address to the last element.

One dimensional array can be declared as

double [ ] sample = {23.45,56.78,78.90};

int [] marks = new int[5] {86,78,89,56,34};

int [] marks = new int[] {86,78,89,56,34};

Multi-dimensional arrays are also called rectangular array.

The simplest form of the multidimensional array is the two-dimensional array. A two-dimensional array is, in essence, a list of one-dimensional arrays.

A two dimensional array can be thought of as a table which will have x number of rows and y number of columns.

Example of multi dimensional array is as following;

class program { public static void Main(string[] args) { int[,] sample = new int[2,3] { {1,2,3},{4,5,6} }; int i, j; for (i = 0; i < 2; i++) { for (j = 0; j < 3; j++ ) {Console.WriteLine("sample{0} ,{1} = {2} ", i, j, sample[i,j]); }} Console.ReadKey();}}

ArrayList:

Represents an array of objects whose size is dynamically increased as required.

Basic operation for ArrayList: o Add: Add an Item in an ArrayList o Insert: Insert an Item in a specified position in an ArrayList o Remove: Remove an Item from ArrayList o Remove At: remove an item from a specified position o Sort: Sort Items in an ArrayList

Methods of the ArrayList:

Add:

How to add an Item in an ArrayList ?

Number[0] Number[2] Number[3] Number[4] Number[5] Number[6] …………

First Element Last Element

Page 62: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology C#.Net

62

Syntax: ArrayList.add (object)

Object: The Item to be add the ArrayList

Array Listarr;

arr.Add ("Item1");

Insert:

How to Insert an Item in an Array List?

Syntax: ArrayList.insert (index, object)

Index: The position of the item in an ArrayList

object : The Item to be add the ArrayList

Array Listarr;

arr.Insert(3, "Item3");

Remove:

How to remove an item from arrayList ?

Syntax : ArrayList.Remove(object)

object : The Item to be add the ArrayList

arr.Remove("item2");

Remove At:

How to remove an item in a specified position from an ArrayList?

Syntax : ArrayList.RemoveAt(index)

index : the position of an item to remove from an ArrayList

ItemList.RemoveAt(2)

Sort:

How to sort ArrayList ?

Syntax : ArrayList.Sort()

Code: ArayList Step-1 Design a Win form with simple Button Control

Double click on the button ArrayList which is shown in the figure, now click event of the button we have to write the following code,

using System.Collections; private void btnArraylist_Click(object sender, EventArgs e){

Page 63: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology C#.Net

63

int i = 0; ArrayList ItemList = newArrayList(); ItemList.Add("Item4"); ItemList.Add("Item5"); ItemList.Add("Item2"); ItemList.Add("Item1"); ItemList.Add("Item3"); MessageBox.Show ("Shows Added Items"); for (i = 0; i<= ItemList.Count - 1; i++) { MessageBox.Show(ItemList[i].ToString()); } //insert an item ItemList.Insert(3, "Item6"); //sort itemms in an arraylist ItemList.Sort(); //remove an item ItemList.Remove("Item1"); //remove item from a specified index ItemList.RemoveAt(3); MessageBox.Show("Shows final Items the ArrayList"); for (i = 0; i<= ItemList.Count - 1; i++) { MessageBox.Show(ItemList[i].ToString()); }}

Explain Concept in c# (Modifiers, Properties and Indexers, Attributes and Reflection) Modifiers

PUBLIC The item is visible to any other code, no restrictions on the use of a class declared as Public.

PRIVATE The item is visible only inside the type to which it belongs, members in class A that are marked private are accessible only to methods of class A.

PROTECTED The item is visible only to any derived type, members in class A that are marked protected are accessible to methods of class A and also to methods of classes derived from class A.

INTERNAL The item is visible only within its containing assembly, members in class A that are marked internal are accessible to methods of any class in A’s assembly.

INTERNAL PROTECTED The item is visible to any code within its containing assembly and also to any code inside a derived type, members in class A that are marked protected internal are accessible to methods of class A, to methods of classes derived from class A, and also to any class in A’s assembly.

Page 64: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology C#.Net

64

Properties and Indexers (What is Property? What is indexer? Differentiate Property & Indexer. Explain it with Suitable Example.)

Properties are named members of classes, structures, and interfaces. Member variables or methods in a class or structures are called Fields.

Properties are an extension of fields and are accessed using the same syntax.

They use accessors through which the values of the private fields can be read, written or manipulated.

Properties do not name the storage locations. Instead, they have accessors that read, write, or compute their values.

For example, let us have a class named Student, with private fields for age, name and code. We cannot directly access these fields from outside the class scope, but we can have properties for accessing these private fields.

An indexer allows an object to be indexed like an array.

When you define an indexer for a class, this class behaves like a virtual array.

You can then access the instance of this class using the array access operator ([ ]).

Declaration of behavior of an indexer is to some extent similar to a property. Like properties, you use get and set accessors for defining an indexer.

However, properties return or set a specific data member, whereas indexers returns or sets a particular value from the object instance.

In other words, it breaks the instance data into smaller parts and indexes each part, gets or sets each part.

Defining a property involves providing a property name. Indexers are not defined with names, but with this keyword, which refers to the object instance.

Properties Indexer Identified by its name. Identified by its signature. Accessed through a simple name or a member access.

Accessed through an element access.

Can be a static or an instance member. Must be an instance member. A get accessor of a property has no parameters. A get accessor of an indexer has the same formal

parameter list as the indexer. A set accessor of a property contains the implicit value parameter.

A set accessor of an indexer has the same formal parameter list as the indexer, in addition to the value parameter.

Example of the properties and indexer are as following,

namespace Properties_Example (Properties Example) { class Property_Examle { private string sub_name; private int sub_code; public string prt_sub_name { get { return sub_name; } set { sub_name = value; } } public int prt_sub_code //Property Declared for sub_code

Page 65: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology C#.Net

65

{ set { sub_code = value; } get { return sub_code; } } public void WriteData() { Console.WriteLine("Subject Name:{0}",sub_name); Console.WriteLine("Subject Code:{0}\n",sub_code); } } class Program { static void Main(string[] args) { Property_Examle p = new Property_Examle(); p.prt_sub_name = "IAP"; p.prt_sub_code = 2350701; p.WriteData(); p.prt_sub_name = "Java"; p.prt_sub_code = 2350703; p.WriteData(); Console.ReadKey(); }}} namespace Indexers (Indexer Example) { class Indexers_Example { private string[] sub_name = new string[5]; public string this[int index] { get { return sub_name[index]; } set { sub_name[index] = value; } }} class Program { static void Main(string[] args) { Indexers_Example ie = new Indexers_Example(); ie[0] = "IAP"; ie[1] = "Java"; ie[2] = "MCCP"; ie[3] = "Project-I"; ie[4]= "Computer Networks"; Console.WriteLine("Subject of 5th C.E."); for (int i = 0; i < 5; i++) { Console.WriteLine("Subject-{0}: {1} ",i+1,ie[i]); }

Page 66: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology C#.Net

66

Console.ReadKey(); }}} Attributes and Reflection

An attribute is a declarative tag that is used to convey information to runtime about the behaviors of various elements like classes, methods, structures, enumerators, assemblies etc., in your program.

You can add declarative information to a program by using an attribute. A declarative tag is depicted by square ([ ]) brackets placed above the element it is used for.

Attributes are used for adding metadata, such as compiler instruction and other information such as comments, description, methods and classes to a program.

Reflection objects are used for obtaining type information at runtime. The classes that give access to the metadata of a running program are in the System.Reflection namespace.

The System.Reflection namespace contains classes that allow you to obtain information about the application and to dynamically add types, values and objects to the application.

Uses of Reflection:

It allows view attribute information at runtime.

It allows examining various types in an assembly and instantiate these types.

It allows late binding to methods and properties

It allows creating new types at runtime and then performs some tasks using those types.

Explain Reflection API in C# with Example. Reflection is the ability of a managed code to read its own metadata for the purpose of finding assemblies,

modules and type information at runtime. Reflection provides objects that encapsulate assemblies, modules and types.

By using Reflection in C#, one is able to find out details of an object, method, and create objects and invoke methods at runtime.

using System; using System.Reflection; namespace Reflection_API { Public class MyClass { Public virtual intAddNumb(int numb1, int numb2) { int result = numb1 + numb2; return result; } } Class Program { Static void Main (string[] args) { Console.WriteLine ("\nReflection.MethodInfo"); MyClass myClassObj = new MyClass(); Type myTypeObj = myClassObj.GetType();

Page 67: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology C#.Net

67

Method InfomyMethodInfo = myTypeObj.GetMethod("AddNumb"); object[] mParam = new object[] { 5, 10 }; Console. Write("\nFirst method - " + myTypeObj.FullName + " returns " + myMethodInfo.Invoke(myClassObj, mParam) + "\n"); Console.ReadKey ();}}}

Unsafe code in c#

The unsafe code or the unmanaged code is a code block that uses a pointer variable.

A pointer is a variable whose value is the address of another variable i.e., the direct address of the memory location

Like any variable or constant, you must declare a pointer before you can use it to store any variable address.

The general form of a pointer variable declaration is:

type *var-name;

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace UnsafeCode_Examle { Class Unsafe_Example { Public void UnsafeMethod() { unsafe { int x = 10; int* ptr1 = &x; Console.WriteLine((int)ptr1); Console.WriteLine(*ptr1); } } } class Program { staticvoid Main(string[] args) { { Unsafe_Exampleobj = new Unsafe_Example(); obj.UnsafeMethod(); Console.ReadKey(); } } }}}

Page 68: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology C#.Net

68

Now to after writing this code, the code will not directly run because visual studio doesn’t allow to run the unsafe application.

So to execute this application, go to the Solution Explorer Right Click on the Solution Name Go to the Properties Build Check the check box Allow unsafe code.

Now you can run this application without any error.

Explain Events & Delegates with Example in c#

A delegate is a reference type variable that holds the reference to a method. The reference can be changed at runtime.

Delegates allow methods to be passed as parameters.

Delegates can be chained together; for example, multiple methods can be called on a single event.

A delegate can refer to a method, which have the same signature as that of the delegate.

Once a delegate type has been declared, a delegate object must be created with the new keyword and be associated with a particular method.

When creating a delegate, the argument passed to the new expression is written like a method call, but without the arguments to the method.

Events are basically a user action like key press, clicks, mouse movements etc., or some occurrence like system generated notifications.

The events are declared and raised in a class and associated with the event handlers using delegates within the same class or some other class.

The class containing the event is used to publish the event. This is called the publisher class

Some other class that accepts this event is called the subscriber class.

A publisher is an object that contains the definition of the event and the delegate.

A subscriber is an object that accepts the event and provides an event handler.

To declare an event inside a class, first a delegate type for the event must be declared. Public delegate void SimpleDelegate();

Next, the event itself is declared, using the event keyword: public static event SimpleDelegate Simply;

namespace Event_With_Delegates { delegate void SimpleDelegate(); class EventExample { public static event SimpleDelegate Simply; private static void Hello() { Console.WriteLine("It's Event with Delegates Example"); } private static void Hello1() { Console.WriteLine("It's Delegates Example");

Page 69: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology C#.Net

69

} static void Main(string[] args) { Simply += new SimpleDelegate(Hello); Simply +=new SimpleDelegate(Hello1); Simply(); Console.ReadKey(); } }

Explain Stream Reader & Stream Writer class for File Stream.

File handling is an unmanaged resource in your application system. It is outside your application domain (unmanaged resource). It is not managed by CLR.

Data is stored in two ways, persistent and non-persistent manner.

When you open a file for reading or writing, it becomes stream.

Stream: Stream is a sequence of bytes traveling from a source to a destination over a communication path.

The two basic streams are input and output streams. Input stream is used to read and output stream is used to write.

The System.IO namespace includes various classes for file handling.

The parent class of file processing is stream. Stream is an abstract class, which is used as the parent of the classes that actually implement the necessary operations.

The primary support of a file as an object is provided by a .NET Framework class called File. This static class is equipped with various types of (static) methods to create, save, open, copy, move, delete, or check the existence of a file.

StreamWriter Class: The StreamWriter class in inherited from the abstract class TextWriter. The TextWriter class represents a

writer, which can write a series of characters.

The following table describes some of the methods used by StreamWriter class.

Close Closes the current StreamWriter object and the underlying stream

Flush Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream

Write Writes to the stream

WriteLine Writes data specified by the overloaded parameters, followed by end of line

using System; using System.Text; using System.IO;

Page 70: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology C#.Net

70

namespace FileWriting_SW { class Program { class FileWrite { public void WriteData() { FileStream fs= new FileStream("c:\\test.txt", FileMode.Append, FileAccess.Write); StreamWriter sw = new StreamWriter(fs); Console.WriteLine("Enter the text which you want to write to the file"); string str = Console.ReadLine(); sw.WriteLine(str); sw.Flush(); sw.Close(); fs.Close(); } } static void Main(string[] args) { FileWrite wr = new FileWrite(); wr.WriteData(); } }}

StreamReader Class:

The StreamReader class is inherited from the abstract class TextReader. The TextReader class represents a reader, which can read series of characters.

The following table describes some methods of the StreamReader class.

Close Closes the object of StreamReader class and the underlying stream, and release any system resources associated with the reader

Peek Returns the next available character but doesn't consume it

Read Reads the next character or the next set of characters from the stream

ReadLine Reads a line of characters from the current stream and returns data as a string

Seek Allows the read/write position to be moved to any position with the file

using System; using System.IO; namespace FileReading_SR { class Program { class FileRead {

Page 71: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology C#.Net

71

public void ReadData() { FileStream fs = new FileStream ("c:\\test.txt", FileMode.Open, FileAccess.Read); StreamReader sr = new StreamReader(fs); Console.WriteLine ("Program to show content of test file"); sr.BaseStream.Seek(0, SeekOrigin.Begin); string str = sr.ReadLine(); while (str != null) { Console.WriteLine (str); str = sr.ReadLine(); } Console.ReadLine(); sr.Close(); fs.Close(); } } static void Main(string[] args) { FileRead wr = new FileRead(); wr.ReadData(); } }}

What is Exception in c#? Explain Exception handling in c# with Example.

An exception is a problem that arises during unsafe code executes of a program.

Exceptions provide a way to transfer control from one part of a program to another. C# exception handling is built upon four keywords: try, catch, finally and throw.

try: A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch blocks.

catch: A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception

finally: The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.

throw: A program throws an exception when a problem shows up. This is done using a throw keyword.

A try/catch block is placed around the code that might generate an exception.

Code within a try/catch block is referred to as protected code.

The exception classes in C# are mainly directly or indirectly derived from the System.Exception class.

Some of the exception classes derived from the System.Exception class are the System.ApplicationException and System.SystemException classes.

Using System; Namespace ErrorHandlingApplication {

Page 72: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology C#.Net

72

Class DivNumbers { int result; DivNumbers() { result=0; } Public void division (int num1,int num2) { try { result= num1 / num2; } Catch (DivideByZeroException e) { Console.WriteLine ("Exception caught: {0}", e); } finally { Console.WriteLine ("Result: {0}", result); } } Static void Main(string[]args) { DivNumbers d =newDivNumbers(); d.division(25,0); Console.ReadKey (); } } }

What is GDI+? Give example showing use of GDI+?

The Graphics Device Interface (GDI) is a Microsoft Windowsapplication programming interface and core operating system component responsible for representing graphical objects and transmitting them to output devices such as monitors and printers.

GDI is responsible for tasks such as drawing lines and curves, rendering fonts and handling palettes.

It is not directly responsible for drawing windows, menus, etc.; that task is reserved for the user subsystem, which resides in user32.dll and is built atop GDI.

Graphic Classes’ Methods:

DrawArc Draws an arc from the specified ellipse. DrawBezier Draws a cubic bezier curve. DrawBeziers Draws a series of cubic Bezier curves.

Page 73: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology C#.Net

73

DrawClosedCurve Draws a closed curve defined by an array of points. DrawCurve Draws a curve defined by an array of points. DrawEllipse Draws an ellipse. DrawImage Draws an image. DrawLine Draws a line. DrawPath Draws the lines and curves defined by a GraphicsPath. DrawPie Draws the outline of a pie section. DrawPolygon Draws the outline of a polygon. DrawRectangle Draws the outline of a rectangle. DrawString Draws a string. FillEllipse Fills the interior of an ellipse defined by a bounding rectangle. FillPath Fills the interior of a path. FillPie Fills the interior of a pie section. FillPolygon Fills the interior of a polygon defined by an array of points. FillRectangle Fills the interior of a rectangle with a Brush. FillRectangles Fills the interiors of a series of rectangles with a Brush. FillRegion Fills the interior of a Region.

Graphic’s Object:

Brush Used to fill enclosed surfaces with patterns,colors, or bitmaps. Pen Used to draw lines and polygons, including rectangles, arcs, and pies Font Used to describe the font to be used to render text

Color Used to describe the color used to render a particular object. In GDI+ color can be alpha blended

Brush Used to fill enclosed surfaces with patterns,colors, or bitmaps.

Example of the GDI+ is as following,

Step-1 Open the visual studio, click on the new windows application with C# language,

Step-2 After that drag and drop two button on the windows forms.

Step-3 Double click on the button1 and write the code which is shown in the example

Step-4 Double click on the button1 and write the code which is shown in the example

Step-5 now run the application.

Page 74: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology C#.Net

74

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace GDI_ { Public partialclassForm1 :Form { public Form1() { InitializeComponent(); } Private void button1_Click (object sender, EventArgs e) { Graphics g = this.CreateGraphics(); Pen p = newPen(Color.Tomato,2); g.DrawEllipse(p,150,25,50,50); g.DrawEllipse(p, 160, 35, 10, 10); g.DrawEllipse(p, 180, 35, 10, 10); g.DrawArc(p, 150, 35, 50, 50, 45, 90); g.DrawRectangle(p, 150, 75, 50, 100); g.DrawLine(p, 175, 175, 150, 250); g.DrawLine(p, 175, 175, 200, 250); } Private void button2_Click (object sender, EventArgs e) { Graphics g = this.CreateGraphics(); SolidBrush sb = new SolidBrush(Color.Teal);

Page 75: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology C#.Net

75

g.FillEllipse(sb, 150, 25, 50, 50); sb.Color = Color.Black; g.FillEllipse(sb, 160, 35, 10, 10); g.FillEllipse(sb, 180, 35, 10, 10); sb.Color = Color.Black; g.FillPie(sb, 150, 35, 50, 30, 45, 90); sb.Color = Color.GreenYellow; g.FillRectangle(sb, 150, 75, 50, 100); } }}

Output

Page 76: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology ASP.Net

76

ASP.Net

Introduction to ASP.Net:

Asp.net Refers as Active Server Page .net which is server side object oriented programming language.

Asp.net is language of Microsoft.net framework to develop web applications.

Benefits using Asp.net:

Easier OOP Language Quick Drag & Drop control Code Separation

Easier database operations Version Compatibility High security

Easy app. Development Highly Integrated IDE Etc

Asp.net uses to develop dynamic web pages, websites, web services and web applications.

Asp.net is built on the CLR (Common Language Runtime) that allows user to write Asp.net program using any .net framework supported languages like C#, VB, Visual C++, J# etc.

Asp.net also Supports ADO.Net (ActiveX Data Objects.Net) that helps to connect and work with data stored in database.

Asp.net also provides Web services through which Same Service can be applicable to more than one website. E.g. weather, cricket live score etc.

Asp.net provides everything Readymade such as Rich controls, Validation Controls, data bound controls, AJAX controls for developing easier, fast and highly dynamic web applications.

Directory Structure of Asp.net:

Bin App_Code App_GlobalResources App_LocalResources

App_Data App_Themes App_Browsers App_Webreferences

Differentiate ASP and ASP.Net

ASP.Net ASP Language OOP language Scripting Language Inheritance Supports Doesn’t Support Code behind files Separate file for code and data both Single file for code and data Configuration files Machine.config, Web.Config No Configuration files Custom Controls Supports Doesn’t Support Database Language ADO.Net with XML integration Simple ADO with limited functionalities

Page 77: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology ASP.Net

77

Explain ASP.Net Webpage life cycle & Events When a user request for Asp.net page, the page undergoes many stages that is called its life cycle.

Various stages in ASP.Net Web Page

Stages What is done in Stages?

Page Request Asp.Net checks that request of the page is new or old, if new then it compiles and executes that page and if request is old, cached copy will be returned.

Start Request And Response properties are set and using IsPostBack property new or old request can be identified.

Page Initialization

In page, each control is initialized. Themes will be loaded. If requested page is old then post back data is not loaded.

Load If current request is old one, the property of control is loaded with data from view and control state.

Postback Event Handling

If request for the page is old one, then any event handler can be invoked.

Validation After loading the page, the validation controls are used to invoke Validate method for error free access.

Rendering All controls on the page are saved. During rendering, render method for each control on page and writes it to output stream object of page response property.

Unload Request and response properties of the page are unloaded and cleaning performed if required.

Asp.Net Pages Life Cycle Events

Events Working Of Events

PreInit First event of Asp.net Page Life cycle. It checks whether the page is processed for the first time or not. It also creates and recreates dynamic controls, sets master page and themes. It sets and gets profile property.

Init This event is raised after initialization of all controls and applying skin properties and initialize or read control properties.

Load This event is called to set control properties and establish database connections. Page class calls OnLoad event of web page after that calls event for each child control, until page is loaded.

Explain various Server Controls of ASP.Net Asp.net provides many built in server controls that can be easily drag and drop to the web pages Controls:

Text Box Check Box Radio Button Label

Button Hyper Link Image Etc.

Page 78: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology ASP.Net

78

Common Properties for all controls:

ID Runat Text CssClass

Height Width Auto post back Visible

All controls are derived from System.Web.UI.WebControls name space.

Each server control must have runat=”Server ” property to execute.

Text Box:

This control is used to take input from user into a default string format.

<asp:TextBox ID=”txtName” runat=”server” AutoPostBack=”true” height=”10px” width=”10px” visible=”true”> </asp:TextBox>

Example:

Check Box:

This control is used to select multiple values from a list.

<asp:CheckBox ID=”cbApple” runat=”server” AutoPostBack=”true” visible=”true” text=”Apple”> <asp:CheckBox>

Example:

Apple Banana Grapes Guava

Radio Button:

This control is used to select Single value from a list.

<asp:RadioButton ID=”rbMale” runat=”server” AutoPostBack=”True” Visible=”True” Group=”one” Text=”Male”> </asp:RadioButton>

<asp:RadioButton ID=”rbFemale” runat=”server” AutoPostBack=”True” Visible=”True” Group=”one” Text=”Female”> </asp:RadioButton>

Example:

Male Female

Label:

This Control is used to display information on the web Page.

<asp:Label ID=”Label1” runat=”server” Visible=”True” Text=”Hi This Is Asp.Net!!!”> <asp:Label>

Enter your Name….

Page 79: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology ASP.Net

79

Example: Hi this Is Asp.Net !!!

Button:

This control provides firing of various events at a single click.

Button Provides page navigation as well as event firing.

<asp:Button ID=”btnClickMe” runat=”server” Text=”Click Me” OnClick=”Button1_Click” />

Example:

HyperLink:

This control provides easy navigation between various Pages.

NavigateUrl = address of destination page

<asp:HyperLink ID=”hlHome” runat=”Server” NavigateUrl=”Home.aspx” Text=”Home Page”></asp:HyperLink>

Example:

Home navigate to Home page on single Click

Image:

This Control is used to display images on the web page.

ImageUrl = Location of the image in application folder or in computer.

AlternateText= alternate text if image is not found

<asp:Image ID=”Img” runat=”server” ImageUrl=”~/images/ab.jpg” AlternateText=”Jerry”/>

Example:

Explain various Validation Controls of ASP.Net

Asp.Net provides various validation controls for error free access for the web page. This validation Controls validates the input for controls. So that any mismatching and faulty data cannot be inserted to the data storage. All Validations controls are runs at client side.

Various Validation controls are:

Click Me

Page 80: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology ASP.Net

80

Required Field Validator Range Validator Regular Expression Validator Compare Validator Custom Validator Validation Summary

Common Properties

Property Name Description Required /Optional ID Unique ID for every Validation control Required Runat Declared as Asp.Net Control Required ControlToValidate ID of the control for which Validation control is used Required ErrorMessage Displays message when validation violates Required Validation Group To be the part of particular validation Group Optional Display Display Error message either static or dynamically Optional

Required Field Validator

It provides validation for emptiness of any control. This Validator is applied to such controls where input is necessary.

<asp:TextBox ID=”TextBox1” runat=”server” AutoPostBack=”true” height=”10px” width=”10px” visible=”true”> </asp:TextBox> <asp:RequiredFieldValidator ID=”rfv1” runat=”server” ControlToValidate=”TextBox1” ErrorMessage=”Text Box must not empty”></ asp:RequiredFieldValidator> Example:

Range Validator It provides validation for range of an input by setting minimum value and maximum value. This Validator is used when input is taken between certain type of values within certain Range To specify The data for the same datatype e.g. number, date etc.. E.g. Salary must between 10000 and 50000. Special Attributes:

MinValue MaxValue Type

<asp:TextBox ID=”txtVal” runat=”server” AutoPostBack=”true” height=”10px” width=”10px”

Text Box must not empty

Page 81: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology ASP.Net

81

visible=”true”> </asp:TextBox> <asp:RangeValidator ID=”rv1” runat=”server” ControlToValidate=”txtval” ErrorMessage=”Salary between 10000 to 50000” type=”Integer” MinValue=”10000” MaxValue=”50000”> </asp:RangeValidator> Example

Regular Expression Validator It provides complex Kind of validation that is related with some pattern or some logic. Such as email validation. Validation can be done using regular expressions to validate special inputs. Special attributes:

Validation expression

<asp:TextBox ID=”TextBox1” runat=”server” AutoPostBack=”true” height=”10px” width=”10px” visible=”true”> </asp:TextBox> <asp:RegularExpressionValidator ID=”rev1” runat=”server” ControlToValidate=”TextBox1” ValidationExpression=”^[0-9 \’ ‘]+” ErrorMessage=”Number is not Valid”> </asp:RegularexpressionValidator>

Example

Compare Validator:

It compares two controls of same data type or with specific value.

Validation can be done on two controls.

E.g. Comparison of password and re-password

Special attribute:

Control to Compare

<asp:TextBox ID=”TextBox1” runat=”server” AutoPostBack=”true” height=”10px” width=”10px” visible=”true”> </asp:TextBox> <asp:TextBox ID=”TextBox2” runat=”server” AutoPostBack=”true” height=”10px” width=”10px” visible=”true”> </asp:TextBox> <asp:CompareValidator ID=”cv1” runat=”server” ControlToValidate=”TextBox2” ControlToCompare=”TextBox2” ErrorMessage=”Value doesn’t match” ></asp:CompareValidator>

abc@yahoo_in Email is not valid

9999 salary between 10000 to 50000

Page 82: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology ASP.Net

82

Example:

Custom validator: This validator validates the input as per user’s preferences.

It is having a javascript function that calls the validation logic.

E.g. birthdate validation, user must be above 18 years etc.

Special Attributes

ClientValidationFunction

Funaction written in code behind file

<asp:TextBox ID=”txtBdate” runat=”server” AutoPostBack=”true” height=”10px” width=”10px” visible=”true”> </asp:TextBox> <asp:CustomValidator ID=”cv1” runat=”server” ControlToValidate=”TextBox2” ClientValidationFunction=”checkAge” ErrorMessage=”Age must be above 18” ></asp:CustomValidator> Check Age Function: Private CheckAge() { String s = txtbdate.Text.Trim(); DateTime d = DateTime.Now() – (DateTime)s; If(d.Years < 18 ) { Cv1.ErrorMessage =”Age must above 18”; }

Example:

Validation Summary: Validation summary provides all the validation errors as a list at one time at the end.

Special attributes:

ShowSummary (Boolean)

Explain various List Controls in ASP.Net

Asp.Net provides many built in List controls to show the data in the form of list.

User can select one or more value from the list.

List controls are many and they are used as per user’s requirement

22/10/1999 Age must above 18

abc@yahoo_in Value doesn’t match abc@yahooin

Page 83: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology ASP.Net

83

Controls Functions Examples

DropDownList Provides a list of items with only one item visible at a time and user can select single or multiple items.

Country List

ListBox Provides all the data in a box format and user can select one and more data. List of fruits

CheckBoxList Provides a checkbox with each data and user can select more than one item. Hobbies

RadioButtonList Provides a list from which only one item can be select. Gender

Bulleted List Used to show Important Highlighted data. Imp. Points

All the list controls having two main properties:

1. DataValueField = It is used store the value of the member. 2. DataTextField = It is used to store the data that is used for display the member information on the screen.

Let us take a simple example to explain all controls at once.

You can add Items via Back End using ListItem Class.

Each and every item in the each list control is stored in List Item Class.

Adding items to list control (from the code behind)

Add() – Used to add list item to the list of items

Remove() - Used to remove list item from list of items

E.g.

Foreach(ListItem li in ddlCountry.Items) { li.Items.Add(new ListItem(txtData.Text.Trim(),txtValue.Text.Trim())); // Adding List item with Value. li.Items.Remove(txtData.Text.Trim()); // Remove list item from list control }

Example <asp:ListBox ID="ListBox1" runat="server"> <asp:ListItem>Apple</asp:ListItem> <asp:ListItem>Banana</asp:ListItem> <asp:ListItem>Mango</asp:ListItem> </asp:ListBox> <asp:CheckBoxList ID="CheckBoxList1" runat="server"> <asp:ListItem>Cricket</asp:ListItem>

Page 84: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology ASP.Net

84

<asp:ListItem>football</asp:ListItem> <asp:ListItem>Hockey</asp:ListItem> </asp:CheckBoxList>

<asp:DropDownList ID="DropDownList1" runat="server"> <asp:ListItem>Rajkot</asp:ListItem> <asp:ListItem>hadala</asp:ListItem> <asp:ListItem>Junagadh</asp:ListItem> </asp:DropDownList> <asp:RadioButtonList ID="RadioButtonList1" runat="server"> <asp:ListItem>Male</asp:ListItem> <asp:ListItem>Female</asp:ListItem> </asp:RadioButtonList> <asp:BulletedList ID="BulletedList1" runat="server"> <asp:ListItem>News</asp:ListItem> <asp:ListItem>Events</asp:ListItem> </asp:BulletedList>

Explain various Data Controls of ASP.Net

Data controls are used to display records from database in a repeated manner.

The results can be customized according to the query style and user preferences.

Custom edit and paging and select record type functionalities are ready made available.

Just drag and drop data controls and display the records according to your need.

Data controls having different purpose. o Grid View is used for when you need to display records in tabular format and perform operations on

same record. o Repeater controls are used to display data with specific and custom standard. o Data List is used when you need to repeat controls with complete custom format.

Some Controls are mentioned and explained below:

Page 85: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology ASP.Net

85

Grid View, Data List, Repeater Control Grid View

<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="Id" DataSourceID="SqlDataSource1"> <Columns> <asp:BoundFieldDataField="Id" HeaderText="Id" InsertVisible="False" ReadOnly="True" SortExpression="Id" /> <asp:BoundFieldDataField="Name" HeaderText="Name" SortExpression="Name" /> <asp:BoundFieldDataField="College" HeaderText="College" SortExpression="College" /> </Columns> </asp:GridView> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString%>" SelectCommand="SELECT * FROM [Student]"></asp:SqlDataSource><br />

Special Attribute: BoundField

It is used for creating data field by giving data value field from sqldatasource.

TemplateField

It is used to add custom control to the particular cell to all records. Properties:

When you bound data controls by attaching data source directly and generate auto insert, update and delete statements, it will give you following elements.

Enable Paging: to enable paging to data control

Enable Sorting: to enable field wise sorting

Enable Deleting: to enable delete of particular column

Repeater Control

<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource2"> <HeaderTemplate> <table border=1 width="150px"> <tr><td>Id</td> <td>Name</td> <td>College</td></tr></table> </HeaderTemplate> <ItemTemplate> <table border=1 width="150px"> <tr><td><asp:Label ID="id" Text='<%#Eval("Id") %>' runat="server"></asp:Label></td> <td><asp:Label ID="Name" Text='<%#Eval("Name") %>' runat="server"></asp:Label></td> <td><asp:Label ID="College" Text='<%#Eval("College") %>' runat="server"></asp:Label></td></tr> </table>

Page 86: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology ASP.Net

86

</ItemTemplate> </asp:Repeater> <asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString%>" SelectCommand="SELECT * FROM [Student]"></asp:SqlDataSource>

Data List

<asp:DataList ID="DataList1" runat="server" DataKeyField="Id"

DataSourceID="SqlDataSource3" RepeatDirection="Horizontal">

<ItemTemplate>

Id:<asp:Label ID="Id" runat="server" Text='<%# Eval("Id") %>' /><br />

Name:<asp:Label ID="Name" runat="server" Text='<%# Eval("Name") %>' /> College:<asp:Label ID="College" runat="server" Text='<%# Eval("College") %>' /></ItemTemplate>

</asp:DataList>

<asp:SqlDataSource ID="SqlDataSource3" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString%>"

SelectCommand="SELECT * FROM [Student]"></asp:SqlDataSource>

All the attributes are explained in previous example.

The Output can be like this:

Explain various Rich server Controls in ASP.Net Rich server controls are used to deploy rich applications in very easy manner.

Such as to rotate advertisements in webpage.

Rich customized online calendar control.

Ad rotator Ad rotator controls are used to rotate advertisements on web screen using XML.

XML file make the control more effective.

Page 87: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology ASP.Net

87

Structure of XML File:

<Advertisements> // shows the Advertisement file <Ad> // used for each advertisement element <ImageUrl>rose1.jpg</ImageUrl> // Define image url for particular element <NavigateUrl>http://www.1800flowers.com </NavigateUrl> // used for navigation to other page <AlternateText> Order flowers and more</AlternateText> // display text when image is not found <Impressions>20</Impressions> // how many times repaeats this image out of 100 <Keyword>flowers</Keyword> // To displays some special category images </Ad> </Advertisements>

Example Ad rotator <asp:AdRotator ID="AdRotator1" runat="server" AdvertisementFile ="~/ads.xml" onadcreated="AdRotator1_AdCreated" /> //Ads.xml file// <Advertisements> <Ad> <ImageUrl>rose1.jpg</ImageUrl> <NavigateUrl>http://www.1800flowers.com</NavigateUrl> <AlternateText> Order flowers, roses, gifts and more </AlternateText> <Impressions>20</Impressions> <Keyword>flowers</Keyword> </Ad> <Ad> <ImageUrl>rose2.jpg</ImageUrl> <NavigateUrl>http://www.babybouquets.com.au</NavigateUrl> <AlternateText>Order roses and flowers</AlternateText> <Impressions>20</Impressions> <Keyword>gifts</Keyword> </Ad> <Ad> <ImageUrl>rose3.jpg</ImageUrl> <NavigateUrl>http://www.flowers2moscow.com</NavigateUrl> <AlternateText>Send flowers to Russia</AlternateText> <Impressions>20</Impressions> <Keyword>russia</Keyword> </Ad>

</Advertisements>

Page 88: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology ASP.Net

88

Output:

Calendar Control Calendar controls are used to maintain online calendar.

Customized calendar is developed with reminders, birthdays etc.

Example Calendar Control: <h3> Your Birthday:</h3> <asp:CalendarID="Cal1" runat="server" SelectionMode="DayWeekMonth" onselectionchanged="Calendar1_SelectionChanged"> </asp:Calendar> </div> <p>Todays date is: <asp:LabelID="lblday" runat="server"></asp:Label></p> <p>Your Birthday is: <asp:LabelID="lblbday" runat="server"></asp:Label></p> //Code Behind file// protected void Calendar1_SelectionChanged(object sender, EventArgs e) { lblday.Text = Calendar1.TodaysDate.ToShortDateString(); lblbday.Text = Calendar1.SelectedDate.ToShortDateString();}

Page 89: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology ASP.Net

89

Explain various State management policies in ASP.Net

You can preserve the state of the application either at the server or the client end.

The state of a web application helps you to store the runtime changes that have been made to the web application.

For example, a user selects and saves some products in the shopping cart of an online shopping websites.

For that you have to store it to state, otherwise the changes are discarded.

There are various methods for storing state information.

Hidden fields

Cookies

Query Strings

Application state

Session State

Profile Properties

Page-Level State [View State] In Asp.Net, the ViewState property is used to store the page-level state of a web page, the ViewState

property the state information of a single user, as long as the user is working with the page. The ViewState property is used when a form is submitted and presented second time to a user, as it retains

the information entered in the form’s controls first time. The VIEWSTATE property at each page is initialized and stored in ViewState. The string is assigned to the Value attribute of VIEWSTATE field and is sent as a part of the web page.

ViewState[“User-definedKey”] = user-definedValue; Response.Write(ViewState[“user-DefinedKey”]);

Cookies

Cookie is a small amount of data that is stored as a text file on client system or in client browser’s session.

It stores site specific information of a user, such as user name and inputs.

Cookies can be created temporarily with the specific expiration time.

Cookies can be created permanent, called as persistent cookies.

When a page is requested, the client sends information in form of cookies along request information.

The server reads cookie and extract value.

HttpCookie kukie; If (Request.Cookies[txtName.text] == null) Kukie = new HttpCookie(txtName.Text, txtValue.Text); Kukie.values.Add(txtvalname.Text, txtvalvalue.Text); Kukie.Expires = System.DateTime.Now.AddDays(1); Response.AppendCookie(Kukie);

Page 90: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology ASP.Net

90

ASP.Net Session State Session is defined as the period of time, in which a user interacts with a web application. Session state is a collection of data, which are related to a session and stored on a server. Session state acts as memory in the form of a hash table with key-value pair. Each user is given unique session ID when the session begins. Session state can be implemented in the following Modes:

In-Process In this mode, session state memory is kept within the Asp.Net process. This mode applies to the web

applications that are hosted on a single server.

Out-of-Process In this mode, you get performance of reading from memory and the reliability of a separate process that

manages the state for all servers.

SQL Server Here reliability of data within a web application with help of database. When you are using SQL server

the session is stored in SQL on a different server than to your website server. One special server is used to store session.

Configuring Session state Following parameters with example coding:

<configuration> <sessionState Mode = “inproc” or “Outproc” or “Sqlserver” Cookieless=”false” Timeout=”20” Sqlconnectionstring= “data source=127.0.0.1;user id = <userid>; password = <Password>” Server=”127.0.0.1” Port=”42424”/> </configuration>

Read and write Data from Session:

Write Data to Session

Session[“variable name”] = Some value; e.g. Session[“Email”]= txtEmail.text;

Read Data from session

Some control = Session[“Variable name”]; e.g. lblsession.Text = Session[“Email”].ToString();

Page 91: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology ASP.Net

91

Explain the concepts of Master Page and Nested Master Page in ASP.Net Master page

Master pages enable the template based development of a website. Master defines the overall layout of a web application and all pages are derived from master page so that

they have a common look. Master page having .master extension. Define master page using @Master directive on top a web page. The Content of master pages is fixed for all derived pages. To place the changing data for every pages

master page provide <ContentPlaceHolder> where each page hold its local content. <asp:ContentPlaceHolder ID=”cph” runat=”server”>

<%@ Page language=”C#” MasterPageFile=”~/masterpage.master” Title= “contentPage”>

Major characteristics of a master page: Defining common properties of a website, such as header, footer, banners, navigation menus and

other elements that can be accessed by the content pages. Allowing single or multiple content pages to access single or multiple master pages. Displaying the content of each content page in content place holder. Master pages are of two types:

Simple master Page

Nested Master Page:

Here you can merge the master page and content page. Simply, Main master page another master page for some selected pages that is called nested master

page. It is used to give common and distinguish look from master page for some special module

Simple Master Page

Content Page

Final Page

Page 92: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology ASP.Net

92

Explain the ASP.Net Themes with Skin file

Themes in Asp.Net enable you to define the style properties and the change the appearance of a Web Page. They provides User friendly interface with similar all over look with optimized code. You can set theme in master page directive in master page as well in web.config also. Theme can be defined as collection of element that is common look and feel for whole application. The Key Features are as follows:

Providing flexibility to easily change the appearance of all web pages just by making changes in few template files with minimum possible efforts.

Providing various options to customize a web page. E.g. in Orkut, you can change website appearance as per your requirement.

Themes contain three elements:

Skin It is having .skin extension that contains tags, property settings and formatting options for server side

controls. Such as Label, TextBox and Button.

Skin is divided into following two groups:

o Default: Default skin is applied automatically to all the controls of the same type in web page, when

theme is applied to the page. SkinID attributes is used to determine whether the applied skin is default or not. If SkinID is

not present in current tag means it is a default skin.

o Named: It is a customized skin that is applied to controls when theme is applied.

Nested master Page

Content page 1 Master Page 1 Content page 2 Master Page 2

Final Page 1 Final Page 2

Page 93: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology ASP.Net

93

It has SkinID property which allows different styles to different controls.

CSS Refers to a mechanism of adding fonts, colors, styles and behavior to web pages.

CSS is used to provide the visual inheritance to all the web pages in the website.

It is an Asp.Net file with .css extension and applies a style sheet as a part of theme in a web page.

It should include in App_theme folder.

Image Helps the web page making more attractive, interactive and user friendly.

In addition to skins and CSS, themes can also include other resource file as script files or sound files.

Page 94: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology Web Services & XML

94

Web Services and XML

What is web Service in .Net? Write a Program to create Web Service and another program to consume same web service. (Take simple web method to add two integer numbers)

A web service is an entity that you can develop to provide particular functionality over the internet.

For example weather information, live score of cricket, simple and compound interest formula.

For such purposes you make a web service for each. It will useful not only for one website but also for many other websites those are providing same facilities.

Developer just needs to consume the web services and then its required function is working.

So, it is better to develop a web service common to all instead of writing the same business logic for all websites.

And moreover web service provides common functionalities and results for all websites.

And web service irrespective from any programming language as it is based on XML so can be useful to all language based applications.

Web Service messages are formatted as XML, a standard way for communication between two incompatible system. And this message is sent via HTTP, so that they can reach to any machine on the internet without being blocked by firewall.

Take an example to demonstrate web service

Right click on project Add new item select web services OK

public class WebService1 : System.Web.Services.WebService { [WebMethod] public string HelloWorld() { return "Hello World"; } [WebMethod] public int sum(int a, int b) { return a+b; } }

Now you have to add web reference to achieve web services working for any application.

Web services for solution only

Web services for local machine

Web services over internet

Consume web service Make an object of web service and you can call any method within that web service.

public partial class counter : System.Web.UI.Page

Page 95: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology Web Services & XML

95

{ protected void Page_Load(object sender, EventArgs e){} protected void btnAdd_Click(object sender, EventArgs e) { WebService1 intsum = new WebService1(); int a = Convert.ToInt32(txt1.Text); int b = Convert.ToInt32(txt2.Text); lblSum.Text=intsum.sum(a,b).ToString(); } Designer Page: No 1<asp:TextBox ID="txt1" runat="server"></asp:TextBox><br /> No 2<asp:TextBox ID="txt2" runat="server"></asp:TextBox><br /><br /> <asp:Button ID="btnAdd" runat="server" Text="Add" onclick="btnAdd_Click" />&nbsp; <asp:Label ID="lblSum" runat="server"></asp:Label>

Output Would be:

Page 96: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology Advanced .Net Concepts

96

Advanced .Net Concepts

AJAX controls with Update Panel

AJAX is asynchronous Java Script and XML AJAX is not a programming language for developing websites. It is a collection of technologies to refresh the highly dynamic page according to page update approach not

according to page replacement approach. AJAX controls are very useful because in a highly loaded graphical web page to refresh the content of small

control, we have to reload the whole page, it took too much time. As well as tedious for user to use such web sites. But AJAX controls are capable that they only update the data of required contents only. Not the whole page. So page is quick updated. And easy to use graphically loaded web pages for highly dynamic interactions.

Script manager Control It helps to implement AJAX functionalities in Asp.Net website. On which page you want AJAX functionalities you have to add Script manager control. It is responsible for managing client scripts for AJAX enabled website. Without Script Manager Control AJAX functionalities are useless.

Update Panel Control

<form id="form1"runat="server"> <asp:ScriptManagerID="ScriptManager1"runat="server"/> <asp:UpdatePanelrunat="server" id="UpdatePanel"updatemode="Conditional"> <Triggers> <asp:AsyncPostBackTriggercontrolid="UpdateButton2"eventname="Click"/> </Triggers> <ContentTemplate> <asp:Labelrunat="server" id="DateTimeLabel1"/> <asp:Buttonrunat="server" id="UpdateButton1"onclick="UpdateButton_Click" text="Update"/> </ContentTemplate> </asp:UpdatePanel> <asp:UpdatePanelrunat="server" id="UpdatePanel1"updatemode="Conditional"> <ContentTemplate> <asp:Labelrunat="server" id="DateTimeLabel2"/> <asp:Buttonrunat="server" id="UpdateButton2"onclick="UpdateButton_Click" text="Update"/> </ContentTemplate> </asp:UpdatePanel> </form> Code Behind File

Page 97: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology Advanced .Net Concepts

97

protectedvoidUpdateButton_Click(object sender, EventArgs e) { DateTimeLabel1.Text =DateTime.Now.ToString(); DateTimeLabel2.Text =DateTime.Now.ToString();}

Explain WPF with its features

Windows Presentation Foundation (WPF) is a means for the programmer to create Windows applications possessing rich user interfaces and graphics which the classic .NET Windows applications lack. The initial version of WPF was released as a part of .NET 3.0 and it was really like a preview of WPF itself. The actual version of WPF was released as a part of .NET Framework 3.5.

High level architecture of WPF:

Features of WPF Declarative Programming

WPF application paves the way for the developers to define the thick client UI in a declarative way, which was never supported by the traditional .NET windows forms. Tasks like defining a template for a control, creating a control hierarchy and similar work would be much easier if it is done in a declarative fashion. In WPF declarative programming was made possible with the introduction of Extensible Application Markup Language (XAML). It can be compared to the HTML part in a web user interface.

Independent of screen resolution

Page 98: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology Advanced .Net Concepts

98

This is a neat feature of WPF. What I mean by independency of screen resolution is, the WPF user interface will look better even on a screen with low resolution. It uses DirectX components whereas the Windows Forms applications make use of the User 32 components of a machine. WPF framework has the Media Integration Layer (MIL) in order to talk to the DirectX components. The direct components impose a vector based graphics on the WPF user interface. The below screen shot will show you the difference between the Windows forms UI and WPF UI at lower resolutions of the screen.

Control Inside a control WPF allows you to provide not only the text but it also allows you to define a control as a content of another basic control like a Button. This feature is truly astonishing fact for the developers and this lets the world know, what the power of WPF is when it comes to user interfaces. You can have a Text Box inside a Button for example.

Control transforms o WPF contains a handful of 2D transforms which will enable you to change the size, position, rotation

angle and also allows skewing. Control transforms can be performed in two

waysLayoutTransform and RenderTransform. o Rotate transform o Scale transform o Skew transform o Translate transform o Matrix transformation

Control Templates What if the user wants to change the shape of a button, this will definitely sound weird for .NET developers. Now it can be done in WPF by defining the control template. For example you can declare a Button on your WPF window and can change its shape to elliptical.

2D, 3D, graphics, animation and Media This is a vast topic in WPF, in my opinion these features make WPF a much more unique technology which mixes both controls and graphics to be tightly coupled. I will be touching some key features under this topic.

Explain WCF and simple Example

Windows Communication Foundation (WCF) is a framework for building service-oriented applications.

Using WCF, you can send data as asynchronous messages from one service endpoint to another. A service endpoint can be part of a continuously available service hosted by IIS, or it can be a service hosted in an application.

An endpoint can be a client of a service that requests data from a service endpoint.

The messages can be as simple as a single character or word sent as XML, or as complex as a stream of binary data. A few sample scenarios include:

o A secure service to process business transactions. o A service that supplies current data to others, such as a traffic report or other monitoring service. o A chat service that allows two people to communicate or exchange data in real time.

Page 99: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology Advanced .Net Concepts

99

o A dashboard application that polls one or more services for data and presents it in a logical presentation.

o Exposing a workflow implemented using Windows Workflow Foundation as a WCF service. o A Silver light application to poll a service for the latest data feeds. o In summary, WCF is designed to offer a manageable approach to creating Web services and Web

service clients.

Features of WCF Service Orientation

Interoperability

Multi message patterns

Service Metadata and data contracts

Security

Durable messages

Transactions

AJAX and REST support

Extensibility

Steps to follow:

In Visual Studio New Project WCF WCF Service library Give name as myLib and click OK. Add Service1.vb and Iservice1.vb Files to project. Now Right Click on project Add reference Select System.ServiceModel Then open Service1.vb Imports System ImportsSystem.ServiceModel PublicClass Service1 Implements IService1 PublicFunctionGetName(ByVal value AsString) AsStringImplements IService1.GetData Console.WriteLine("Hello {0}", value) ReturnString.Format("Hello {0}", value) EndFunction EndClass Then open Iservice1.vb <ServiceContract()> PublicInterface IService1 <OperationContract()> FunctionGetData(ByVal value AsString) AsString

Page 100: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology Advanced .Net Concepts

100

EndInterface Now host and run service File Add new Project Select Console Application Name WcHost Add Module1.vb Right click on WcHost and Add reference. Imports System ImportsSystem.ServiceModel ImportsSystem.ServiceModel.Description Imports myLib.Service1 Module Module1 Sub Main() ' Step 1 Create a URI to serve as the base address DimbaseAddressAsNew Uri("http://localhost:8000/SayHelloService") ' Step 2 Create a ServiceHost instance DimselfHostAsNewServiceHost(GetType(myLib.Service1), baseAddress) Try ' Step 3 Add a service endpoint ' Add a service endpoint selfHost.AddServiceEndpoint(GetType(myLib.IService1), _ NewWSHttpBinding(), "HelloService") ' Step 4 Enable metadata exchange. DimsmbAsNewServiceMetadataBehavior() smb.HttpGetEnabled = True selfHost.Description.Behaviors.Add(smb) ' Step 5 Start the service selfHost.Open() Console.WriteLine("The service is ready.") Console.WriteLine("Press <ENTER> to terminate service.") Console.WriteLine() Console.ReadLine() ' Close the ServiceHostBase to shutdown the service. selfHost.Close() CatchceAsCommunicationException Console.WriteLine("An exception occurred: {0}", ce.Message) selfHost.Abort() EndTry EndSub

Page 101: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology Advanced .Net Concepts

101

EndModule Build WcHost.

Create console application WcClient Add Reference System. ServiceModel Add Service reference Put "http://localhost:8000/SayHelloService" in address. Now run wcHost.exe, you can locate it in ..\wcHost\bin\Debug folder. When wcHost runs, then click go in add service reference window and wait. Select Service 1 and Click Ok Configure WCF Client Open WcClientapp.config from solution explorer. <?xml version="1.0" encoding="utf-8" ?> <configuration> <system.diagnostics> <sources> <!-- This section defines the logging configuration forMy.Application.Log --> <source name="DefaultSource"switchName="DefaultSwitch"> <listeners> <add name="FileLog"/> <!-- Uncomment the below section to write to the Application Event Log --> <!--<add name="EventLog"/>--> </listeners> </source> </sources> <switches> <addname="DefaultSwitch"value="Information"/> </switches> <sharedListeners> <addname="FileLog" type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" initializeData="FileLogWriter"/> <!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log --> <!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/>--> </sharedListeners> </system.diagnostics> <system.serviceModel> <bindings>

Page 102: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology Advanced .Net Concepts

102

<wsHttpBinding> <bindingname="WSHttpBinding_IService1"/> </wsHttpBinding> </bindings> <client> <endpointaddress="http://localhost:8000/SayHelloService/HelloService" binding="wsHttpBinding"bindingConfiguration="WSHttpBinding_IService1" contract="ServiceReference1.IService1"name="WSHttpBinding_IService1"> <identity> <userPrincipalNamevalue="ERP001\Manager1"/> </identity> </endpoint> </client> </system.serviceModel> </configuration> In Moduel1.vb Imports System ImportsSystem.ServiceModel Imports wcClient.ServiceReference1 Module Module1 Dim Client AsNew Service1Client Sub Main() Console.WriteLine("Client Window") Console.WriteLine("{0}", Client.GetData(Console.ReadLine())) ' Step 3: Closing the client gracefully closes the connection and cleans up resources. Client.Close() Console.WriteLine() Console.WriteLine("Press <ENTER> to terminate client.") Console.ReadLine() EndSub EndModule Build And Run WcClient

Page 103: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology Advanced .Net Concepts

103

Silverlight in ASP.Net

Silver light is a web based technology that allows web designers and developers to stretch the boundaries of web application development.

It is an integration of the rich user interface of desktop applications and the transparency of other web languages, such as html and java script.

Silver light allows you to develop web applications that contain high-fidelity multimedia content and eye catching visual effects.

The primary components of silver light include HTML, Java script, XAML and .net Framework.

While developing silver light applications you will be using the combination of varied features of these technologies.

It has two main features:

.net framework for silver light

Core presentation framework

.Net framework for silver light Silver light comes with a smaller version of .net framework.

The .net frame work in silver light component also enables you to easily access data and services at remote locations through WCF.

In addition, you can use HTTP objects, cross-domain HTTP requests, Really simple Syndication (RSS) feeds, JSON and SOAP services in Silver light application.

Core Presentation Framework It is a component in Silver light that offers the features and services for designing the UI of silver light

applications through controls, styles, templates, 2-d vectors graphics, animations and multimedia.

This component also allows you to incorporate user input and interactivity through various input devices.

Page 104: Net Introduction - Engineering Colleges in Rajkot · Data and XML Classes (ADO.NET, SQL, XML, etc…) These classes extend the FCL to support data management and XML manipulation

Darshan Institute of Engineering & Technology Advanced .Net Concepts

104

Moreover you can also manage the digital rights of multimedia contents used in silver light application through this component.

Silver light controls The controls in silver light correspond to different XAML elements.

E.g Border, button, Canvas, Content Control, Data Grid, data Picker, Image etc.