1. Unit-05/Lecture-01
Interfacing with the End User
Interfacing with the End User:-
An Interface type is an abstraction. We use an Interface to create a contract. Each type that
implements the Interface must have certain Functions. And this makes it possible to call those
Functions through an Interface reference.
ASP.Net Programming Model
ASP.Net provides two types of programming models:
• Web Forms - this enables you to create the user interface and the application logic that
would be applied to various components of the user interface.
• WCF Services - this enables you to remote access some server-side functionalities.
For this chapter, you need to use Visual Studio Web Developer, which is free. The IDE is almost
same as you have already used for creating the Windows Applications.
Web Forms:-
Web forms consists of:
• User interface
• Application logic
User interface consists of static HTML or XML elements and ASP.Net server controls. When you
create a web application, HTML or XML elements and server controls are stored in a file with
.aspx extension. This file is also called the page file.
The application logic consists of code applied to the user interface elements in the page. You
write this code in any of .Net language like, VB.Net, or C#.
Example:-
Let us create a new web site with a web form, which will show the current date and time, when
a user clicks a button. Take the following steps:
2. 1. Select File -> New -> Web Site. The New Web Site Dialog Box appears.
2. Select the ASP.Net Empty Web Site templates. Type a name for the web site and select a
location for saving the files.
3. You need to add a Default page to the site. Right click the web site name in the Solution
Explorer and select Add New Item option from the context menu. The Add New Item
dialog box is displayed:
4. Select Web Form option and provide a name for the default page. We have kept it as
Default.aspx. Click the Add button.
5. The Default page is shown in Source view
6. Set the title for the Default web page by adding a value to the
7. To add controls on the web page, go to the design view. Add three labels, a text box and
a button on the form.
8. Double-click the button and add the following code to the Click event of the button:
Protected Sub Button1_Click(sender As Object, e As EventArgs) _
Handles Button1.Click
3. Label2.Visible = True
Label2.Text = "Welcome to Tutorials Point: " + TextBox1.Text
Label3.Text = "You visited us at: " + DateTime.Now.ToString()
End Sub
When the above code is executed and run using Start button available at the Microsoft Visual
Studio tool bar, the following page opens in the browser:
Enter your name and click on the Submit button:
4. VB.NET -Graphic User Interface- Some basic controls:
Basic Controls
Label is a control in which icons or uneditable text is displayed.
Textbox is a control in which the user inputs data from the keyboard. This area also can display
information.
Button is a control that triggers an event when clicked.
CheckBox is a control that is either selected or unselected.
ComboBox is a drop-down list of items from which the user can make a selection
either by clicking an item in the list or by typing into a box.
ListBox is a control in which a list of items is displayed. The user can make a
selection from the list by clicking on any item. Multiple elements can be selected.
Panel is a container control in which controls can be placed.
PictureBox is a control that allows the user to display images.
Label : common
5. properties
and events
Description
Common
properties Font
Text
TextAlign
The font of text to be displayed on the label
The text of the label
The alignment of the text(left, center, right,
bottom, middle, top)
TextBox : common
properties and events
Description
Common properties
Font Text Multiline
ReadOnly
The font of text to be displayed on the textbox
The text of the textbox
If true; the textbox can accept multi lines of text.
If false, the textbox accept a single line of text
If true, the text of the textbox cannot be edited.
False is the default value of the control.
Common events Key
press
TextChanged
This event is triggered when the keyboard is
pressed.
This event is triggered when the text of the
textbox is changed.
Button : common
properties and events
Description
Common properties Text The text displayed on the control
Common events
Click
This event is triggered when the button is
clicked.
CheckBox : common
properties and events
Description
Common properties
Checked Text Common
events
CheckedChanaged
Indicates whether the checkbox is checked
The text displayed on the right of the checkbox
This event is triggered when the checkbox is
checked or unchecked.
6. ComboBox : common
properties and events Description
Common properties
Items
The collection of items of the combobox
Common events
SelectedIndexChanged
This event is triggered when an item of the
combobox is selected.
ListBox : common
properties and events
Common properties
Items
The collection of items of the listbox
Common events
electedIndexChanged
This event is triggered when an item of the
listbox is selected.
Panel : common
properties and events
Description
Common properties
AutoScroll
BorderStyle
Indicates whether scroll bars appear when the
panel is not big enough to contain controls. Sets
the border of the panel.
PictureBox : common
properties and events
Description
Common properties
Image
SizeMode
Set the image to display in the picturebox.
Controls image sizing and positioning (Values:
Normal, StretchImage, AutoSize, CenterImage).
Common events Click
This event is triggered when the picturebox is
clicked.
7. Unit-05/Lecture-02
Reports handling, Design issue of report handling
Reports handling- Report data with CrystalReport:-
Visual Studio 2008 comes with a useful reporting tool--Crystal Report that enables you to
generate reports to show your data retrieved from a database. In this page we will discuss
about how to get data stored in a table of a Microsoft SQL SERVER database to display on a
form of your project.
Suppose that you want to create a report to display the data from TblProduct of Sale And Stock
database. This database exists in Microsoft SQL SERVER(in my machine, i have SQL SEVER 2005).
The user that has a right to login to the database is called as and its password is 123. This login
information is useful when we connect the database using VB.NET code. The steps below will
help you to get thing done.
Step 1: Add a DataSet to the project
+Now create a new project in Visual Studio 2008. In my case, i created a project called
ReportVB. Right-click the project name->Add->New Item. Under Categories, select Data and
under Templates select Dataset.
S.NO RGPV QUESTIONS Year Marks
Q.1
8. On the Server Explorer next to the active dataset window, click Connect to Database icon to add
a connection to the database server. On the Add Connection dialog, click Change button of the
Data source block to show the Change Data Source dialog.
Then on the Change Data Source dialog, select Microsoft SQL Server. After that you will see a
new Add Connection dialog that shows the Server name box. In this box, you need to enter the
name of your SQL SERVER. In my case, this name is Dcc-pc.In the Log on to the server block,
select Use SQL Server Authentication. Then type the user name and password in to the User
9. name box and Password box.
In the Connection to a database, select Select or enter a database name option. Then click the
dropdown list to select SaleAndStock database( a sample database used in this tutorial).
Click Test Connection button to test the connection to the SQL SERVER. If there is a dialog
showing that the Connection is succeeds, it means that you can move to the next step. If an
error occurs you need to check what you have provided again.
Step 2: Add the TblProduct table to the dataset
After you connected successfully to the SQL Server database, look Server Explorer again and
click Data Connection to expand it then select the connection that you have created in the
previous step. Then click Tables to expand and drag the TblProduct table to the dataset
designer window.
10. Step 3: Add a Crystal Report and link to the table of dataset
Now you have a schema of a dataset that connects to the TblProduct of the SaleAndStock
database located in SQL Server. The next step is to add a Crystal Report item in to your project.
Right-click the project name (ReportVB)->Add->New Item. On the New Item dialog, under
Categories select Reporting and under Templates select. You will see the Crystal Reports Gallery
dialog. Select As a Blank Report to create a blank report and accept the default name
(CrystalReport1).
11. To link to the table of the dataset, right-click Field Explorer next to the active window of
CrystalReport1 then select Database Expert. You will see the dialog as shown below:
Select Project Data and select ADO.NET Datasets, then you will see the TblProduct table. Select
this table and click the arrow button to add the table to the Selected Table area. Click OK.
+Now back to the active window of the CrystalReport1 and drag fields of TblProduct table that
you want to the designer area of the CrystalReport1.
13. Introduction to ASP.NET[RGPV/June2009/Dec2010,Dec2011,Dec2013]
Classic ASP - Active Server Pages
Active Server Pages (ASP), also known as Classic ASP, was introduced in 1998 as Microsoft's first
server side scripting engine.
ASP is a technology that enables scripts in web pages to be executed by an Internet server.
ASP pages have the file extension .asp, and are normally written in VBScript.
ASP.NET Razor:-Razor is new and simple markup syntax for embedding server code into
ASP.NET web pages, much like Classic ASP.
Razor has the power of traditional ASP.NET, but is easier to use and easier to learn.
ASP.NET Programming Languages:-This tutorial covers the following programming languages:
• Visual Basic (VB.NET)
• C# (Pronounced C sharp)
ASP.NET Server Technologies:-This tutorial covers the following server technologies:
• Web Pages (with Razor syntax)
• MVC (Model View Controller)
• Web Forms (traditional ASP.NET)
ASP.NET Development Tools:-ASP.NET supports the following development tools:
• WebMatrix
• Visual Web Developer
• Visual Studio
This tutorial uses WebMatrix for Web Pages, and Visual Web Developer for MVC and Web
Forms.
ASP.NET File Extensions
• Classic ASP files have the file extension .asp
• ASP.NET files have the file extension .aspx
• ASP.NET files with Razor C# syntax have the file extension .cshtml
14. • ASP.NET files with Razor VB syntax have the file extension .vbhtml
ASP.NET is an open source server-side Web application framework designed for Web
development to produce dynamic Web pages. It was developed by Microsoft to allow
programmers to build dynamic web sites, web applications and web services. It was first
released in January 2002 with version 1.0 of the .NET Framework, and is the successor to
Microsoft's Active Server Pages (ASP) technology. ASP.NET is built on the Common Language
Runtime (CLR), allowing programmers to write ASP.NET code using any supported .NET
language. The ASP.NET SOAP extension framework allows ASP.NET components to process
SOAP messages.
ASP.NET is a unified Web development model that includes the services necessary for you to
build enterprise-class Web applications with a minimum of coding. ASP.NET is part of the .NET
Framework, and when coding ASP.NET applications you have access to classes in the .NET
Framework. You can code your applications in any language compatible with the common
language runtime (CLR), including Microsoft Visual Basic, C#, JScript .NET, and J#. These
languages enable you to develop ASP.NET applications that benefit from the common language
runtime, type safety, inheritance, and so on.
ASP.NET includes:
• A page and controls framework
• The ASP.NET compiler
• Security infrastructure
• State-management facilities
• Application configuration
• Health monitoring and performance features
• Debugging support
• An XML Web services framework
• Extensible hosting environment and application life cycle management
• An extensible designer environment
Web Pages is one of the 3 programming models for creating ASP.NET web sites and web
applications.
The other two programming models are Web Forms and MVC (Model, View, Controller).
Web Pages is the simplest programming model for developing ASP.NET web pages. It provides
15. an easy way to combine HTML, CSS, JavaScript and server code:
• Easy to learn, understand, and use
• Built around single web pages
• Similar to PHP and Classic ASP
• Server scripting with Visual Basic or C#
• Full HTML, CSS, and JavaScript control
Web Pages is easy extendable with programmable Web Helpers, including database, video,
graphics, social networking and much more.
With MS Visual Studio installed, we're ready to create our first ASP.NET website. In VS, this is
very easy. Open the File menu and select "New Web Site". You will be presented with the
following dialog:
You need to select "ASP.NET Web Site", if it's not already selected. You should also name your
new site. This is done by entering a name in the Location box. This text box is probably already
16. filled for you, with the last part being something like "Website1". You can choose to accept this,
as well as the location of the project, or you can enter a new one, like I did. I have created a
folder, "My Websites", and within this folder, I would like to create the new project with the
name of "FirstWebSite". For now, this is less important, but later on you might wish to gather
all your projects in a specific folder.
This tutorial will focus on the C# language. Once again, no knowledge of this is required, so if
you already know another .NET language, you will get to learn some C# with this tutorial as
well. Select C# in the Language dropdown. Now, click the Ok button to create this new website.
We will add a Label control to the page. A Label control is some what simple, since it's just used
to hold a piece of text. Add the following piece of HTML-looking code somewhere between the
set of <form> tags:
<asp:Label runat="server" id="HelloWorldLabel"></asp:Label>
The page will simply have a piece of text which says "Hello, world!" - congratulations, you have
just created your first ASP.NET website! Here is the complete listing:
<%
HelloWorldLabel.Text = "Hello, world!";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label runat="server" id="HelloWorldLabel"></asp:Label>
</div>
</form>
</body>
</html>
Features of ASP.NET:-
The focus of Microsoft’s latest ASP.NET 4has mainly been on improving the performance and
Search-engine Optimization (SEO).
17. Unit-05/Lecture-04
C#.NET and Their features
C#( sharp) is a multi-paradigm programming language encompassing strong typing, imperative,
declarative, functional, generic, object-oriented (class-based), and component-oriented
programming disciplines. It was developed by Microsoft within its .NET initiative and later
approved as a standard by Ecma (ECMA-334) and ISO (ISO/IEC 23270:2006). C# is one of the
programming languages designed for the Common Language Infrastructure. C# is built on the
syntax and semantics of C++, allowing C programmers to take advantage of .NET and the
common language runtime. C# is intended to be a simple, modern, general-purpose, object-
oriented.
Common features:
1. C# is a simple, modern, object oriented language derived from C++ and Java.
2. It aims to combine the high productivity of Visual Basic and the raw power of C++.
3. It is a part of Microsoft Visual Studio7.0.
4. Visual studio supports Vb,VC++,C++,Vbscript,Jscript.All of these languages
provide access to the Microsft .NET platform.
5. .NET includes a Common Execution engine and a rich class library.
6. Microsofts JVM eqiv is Common language run time(CLR).
7. CLR accommadates more than one languages such as C#, VB.NET, Jscript, ASP.NET,C ++.
8. Source code --->Intermediate Language code(IL) ---> (JIT Compiler) Native code.
9. The classes and data types are common to all of the .NET languages.
10. We may develop Console application,Windows application, Web application using C#.
11. In C# microsoft has taken care of C++ problems such as Memory management, pointers
etc.
12. It support garbage collection, automatic memory management and a lot.
MAIN FEATURES OF C#
18. 1. SIMPLE
1. Pointers are missing in C#.
2. Unsafe operations such as direct memory manipulation are not allowed.
3. In C# there is no usage of "::" or "->" operators.
4. Since it's on .NET, it inherits the features of automatic memory management and
garbage collection.
5. Varying ranges of the primitive types like Integer,Floats etc.
6. Integer values of 0 and 1 are no longer accepted as boolean values.Boolean values are
pure true or false values in C# so no more errors of "="operator and "=="operator.
7. "==" is used for comparison operation and "=" is used for assignment operation.
2. MODERN
1. C# has been based according to the current trend and is very powerful and simple for
building interoperable, scable, robust applications.
2. C# includes built in support to turn any component into a web service that can be
invoked over the internet from any application runing on any platform.
3. OBJECT ORIENTED
1. C# supports Data Encapsulation, inheritance,polymorphism, interfaces.
2. (int,float, double) are not objects in java but C# has introduces structures(structs) which
enable the primitive types to become objects.
int i=1;
string a=i Tostring(); //conversion (or) Boxing
4. TYPE SAFE
1. In C# we cannot perform unsafe casts like convert double to a boolean.
2. Value types (priitive types) are initialized to zeros and reference types (objects and
classes) are initialized to null by the compiler automatically.
3. arrays are zero base indexed and are bound checked.
4. Overflow of types can be checked.
5. INTEROPERABILITY
19. 1. C# includes native support for the COM and windows based applications.
2. Allowing restriced use of native pointers.
3. Users no longer have to explicityly implement the unknown and other COM interfacers,
those features are built in.
4. C# allows the users to use pointers as unsafe code blocks to manipulate your old code.
5. Components from VB NET and other managed code languages and directlyt be used in
C#.
6. SCALABLE AND UPDATEABLE
1. .NET has introduced assemblies which are self describing by means of their manifest.
manifest establishes the assembly identity, version, culture and digital signature etc.
Assemblies need not to be register anywhere.
2. To scale our application we delete the old files and updating them with new ones. No
registering of dynamic linking library.
3. Updating software components is an error prone task. Revisions made to the code. can
effect the existing program C# support versioning in the language. Native support for
interfaces and method overriding enable complex frame works to be developed and
evolved over time.
Net versioning in terms of the Framework, "this will be a 2.0 development project," but it is
important to understand there are actually three independently versioned components to
consider:
• Language (such as C#)
• Common Language Runtime (CLR)
• .Net Framework
# Version CLR Version Framework Version
1.0 1.0 1.0
1.1 1.1 1.1
2.0 2.0
2.0
3.0
3.0 2.0 (updated) 3.5
.Net 3.0, these components were released as a logical unit, but things got out of sync when the
20. 3.0 Framework did not include a new version of C# or the CLR. For this reason, some think.Net
3.0 should have been released as ".Net 2.5." So what is the 3.0 Framework then? It's a set of
libraries (formerly WinFX) that depend on and extend the .Net 2.0 Framework and provide
revolutionary technologies such as Windows Communication Foundation (WCF), Windows
Workflow Foundation (WF) and Windows Presentation Foundation (WPF).
Developers can exploit the.Net version synchronicity issue by utilizing 3.0 and 3.5 Framework
features on a machine that only has the .Net 2.0 Framework installed. Although I am not
advocating this technique (especially to circumvent configuration or security controls), it can be
accomplished by referencing libraries such as System.
Program structure:-
Whether it is a console or a graphical interface application, the program must have an entry
point of some sort. The entry point of the C# application is the Main method. There can only be
one, and it is a static method in a class. The method usually returns void and is passed
command-line arguments as an array of strings.
static void Main(string[] args)
{
}
// OR Main method can be defined without parameters.
static void Main()
{
}
A Main-method is also allowed to return an integer value if specified.
static int Main(string[] args)
{
return 0;
}
Namespaces:
Namespaces are a part of a type name and they are used to group and/or distinguish named
entities from other ones.
ystem.IO.DirectoryInfo // DirectoryInfo is in the System.IO-namespace
namespace FooNamespace
{
21. // Members
}
using statement
The using statement loads a specific namespace from a referenced assembly. It is usually placed
in the top (or header) of a code file but it can be placed elsewhere if wanted, e.g. inside classes.
using System;
using System.Collections;
using Net = System.Net;
using DirInfo = System.IO.DirectoryInfo;
Operators:-
Operator category Operators
Arithmetic +, -, *, /, %
Logical (boolean and
bitwise)
&, |, ^, !, ~, &&, ||, true, false
String concatenation +
Increment, decrement ++, --
Shift <<, >>
Relational ==, !=, <, >, <=, >=
Assignment =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
Member access .
Indexing []
Cast ()
Conditional ?:
Object creation new
S.NO RGPV QUESTIONS Year Marks
Q.1 Write in brief about the importance of C# .NET. June2009 10
22. Q.2 Explain the C#. Dec2010 05
Q.3 Write short notes: C#. Dec2011 04
Q.4 Write short notes: C# features Dec2013 04
Unit-05/Lecture-05
Object Orientation concept
Object Oriented Programming (OOP) is a programming model where programs are organized
around objects and data rather than action and logic.
OOP allows decomposition of a problem into a number of entities called objects and then builds
data and functions around these objects.
1. The software is divided into a number of small units called objects. The data and
functions are built around these objects.
2. The data of the objects can be accessed only by the functions associated with that
object.
3. The functions of one object can access the functions of another object.
23. Class:-
A class is the core of any modern Object Oriented Programming language such as C#.In OOP
languages it is mandatory to create a class for representing data. A class is a blueprint of an
object that contains variables for storing data and functions to perform operations on the
data. A class will not occupy any memory space and hence it is only a logical representation of
data.
To create a class, you simply use the keyword "class" followed by the class name:
class Student
{
}
Object:-
Objects are the basic run-time entities of an object oriented system. They may represent a
person, a place or any item that the program must handle.
"An object is a software bundle of related variable and methods."
"An object is an instance of a class" class will not occupy any memory space. Hence to work
with the data represented by the class you must create a variable for the class, that is called
an object. When an object is created using the new operator, memory is allocated for the
class in the heap, the object is called an instance and its starting address will be stored in the
object in stack memory. When an object is created without the new operator, memory will
not be allocated in the heap, in other words an instance will not be created and the object in
the stack contains the value null.
public class student
{
}
student objstudent=new student ();
According to the above sample we can say that Student object, named objstudent, has
created out of the student class.
Encapsulation:
Encapsulation is a process of binding the data members and member functions into a single
unit.
24. Example for encapsulation is class. A class can contain data structures and methods.
Consider the following class
public class Aperture
{
public Aperture ()
{
}
protected double height;
protected double width;
protected double thickness;
public double get volume()
{
Double volume=height * width * thickness;
if (volume<0)
return 0;
return volume;
}
}
In this example we encapsulate some data such as height, width, thickness and method Get
Volume.
Inheritance:
Inheritance is a process of deriving the new class from already existing class
C# is a complete object oriented programming language. Inheritance is one of the primary
concepts of object-oriented programming. It allows you to reuse existing code. Through
effective use of inheritance, you can save lot of time in your programming and also reduce
errors, which in turn will increase the quality of work and productivity. A simple example to
understand inheritance in C#.
Using System;
Public class BaseClass
{
Public BaseClass ()
{
Console.WriteLine ("Base Class Constructor executed");
}
Public void Write ()
{
Console.WriteLine ("Write method in Base Class executed");
25. }
}
Public class ChildClass: BaseClass
{
Public ChildClass ()
{
Console.WriteLine("Child Class Constructor executed");
}
Public static void Main ()
{
ChildClass CC = new ChildClass ();
CC.Write ();
}
}
In the Main () method in ChildClass we create an instance of childclass. Then we call the write ()
method. If you observe the ChildClass does not have a write () method in it. This write ()
method has been inherited from the parent BaseClass.
The output of the above program is
Output:
Base Class Constructor executed
Child Class Constructor executed
Write method in Base Class executed
In C# the syntax for specifying BaseClass and ChildClass relationship is shown below. The
base class is specified by adding a colon, ":", after the derived class identifier and then
specifying the base class name.
Syntax: class ChildClassName: BaseClass
{
//Body
}
C# supports single class inheritance only. What this means is, your class can inherit from only
one base class at a time. In the code snippet below, class C is trying to inherit from Class A and B
at the same time. This is not allowed in C#. This will lead to a compile time
error: Class 'C' cannot have multiple base classes: 'A' and 'B'.
public class A
{
26. }
public class B
{
}
public class C : A, B
{
}
In C# Multi-Level inheritance is possible. Code snippet below demonstrates mlti-level
inheritance. Class B is derived from Class A. Class C is derived from Class B. So class C, will have
access to all members present in both Class A and Class B. As a result of multi-level inheritance
Class has access to A_Method(),B_Method() and C_Method().
Constructors and Destructors:
Classes have complicated internal structures, including data and functions, object initialization
and cleanup for classes is much more complicated than it is for simple data structures.
Constructors and destructors are special member functions of classes that are used to construct
and destroy class objects. Construction may involve memory allocation and initialization for
objects. Destruction may involve cleanup and deallocation of memory for objects.
• Constructors and destructors do not have return types nor can they return values.
• References and pointers cannot be used on constructors and destructors because their
addresses cannot be taken.
• Constructors cannot be declared with the keyword virtual.
• Constructors and destructors cannot be declared const, or volatile.
• Unions cannot contain class objects that have constructors or destructors.
Constructors and destructors obey the same access rules as member functions. For example, if
you declare a constructor with protected access, only derived classes and friends can use it to
create class objects.
Example of Constructor
class C
{
private int x;
private int y;
public C (int i, int j)
{
x = i;
y = j;
}
public void display ()
27. {
Console.WriteLine(x + "i+" + y);
}
}
Example of Destructor
class D
{
public D ()
{
// constructor
}
~D ()
{
// Destructor
}
}
Unit-05/Lecture-06
Polymorphism, Abstraction in C#
Polymorphism:
When a message can be processed in different ways is called polymorphism. Polymorphism
means many forms.
Polymorphism is one of the fundamental concepts of OOP.
Polymorphism provides following features:
• It allows you to invoke methods of derived class through base class reference during
runtime.
• It has the ability for classes to provide different implementations of methods that are
S.NO RGPV QUESTIONS Year Marks
Q.1
28. called through the same name.
Polymorphism is of two types:
1. Compile time polymorphism/Overloading
2. Runtime polymorphism/Overriding
Compile Time Polymorphism
Compile time polymorphism is method and operators overloading. It is also called early binding.
In method overloading method performs the different task at the different input parameters.
Example
public class Class1
{
public void NumbersAdd(int a, int b)
{
Console.WriteLine(a + b);
}
public void NumbersAdd(int a, int b, int c)
{
Console.WriteLine(a + b + c);
}
}
In above class we have two methods with same name but having different input
parameters this is called method overloading or compile time polymorphism or early
binding.
Runtime Time Polymorphism
Runtime time polymorphism is done using inheritance and virtual functions. Method overriding
is called runtime polymorphism. It is also called late binding.
Example
/Base Class
public class Bclass
{
public virtual void Sample1()
{
Console.WriteLine("Base Class");
}
}
// Derived Class
29. public class DClass : Bclass
{
public override void Sample1()
{
Console.WriteLine("Derived Class");
}
}
// Using base and derived class
class Program
{
static void Main(string[] args)
{
// calling the overriden method
DClass objDc = new DClass();
objDc.Sample1();
// calling the base class method
Bclass objBc = new DClass();
objBc.Sample1();
}
}
When overriding a method, you change the behavior of the method for the derived class.
Overloading a method simply involves having another method with the same prototype.
Caution: Don't confused method overloading with method overriding, they are different,
unrelated concepts. But they sound similar.
Method overloading has nothing to do with inheritance or virtual methods.
Following are examples of methods having different overloads:
void area(int side);
void area(int l, int b);
void area(float radius);
Practical example of Method Overloading (Compile Time Polymorphism)
using System;
namespace method_overloading
{
class Program
{
public class Print
{
public void display(string name)
30. {
Console.WriteLine ("Your name is : " + name);
}
public void display(int age, float marks)
{
Console.WriteLine ("Your age is : " + age);
Console.WriteLine ("Your marks are :" + marks);
}
}
static void Main(string[] args)
{
Print obj = new Print ();
obj.display ("George");
obj.display (34, 76.50f);
Console.ReadLine ();
}
}
}
Note: In the code if you observe display method is called two times. Display method will work
according to the number of parameters and type of parameters.
Abstraction:-
Abstraction is "To represent the essential feature without representing the background
details."Abstraction lets you focus on what the object does instead of how it does it.
Abstraction provides you a generalized view of your classes or objects by providing relevant
information. Abstraction is the process of hiding the working style of an object, and showing the
information of an object in an understandable manner.
• Abstraction defines way to abstract or hide your data and members from outside world.
• Classes use the concept of abstraction and are defined as a list of abstract attributes.
• Simply speaking Abstraction is hiding the complexities of your class or struct or in a
generic term Type from outer world.
• This is achieved by means of access specifiers
Example1: A Laptop consists of many things such as processor, motherboard, RAM, keyboard,
31. LCD screen, wireless antenna, web camera, usb ports, battery, speakers etc. To use it, you don't
need to know how internally LCD screens, keyboard, web camera, battery, wireless antenna,
speaker’s works. You just need to know how to operate the laptop by switching it on. Think
about if you would have to call to the engineer who knows all internal details of the laptop
before operating it. This would have highly expensive as well as not easy to use everywhere by
everyone.
So here the Laptop is an object that is designed to hide its complexity.
How to abstract: - By using Access Specifiers
.Net has five access Specifiers
Public -- Accessible outside the class through object reference.
Private -- Accessible inside the class only through member functions.
Protected -- Just like private but Accessible in derived classes also through member
functions.
Internal -- Visible inside the assembly. Accessible through objects.
Protected Internal -- Visible inside the assembly through objects and in derived classes outside
the assembly through member functions.
Code Example:
namespace AbstractClasses
{
class Program
{
static void Main(string[] args)
{
Dog dog = new Dog();
Console.WriteLine(dog.Describe());
Console.ReadKey();
}
}
abstract class FourLeggedAnimal
{
public virtual string Describe()
{
return "Not much is known about this four legged animal!";
}
32. }
class Dog : FourLeggedAnimal
{
}
}
Advantages of abstraction are the hiding of implementation details, component reuse,
extensibility, and testability. When we hide implementation details, we reveal a cleaner, more
comprehensible and usable interface to our users. We are separating our interface from our
implementation, and this makes component reuse more practical. Many, if not all of the object-
oriented concepts we have discussed throughout this document play a role in the abstraction
principle. Working together, their end goal is the same, to produce software that is flexible,
testable, maintainable, and extensible.
Unit-05/Lecture-07
Exception Handling, Event Handling
Exception Handling:-
An exception is a problem that arises during the execution of a program. A C# exception is a
response to an exceptional circumstance that arises while a program is running, such as an
attempt to divide by zero.
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
S.NO RGPV QUESTIONS Year Marks
Q.1
33. 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.
Syntax
Assuming a block will raise and exception, a method catches an exception using a combination
of the try and catch keywords. 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, and the syntax for
using try/catch looks like the following:
try
{
// statements causing exception
}
catch( ExceptionName e1 )
{
// error handling code
}
catch( ExceptionName e2 )
{
// error handling code
}
catch( ExceptionName eN )
{
// error handling code
}
finally
{
// statements to be executed
}
Exception Classes in C#
C# exceptions are represented by classes. The exception classes in C# are mainly directly or
34. 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.
The System.ApplicationException class supports exceptions generated by application
programs. So the exceptions defined by the programmers should derive from this class.
The System.SystemException class is the base class for all predefined system exception.
The following table provides some of the predefined exception classes derived from the
Sytem.SystemException class:
Exception Class Description
System.IO.IOException Handles I/O errors.
System.IndexOutOfRangeException
Handles errors generated when a method refers to
an array index out of range.
System.ArrayTypeMismatchException
Handles errors generated when type is mismatched
with the array type.
System.NullReferenceException
Handles errors generated from deferencing a null
object.
System.DivideByZeroException
Handles errors generated from dividing a dividend
with zero.
System.InvalidCastException Handles errors generated during typecasting.
System.OutOfMemoryException
Handles errors generated from insufficient free
memory.
try-catch-finally block in C#:
As mentioned earlier any exception that occurs inside the try block, transfers control to the
appropriate catch block and later to the finally block. In C#, both catch and finally blocks are
optional. The try block can exist either with one or more catch blocks or a finally block or with
both catch and finally blocks.
In cases when there is no exception inside the try block, the control directly transfers to finally
block. So the statements inside the finally block are always executed. C#, exceptions are objects
35. Unit-05/Lecture-08
Debugging in vb.net
Debugging is a process by which the errors in coding are set right. For this we need to know the
type of errors and when they occur.
Types of Error
Programming errors are generally broken down into three types: Design-time, Runtime, and
Logic errors.
A Design-time error is also known as a syntax error. These occur when the environment you're
programming in doesn't understand your code. These are easy to track down in VB.NET,
because you get a blue wiggly line pointing them out. If you try to run the programme, you'll
get a dialogue box popping up telling you that there were Build errors.
These type of errors are triggered while compiling, when the code is not understandable
to the compiler.Usually this type of errors occur due to bad syntax like wrong keywords,
programming structure mistakes.
36. Syntax errors in vb.net 2008 are highlighted using a line and also a tool tip appears specifying
the reason for the error, as the mouse is moved near the point where the error occured. These
errors are also displayed in the Error List window in the bottom of the screen.
Run-Time Errors:
Runtime errors are a lot harder to track down. As their name suggests, these errors occur when
the programme is running. They happen when your programme tries to do something it
shouldn't be doing. An example is trying to access a file that doesn't exist. Runtime errors
usually cause your programme to crash. If and when that happens, you get the blame. After all,
you're the programmer, and you should write code to trap runtime errors. If you're trying to
open a database in a specific location, and the database has been moved, a Runtime error will
occur. It's your job to predict a thing like this, and code accordingly.
These type of errors are exceptions triggered when the code is executing something that is
illegal to vb.net environment. Some of the example's for this are division by zero, trying to
access an non existent file, declaring arrays out of bounds etc.Run time errors can be handled
using the vb.net code also.
37. Run time errors in vb.net are displayed using a yellow padding over the code, along with a
window specifying the exception handled, with the troubleshooting tips, the Actions required
in detail.
Logical Errors:
Logic errors also occur when the programme is running. They happen when your code doesn't
quite behave the way you thought it would. A classic example is creating an infinite loop of the
type "Do While x is greater than 10". If x is always going to be greater than 10, then the loop
has no way to exit, and just keeps going round and round. Logic errors tend not to crash your
programme. But they will ensure that it doesn't work properly.These errors are defined as
errors that are very hard to find out. The code may compile and run properly but may produce
undesired results. Incorrect for an expression like 2 instead of 20 may also be considered as a
logical error.
Debugging Tools: -
Debugging tools built into vb.net can be accessed under Tools->Options. Click on the the
'+' against Text Editor and on the '+' against Basic. Now select VB Specific, all the options
has to checked to get the following debugging options.
38. Automatic insertion of end constructs:
By enabling this option when end constructs are added automatically. When Sub Main is typed
in End Sub is added automatically.
Pretty Listing (reformatting) of Code:
By enabling this option extra spaces in the code are removed, tab position is set, missing
controls structure statements are added, paranthesis are added to function calls, end quotes
are added, dates reformatted.
Enable Outlining Mode:
By enabling this option a section of the code can be collapsed and viewed as required by
clicking on the '+' and '-' signs in the outline.
Automatic Insertion of Interface and MustOverride Members:
By enabling this option the editor inserts prototypes for members that are implemented,
inherited or overidden.
Enable Error Correction suggestions:
By enabling this option, solutions to common errors with an option to select the appropriate
correction that can be applied to the code are added.
Exception Handling.
Exceptions Handling are errors that are triggered at runtime, that are handled in VB.net
using structured error handling with the Try..Catch..Finally statement. The On erro goto, On
Error Resume Next statement is used for unstructured error handling.
The exceptions can be handled in the Try..Catch..finally using the Built-in exception handling
methods.
Example1:
Module Module1
Sub Main()
Dim a(3) As Integer
Try
a(5) = 45
Catch ex As IndexOutOfRangeException
Console.WriteLine(ex.Message)
Catch ex As Exception
Console.WriteLine(ex.Message)
Finally
Console.WriteLine("End of Execution")
39. End Try
Console.Read()
End Sub
End Module
Result:
Index was outside the bounds of the array
End of Execution
Description:
In the above example, the dimension of the array declared is '3' and the array given array under
the Try statement is '5'. The exception is caught by the catch statement using the specific
exception option IndexOutOfRangeException and even the Exception option display messages
for all exceptions.
On Error Goto Statement: Example2:
Module Module1
Sub Main()
Dim i, j As Integer
For i = 0 To 10 Step 1
On Error GoTo ErrorHandler
j = 100 / i
Console.WriteLine("Value of j is::")
Console.WriteLine(j)
Next
ErrorHandler:
Console.WriteLine("Division by zero error")
Console.Read()
End Sub
End Module
Result:
Division by zero error
On Error Goto Statement:
In the above example the ustructured error handling statement On Error Goto is used along
with the ErrorHandler to display the error message that diverts the flow of the program itself.
Example3:
Module Module1
Public Class student
Public Function Add(ByVal i As Integer,
ByVal j As Integer) As Integer
Console.WriteLine("Result:"(i / j))
End Function
40. End Class
Sub Main()
On Error Resume Next
Dim obj As New student
obj.Add(10, 0)
Console.WriteLine("Check the Arguments")
Console.Read()
End Sub
End Module
Result:
Check the Arguments
Unit-05/Lecture-09
Asp.net Webserver Controls
Web Servers controls are objects placed on a page with the purpose of read and write data. These
objects have a consistent programming model and their properties (attributes) can be accessed
programmatically. A Server Control starts with <asp: followed by the object name <asp:textbox
. They must contain two other properties, ID which must be unique and runat=”server” which
tells the web server to give the control server side processing. They can be self closed by having
a forward slash (/) before the ending tag or have a closing tag:
<asp:textbox id=”txt” runat=”server” />
<asp:textbox id=”txt” runat=”server” ></asp:textbox>
After a control is processed by the web server, a standard HTML tag is sent to the browser for
displaying. The above example will be rendered as:
<input type=”text” name=”txt” id=”txt” />
Button <asp:button/>
S.NO RGPV QUESTIONS Year Marks
Q.1
41. Post back control for form submission.
Properties:
Example: <asp:button id=”btn” runat=”server” text=”Search”/>
Checkbox <asp:checkbox/>
Selection control (multiple selections).
Properties:
Example: <asp:checkbox id=”ck” runat=”server” text=”Diploma”/>
DropdownList <asp:dropdownlist>…</asp:dropdownlist>
Single selection control that displays a collection of list items.
Properties:
Example: <asp:dropdownlist id="countries" runat="server">
<asp:listitem Text="Select" Value=""/>
<asp:listitem Text="UK" Value="UK"/>
<asp:listitem Text="Ireland" Value="Ireland"/>
</asp:dropdownlist>
Hyperlink <asp:hyperlink/>
Navigation control to move from page to page.
Id=”btn”
Runat=”server”
Text=”Search”
Enabled=”true/false”
Creates an unique identifier
Sets the button for server side processing
Displays text on the button
Enables or Disables the button
Id=”ck”
Runat=”server”
Text=”Diploma”
Checked=”true/false”
Creates an unique identifier
Sets the checkbox for server side processing
Displays text on checkbox
Checks or Uncheck the checkbox
Id=”lb”
Runat=”server”
AutoPostBack=”true,false”
Creates an unique identifier
Sets the button for server side processing
Set auto submission on item selected
42. Properties:
Example: <asp:image id=”img” runat=”server” ImageURL=”ImageName.gif”/>
Image <asp:image/>
Displays image defined as ImageUrl
Properties:
Example: <asp:image id=”img” runat=”server” ImageURL=”ImageName.gif”/>
Label <asp:label/>
Output control used to display text at a specific location on a page.
Properties:
Example: <asp:label id=”msg” runat=”server” text=”Welcome to ASP.Net”/>
Link Button <asp:linkbutton>
Post back control for form submission. It renders as a link.
Properties:
Id=”hl”
Runat=”server”
NavigateURL=”controls.aspx”
Text=”Asp.Net Controls”
Creates an unique identifier
Sets the image for server side processing
Maps the file to link to
Creates the text link
Id=”img”
Runat=”server”
ImageURL=”hello.gif”
Width=”200”
Height=”200”
ToolTip=”Hello Message”
Creates an unique identifier
Sets the image for server side processing
Maps the image file to display
Sets Image width
Sets image height
Display text when mouse is over
Id=”msg”
Runat=”server”
Text=”some text”
Creates an unique identifier
Sets the textbox for server side processing
Displays text inside the box
43. Example: <asp:linkbutton id=”btn” runat=”server” text=”Search”/>
Listbox <asp:listbox>…</asp:listbox>
Multiple selection control that displays a collection of list items.
Properties:
Example: <asp:listbox id="countries" runat="server">
<asp:listitem Text="UK" Value="UK"/>
<asp:listitem Text="Ireland" Value="Ireland"/>
</asp:lisbox>
Panel <asp:panel>…</asp:panel>
Container for other controls.
Properties:
Example: <asp:panel id="pn" runat="server" visible=”true”>
<asp:label id=”msg2” runat=”server” text=”Control inside a panel”/>
</asp:panel>
Radio Button <asp:radiobutton/>
Id=”lb”
Runat=”server”
Text=”Search”
Enabled=”true/false”
Creates an unique identifier
Sets the button for server side processing
Displays text on the button
Enables or Disables the button
Id=”lb”
Runat=”server”
CssClass=”box”
Rows=”Number”
SelectionMode=”single/multiple”
Creates an unique identifier
Sets the button for server side processing
Sets a Stylesheet class
Sets the visible number of rows
Sets single or multiple selection
Id=”pn”
Runat=”server”
Visible=”true/false”
Creates an unique identifier
Sets the panel for server side processing
Sets its visibility
44. Single selection control belonging to a group.
Properties:
Example:
<asp:radiobutton id=”rb” runat=”server” GroupName=”gender” text=”Female”
checked=”true”/>
<asp:radiobutton id=”rb2” runat=”server” text=”Male” />
Table <asp:table>…</asp:table>
Builds up a HTML table.
Properties:
Table Row <asp:tablerow>…</asp:tablerow>
Creates table rows.
Properties:
Id=”lb”
Runat=”server”
CssClass=”box”
Text=”Female”
GroupName=”gender”
Checked=”true/false”
Creates an unique identifier
Sets the radiobutton for server side processing
Sets a Stylesheet class
Displays text on radiobutton
Sets a group it belongs to
Checks or Uncheck the radiobutton
Id=”lb”
Runat=”server”
BackColor=”#f6f6da”
Cellspacing=”2”
Cellpadding=”2”
Width=”500”
Height=”500”
HorizontalAlign=”center/right”
GridLines=”both/none/vertical/horizontal”
BorderWidth=”1”
Creates an unique identifier
Sets the table for server side processing
Sets a background colour
Sets distance between cells
Sets distance around the cells’ contents
Set table width
Sets table height
Sets table alignment
Sets what borders to display
Sets border height