SlideShare a Scribd company logo
1 of 48
Unit-04/Lecture-01
Pattern roles and relationship
Design Patterns:-[RGPV/Dec2011, Dec2013]
Because there is so much general material available on the aims and the documentation of
design patterns for executable applications, I will restrict this discussion to a few basic points
before moving on to look at the patterns I find most useful in ASP.NET. The References section
at the end of Part 3 of this series of articles contains links to many useful resources and Web
sites related to design patterns in general.
While many people (myself included) find the term "design patterns" just a little scary - due not
least to the way that they are usually described and documented - most developers use
informal patterns every day when writing code. Constructs such as try...catch, using, and switch
(Select Case) statements all follow standard patterns that developers have learned over time. In
fact, patterns can be:
• Informal Design Patterns - such as the use of standard code constructs, best practice,
well structured code, common sense, the accepted approach, and evolution over time
• Formal Design Patterns - documented with sections such as "Context", "Problem",
"Solution", and a UML diagram
Formal patterns usually have specific aims and solve specific issues, whereas informal patterns
tend to provide guidance that is more general. Formal patterns usually have specific aims and
solve specific issues, whereas informal patterns tend to provide guidance that is more general.
Brad Appleton, author of the book "Software Configuration Management Patterns: Effective
Teamwork, Practical Integration", describes design patterns, pattern languages, and the need
for them in software engineering and development, like this:
"Fundamental to any science or engineering discipline is a common vocabulary for expressing
its concepts, and a language for relating them together."
"... a body of literature to help software developers resolve recurring problems encountered
throughout all of software development."
"... a shared language for communicating insight and experience about these problems and
their solutions."
"A pattern is a named nugget of insight that conveys the essence of a proven solution to a
recurring problem within a certain context amidst competing concerns."
(from "Patterns and Software: Essential Concepts and Terminology")
The following sections of this article and the following two articles aim to demonstrate how you
can use some of the common formal patterns (some with minor adaptations to suit ASP.NET
requirements) in your Web applications to achieve the aims set out so succinctly by the Hillside
Group. You can download the reasonably simple example application and open it in Visual
Studio 2005, or install it to run under Internet Information Services (IIS). The download file
includes a ~readme.txt file that describes the setup requirements.
Design patterns fall into groups, based on the type and aims of the pattern. For example, some
patterns provide presentation logic for displaying specific views that make up the user interface.
Others control the way that the application behaves as the user interacts with it. There are also
groups of patterns that specify techniques for persisting data, define best practices for data
access, and indicate optimum approaches for creating instances of objects that the application
uses. The following list shows some of the most common design patterns within these groups:
• Presentation Logic
o Model-View-Controller (MVC)
o Model-View-Presenter (MVP)
o Use Case Controller
• Host or Behavioral
o Command
o Publish-Subscribe / Observer
o Plug-in / Module / Intercepting Filter
• Structural
o Service Agent / Proxy / Broker
o Provider / Adapter
• Creational
o Factory / Builder / Injection
o Singleton
• Persistence
o Repository
Designs on Classes:-
• Singleton Pattern :-
The creational pattern that describes how to ensure that only one instance of aclass can be
activated. All objects that use the singleton instance use the same one.
• Bridge Pattern :-
The structural pattern that prescribes the de−coupling of the implementation of a
class from its interface so that the two can evolve independently of each other.
• Strategy Pattern
The structural pattern that prescribes the de−coupling of the implementation of a
class from its interface so that algorithms, or any operation or process, can be interchanged.
Algorithm implementation can thus vary independently from the client or consumer objects
that need it. Strategy is very similar to Bridge; however, Strategy is used to interchange
implementation at runtime.
• State Pattern
The behavioral pattern that provides a framework for using an object hierarchy as a
state machineas an OO alternative to constant or variable state data, complex conditional
statements, enumeration constants, and map tables.
• Composite Pattern
The structural pattern that prescribes how classes can be composed (and aggregated) into
tree−like hierarchies.
• Iterator Pattern
The behavioral pattern for a class that provides a way to access the aggregated or
composite elements of objects of a collection . This chapter will implement an iterator as an
implementation .
• Adapter Pattern
The structural pattern that prescribes the conversion of an interface to a class into
Another interface a client object can use transparently. Adapter, affectionately known as
Wrapper.
• Null Pattern
A behavioral pattern providing an alternative to Nothing in Visual Basic .
• Delegate Pattern
The Delegate pattern prescribes how to wrap a singleton method signature in a special class,
which is then used as a "pointer" to a method in another class or object.
The Model-View-Controller and Model-View-Presenter Patterns:-
The Model-View-Controller (MVC) and Model-View-Presenter (MVP) Patterns improve reusability of
business logic by separating the three components required to generate and manage a specific user
interface (such as a single Web page). The Model contains the data that the View (the Web page) will
display and allow the user to manipulate. The Controller or Presenter links the Model and the View, and
manages all interaction and processing of the data in the Model
 Roles:-
The concept of roles has been discussed broadly in the literature. The properties regarded as
characteristic for the role a few core properties seem to be largely unques-tioned. This
includes the property that a single object can play several roles of different or the same kind
both simultaneously and sequentially, and that the same role can be played by different
objects of the same and different kinds. Raised to the type level, this means that the
relationship between role types and class types.
Roles and behavior:-
A role elicits the behaviour of an object in a given context. For instance, the role of father
specifies behaviour expected from a man in the context of his fatherhood. On an abstract level,
the role-specific behaviour is specified independently from the (na-ture of the) role player; in
general, the class of the role player should be substitutable by another without compromising
the role specification.
Roles and state :-
The role-as-interface view is often challenged by the observation that roles appear to have role-
specific state. And indeed, it seems reasonable that a person in the Employee role has some role-
specific data such as telephone number and salary. Even if this state were made part of the role-
as-type definition (replacing Interfaces by abstract classes as role representations), this would not
allow a single person to have several office phone numbers and salaries at the same time (namely
one per employment). This is a problem since as noted above, being able to play the same role
multiply at the same time is a defining characteristic of the role
Concept . The role object pattern solves this problem.
The role object pattern:-
The role object pattern represents the roles an object plays by adjunct instances, the role
objects. Each role object is an instance of a certain class, its role type. The role type specifies
role-specific state and behaviour; by instantiating the same role type several times and
adjoining the instances to the same role player object, the problem of multiple phone numbers
and salaries is solved. At the same time, the role class can implement role specific behaviour
independently from the role player class, and forward player-specific requests to the player.
Role and counter role :-
Intuitively, a role is meaning less without one (or more) counter roles, the one(s) with which its
player interacts and for which the associated behaviour is required. Role and counter role(s)
together form an interaction pattern — so metimes called collaboration —, with parts of the
behaviour being specific to the interaction, and parts being contributed by the role players.
 Relationship:-
A model is not complete unless the relationships between elements are described properly. The
Relationship gives a proper meaning to an UML model. Following are the different types of
Relationships available in UML.
• Dependency
• Association
• Generalization
• Composition
Dependency Notation:
Dependency is an important aspect in UML elements. It describes the dependent elements and
The direction of dependency.Dependency is represented by a dotted arrow as shown below.
The arrow head represents the independent element and the other end the dependent
element.
Class diagram showing dependency between "Car" class and "Wheel" class (An even clearer
example would be "Car depends on Wheel", because Car
Association Notation:
Association describes how the elements in an UML diagram are associated. In simple word it
describes how many elements are taking part in an interaction. Association is represented by a
dotted line with (without) arrows on both sides. The two ends represent two associated
elements as shown below. The multiplicity is also mentioned at the ends to show how many
objects are associated.
Class diagram example of association between two classes
Generalization Notation:
The Generalization relationship ("is a") indicates that one of the two related classes (the
subclass) is considered to be a specialized form of the other (the super type) and superclass is
considered as 'Generalization' of subclass. In practice, this means that any instance of the
subtype is also an instance of the superclass. An exemplary tree of generalizations of this form
is found in biological classification: human beings are a subclass of simian, which are a subclass
of mammal, and so on. The relationship is most easily understood by the phrase 'an A is a B' (a
human is a mammal, a mammal is an animal).
The UML graphical representation of a Generalization is a hollow triangle shape on the super
class end of the line (or tree of lines) that connects it to one or more subtypes.The
generalization relationship is also known as the inheritance or "is a" relationship.
The super class (base class) in the generalization relationship is also known as the "parent",
super class, base class, or base type. The subtype in the specialization relationship is also known
as the "child", subclass, derived class, derived type, inheriting class, or inheriting type.
Note that this relationship bears no resemblance to the biological parent/child relationship: the
use of these terms is extremely common, but can be misleading.
Generalization-Specialization relationship
A is a type of B
E. g. "an oak is a type of tree", "an automobile is a type of vehicle"
Generalization can only be shown on class diagrams and on Use case diagrams.
Class diagram showing generalization between one super class and two subclasses
Composition Notations:-
Composition is a stronger variant of the "has a" association relationship; composition is more
specific than aggregation. Composition usually has a strong life cycle dependency between
instances of the container class and instances of the contained class(es): if the container is
destroyed, normally every instance that it contains is destroyed as well. (Note that, where
allowed, a part can be removed from a composite before the composite is deleted, and thus not be
deleted as part of the composite.)
Class diagram showing Composition between two classes at top and Aggregation between two
classes at bottom
Unit-04/Lecture-02
Accessing database: ADO.NET [RGPV/Dec2010,Dec2013]
 ADO.NET:-
ADO.NET provides consistent access to data sources such as SQL Server and XML, and to data
sources exposed through OLE DB and ODBC. Data-sharing consumer applications can use
ADO.NET to connect to these data sources and retrieve, handle, and update the data that they
contain.
ADO.NET separates data access from data manipulation into discrete components that can be
used separately or in tandem. ADO.NET includes .NET Framework data providers for
connecting to a database, executing commands, and retrieving results. Those results are either
processed directly, placed in an ADO.NET DataSet object in order to be exposed to the user in
an ad hoc manner, combined with data from multiple sources, or passed between tiers. The
DataSet object can also be used independently of a .NET Framework data provider to manage
data local to the application or sourced from XML.
The ADO.NET classes are found in System.Data.dll, and are integrated with the XML classes
found in System.Xml.dll. For sample code that connects to a database, retrieves data from it, and
then displays that data in a console window, see ADO.NET Code Examples.
ADO.NET provides functionality to developers who write managed code similar to the
functionality provided to native component object model (COM) developers by ActiveX Data
Objects (ADO). We recommend that you use ADO.NET, not ADO, for accessing data in your
.NET applications.ADO.NET provides the most direct method of data access within the .NET
Framework. For a higher-level abstraction that allows applications to work against a conceptual
model instead of the underlying storage model, see the ADO.NET Entity Framework.
S.NO RGPV QUESTIONS Year Marks
Q.1 Write short notes: Roles and Relationship Dec2013 04
Q.2 Explain class design pattern in brief. Dec2011 10
Q.3 What is the role of s/w pattern in oop? Explain with their
types.
Dec2010 10
ADO.NET is an object-oriented set of libraries that allows you to interact with data sources.
Commonly, the data source is a database, but it could also be a text file, an Excel spreadsheet, or
an XML file. For the purposes of this tutorial, we will look at ADO.NET as a way to interact
with a data base.
As you are probably aware, there are many different types of databases available. For example,
there is Microsoft SQL Server, Microsoft Access, Oracle, Borland Interbase, and IBM DB2, just
to name a few. To further refine the scope of this tutorial, all of the examples will use SQL
Server.
ADO.NET is a set of classes that expose data access services to the .NET developer. The
ADO.NET classes are found in System.Data.dll and are integrated with the XML classes in
System.Xml.dll.
There are two central components of ADO.NET classes: the DataSet, and the .NET Framework
Data Provider.
Data Provider is a set of components including:
• the Connection object (SqlConnection, OleDbConnection, OdbcConnection,
OracleConnection)
• the Command object (SqlCommand, OleDbCommand, OdbcCommand, OracleCommand)
• the DataReader object (SqlDataReader, OleDbDataReader, OdbcDataReader,
OracleDataReader)
• the DataAdapter object (SqlDataAdapter, OleDbDataAdapter, OdbcDataAdapter,
OracleDataAdapter).
DataSet object represents a disconnected cache of data which is made up of DataTables and
DataRelations that represent the result of the command.
The ADO.NET Object Model
DataSet:-
The DataSet is similar to an array of disconnected Recordset objects. It supports disconnected
data access and operations, allowing greater scalability because you no longer have to be
connected to the database all the time. DataSet is a copy of an extracted data being downloaded
and cached in the client system.
The DataSet object is made up of two objects:
• DataTableCollection object containing null or multiple DataTable objects (Columns,
Rows, Constraints).
• DataRelationCollection object containing null or multiple DataRelation objects
which establish a parent/child relation between two DataTable objects.
//Create a DataSet
DataSet dset = new DataSet();
There are two types of DataSets:
1. Typed DataSet
2. Untyped DataSet
1. Typed DataSet is derived from the base DataSet class and then uses information in an XML
Schema file (.xsd file) in order to generate a new class. Information from the schema (tables,
columns, and so on) is generated and compiled into this new DataSet class as a set of first-class
objects and properties. Typed dataset is easier to read. It's also supported by IntelliSense in the
Visual Studio Code Editor. At compile time, it has type checking so that there are less errors in
assigning values to DataSet members. Therefore, using Typed DataSet has many advantages.
2. Untyped DataSet is not defined by a schema, instead, you have to add tables, columns and other
elements to it yourself, either by setting properties at design time or by adding them at run time. Typical
scenario: if you don't know in advance what the structure of your program is that is interacting with a
component that returns a DataSet.
When you decide whether your application should use a DataReader (see Retrieving Data Using
a DataReader) or a DataSet (see DataSets, DataTables, and DataViews), consider the type of
functionality that your application requires. Use a DataSet to do the following:
• Cache data locally in your application so that you can manipulate it. If you only need to
read the results of a query, the DataReader is the better choice.
• Remote data between tiers or from an XML Web service.
• Interact with data dynamically such as binding to a Windows Forms control or
combining and relating data from multiple sources.
• Perform extensive processing on data without requiring an open connection to the data
source, which frees the connection to be used by other clients.
 DataAdapter:-
In ADO.NET, a DataAdapter functions as a bridge between a data source, and a disconnected
data class, such as a DataSet. At the simplest level it will specify SQL commands that provide
elementary CRUD functionality. At a more advanced level it offers all the functions required in
order to create Strongly Typed DataSets, including DataRelations. Data adapters are an integral
part of ADO.NET managed providers, which are the set of objects used to communicate
between a data source and a dataset. (In addition to adapters, managed providers include
connection objects, data reader objects, and command objects.) Adapters are used to exchange
data between a data source and a dataset. In many applications, this means reading data from
a database into a dataset, and then writing changed data from the dataset back to the
database. However, a data adapter can move data between any source and a dataset. For
example, there could be an adapter that moves data between a Microsoft Exchange server and
a dataset.
SELECT statement using SqlDataAdapter
string ConnectionString = "Integrated Security = SSPI;" +
"Initial catalog = Northwind; " + " Data Source = localhost; ";
string SQL = "SELECT CustomerID, CompanyName FROM Customers";
SqlConenction conn = new SqlConnection(ConnectionString);
// open the connection
conn.Open();
// Create a SqlDataAdapter object
SqlDataAdapter adapter = new SqlDataAdapter(SQL, conn);
Create an ODBC Database Connection:-
If you have an ODBC database called "northwind" you can connect to the database with the
following ASP code:
<%
set conn=Server.CreateObject("ADODB.Connection")
conn.Open "northwind"
%>
With an ODBC connection, you can connect to any database, on any computer in your network,
as long as an ODBC connection is available.
An ODBC Connection to an MS Access Database
Here is how to create a connection to a MS Access Database:
1. Open the ODBC icon in your Control Panel.
2. Choose the System DSN tab.
3. Click on Add in the System DSN tab.
4. Select the Microsoft Access Driver. Click Finish.
5. In the next screen, click Select to locate the database.
6. Give the database a Data Source Name (DSN).
7. Click OK.
Note that this configuration has to be done on the computer where your web site is located. If
you are running Personal Web Server (PWS) or Internet Information Server (IIS) on your own
computer, the instructions above will work, but if your web site is located on a remote server,
you have to have physical access to that server, or ask your web host to do this for you.
 ADO.NET Objects:-
ADO.NET includes many objects you can use to work with data. This section introduces some of
the primary objects you will use. Over the course of this tutorial, you'll be exposed to many
more ADO.NET objects from the perspective of how they are used in a particular lesson. The
objects below are the ones you must know. Learning about them will give you an idea of the
types of things you can do with data when using ADO.NET.
The SqlConnection Object:-
To interact with a database, you must have a connection to it. The connection helps identify the
database server, the database name, user name, password, and other parameters that are
required for connecting to the data base. A connection object is used by command objects so
they will know which database to execute the command on.
The SqlCommand Object:-
The process of interacting with a database means that you must specify the actions you want to
occur. This is done with a command object. You use a command object to send SQL statements
to the database. A command object uses a connection object to figure out which database to
communicate with. You can use a command object alone, to execute a command directly, or
assign a reference to a command object to an SqlDataAdapter, which holds a set of commands
that work on a group of data as described below.
The SqlDataReader Object:-
Many data operations require that you only get a stream of data for reading. The data reader
object allows you to obtain the results of a SELECT statement from a command object. For
performance reasons, the data returned from a data reader is a fast forward-only stream of
data. This means that you can only pull the data from the stream in a sequential manner This is
good for speed, but if you need to manipulate data, then a DataSet is a better object to work
with.
The DataSet Object:-
DataSet objects are in-memory representations of data. They contain multiple Datatable
objects, which contain columns and rows, just like normal database tables. You can even define
relations between tables to create parent-child relationships. The DataSet is specifically
designed to help manage data in memory and to support disconnected operations on data,
when such a scenario make sense. The DataSet is an object that is used by all of the Data
Provders, which is why it does not have a Data Provider specific prefix.
S.NO RGPV QUESTIONS Year Marks
Q.1 Write short notes:
i)Data Adapter Objection) Data Reader Object
Dec2010 10
Q.2 Describe the procedure of accessing database with
ADO.NET.Explain the advantages and drawback of using
ADO.NET.
Dec2013 07
Unit-04/Lecture-03
Advanced Interface Patterns: Adapters and Delegates understanding deligates,
declearing the delegate. [RGPV/June2009,Dec2010,Dec2011]
 Adapters:-
Definition: Convert the interface of a class into another interface clients expect. Adapter lets
classes work together that couldn't otherwise because of incompatible interfaces.
The classes and/or objects participating in this pattern are:
• Target (ChemicalCompound)
o Defines the domain-specific interface that Client uses.
• Adapter (Compound)
o Adapts the interface Adaptee to the Target interface.
• Adaptee (ChemicalDatabank)
o Defines an existing interface that needs adapting.
• Client (AdapterApp)
o Collaborates with objects conforming to the Target interface.
sample code in C#
This structural code demonstrates the Adapter pattern which maps the interface of one class
onto another so that they can work together. These incompatible classes may come from
different libraries or frameworks.
Show code
// Adapter pattern -- Structural example
UML class diagram
The Data Adapter
The Data Adapter is a property of the OLEDB object, hence the full stop between the two:
OleDb.OleDbDataAdapter
We're passing this object to the variable called da. This variable will then hold a reference to
the Data Adapter.
While the second line in the code above sets up a reference to the Data Adapter, the third line
creates a new Data Adapter object. You need to put two things in the round brackets of the
Object declaration: Your SQL string (which we'll get to shortly), and your connection object. Our
Connection Object is stored in the variable which we've called con. (Like all variable you can call
it practically anything you like. We've gone for something short and memorable.) You then pass
the New Data Adapter to your variable (da for us):
da = New OleDb.OleDbDataAdapter(sql, con )
We need something else, though. The sql in between the round brackets is the name of a
variable. We haven't yet set this up. We'll have a look at SQL in a moment. But bear in mind
what the Data Adaptor is doing: Acting as a go-between for the Connection Object and the
Data Set
 Delegates:-
Delegates are objects that refer to methods. They are sometimes described as type-safe
function pointers because they are similar to function pointers used in other
programming languages. But unlike function pointers, Visual Basic delegates are a
reference type based on the class System.Delegate. Delegates can reference both
shared methods — methods that can be called without a specific instance of a class —
and instance methods.
Instantiating Delegates
public delegate void printString(string s);
...
printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);
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. For example:
Before using a delegate, you must create it or you can use one of the built-in delegates of the
.NET Framework. The basic formula to create a delegate is:
[modifier] Delegate Sub/Function Name (parameter(s)) As ReturnType
The modifier factor can be Public, Private, or Friend. This is followed by either the Delegate Sub
or the Delegate Function expression.
A delegate must have a name: The Name factor of this formula. The name follows the rules we
have been observing for valid names of the Visual Basic language.
Because a delegate is some type of a template for a procedure, you must use parentheses. If
this procedure will not take any argument, you can leave the parentheses empty.
If the delegate will be associated with a sub-procedure, there is no return type. Here is an
example:
Module Exercise
Delegate Sub Messenger()
End Module
If the delegate is a function-type, you must specify a ReturnType. This can be any of the data
types we have used so far, or it can be a class.
Delegates and Classes:-
When it comes to delegates, not only can you use a normal procedure, you can use the method
of a class to associate to a delegate. You can start by creating the class and the necessary
method. Here is an example:
Module Exercise
Private Class Example
Public Sub Welcome()
MsgBox("A delegate with class")
End Sub
End Class
End Module
Of course, before using the delegate, you must declare it. This is done exactly as previously. The
delegate must be of the same type as the method (sub-procedure or function).
Delegates are pointers that are used to store and tranfer information like the memory
address, event handled by functions and subroutines. Delagates are type safe, since they check
for the signatures of functions and subroutines only if same, they transfer information. A
delegate is declared using the keyword Delegate to a function or procedure name.
Example:
Module Module1
Public Delegate Function del1(ByVal x As Integer,
ByVal y As Integer) As Integer
Public Delegate Sub Display()
Public Function check(ByVal x As Integer,
ByVal y As Integer) As Integer
Return (x + y)
End Function
Public Function multi(ByVal x As Integer,
ByVal y As Integer) As Integer
Return (x * y)
End Function
Class deleg
Public Sub Disp()
Console.WriteLine("Method inside the Class")
Unit-04/Lecture-04
Introduction to Window forms creation, Introduction to Threading
[RGPV/Dec2010,Dec2011]
Let's start with creating a Window Forms Application by following the following steps in
Microsoft Visual Studio: File -> New Project -> Windows Forms Applications
Finally, select OK, Microsoft Visual Studio creates your project and displays following window
Form with a name Form1.
Visual Basic Form is the container for all the controls that make up the user interface. Every
window you see in a running visual basic application is a form, thus the terms form and window
describe the same entity. Visual Studio creates a default form for you when you create a
Windows Forms Application.
Every form will have title bar on which the form's caption is displayed and there will be buttons
to close, maximize and minimize the form shown below:
If you click the icon on the top left corner, it opens the control menu, which contains the
various commands to control the form like to move control from one place to another place, to
maximize or minimize the form or to close the form.
 Introduction to Threading:-
A thread is a sequence of instructions executed within the context of a process.
MultiThreading is achieved when a program uses multiple execution threads allowing
each thread to share the CPU concurrently depending on the priority assigned to these
threads. This helps in the optimum usage of System Resources.
The System.Threading namespace provides classes and interfaces that enable multi-
threaded programming. This namespace includes a ThreadPool class that manages groups
of threads, a Timer class that enables a delegate to be called after a specified amount of
time, and a Mutex class for synchronizing mutually-exclusive threads. I also provides
classes for thread scheduling, wait notification, and deadlock resolution.
using System.Threading;
Creating Threads:-
Creating a thread in C# is close to trivial, but not quite. The only non-trivial thing about creating
a thread is .NET delegate-classes. Let me explain in few words what is a delegate class. The
delegate is a wrapper around a code construct in the .NET. The code construct could be an
object instance, an instance method or a static method.
Delegates are used when you want to pass one of the three code constructs as a parameter to
another method. When creating a new thread you have to use the ThreadStart delegate
class to wrap the instance method that will be executed in the newly created thread. The
instance method must return void and must not have any parameters.
void ThreadStart()
To create a new thread, first create a new ThreadStart object, passing the instance method of
the thread procedure in the constructor. The new delegate object is then passed to the
constructor of the Thread.
To create a new thread, first create a new ThreadStart object, passing the instance method of
the thread procedure in the constructor. The new delegate object is then passed to the
constructor of the Thread.
Thread thread = new Thread(
new ThreadStart(obj.ThreadStart));
Example:-
using System;
using System.Threading;
class Program
{
static void Main()
{
Thread thread1 = new Thread(new ThreadStart(A));
Thread thread2 = new Thread(new ThreadStart(B));
thread1.Start();
thread2.Start();
thread1.Join();
thread2.Join();
}
static void A()
{
Thread.Sleep(100);
Console.WriteLine('A');
}
static void B()
{
Thread.Sleep(1000);
Console.WriteLine('B');
}
}
Out put
A
B
 Multithreading:-
A thread is an independent stream of instructions in a program. Each written program is a
paradigm of sequential programming in which they have a beginning, an end, a sequence, and
a single point of execution. A thread is similar to sequential program. However, a thread itself
is not a program, it can’t run on its own, but runs within a program.
The real concern surrounding threads is not about a single sequential thread, but rather the
use of multiple threads in a single program all running at the same time and performing
different tasks. This mechanism referred as Multithreading. A thread is considered to be a
lightweight process because it runs within the context of a program and takes advantage of
resources allocated for that program.
Threads are important both for client and server applications. While in C# program coding,
when you type something in editor, the dynamic help (intellisense) Windows immediately
shows the relevant topics that fit to the code. One thread is waiting for input from the user,
while other does some background processing. A third thread can store the written data in a
temporary file, while another one downloads a file from a specific location.
With the task manager, you can turn on the Thread column and see the processes and the
number of threads for every process. Here, you can notice that only cmd.exe is running inside a
single thread while all other applications use multiple threads.
Example:
using System;
using System.Threading;
public class Test
{
static void Main()
{
ThreadStart job = new ThreadStart(ThreadJob);
Thread thread = new Thread(job);
thread.Start();
for (int i=0; i < 5; i++)
{
Console.WriteLine ("Main thread: {0}", i);
Thread.Sleep(1000);
}
}
static void ThreadJob()
{
for (int i=0; i < 10; i++)
{
Console.WriteLine ("Other thread: {0}", i);
Thread.Sleep(500);
}
}
S.NO RGPV QUESTIONS Year Marks
Q.1 Write short notes: Multithreading. Dec2010 04
Q.2 Write a short notes: Form designer Dec2010 04
Q.3 How to stop closing process of form?Explain with
example
Dec2011 10
Unit-04/Lecture-05
MDI Applications:Creating MDI Parent/Child [RGPV/Dec2009]
The Multiple Document Interface (MDI) :-
The Multiple Document Interface (MDI) was designed to simplify the exchange of information
among documents, all under the same roof. With the main application, you can maintain
multiple open windows, but not multiple copies of the application. Data exchange is easier
when you can view and compare many documents simultaneously.
You almost certainly use Windows applications that can open multiple documents at the same
time and allow the user to switch among them with a mouse-click. Multiple Word is a typical
example, although most people use it in single document mode. Each document is displayed in
its own window, and all document windows have the same behavior. The main Form, or MDI
Form, isn't duplicated, but it acts as a container for all the windows, and it is called the parent
window. The windows in which the individual documents are displayed are called Child
windows.
An MDI application must have at least two Form, the parent Form and one or more child Forms.
Each of these Forms has certain properties. There can be many child forms contained within the
parent Form, but there can be only one parent Form.
The parent Form may not contain any controls. While the parent Form is open in design mode,
the icons on the ToolBox are not displayed, but you can't place any controls on the Form. The
parent Form can, and usually has its own menu.
To create an MDI application, follow these steps:
1. Start a new project and then choose Project >>> Add MDI Form to add the parent Form.
2. Set the Form's caption to MDI Window
3. Choose Project >>> Add Form to add a SDI Form.
4. Make this Form as child of MDI Form by setting the MDI Child property of the SDI Form
to True. Set the caption property to MDI Child window.
Parent and Child Menus
MDI Form cannot contain objects other than child Forms, but MDI Forms can have their own
menus. However, because most of the operations of the application have meaning only if there
is at least one child Form open, there's a peculiarity about the MDI Forms. The MDI Form
usually has a menu with two commands to load a new child Form and to quit the application.
The child Form can have any number of commands in its menu, according to the application.
When the child Form is loaded, the child Form's menu replaces the original menu on the MDI
Form
Following example illustrates the above explanation.
* Open a new Project and name the Form as Menu.frm and save the Project as Menu.vbp
* Design a menu that has the following structure.
<> MDIMenu Menu caption
• MDIOpen opens a new child Form
• MDIExit terminates the application
* Then design the following menu for the child Form
<> ChildMenu Menu caption
• Child Open opens a new child Form
• Child Save saves the document in the active child Form
• Child Close Closes the active child Form
At design time double click on MDI Open and add the following code in the click event of the
open menu.
Form1.Show
And so double click on MDI Exit and add the following code in the click event
End
Double click on Child Close and enter the following code in the click event
Unload Me
Before run the application in the project properties set MDI Form as the start-up Form. Save
and run the application. Following output will be displayed.
An essential element of Multiple-Document Interface (MDI) Applications is MDI child forms, as
these are the center of user interaction.
In the following procedure, you will create MDI child forms that display a RichTextBox control,
similar to most word-processing applications. Substituting the RichTextBox control with other
controls, such as the DataGrid control, or a mixture of controls allows you to create MDI child
windows (and, by extension, MDI applications) with diverse possibilities.
To create an MDI parent form at design time
1. Create a Windows Application. For more information, see Creating a Windows
Application Project.
2. In the Properties window, set the IsMDIContainer property to true.
This designates the form as an MDI container for child windows.
Note While setting properties in the Properties window, you can also set the
WindowState property to Maximized, if you like, as it is easiest to manipulate MDI child
windows when the parent form is maximized. Additionally, be aware that the edge of
the MDI parent form will pick up the system color (set in the Windows System control
panel), rather than the back color you set using the Control.BackColor property.
3. From the Toolbox, drag a MainMenu component to the form. Create a top-level menu
item with the Text property set to &File with submenu items called &New and &Close.
Also create a top-level menu item called &Window.
The first menu will create, and hide menu items at run time, and the second menu will
keep track of the open MDI child windows. At this point, you have created an MDI
parent window. For more information on creating menus and menu items, see Adding
Menus and Menu Items to Windows Forms.
4. Press F5 to run the application. For information about creating MDI child windows that
operate within the MDI parent form, see Creating MDI Child Forms.
To create MDI child forms
1. Create an MDI parent form that has a menu structure containing File and Window top-
level menu items and New and Close menu items. For more information on creating
MDI parent forms, see Creating MDI Parent Forms.
2. In the drop-down list at the top of the Properties window, select the menu item that
corresponds to the &Window menu item and set the MdiList property to true.
This will enable the Window menu to maintain a list of open MDI child windows with a
check mark next to the active child window.
3. In Solution Explorer, right-click the project, point to Add, and then select Add New Item.
This form will be the template for your MDI child forms.
Note The MDI child form you create in this step is a standard Windows Form. As such,
it has an Opacity property, which allows you to control the transparency of the form.
However, the Opacity property was designed for top-level windows. Do not use it with
MDI child forms, as painting problems can occur.
4. In the Add New Item dialog box, select Windows Form (in Visual Basic or in Visual C#) or
Windows Forms Application (.NET) (in Visual C++) from the Templates pane. In the
Name box, name the form Form2. Click the Open button to add the form to the project.
The Windows Forms Designer opens, displaying Form2.
5. Drag a RichTextBox control from the Toolbox to the form.
6. In the Properties window, set the Anchor property to Top, Left and the Dock property
to Fill.
This causes the RichTextBox control to completely fill the area of the MDI child form,
even when the form is resized.
7. Create a Click event handler for the New menu item. For more information about
creating event handlers, see Creating Event Handlers on the Windows Forms Designer.
8. Insert code similar to the following to create a new MDI child form when the user clicks
the New menu item (In the example below, the event handler handles the Click event
for MenuItem2. Be aware that, depending on the specifics of your application
architecture, your New menu item may not be MenuItem2.)
Visual Basic
Protected Sub MDIChildNew_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MenuItem2.Click
Dim NewMDIChild As New Form2()
'Set the Parent Form of the Child window.
NewMDIChild.MdiParent = Me
'Display the new form.
NewMDIChild.Show()
End Sub
// C#
protected void MDIChildNew_Click(object sender, System.EventArgs e){
Form2 newMDIChild = new Form2();
// Set the Parent Form of the Child window.
newMDIChild.MdiParent = this;
// Display the new form.
newMDIChild.Show();
}
// C++
private:
System::Void menuItem2_Click(System::Object * sender,
System::EventArgs * e)
{
Form2 *newMDIChild = new Form2();
// Set the Parent Form of the Child window.
newMDIChild->MdiParent = this;
// Display the new form.
newMDIChild->Show();
}
Unit-04/Lecture-06
Events Data Processing and I/O: Menus and tool bars, Collecting
Input:Button,Textbox,Checkbox, radio button,commbobox[RGPV/Dec2013]
Menus and tool bars:-
 Button Control
Button Control in VB.NET is used to trigger some action for the form. Just by clicking
on the button the information is managed effectively in Visual Basic. The Button control
represents a standard Windows button. It is generally used to generate a Click event by
providing a handler for the Click event.
Explanation:
• Select the form on which the button resides.
• In the Properties window, set the form's Button property to the Button control's name.
• To respond to a button click, In the button's Click event handler write the code to run.
Button1_Click must be bound to the control.
• ForeColor,Text properties of the button control are changed.
• Click event of the button is used to display a message.
create a label by dragging a Button control from the Toolbox ad dropping it on the form.
S.NO RGPV QUESTIONS Year Marks
Q.1 Discuss the Multiple Document Interface (MDI).How to
create MDI child form.
Dec2009 10
 Textbox:-
Text box controls allow entering text on a form at runtime. By default, it takes a single line of
text, however, you can make it accept multiple texts and even add scroll bars to it.
Let's create a text box by dragging a Text Box control from the Toolbox and dropping it on the
form.
The Text property is the one you'll reference most often in code, and conveniently it's the
default property for the TextBox control. Three other frequently used properties are these:
• The SelStart property sets or returns the position of the blinking caret (the insertion
point where the text you type appears). Note that the blinking cursor inside TextBox and
other controls is named caret, to distinguish it from the cursor (which is implicitly the
mouse cursor). When the caret is at the beginning of the contents of the TextBox
control, SelStart returns 0; when it's at the end of the string typed by the user, SelStart
returns the value Len(Text). You can modify the SelStart property to programmatically
move the caret.
• The SelLength property returns the number of characters in the portion of text that has
been highlighted by the user, or it returns 0 if there's no highlighted text. You can assign
a nonzero value to this property to programmatically select text from code.
Interestingly, you can assign to this property a value larger than the current text's length
without raising a run-time error.
• The SelText property sets or returns the portion of the text that's currently selected, or
it returns an empty string if no text is highlighted. Use it to directly retrieve the
highlighted text without having to query Text, SelStart, and SelLength properties. What's
even more interesting is that you can assign a new value to this property, thus replacing
the current selection with your own. If no text is currently selected, your string is simply
inserted at the current caret position.
When you want to append text to a TextBox control, you should use the following code (instead
of using the concatenation operator) to reduce flickering and improve performance:
Text1.SelStart = Len(Text1.Text)
Text1.SelText = StringToBeAdded
One of the typical operations you could find yourself performing with these properties is
selecting the entire contents of a TextBox control.
 Checkbox:-
The CheckBox control allows the user to set true/false or yes/no type options. The user can
select or deselect it. When a check box is selected it has the value True, and when it is cleared,
it holds the value False.
Let's create two check boxes by dragging CheckBox controls from the Toolbox and dropping on
the form.
The CheckBox control has three states, checked, unchecked and indeterminate. In the
indeterminate state, the check box is grayed out. To enable the indeterminate state, the
ThreeState property of the check box is set to be True.
S.N Property Description
1 Appearance Gets or sets a value determining the appearance of the check box.
2 AutoCheck Gets or sets a value indicating whether the Checked or
CheckedState value and the appearance of the control
automatically change when the check box is selected.
3 CheckAlign
Gets or sets the horizontal and vertical alignment of the check
mark on the check box.
4 Checked Gets or sets a value indicating whether the check box is selected.
5 CheckState Gets or sets the state of a check box.
6 Text Gets or sets the caption of a check box.
7 ThreeState
Gets or sets a value indicating whether or not a check box should
allow three check states rather than two.
radio button
The RadioButton control is used to provide a set of mutually exclusive options. The user can
select one radio button in a group. If you need to place more than one group of radio buttons in
the same form, you should place them in different container controls like a GroupBox control.
Let's create three radio buttons by dragging RadioButton controls from the Toolbox and
dropping on the form.
The Checked property of the radio button is used to set the state of a radio button. You can
display text, image or both on radio button control. You can also change the appearance of the
radio button control by using the Appearance property.
Properties of the RadioButton Control
The following are some of the commonly used properties of the RadioButton control:
S.N Property Description
1 Appearance
Gets or sets a value determining the appearance of the radio
button.
2 AutoCheck
Gets or sets a value indicating whether the Checked value and the
appearance of the control automatically change when the control
is clicked.
3 CheckAlign
Gets or sets the location of the check box portion of the radio
button.
4 Checked Gets or sets a value indicating whether the control is checked.
5 Text Gets or sets the caption for a radio button.
6 TabStop
Gets or sets a value indicating whether a user can give focus to
the RadioButton control using the TAB key.
 Commbobox:-
The ComboBox control is used to display a drop-down list of various items. It is a combination
of a text box in which the user enters an item and a drop-down list from which the user selects
an item.
Let's create a combo box by dragging a ComboBox control from the Toolbox and dropping it on
the form.
You can populate the list box items either from the properties window or at runtime. To add
items to a ListBox, select the ListBox control and go to the properties window for the properties
of this control. Click the ellipses (...) button next to the Items property. This opens the String
Collection Editor dialog box, where you can enter the values one at a line.
Properties of the ComboBox Control:-
The following are some of the commonly used properties of the ComboBox control:
S.N Property Description
1 AllowSelection
Gets a value indicating whether the list enables selection of
list items.
2 AutoComplete
CustomSource
Gets or sets a custom
System.Collections.Specialized.StringCollection to use when
the AutoCompleteSourceproperty is set to CustomSource.
3 AutoCompleteMode
Gets or sets an option that controls how automatic
completion works for the ComboBox.
4 AutoCompleteSource
Gets or sets a value specifying the source of complete
strings used for automatic completion.
5 DataBindings Gets the data bindings for the control.
6 DataManager Gets the CurrencyManager associated with this control.
Unit-04/Lecture-07
S.NO RGPV QUESTIONS Year Marks
Q.1 What are the features of a combo box control? Write
properties and methods of combo box with description of
each.
Dec2013 07
Q.2 Write steps to create and run an application that displays and
hides the controls and form.
Dec2013 07
Special controls:calendar,list box, labeling statusbar,icon,picture box,
image[RGPV/June2009]
 Calendar:-
This control is used to select a date in an application at runtime. Using this control calendar for
one or more months can be displayed, so that a single date or a range of dates can be selected
using this control.
Explanation:
• The DateSelected event of the Month Calendar Control is used.
• Using the SelectRange property, the month of the starting date of selection is returned.
• Textbox displays the month as an integer value.
Properties Description
AnnuallyBoldedDate
Property holds an array of DateTime objects specifying which days
should be bold.
BoldedDates
Property used to Get or sets an array of DateTime objects specifying
which dates shpuld be bold.
CalendarDimensions Property used to Get or set the number of columns.
FirstDayOfWeek Property to get or set the first day of the week.
MaxDate Property to get or set the maximum possible date.
MaxSelectionCount Property holds the maximum number of days that can be selected.
MinDate Property to get or set the minimum possible date.
ScrollChange Property holds the scroll rate.
SelectionEnd Property used to set or get the end date of the selected range.
SelectionRange Property used to get the selected range of date from the control.
SelectionStart Property used set or get the start date of the selected range.
SingleMonthSize Property returns the minimum size in which to display a month.
ShowTodayCircle Property set the todays date inside a circle.
TodaysDate Property set or get the todays date.
TodayDateSet Property specifies whether the Date Time property has been set.
 list box:-
The ListBox represents a Windows control to display a list of items to a user. A user can select
an item from the list. It allows the programmer to add items at design time by using the
properties window or at the runtime.
Let's create a list box by dragging a ListBox control from the Toolbox and dropping it on the
form.
You can populate the list box items either from the properties window or at runtime. To add
items to a ListBox, select the ListBox control and get to the properties window, for the
properties of this control. Click the ellipses (...) button next to the Items property. This opens
the String Collection Editor dialog box, where you can enter the values one at a line.
 Picture box:-
PictureBox Control is used to display an image of the file formats like png, gif, jpeg, bmp, wmf,
ico, pcx, tga, tiff. Images can be loaded either at the design time or at runtime.
The PictureBox control is used for displaying images on the form. The Image property of the
control allows you to set an image both at design time or at run time.
Let's create a picture box by dragging a PictureBox control from the Toolbox and dropping it on
the form.
You can load images in many different graphic formats, including bitmaps (BMP), device
independent bitmaps (DIB), metafiles (WMF), enhanced metafiles (EMF), GIF and JPEG
compressed files, and icons (ICO and CUR). You can decide whether a control should display a
border, resetting the BorderStyle to 0-None if necessary. Another property that comes handy in
this phase is AutoSize: Set it to True and let the control automatically resize itself to fit the
assigned image.
Picture1.Picture = LoadPicture("c:windowssetup.bmp")
and you can clear the current image using either one of the following statements:
' These are equivalent.
Picture1.Picture = LoadPicture("")
Set Picture1.Picture = Nothing
The LoadPicture function has been extended in Visual Basic 6 to support icon files containing
multiple icons.
 ProgressBar Control:-
Progress Bar Control is used to display the progress of a task in Visual Basic. Mostly
the progress bar is used while accessing the databases, or downloading or copying files
from the network resources.
Explanation:
• Using the click event of a button the timer is enabled first.
• With the timer tick event the progress bar value is increased till its maximum in a loop.
• When the progress bar is at its maximum the timer is disabled.
Unit-04/Lecture-08
S.NO RGPV QUESTIONS Year Marks
Q.1 Explain List box control. How we can add items to list box?
Also explain multi list box.
June2009 10
List view,tree view ,date and time picker, tool bars
 List view:-
ListView Control is used to display the list of items as in the right pane of windows explorer.
Type of icons can be added to these controls easily, items can be arranged neatly.
Explanation:
• A List view control and a text box control is used in the example.
• Add the listview items using the Items property.
• Using the SelectedIndexChanged event, the SelectedIndices value is checked.
• Based on the item selected, the TextBox displays a message.
The ListView control is used to display a list of items. Along with the TreeView control, it allows
you to create a Windows Explorer like interface.
Let's click on a ListView control from the Toolbox and place it on the form.
The ListView control displays a list of items along with icons. The Item property of the ListView
control allows you to add and remove items from it. The SelectedItem property contains a
collection of the selected items. The MultiSelect property allows you to set select more than
one item in the list view. The CheckBoxes property allows you to set check boxes next to the
item
 Tree view:-
TreeView Control is used to display parent, child nodes in a hierarchy just as in windows
explorer window that can be collapsed when clicked.
The TreeView control is used to display hierarchical representations of items similar to the ways
the files and folders are displayed in the left pane of the Windows Explorer. Each node may
contain one or more child nodes.
Let's click on a TreeView control from the Toolbox and place it on the form.
Explanation:
• Root Nodes and Child Nodes are added to the control using the Nodes property.
• Appropriate names are provided to the nodes.
• AfterSelect event of the control is used to set blue color for the selected nodes alone.
• Thus you can know about treeview control in VB.NET.
 Date and Time:-
DateTimePicker Control is used select a date and time for a date range specified using a
MinDate and MaxDate properties.
The DateTimePicker control allows selecting a date and time by editing the displayed values in
the control. If you click the arrow in the DateTimePicker control, it displays a month calendar,
like a combo box control. The user can make selection by clicking the required date. The new
selected value appears in the text box part of the control.
The MinDate and the MaxDate properties allow you to put limits on the date range.
Explanation:
• A Label,DateTimePicker and button control is used in the example.
• The Date range is set to the DateTimePicker Control using the MinDate and MaxDate
property.
• On the button click event, the value of the DateTimePicker is returned.
• The value of selected is displayed in the Text Box
S.NO RGPV QUESTIONS Year Marks
Q.1
Unit-04/Lecture-09
Progress bar,grids,Tool tip,The error provider Control
 Progress bar:-
Progress Bar Control is used to display the progress of a task in Visual Basic. Mostly the
progress bar is used while accessing the databases, or downloading or copying files from the
network resources.
It represents a Windows progress bar control. It is used to provide visual feedback to your users
about the status of some task. It shows a bar that fills in from left to right as the operation
progresses.
Let's click on a ProgressBar control from the Toolbox and place it on the form.
The main properties of a progress bar are Value, Maximum and Minimum. The Minimum and
Maximum properties are used to set the minimum and maximum values that the progress bar
can display. The Value property specifies the current position of the progress bar.
The ProgressBar control is typically used when an application performs tasks such as copying
files or printing documents. To a user the application might look unresponsive if there is no
visual cue. In such cases, using the ProgressBar allows the programmer to provide a visual
status of progress.
Explanation:
• Using the click event of a button the timer is enabled first.
• With the timer tick event the progress bar value is increased till its maximum in a loop.
• When the progress bar is at its maximum the timer is disabled.
 Tool bars:-
Tooltip Control is used to display explanatory text when the mouse rest on a control or
window. This control is helpful in providing a quick help to users.
Explanation:
• First the BackColor and ForeColor property is set for the tooltip control.
• Type of icon is set using the ToolTipIcon property.
Using the MouseHover event of a textbox, the tooltip is displayed
ErrorProvider control
The errorprovider control provides a user interface to indicate to the user that a control on a
form has an error associated with it, or The ErrorProvider component provides an easy way to
set validation errors. It allows us to set an error message for any control on the form when the
input is not valid. When an error message is set, an icon indicating the error will appear next to
the control and the error message is displayed as Tool Tip when the mouse is over the control.
 Errorprovider properties:-
Icon - Icon property are used to indicate an error.
ContainerControl - ContainerControl property are used to parent control, usually the form, that
contains the data-bound controls on which the errorprovider can display error icon.
The Windows Forms ErrorProvider component is used to validate user input on a form or
control. It is typically used in conjunction with validating user input on a form, or displaying
errors within a dataset. An error provider is a better alternative than displaying an error
message in a message box, because once a message box is dismissed, the error message is no
longer visible. TheErrorProvider component displays an error icon ( ) next to the relevant
control, such as a text box; when the user positions the mouse pointer over the error icon, a
ToolTip appears, showing the error message string.
The ErrorProvider component's key properties are DataSource, ContainerControl, and Icon.
The ContainerControl property must be set to the appropriate container (usually the Windows
Form) in order for the ErrorProvider component to display an error icon on the form. When the
component is added in the designer, the ContainerControl property is set to the containing
form; if you add the control in code, you must set it yourself.
Displaying Error Icons for Form Validation with the Windows Forms ErrorProvider Component
You can use a Windows Forms ErrorProvider component to display an error icon when the user
enters invalid data. You must have at least two controls on the form in order to tab between
them and thereby invoke the validation code.
To display an error icon when a control's value is invalid
1. Add two controls - for example, text boxes - to a Windows Form.
2. Add an ErrorProvider component to the form.
3. Select the first control and add code to its Validating event handler. In order for this
code to run properly, the procedure must be connected to the event. For more
information, seeCreating Event Handlers on the Windows Forms Designer, Creating
Event Handlers at Run Time for Windows Forms, and Creating Event Handlers in the
Visual Basic Code Editor.
The following code tests the validity of the data the user has entered; if the data is
invalid, the SetError method is called. The first argument of the SetError method
specifies which control to display the icon next to. The second argument is the error text
to display.
Private Sub TextBox1_Validating (ByVal Sender As Object, _
ByVal e As System.ComponentModel.CancelEventArgs) Handles _
TextBox1.Validating
If Not IsNumeric(TextBox1.Text) Then
ErrorProvider1.SetError(TextBox1, "Not a numeric value.")
Else
' Clear the error.
ErrorProvider1.SetError(TextBox1, "")
End If
End Sub
Mca 504 dotnet_unit4

More Related Content

What's hot

Design Patterns & JDK Examples
Design Patterns & JDK ExamplesDesign Patterns & JDK Examples
Design Patterns & JDK ExamplesEnder Aydin Orak
 
Design Patterns
Design PatternsDesign Patterns
Design Patternssoms_1
 
Unified Modeling Language (UML)
Unified Modeling Language (UML)Unified Modeling Language (UML)
Unified Modeling Language (UML)ppd1961
 
Unified Modeling Language
Unified Modeling LanguageUnified Modeling Language
Unified Modeling Languagesurana college
 
UML Diagrams- Unified Modeling Language Introduction
UML Diagrams- Unified Modeling Language IntroductionUML Diagrams- Unified Modeling Language Introduction
UML Diagrams- Unified Modeling Language IntroductionRamakant Soni
 
Design patterns ppt
Design patterns pptDesign patterns ppt
Design patterns pptAman Jain
 
Brief Introduction to Domain Modeling
Brief Introduction to Domain ModelingBrief Introduction to Domain Modeling
Brief Introduction to Domain ModelingGraham McLeod
 
UML- Unified Modeling Language
UML- Unified Modeling LanguageUML- Unified Modeling Language
UML- Unified Modeling LanguageShahzad
 
Intro to UML - Use Case diagrams
Intro to UML - Use Case diagramsIntro to UML - Use Case diagrams
Intro to UML - Use Case diagramsjsm1979
 
Design Patterns Presentation - Chetan Gole
Design Patterns Presentation -  Chetan GoleDesign Patterns Presentation -  Chetan Gole
Design Patterns Presentation - Chetan GoleChetan Gole
 
Basic design pattern interview questions
Basic design pattern interview questionsBasic design pattern interview questions
Basic design pattern interview questionsjinaldesailive
 

What's hot (20)

Design Patterns & JDK Examples
Design Patterns & JDK ExamplesDesign Patterns & JDK Examples
Design Patterns & JDK Examples
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
UML Trainings
UML TrainingsUML Trainings
UML Trainings
 
Design Pattern
Design PatternDesign Pattern
Design Pattern
 
Unified Modeling Language (UML)
Unified Modeling Language (UML)Unified Modeling Language (UML)
Unified Modeling Language (UML)
 
Usecase Presentation
Usecase PresentationUsecase Presentation
Usecase Presentation
 
Unified Modeling Language
Unified Modeling LanguageUnified Modeling Language
Unified Modeling Language
 
UML Diagrams- Unified Modeling Language Introduction
UML Diagrams- Unified Modeling Language IntroductionUML Diagrams- Unified Modeling Language Introduction
UML Diagrams- Unified Modeling Language Introduction
 
Design patterns ppt
Design patterns pptDesign patterns ppt
Design patterns ppt
 
Brief Introduction to Domain Modeling
Brief Introduction to Domain ModelingBrief Introduction to Domain Modeling
Brief Introduction to Domain Modeling
 
UML- Unified Modeling Language
UML- Unified Modeling LanguageUML- Unified Modeling Language
UML- Unified Modeling Language
 
Ooad static diagram
Ooad static diagramOoad static diagram
Ooad static diagram
 
Uml
UmlUml
Uml
 
Intro to UML - Use Case diagrams
Intro to UML - Use Case diagramsIntro to UML - Use Case diagrams
Intro to UML - Use Case diagrams
 
Unified Modeling Language
Unified Modeling LanguageUnified Modeling Language
Unified Modeling Language
 
Sda 8
Sda   8Sda   8
Sda 8
 
Design Patterns Presentation - Chetan Gole
Design Patterns Presentation -  Chetan GoleDesign Patterns Presentation -  Chetan Gole
Design Patterns Presentation - Chetan Gole
 
Design pattern
Design patternDesign pattern
Design pattern
 
Basic design pattern interview questions
Basic design pattern interview questionsBasic design pattern interview questions
Basic design pattern interview questions
 
Uml
UmlUml
Uml
 

Similar to Mca 504 dotnet_unit4

Architecture and design
Architecture and designArchitecture and design
Architecture and designhimanshu_airon
 
Unit-II(STATIC UML DIAGRAMS).ppt
Unit-II(STATIC UML DIAGRAMS).pptUnit-II(STATIC UML DIAGRAMS).ppt
Unit-II(STATIC UML DIAGRAMS).pptganeshkarthy
 
Object Oriented Database
Object Oriented DatabaseObject Oriented Database
Object Oriented DatabaseMegan Espinoza
 
Object oriented methodologies
Object oriented methodologiesObject oriented methodologies
Object oriented methodologiesnaina-rani
 
Technical-design-for-Angular-apps.pdf
Technical-design-for-Angular-apps.pdfTechnical-design-for-Angular-apps.pdf
Technical-design-for-Angular-apps.pdfSakthivelPeriyasamy6
 
MC0083 – Object Oriented Analysis &. Design using UML - Master of Computer Sc...
MC0083 – Object Oriented Analysis &. Design using UML - Master of Computer Sc...MC0083 – Object Oriented Analysis &. Design using UML - Master of Computer Sc...
MC0083 – Object Oriented Analysis &. Design using UML - Master of Computer Sc...Aravind NC
 
Ooad lab manual
Ooad  lab manualOoad  lab manual
Ooad lab manualPraseela R
 
Software Engineering Tools and Practices.pdf
Software Engineering Tools and Practices.pdfSoftware Engineering Tools and Practices.pdf
Software Engineering Tools and Practices.pdfMeagGhn
 
ASP.NET System design 2
ASP.NET System design 2ASP.NET System design 2
ASP.NET System design 2Sisir Ghosh
 
SOLID Principles and The Clean Architecture
SOLID Principles and The Clean ArchitectureSOLID Principles and The Clean Architecture
SOLID Principles and The Clean ArchitectureMohamed Galal
 
CASE Tools lab.ppt
CASE Tools lab.pptCASE Tools lab.ppt
CASE Tools lab.pptRAJESH S
 
Object-oriented modeling and design.pdf
Object-oriented modeling and  design.pdfObject-oriented modeling and  design.pdf
Object-oriented modeling and design.pdfSHIVAM691605
 

Similar to Mca 504 dotnet_unit4 (20)

Elaboration
ElaborationElaboration
Elaboration
 
Ooad
OoadOoad
Ooad
 
Design UML diagrams
Design UML diagramsDesign UML diagrams
Design UML diagrams
 
Design UML diagrams
Design UML diagramsDesign UML diagrams
Design UML diagrams
 
Architecture and design
Architecture and designArchitecture and design
Architecture and design
 
Unit-II(STATIC UML DIAGRAMS).ppt
Unit-II(STATIC UML DIAGRAMS).pptUnit-II(STATIC UML DIAGRAMS).ppt
Unit-II(STATIC UML DIAGRAMS).ppt
 
uml2-1214558329929112-8.ppt
uml2-1214558329929112-8.pptuml2-1214558329929112-8.ppt
uml2-1214558329929112-8.ppt
 
Object Oriented Database
Object Oriented DatabaseObject Oriented Database
Object Oriented Database
 
Object oriented methodologies
Object oriented methodologiesObject oriented methodologies
Object oriented methodologies
 
Object oriented analysis and design unit- iv
Object oriented analysis and design unit- ivObject oriented analysis and design unit- iv
Object oriented analysis and design unit- iv
 
MVC
MVCMVC
MVC
 
Technical-design-for-Angular-apps.pdf
Technical-design-for-Angular-apps.pdfTechnical-design-for-Angular-apps.pdf
Technical-design-for-Angular-apps.pdf
 
Intro Uml
Intro UmlIntro Uml
Intro Uml
 
MC0083 – Object Oriented Analysis &. Design using UML - Master of Computer Sc...
MC0083 – Object Oriented Analysis &. Design using UML - Master of Computer Sc...MC0083 – Object Oriented Analysis &. Design using UML - Master of Computer Sc...
MC0083 – Object Oriented Analysis &. Design using UML - Master of Computer Sc...
 
Ooad lab manual
Ooad  lab manualOoad  lab manual
Ooad lab manual
 
Software Engineering Tools and Practices.pdf
Software Engineering Tools and Practices.pdfSoftware Engineering Tools and Practices.pdf
Software Engineering Tools and Practices.pdf
 
ASP.NET System design 2
ASP.NET System design 2ASP.NET System design 2
ASP.NET System design 2
 
SOLID Principles and The Clean Architecture
SOLID Principles and The Clean ArchitectureSOLID Principles and The Clean Architecture
SOLID Principles and The Clean Architecture
 
CASE Tools lab.ppt
CASE Tools lab.pptCASE Tools lab.ppt
CASE Tools lab.ppt
 
Object-oriented modeling and design.pdf
Object-oriented modeling and  design.pdfObject-oriented modeling and  design.pdf
Object-oriented modeling and design.pdf
 

More from Rai Saheb Bhanwar Singh College Nasrullaganj (20)

lec34.ppt
lec34.pptlec34.ppt
lec34.ppt
 
lec33.ppt
lec33.pptlec33.ppt
lec33.ppt
 
lec31.ppt
lec31.pptlec31.ppt
lec31.ppt
 
lec32.ppt
lec32.pptlec32.ppt
lec32.ppt
 
lec42.ppt
lec42.pptlec42.ppt
lec42.ppt
 
lec41.ppt
lec41.pptlec41.ppt
lec41.ppt
 
lec39.ppt
lec39.pptlec39.ppt
lec39.ppt
 
lec38.ppt
lec38.pptlec38.ppt
lec38.ppt
 
lec37.ppt
lec37.pptlec37.ppt
lec37.ppt
 
lec23.ppt
lec23.pptlec23.ppt
lec23.ppt
 
lec21.ppt
lec21.pptlec21.ppt
lec21.ppt
 
lec20.ppt
lec20.pptlec20.ppt
lec20.ppt
 
lec19.ppt
lec19.pptlec19.ppt
lec19.ppt
 
lec18.ppt
lec18.pptlec18.ppt
lec18.ppt
 
lec17.ppt
lec17.pptlec17.ppt
lec17.ppt
 
lec16.ppt
lec16.pptlec16.ppt
lec16.ppt
 
lec30.ppt
lec30.pptlec30.ppt
lec30.ppt
 
lec28.ppt
lec28.pptlec28.ppt
lec28.ppt
 
lec27.ppt
lec27.pptlec27.ppt
lec27.ppt
 
lec26.ppt
lec26.pptlec26.ppt
lec26.ppt
 

Recently uploaded

How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitolTechU
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPCeline George
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupJonathanParaisoCruz
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfMr Bounab Samir
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 

Recently uploaded (20)

How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Capitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptxCapitol Tech U Doctoral Presentation - April 2024.pptx
Capitol Tech U Doctoral Presentation - April 2024.pptx
 
What is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERPWhat is Model Inheritance in Odoo 17 ERP
What is Model Inheritance in Odoo 17 ERP
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
MARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized GroupMARGINALIZATION (Different learners in Marginalized Group
MARGINALIZATION (Different learners in Marginalized Group
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdfLike-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
Like-prefer-love -hate+verb+ing & silent letters & citizenship text.pdf
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 

Mca 504 dotnet_unit4

  • 1. Unit-04/Lecture-01 Pattern roles and relationship Design Patterns:-[RGPV/Dec2011, Dec2013] Because there is so much general material available on the aims and the documentation of design patterns for executable applications, I will restrict this discussion to a few basic points before moving on to look at the patterns I find most useful in ASP.NET. The References section at the end of Part 3 of this series of articles contains links to many useful resources and Web sites related to design patterns in general. While many people (myself included) find the term "design patterns" just a little scary - due not least to the way that they are usually described and documented - most developers use informal patterns every day when writing code. Constructs such as try...catch, using, and switch (Select Case) statements all follow standard patterns that developers have learned over time. In fact, patterns can be: • Informal Design Patterns - such as the use of standard code constructs, best practice, well structured code, common sense, the accepted approach, and evolution over time • Formal Design Patterns - documented with sections such as "Context", "Problem", "Solution", and a UML diagram Formal patterns usually have specific aims and solve specific issues, whereas informal patterns tend to provide guidance that is more general. Formal patterns usually have specific aims and solve specific issues, whereas informal patterns tend to provide guidance that is more general. Brad Appleton, author of the book "Software Configuration Management Patterns: Effective Teamwork, Practical Integration", describes design patterns, pattern languages, and the need for them in software engineering and development, like this: "Fundamental to any science or engineering discipline is a common vocabulary for expressing its concepts, and a language for relating them together." "... a body of literature to help software developers resolve recurring problems encountered throughout all of software development." "... a shared language for communicating insight and experience about these problems and their solutions." "A pattern is a named nugget of insight that conveys the essence of a proven solution to a recurring problem within a certain context amidst competing concerns." (from "Patterns and Software: Essential Concepts and Terminology")
  • 2. The following sections of this article and the following two articles aim to demonstrate how you can use some of the common formal patterns (some with minor adaptations to suit ASP.NET requirements) in your Web applications to achieve the aims set out so succinctly by the Hillside Group. You can download the reasonably simple example application and open it in Visual Studio 2005, or install it to run under Internet Information Services (IIS). The download file includes a ~readme.txt file that describes the setup requirements. Design patterns fall into groups, based on the type and aims of the pattern. For example, some patterns provide presentation logic for displaying specific views that make up the user interface. Others control the way that the application behaves as the user interacts with it. There are also groups of patterns that specify techniques for persisting data, define best practices for data access, and indicate optimum approaches for creating instances of objects that the application uses. The following list shows some of the most common design patterns within these groups: • Presentation Logic o Model-View-Controller (MVC) o Model-View-Presenter (MVP) o Use Case Controller • Host or Behavioral o Command o Publish-Subscribe / Observer o Plug-in / Module / Intercepting Filter • Structural o Service Agent / Proxy / Broker o Provider / Adapter • Creational o Factory / Builder / Injection o Singleton • Persistence o Repository
  • 3. Designs on Classes:- • Singleton Pattern :- The creational pattern that describes how to ensure that only one instance of aclass can be activated. All objects that use the singleton instance use the same one. • Bridge Pattern :- The structural pattern that prescribes the de−coupling of the implementation of a class from its interface so that the two can evolve independently of each other. • Strategy Pattern The structural pattern that prescribes the de−coupling of the implementation of a class from its interface so that algorithms, or any operation or process, can be interchanged. Algorithm implementation can thus vary independently from the client or consumer objects that need it. Strategy is very similar to Bridge; however, Strategy is used to interchange implementation at runtime. • State Pattern The behavioral pattern that provides a framework for using an object hierarchy as a state machineas an OO alternative to constant or variable state data, complex conditional statements, enumeration constants, and map tables. • Composite Pattern The structural pattern that prescribes how classes can be composed (and aggregated) into tree−like hierarchies. • Iterator Pattern The behavioral pattern for a class that provides a way to access the aggregated or composite elements of objects of a collection . This chapter will implement an iterator as an implementation . • Adapter Pattern The structural pattern that prescribes the conversion of an interface to a class into Another interface a client object can use transparently. Adapter, affectionately known as Wrapper. • Null Pattern A behavioral pattern providing an alternative to Nothing in Visual Basic . • Delegate Pattern The Delegate pattern prescribes how to wrap a singleton method signature in a special class, which is then used as a "pointer" to a method in another class or object. The Model-View-Controller and Model-View-Presenter Patterns:- The Model-View-Controller (MVC) and Model-View-Presenter (MVP) Patterns improve reusability of
  • 4. business logic by separating the three components required to generate and manage a specific user interface (such as a single Web page). The Model contains the data that the View (the Web page) will display and allow the user to manipulate. The Controller or Presenter links the Model and the View, and manages all interaction and processing of the data in the Model  Roles:- The concept of roles has been discussed broadly in the literature. The properties regarded as characteristic for the role a few core properties seem to be largely unques-tioned. This includes the property that a single object can play several roles of different or the same kind both simultaneously and sequentially, and that the same role can be played by different objects of the same and different kinds. Raised to the type level, this means that the relationship between role types and class types. Roles and behavior:- A role elicits the behaviour of an object in a given context. For instance, the role of father specifies behaviour expected from a man in the context of his fatherhood. On an abstract level, the role-specific behaviour is specified independently from the (na-ture of the) role player; in general, the class of the role player should be substitutable by another without compromising the role specification. Roles and state :- The role-as-interface view is often challenged by the observation that roles appear to have role- specific state. And indeed, it seems reasonable that a person in the Employee role has some role- specific data such as telephone number and salary. Even if this state were made part of the role-
  • 5. as-type definition (replacing Interfaces by abstract classes as role representations), this would not allow a single person to have several office phone numbers and salaries at the same time (namely one per employment). This is a problem since as noted above, being able to play the same role multiply at the same time is a defining characteristic of the role Concept . The role object pattern solves this problem. The role object pattern:- The role object pattern represents the roles an object plays by adjunct instances, the role objects. Each role object is an instance of a certain class, its role type. The role type specifies role-specific state and behaviour; by instantiating the same role type several times and adjoining the instances to the same role player object, the problem of multiple phone numbers and salaries is solved. At the same time, the role class can implement role specific behaviour independently from the role player class, and forward player-specific requests to the player. Role and counter role :- Intuitively, a role is meaning less without one (or more) counter roles, the one(s) with which its player interacts and for which the associated behaviour is required. Role and counter role(s) together form an interaction pattern — so metimes called collaboration —, with parts of the behaviour being specific to the interaction, and parts being contributed by the role players.  Relationship:- A model is not complete unless the relationships between elements are described properly. The Relationship gives a proper meaning to an UML model. Following are the different types of Relationships available in UML. • Dependency • Association • Generalization • Composition Dependency Notation: Dependency is an important aspect in UML elements. It describes the dependent elements and The direction of dependency.Dependency is represented by a dotted arrow as shown below. The arrow head represents the independent element and the other end the dependent element.
  • 6. Class diagram showing dependency between "Car" class and "Wheel" class (An even clearer example would be "Car depends on Wheel", because Car Association Notation: Association describes how the elements in an UML diagram are associated. In simple word it describes how many elements are taking part in an interaction. Association is represented by a dotted line with (without) arrows on both sides. The two ends represent two associated elements as shown below. The multiplicity is also mentioned at the ends to show how many objects are associated. Class diagram example of association between two classes Generalization Notation: The Generalization relationship ("is a") indicates that one of the two related classes (the subclass) is considered to be a specialized form of the other (the super type) and superclass is considered as 'Generalization' of subclass. In practice, this means that any instance of the subtype is also an instance of the superclass. An exemplary tree of generalizations of this form is found in biological classification: human beings are a subclass of simian, which are a subclass of mammal, and so on. The relationship is most easily understood by the phrase 'an A is a B' (a human is a mammal, a mammal is an animal). The UML graphical representation of a Generalization is a hollow triangle shape on the super class end of the line (or tree of lines) that connects it to one or more subtypes.The generalization relationship is also known as the inheritance or "is a" relationship. The super class (base class) in the generalization relationship is also known as the "parent", super class, base class, or base type. The subtype in the specialization relationship is also known as the "child", subclass, derived class, derived type, inheriting class, or inheriting type. Note that this relationship bears no resemblance to the biological parent/child relationship: the use of these terms is extremely common, but can be misleading.
  • 7. Generalization-Specialization relationship A is a type of B E. g. "an oak is a type of tree", "an automobile is a type of vehicle" Generalization can only be shown on class diagrams and on Use case diagrams. Class diagram showing generalization between one super class and two subclasses Composition Notations:- Composition is a stronger variant of the "has a" association relationship; composition is more specific than aggregation. Composition usually has a strong life cycle dependency between instances of the container class and instances of the contained class(es): if the container is destroyed, normally every instance that it contains is destroyed as well. (Note that, where allowed, a part can be removed from a composite before the composite is deleted, and thus not be deleted as part of the composite.)
  • 8. Class diagram showing Composition between two classes at top and Aggregation between two classes at bottom Unit-04/Lecture-02 Accessing database: ADO.NET [RGPV/Dec2010,Dec2013]  ADO.NET:- ADO.NET provides consistent access to data sources such as SQL Server and XML, and to data sources exposed through OLE DB and ODBC. Data-sharing consumer applications can use ADO.NET to connect to these data sources and retrieve, handle, and update the data that they contain. ADO.NET separates data access from data manipulation into discrete components that can be used separately or in tandem. ADO.NET includes .NET Framework data providers for connecting to a database, executing commands, and retrieving results. Those results are either processed directly, placed in an ADO.NET DataSet object in order to be exposed to the user in an ad hoc manner, combined with data from multiple sources, or passed between tiers. The DataSet object can also be used independently of a .NET Framework data provider to manage data local to the application or sourced from XML. The ADO.NET classes are found in System.Data.dll, and are integrated with the XML classes found in System.Xml.dll. For sample code that connects to a database, retrieves data from it, and then displays that data in a console window, see ADO.NET Code Examples. ADO.NET provides functionality to developers who write managed code similar to the functionality provided to native component object model (COM) developers by ActiveX Data Objects (ADO). We recommend that you use ADO.NET, not ADO, for accessing data in your .NET applications.ADO.NET provides the most direct method of data access within the .NET Framework. For a higher-level abstraction that allows applications to work against a conceptual model instead of the underlying storage model, see the ADO.NET Entity Framework. S.NO RGPV QUESTIONS Year Marks Q.1 Write short notes: Roles and Relationship Dec2013 04 Q.2 Explain class design pattern in brief. Dec2011 10 Q.3 What is the role of s/w pattern in oop? Explain with their types. Dec2010 10
  • 9. ADO.NET is an object-oriented set of libraries that allows you to interact with data sources. Commonly, the data source is a database, but it could also be a text file, an Excel spreadsheet, or an XML file. For the purposes of this tutorial, we will look at ADO.NET as a way to interact with a data base. As you are probably aware, there are many different types of databases available. For example, there is Microsoft SQL Server, Microsoft Access, Oracle, Borland Interbase, and IBM DB2, just to name a few. To further refine the scope of this tutorial, all of the examples will use SQL Server. ADO.NET is a set of classes that expose data access services to the .NET developer. The ADO.NET classes are found in System.Data.dll and are integrated with the XML classes in System.Xml.dll. There are two central components of ADO.NET classes: the DataSet, and the .NET Framework Data Provider. Data Provider is a set of components including: • the Connection object (SqlConnection, OleDbConnection, OdbcConnection, OracleConnection) • the Command object (SqlCommand, OleDbCommand, OdbcCommand, OracleCommand) • the DataReader object (SqlDataReader, OleDbDataReader, OdbcDataReader, OracleDataReader) • the DataAdapter object (SqlDataAdapter, OleDbDataAdapter, OdbcDataAdapter, OracleDataAdapter). DataSet object represents a disconnected cache of data which is made up of DataTables and DataRelations that represent the result of the command. The ADO.NET Object Model
  • 10. DataSet:- The DataSet is similar to an array of disconnected Recordset objects. It supports disconnected data access and operations, allowing greater scalability because you no longer have to be connected to the database all the time. DataSet is a copy of an extracted data being downloaded and cached in the client system. The DataSet object is made up of two objects: • DataTableCollection object containing null or multiple DataTable objects (Columns, Rows, Constraints). • DataRelationCollection object containing null or multiple DataRelation objects which establish a parent/child relation between two DataTable objects. //Create a DataSet DataSet dset = new DataSet(); There are two types of DataSets: 1. Typed DataSet 2. Untyped DataSet 1. Typed DataSet is derived from the base DataSet class and then uses information in an XML Schema file (.xsd file) in order to generate a new class. Information from the schema (tables, columns, and so on) is generated and compiled into this new DataSet class as a set of first-class objects and properties. Typed dataset is easier to read. It's also supported by IntelliSense in the Visual Studio Code Editor. At compile time, it has type checking so that there are less errors in
  • 11. assigning values to DataSet members. Therefore, using Typed DataSet has many advantages. 2. Untyped DataSet is not defined by a schema, instead, you have to add tables, columns and other elements to it yourself, either by setting properties at design time or by adding them at run time. Typical scenario: if you don't know in advance what the structure of your program is that is interacting with a component that returns a DataSet. When you decide whether your application should use a DataReader (see Retrieving Data Using a DataReader) or a DataSet (see DataSets, DataTables, and DataViews), consider the type of functionality that your application requires. Use a DataSet to do the following: • Cache data locally in your application so that you can manipulate it. If you only need to read the results of a query, the DataReader is the better choice. • Remote data between tiers or from an XML Web service. • Interact with data dynamically such as binding to a Windows Forms control or combining and relating data from multiple sources. • Perform extensive processing on data without requiring an open connection to the data source, which frees the connection to be used by other clients.  DataAdapter:- In ADO.NET, a DataAdapter functions as a bridge between a data source, and a disconnected data class, such as a DataSet. At the simplest level it will specify SQL commands that provide elementary CRUD functionality. At a more advanced level it offers all the functions required in order to create Strongly Typed DataSets, including DataRelations. Data adapters are an integral part of ADO.NET managed providers, which are the set of objects used to communicate between a data source and a dataset. (In addition to adapters, managed providers include connection objects, data reader objects, and command objects.) Adapters are used to exchange data between a data source and a dataset. In many applications, this means reading data from a database into a dataset, and then writing changed data from the dataset back to the database. However, a data adapter can move data between any source and a dataset. For example, there could be an adapter that moves data between a Microsoft Exchange server and a dataset.
  • 12. SELECT statement using SqlDataAdapter string ConnectionString = "Integrated Security = SSPI;" + "Initial catalog = Northwind; " + " Data Source = localhost; "; string SQL = "SELECT CustomerID, CompanyName FROM Customers"; SqlConenction conn = new SqlConnection(ConnectionString); // open the connection conn.Open(); // Create a SqlDataAdapter object SqlDataAdapter adapter = new SqlDataAdapter(SQL, conn); Create an ODBC Database Connection:- If you have an ODBC database called "northwind" you can connect to the database with the following ASP code: <% set conn=Server.CreateObject("ADODB.Connection") conn.Open "northwind" %> With an ODBC connection, you can connect to any database, on any computer in your network, as long as an ODBC connection is available. An ODBC Connection to an MS Access Database Here is how to create a connection to a MS Access Database:
  • 13. 1. Open the ODBC icon in your Control Panel. 2. Choose the System DSN tab. 3. Click on Add in the System DSN tab. 4. Select the Microsoft Access Driver. Click Finish. 5. In the next screen, click Select to locate the database. 6. Give the database a Data Source Name (DSN). 7. Click OK. Note that this configuration has to be done on the computer where your web site is located. If you are running Personal Web Server (PWS) or Internet Information Server (IIS) on your own computer, the instructions above will work, but if your web site is located on a remote server, you have to have physical access to that server, or ask your web host to do this for you.  ADO.NET Objects:- ADO.NET includes many objects you can use to work with data. This section introduces some of the primary objects you will use. Over the course of this tutorial, you'll be exposed to many more ADO.NET objects from the perspective of how they are used in a particular lesson. The objects below are the ones you must know. Learning about them will give you an idea of the types of things you can do with data when using ADO.NET. The SqlConnection Object:- To interact with a database, you must have a connection to it. The connection helps identify the database server, the database name, user name, password, and other parameters that are required for connecting to the data base. A connection object is used by command objects so they will know which database to execute the command on. The SqlCommand Object:- The process of interacting with a database means that you must specify the actions you want to occur. This is done with a command object. You use a command object to send SQL statements to the database. A command object uses a connection object to figure out which database to communicate with. You can use a command object alone, to execute a command directly, or assign a reference to a command object to an SqlDataAdapter, which holds a set of commands that work on a group of data as described below.
  • 14. The SqlDataReader Object:- Many data operations require that you only get a stream of data for reading. The data reader object allows you to obtain the results of a SELECT statement from a command object. For performance reasons, the data returned from a data reader is a fast forward-only stream of data. This means that you can only pull the data from the stream in a sequential manner This is good for speed, but if you need to manipulate data, then a DataSet is a better object to work with. The DataSet Object:- DataSet objects are in-memory representations of data. They contain multiple Datatable objects, which contain columns and rows, just like normal database tables. You can even define relations between tables to create parent-child relationships. The DataSet is specifically designed to help manage data in memory and to support disconnected operations on data, when such a scenario make sense. The DataSet is an object that is used by all of the Data Provders, which is why it does not have a Data Provider specific prefix. S.NO RGPV QUESTIONS Year Marks Q.1 Write short notes: i)Data Adapter Objection) Data Reader Object Dec2010 10 Q.2 Describe the procedure of accessing database with ADO.NET.Explain the advantages and drawback of using ADO.NET. Dec2013 07
  • 15. Unit-04/Lecture-03 Advanced Interface Patterns: Adapters and Delegates understanding deligates, declearing the delegate. [RGPV/June2009,Dec2010,Dec2011]  Adapters:- Definition: Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces. The classes and/or objects participating in this pattern are: • Target (ChemicalCompound) o Defines the domain-specific interface that Client uses. • Adapter (Compound) o Adapts the interface Adaptee to the Target interface. • Adaptee (ChemicalDatabank) o Defines an existing interface that needs adapting. • Client (AdapterApp) o Collaborates with objects conforming to the Target interface. sample code in C# This structural code demonstrates the Adapter pattern which maps the interface of one class onto another so that they can work together. These incompatible classes may come from different libraries or frameworks. Show code // Adapter pattern -- Structural example UML class diagram
  • 16. The Data Adapter The Data Adapter is a property of the OLEDB object, hence the full stop between the two: OleDb.OleDbDataAdapter We're passing this object to the variable called da. This variable will then hold a reference to the Data Adapter. While the second line in the code above sets up a reference to the Data Adapter, the third line creates a new Data Adapter object. You need to put two things in the round brackets of the Object declaration: Your SQL string (which we'll get to shortly), and your connection object. Our Connection Object is stored in the variable which we've called con. (Like all variable you can call it practically anything you like. We've gone for something short and memorable.) You then pass the New Data Adapter to your variable (da for us): da = New OleDb.OleDbDataAdapter(sql, con ) We need something else, though. The sql in between the round brackets is the name of a variable. We haven't yet set this up. We'll have a look at SQL in a moment. But bear in mind what the Data Adaptor is doing: Acting as a go-between for the Connection Object and the Data Set  Delegates:- Delegates are objects that refer to methods. They are sometimes described as type-safe
  • 17. function pointers because they are similar to function pointers used in other programming languages. But unlike function pointers, Visual Basic delegates are a reference type based on the class System.Delegate. Delegates can reference both shared methods — methods that can be called without a specific instance of a class — and instance methods. Instantiating Delegates public delegate void printString(string s); ... printString ps1 = new printString(WriteToScreen); printString ps2 = new printString(WriteToFile); 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. For example: Before using a delegate, you must create it or you can use one of the built-in delegates of the .NET Framework. The basic formula to create a delegate is: [modifier] Delegate Sub/Function Name (parameter(s)) As ReturnType The modifier factor can be Public, Private, or Friend. This is followed by either the Delegate Sub or the Delegate Function expression. A delegate must have a name: The Name factor of this formula. The name follows the rules we have been observing for valid names of the Visual Basic language. Because a delegate is some type of a template for a procedure, you must use parentheses. If this procedure will not take any argument, you can leave the parentheses empty. If the delegate will be associated with a sub-procedure, there is no return type. Here is an example: Module Exercise Delegate Sub Messenger() End Module If the delegate is a function-type, you must specify a ReturnType. This can be any of the data types we have used so far, or it can be a class.
  • 18. Delegates and Classes:- When it comes to delegates, not only can you use a normal procedure, you can use the method of a class to associate to a delegate. You can start by creating the class and the necessary method. Here is an example: Module Exercise Private Class Example Public Sub Welcome() MsgBox("A delegate with class") End Sub End Class End Module Of course, before using the delegate, you must declare it. This is done exactly as previously. The delegate must be of the same type as the method (sub-procedure or function). Delegates are pointers that are used to store and tranfer information like the memory address, event handled by functions and subroutines. Delagates are type safe, since they check for the signatures of functions and subroutines only if same, they transfer information. A delegate is declared using the keyword Delegate to a function or procedure name. Example: Module Module1 Public Delegate Function del1(ByVal x As Integer, ByVal y As Integer) As Integer Public Delegate Sub Display() Public Function check(ByVal x As Integer, ByVal y As Integer) As Integer Return (x + y) End Function Public Function multi(ByVal x As Integer, ByVal y As Integer) As Integer Return (x * y) End Function Class deleg Public Sub Disp() Console.WriteLine("Method inside the Class")
  • 19. Unit-04/Lecture-04 Introduction to Window forms creation, Introduction to Threading [RGPV/Dec2010,Dec2011] Let's start with creating a Window Forms Application by following the following steps in Microsoft Visual Studio: File -> New Project -> Windows Forms Applications Finally, select OK, Microsoft Visual Studio creates your project and displays following window Form with a name Form1.
  • 20. Visual Basic Form is the container for all the controls that make up the user interface. Every window you see in a running visual basic application is a form, thus the terms form and window describe the same entity. Visual Studio creates a default form for you when you create a Windows Forms Application. Every form will have title bar on which the form's caption is displayed and there will be buttons to close, maximize and minimize the form shown below:
  • 21. If you click the icon on the top left corner, it opens the control menu, which contains the various commands to control the form like to move control from one place to another place, to maximize or minimize the form or to close the form.  Introduction to Threading:- A thread is a sequence of instructions executed within the context of a process. MultiThreading is achieved when a program uses multiple execution threads allowing each thread to share the CPU concurrently depending on the priority assigned to these threads. This helps in the optimum usage of System Resources. The System.Threading namespace provides classes and interfaces that enable multi- threaded programming. This namespace includes a ThreadPool class that manages groups of threads, a Timer class that enables a delegate to be called after a specified amount of time, and a Mutex class for synchronizing mutually-exclusive threads. I also provides classes for thread scheduling, wait notification, and deadlock resolution. using System.Threading; Creating Threads:- Creating a thread in C# is close to trivial, but not quite. The only non-trivial thing about creating a thread is .NET delegate-classes. Let me explain in few words what is a delegate class. The delegate is a wrapper around a code construct in the .NET. The code construct could be an object instance, an instance method or a static method. Delegates are used when you want to pass one of the three code constructs as a parameter to another method. When creating a new thread you have to use the ThreadStart delegate
  • 22. class to wrap the instance method that will be executed in the newly created thread. The instance method must return void and must not have any parameters. void ThreadStart() To create a new thread, first create a new ThreadStart object, passing the instance method of the thread procedure in the constructor. The new delegate object is then passed to the constructor of the Thread. To create a new thread, first create a new ThreadStart object, passing the instance method of the thread procedure in the constructor. The new delegate object is then passed to the constructor of the Thread. Thread thread = new Thread( new ThreadStart(obj.ThreadStart)); Example:- using System; using System.Threading; class Program { static void Main() { Thread thread1 = new Thread(new ThreadStart(A)); Thread thread2 = new Thread(new ThreadStart(B)); thread1.Start(); thread2.Start(); thread1.Join(); thread2.Join(); } static void A() { Thread.Sleep(100); Console.WriteLine('A'); } static void B() { Thread.Sleep(1000); Console.WriteLine('B');
  • 23. } } Out put A B  Multithreading:- A thread is an independent stream of instructions in a program. Each written program is a paradigm of sequential programming in which they have a beginning, an end, a sequence, and a single point of execution. A thread is similar to sequential program. However, a thread itself is not a program, it can’t run on its own, but runs within a program. The real concern surrounding threads is not about a single sequential thread, but rather the use of multiple threads in a single program all running at the same time and performing different tasks. This mechanism referred as Multithreading. A thread is considered to be a lightweight process because it runs within the context of a program and takes advantage of resources allocated for that program. Threads are important both for client and server applications. While in C# program coding, when you type something in editor, the dynamic help (intellisense) Windows immediately shows the relevant topics that fit to the code. One thread is waiting for input from the user, while other does some background processing. A third thread can store the written data in a temporary file, while another one downloads a file from a specific location. With the task manager, you can turn on the Thread column and see the processes and the number of threads for every process. Here, you can notice that only cmd.exe is running inside a
  • 24. single thread while all other applications use multiple threads. Example: using System; using System.Threading; public class Test { static void Main() { ThreadStart job = new ThreadStart(ThreadJob); Thread thread = new Thread(job); thread.Start(); for (int i=0; i < 5; i++) { Console.WriteLine ("Main thread: {0}", i); Thread.Sleep(1000); } } static void ThreadJob() { for (int i=0; i < 10; i++) { Console.WriteLine ("Other thread: {0}", i); Thread.Sleep(500); } } S.NO RGPV QUESTIONS Year Marks Q.1 Write short notes: Multithreading. Dec2010 04 Q.2 Write a short notes: Form designer Dec2010 04 Q.3 How to stop closing process of form?Explain with example Dec2011 10
  • 25. Unit-04/Lecture-05 MDI Applications:Creating MDI Parent/Child [RGPV/Dec2009] The Multiple Document Interface (MDI) :- The Multiple Document Interface (MDI) was designed to simplify the exchange of information among documents, all under the same roof. With the main application, you can maintain multiple open windows, but not multiple copies of the application. Data exchange is easier when you can view and compare many documents simultaneously. You almost certainly use Windows applications that can open multiple documents at the same time and allow the user to switch among them with a mouse-click. Multiple Word is a typical example, although most people use it in single document mode. Each document is displayed in its own window, and all document windows have the same behavior. The main Form, or MDI Form, isn't duplicated, but it acts as a container for all the windows, and it is called the parent window. The windows in which the individual documents are displayed are called Child windows. An MDI application must have at least two Form, the parent Form and one or more child Forms. Each of these Forms has certain properties. There can be many child forms contained within the parent Form, but there can be only one parent Form. The parent Form may not contain any controls. While the parent Form is open in design mode, the icons on the ToolBox are not displayed, but you can't place any controls on the Form. The parent Form can, and usually has its own menu. To create an MDI application, follow these steps: 1. Start a new project and then choose Project >>> Add MDI Form to add the parent Form. 2. Set the Form's caption to MDI Window 3. Choose Project >>> Add Form to add a SDI Form. 4. Make this Form as child of MDI Form by setting the MDI Child property of the SDI Form to True. Set the caption property to MDI Child window.
  • 26. Parent and Child Menus MDI Form cannot contain objects other than child Forms, but MDI Forms can have their own menus. However, because most of the operations of the application have meaning only if there is at least one child Form open, there's a peculiarity about the MDI Forms. The MDI Form usually has a menu with two commands to load a new child Form and to quit the application. The child Form can have any number of commands in its menu, according to the application. When the child Form is loaded, the child Form's menu replaces the original menu on the MDI Form Following example illustrates the above explanation. * Open a new Project and name the Form as Menu.frm and save the Project as Menu.vbp * Design a menu that has the following structure. <> MDIMenu Menu caption • MDIOpen opens a new child Form • MDIExit terminates the application * Then design the following menu for the child Form <> ChildMenu Menu caption • Child Open opens a new child Form • Child Save saves the document in the active child Form • Child Close Closes the active child Form At design time double click on MDI Open and add the following code in the click event of the open menu. Form1.Show And so double click on MDI Exit and add the following code in the click event End
  • 27. Double click on Child Close and enter the following code in the click event Unload Me Before run the application in the project properties set MDI Form as the start-up Form. Save and run the application. Following output will be displayed. An essential element of Multiple-Document Interface (MDI) Applications is MDI child forms, as these are the center of user interaction. In the following procedure, you will create MDI child forms that display a RichTextBox control, similar to most word-processing applications. Substituting the RichTextBox control with other controls, such as the DataGrid control, or a mixture of controls allows you to create MDI child windows (and, by extension, MDI applications) with diverse possibilities. To create an MDI parent form at design time 1. Create a Windows Application. For more information, see Creating a Windows Application Project. 2. In the Properties window, set the IsMDIContainer property to true. This designates the form as an MDI container for child windows. Note While setting properties in the Properties window, you can also set the WindowState property to Maximized, if you like, as it is easiest to manipulate MDI child windows when the parent form is maximized. Additionally, be aware that the edge of the MDI parent form will pick up the system color (set in the Windows System control panel), rather than the back color you set using the Control.BackColor property. 3. From the Toolbox, drag a MainMenu component to the form. Create a top-level menu item with the Text property set to &File with submenu items called &New and &Close. Also create a top-level menu item called &Window. The first menu will create, and hide menu items at run time, and the second menu will keep track of the open MDI child windows. At this point, you have created an MDI parent window. For more information on creating menus and menu items, see Adding Menus and Menu Items to Windows Forms. 4. Press F5 to run the application. For information about creating MDI child windows that operate within the MDI parent form, see Creating MDI Child Forms.
  • 28. To create MDI child forms 1. Create an MDI parent form that has a menu structure containing File and Window top- level menu items and New and Close menu items. For more information on creating MDI parent forms, see Creating MDI Parent Forms. 2. In the drop-down list at the top of the Properties window, select the menu item that corresponds to the &Window menu item and set the MdiList property to true. This will enable the Window menu to maintain a list of open MDI child windows with a check mark next to the active child window. 3. In Solution Explorer, right-click the project, point to Add, and then select Add New Item. This form will be the template for your MDI child forms. Note The MDI child form you create in this step is a standard Windows Form. As such, it has an Opacity property, which allows you to control the transparency of the form. However, the Opacity property was designed for top-level windows. Do not use it with MDI child forms, as painting problems can occur. 4. In the Add New Item dialog box, select Windows Form (in Visual Basic or in Visual C#) or Windows Forms Application (.NET) (in Visual C++) from the Templates pane. In the Name box, name the form Form2. Click the Open button to add the form to the project. The Windows Forms Designer opens, displaying Form2. 5. Drag a RichTextBox control from the Toolbox to the form. 6. In the Properties window, set the Anchor property to Top, Left and the Dock property to Fill. This causes the RichTextBox control to completely fill the area of the MDI child form, even when the form is resized. 7. Create a Click event handler for the New menu item. For more information about creating event handlers, see Creating Event Handlers on the Windows Forms Designer. 8. Insert code similar to the following to create a new MDI child form when the user clicks the New menu item (In the example below, the event handler handles the Click event for MenuItem2. Be aware that, depending on the specifics of your application architecture, your New menu item may not be MenuItem2.) Visual Basic
  • 29. Protected Sub MDIChildNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MenuItem2.Click Dim NewMDIChild As New Form2() 'Set the Parent Form of the Child window. NewMDIChild.MdiParent = Me 'Display the new form. NewMDIChild.Show() End Sub // C# protected void MDIChildNew_Click(object sender, System.EventArgs e){ Form2 newMDIChild = new Form2(); // Set the Parent Form of the Child window. newMDIChild.MdiParent = this; // Display the new form. newMDIChild.Show(); } // C++ private: System::Void menuItem2_Click(System::Object * sender, System::EventArgs * e) { Form2 *newMDIChild = new Form2(); // Set the Parent Form of the Child window. newMDIChild->MdiParent = this; // Display the new form. newMDIChild->Show(); }
  • 30. Unit-04/Lecture-06 Events Data Processing and I/O: Menus and tool bars, Collecting Input:Button,Textbox,Checkbox, radio button,commbobox[RGPV/Dec2013] Menus and tool bars:-  Button Control Button Control in VB.NET is used to trigger some action for the form. Just by clicking on the button the information is managed effectively in Visual Basic. The Button control represents a standard Windows button. It is generally used to generate a Click event by providing a handler for the Click event. Explanation: • Select the form on which the button resides. • In the Properties window, set the form's Button property to the Button control's name. • To respond to a button click, In the button's Click event handler write the code to run. Button1_Click must be bound to the control. • ForeColor,Text properties of the button control are changed. • Click event of the button is used to display a message. create a label by dragging a Button control from the Toolbox ad dropping it on the form. S.NO RGPV QUESTIONS Year Marks Q.1 Discuss the Multiple Document Interface (MDI).How to create MDI child form. Dec2009 10
  • 31.  Textbox:- Text box controls allow entering text on a form at runtime. By default, it takes a single line of text, however, you can make it accept multiple texts and even add scroll bars to it. Let's create a text box by dragging a Text Box control from the Toolbox and dropping it on the form.
  • 32. The Text property is the one you'll reference most often in code, and conveniently it's the default property for the TextBox control. Three other frequently used properties are these: • The SelStart property sets or returns the position of the blinking caret (the insertion point where the text you type appears). Note that the blinking cursor inside TextBox and other controls is named caret, to distinguish it from the cursor (which is implicitly the mouse cursor). When the caret is at the beginning of the contents of the TextBox control, SelStart returns 0; when it's at the end of the string typed by the user, SelStart returns the value Len(Text). You can modify the SelStart property to programmatically move the caret. • The SelLength property returns the number of characters in the portion of text that has been highlighted by the user, or it returns 0 if there's no highlighted text. You can assign a nonzero value to this property to programmatically select text from code. Interestingly, you can assign to this property a value larger than the current text's length without raising a run-time error. • The SelText property sets or returns the portion of the text that's currently selected, or it returns an empty string if no text is highlighted. Use it to directly retrieve the highlighted text without having to query Text, SelStart, and SelLength properties. What's even more interesting is that you can assign a new value to this property, thus replacing the current selection with your own. If no text is currently selected, your string is simply inserted at the current caret position. When you want to append text to a TextBox control, you should use the following code (instead of using the concatenation operator) to reduce flickering and improve performance: Text1.SelStart = Len(Text1.Text)
  • 33. Text1.SelText = StringToBeAdded One of the typical operations you could find yourself performing with these properties is selecting the entire contents of a TextBox control.  Checkbox:- The CheckBox control allows the user to set true/false or yes/no type options. The user can select or deselect it. When a check box is selected it has the value True, and when it is cleared, it holds the value False. Let's create two check boxes by dragging CheckBox controls from the Toolbox and dropping on the form. The CheckBox control has three states, checked, unchecked and indeterminate. In the indeterminate state, the check box is grayed out. To enable the indeterminate state, the ThreeState property of the check box is set to be True. S.N Property Description 1 Appearance Gets or sets a value determining the appearance of the check box. 2 AutoCheck Gets or sets a value indicating whether the Checked or
  • 34. CheckedState value and the appearance of the control automatically change when the check box is selected. 3 CheckAlign Gets or sets the horizontal and vertical alignment of the check mark on the check box. 4 Checked Gets or sets a value indicating whether the check box is selected. 5 CheckState Gets or sets the state of a check box. 6 Text Gets or sets the caption of a check box. 7 ThreeState Gets or sets a value indicating whether or not a check box should allow three check states rather than two. radio button The RadioButton control is used to provide a set of mutually exclusive options. The user can select one radio button in a group. If you need to place more than one group of radio buttons in the same form, you should place them in different container controls like a GroupBox control. Let's create three radio buttons by dragging RadioButton controls from the Toolbox and dropping on the form. The Checked property of the radio button is used to set the state of a radio button. You can display text, image or both on radio button control. You can also change the appearance of the radio button control by using the Appearance property. Properties of the RadioButton Control
  • 35. The following are some of the commonly used properties of the RadioButton control: S.N Property Description 1 Appearance Gets or sets a value determining the appearance of the radio button. 2 AutoCheck Gets or sets a value indicating whether the Checked value and the appearance of the control automatically change when the control is clicked. 3 CheckAlign Gets or sets the location of the check box portion of the radio button. 4 Checked Gets or sets a value indicating whether the control is checked. 5 Text Gets or sets the caption for a radio button. 6 TabStop Gets or sets a value indicating whether a user can give focus to the RadioButton control using the TAB key.  Commbobox:- The ComboBox control is used to display a drop-down list of various items. It is a combination of a text box in which the user enters an item and a drop-down list from which the user selects an item. Let's create a combo box by dragging a ComboBox control from the Toolbox and dropping it on the form.
  • 36. You can populate the list box items either from the properties window or at runtime. To add items to a ListBox, select the ListBox control and go to the properties window for the properties of this control. Click the ellipses (...) button next to the Items property. This opens the String Collection Editor dialog box, where you can enter the values one at a line. Properties of the ComboBox Control:- The following are some of the commonly used properties of the ComboBox control: S.N Property Description 1 AllowSelection Gets a value indicating whether the list enables selection of list items. 2 AutoComplete CustomSource Gets or sets a custom System.Collections.Specialized.StringCollection to use when the AutoCompleteSourceproperty is set to CustomSource. 3 AutoCompleteMode Gets or sets an option that controls how automatic completion works for the ComboBox.
  • 37. 4 AutoCompleteSource Gets or sets a value specifying the source of complete strings used for automatic completion. 5 DataBindings Gets the data bindings for the control. 6 DataManager Gets the CurrencyManager associated with this control. Unit-04/Lecture-07 S.NO RGPV QUESTIONS Year Marks Q.1 What are the features of a combo box control? Write properties and methods of combo box with description of each. Dec2013 07 Q.2 Write steps to create and run an application that displays and hides the controls and form. Dec2013 07
  • 38. Special controls:calendar,list box, labeling statusbar,icon,picture box, image[RGPV/June2009]  Calendar:- This control is used to select a date in an application at runtime. Using this control calendar for one or more months can be displayed, so that a single date or a range of dates can be selected using this control. Explanation: • The DateSelected event of the Month Calendar Control is used. • Using the SelectRange property, the month of the starting date of selection is returned. • Textbox displays the month as an integer value. Properties Description AnnuallyBoldedDate Property holds an array of DateTime objects specifying which days should be bold. BoldedDates Property used to Get or sets an array of DateTime objects specifying which dates shpuld be bold. CalendarDimensions Property used to Get or set the number of columns. FirstDayOfWeek Property to get or set the first day of the week. MaxDate Property to get or set the maximum possible date. MaxSelectionCount Property holds the maximum number of days that can be selected. MinDate Property to get or set the minimum possible date. ScrollChange Property holds the scroll rate. SelectionEnd Property used to set or get the end date of the selected range. SelectionRange Property used to get the selected range of date from the control. SelectionStart Property used set or get the start date of the selected range. SingleMonthSize Property returns the minimum size in which to display a month. ShowTodayCircle Property set the todays date inside a circle. TodaysDate Property set or get the todays date. TodayDateSet Property specifies whether the Date Time property has been set.
  • 39.  list box:- The ListBox represents a Windows control to display a list of items to a user. A user can select an item from the list. It allows the programmer to add items at design time by using the properties window or at the runtime. Let's create a list box by dragging a ListBox control from the Toolbox and dropping it on the form. You can populate the list box items either from the properties window or at runtime. To add items to a ListBox, select the ListBox control and get to the properties window, for the properties of this control. Click the ellipses (...) button next to the Items property. This opens the String Collection Editor dialog box, where you can enter the values one at a line.  Picture box:- PictureBox Control is used to display an image of the file formats like png, gif, jpeg, bmp, wmf, ico, pcx, tga, tiff. Images can be loaded either at the design time or at runtime. The PictureBox control is used for displaying images on the form. The Image property of the control allows you to set an image both at design time or at run time. Let's create a picture box by dragging a PictureBox control from the Toolbox and dropping it on the form.
  • 40. You can load images in many different graphic formats, including bitmaps (BMP), device independent bitmaps (DIB), metafiles (WMF), enhanced metafiles (EMF), GIF and JPEG compressed files, and icons (ICO and CUR). You can decide whether a control should display a border, resetting the BorderStyle to 0-None if necessary. Another property that comes handy in this phase is AutoSize: Set it to True and let the control automatically resize itself to fit the assigned image. Picture1.Picture = LoadPicture("c:windowssetup.bmp") and you can clear the current image using either one of the following statements: ' These are equivalent. Picture1.Picture = LoadPicture("") Set Picture1.Picture = Nothing The LoadPicture function has been extended in Visual Basic 6 to support icon files containing multiple icons.  ProgressBar Control:- Progress Bar Control is used to display the progress of a task in Visual Basic. Mostly the progress bar is used while accessing the databases, or downloading or copying files from the network resources. Explanation:
  • 41. • Using the click event of a button the timer is enabled first. • With the timer tick event the progress bar value is increased till its maximum in a loop. • When the progress bar is at its maximum the timer is disabled. Unit-04/Lecture-08 S.NO RGPV QUESTIONS Year Marks Q.1 Explain List box control. How we can add items to list box? Also explain multi list box. June2009 10
  • 42. List view,tree view ,date and time picker, tool bars  List view:- ListView Control is used to display the list of items as in the right pane of windows explorer. Type of icons can be added to these controls easily, items can be arranged neatly. Explanation: • A List view control and a text box control is used in the example. • Add the listview items using the Items property. • Using the SelectedIndexChanged event, the SelectedIndices value is checked. • Based on the item selected, the TextBox displays a message. The ListView control is used to display a list of items. Along with the TreeView control, it allows you to create a Windows Explorer like interface. Let's click on a ListView control from the Toolbox and place it on the form. The ListView control displays a list of items along with icons. The Item property of the ListView control allows you to add and remove items from it. The SelectedItem property contains a collection of the selected items. The MultiSelect property allows you to set select more than one item in the list view. The CheckBoxes property allows you to set check boxes next to the item
  • 43.  Tree view:- TreeView Control is used to display parent, child nodes in a hierarchy just as in windows explorer window that can be collapsed when clicked. The TreeView control is used to display hierarchical representations of items similar to the ways the files and folders are displayed in the left pane of the Windows Explorer. Each node may contain one or more child nodes. Let's click on a TreeView control from the Toolbox and place it on the form. Explanation: • Root Nodes and Child Nodes are added to the control using the Nodes property. • Appropriate names are provided to the nodes. • AfterSelect event of the control is used to set blue color for the selected nodes alone. • Thus you can know about treeview control in VB.NET.  Date and Time:- DateTimePicker Control is used select a date and time for a date range specified using a MinDate and MaxDate properties. The DateTimePicker control allows selecting a date and time by editing the displayed values in the control. If you click the arrow in the DateTimePicker control, it displays a month calendar,
  • 44. like a combo box control. The user can make selection by clicking the required date. The new selected value appears in the text box part of the control. The MinDate and the MaxDate properties allow you to put limits on the date range. Explanation: • A Label,DateTimePicker and button control is used in the example. • The Date range is set to the DateTimePicker Control using the MinDate and MaxDate property. • On the button click event, the value of the DateTimePicker is returned. • The value of selected is displayed in the Text Box S.NO RGPV QUESTIONS Year Marks Q.1
  • 45. Unit-04/Lecture-09 Progress bar,grids,Tool tip,The error provider Control  Progress bar:- Progress Bar Control is used to display the progress of a task in Visual Basic. Mostly the progress bar is used while accessing the databases, or downloading or copying files from the network resources. It represents a Windows progress bar control. It is used to provide visual feedback to your users about the status of some task. It shows a bar that fills in from left to right as the operation progresses. Let's click on a ProgressBar control from the Toolbox and place it on the form. The main properties of a progress bar are Value, Maximum and Minimum. The Minimum and Maximum properties are used to set the minimum and maximum values that the progress bar can display. The Value property specifies the current position of the progress bar. The ProgressBar control is typically used when an application performs tasks such as copying files or printing documents. To a user the application might look unresponsive if there is no visual cue. In such cases, using the ProgressBar allows the programmer to provide a visual status of progress.
  • 46. Explanation: • Using the click event of a button the timer is enabled first. • With the timer tick event the progress bar value is increased till its maximum in a loop. • When the progress bar is at its maximum the timer is disabled.  Tool bars:- Tooltip Control is used to display explanatory text when the mouse rest on a control or window. This control is helpful in providing a quick help to users. Explanation: • First the BackColor and ForeColor property is set for the tooltip control. • Type of icon is set using the ToolTipIcon property. Using the MouseHover event of a textbox, the tooltip is displayed ErrorProvider control The errorprovider control provides a user interface to indicate to the user that a control on a form has an error associated with it, or The ErrorProvider component provides an easy way to set validation errors. It allows us to set an error message for any control on the form when the input is not valid. When an error message is set, an icon indicating the error will appear next to the control and the error message is displayed as Tool Tip when the mouse is over the control.  Errorprovider properties:- Icon - Icon property are used to indicate an error. ContainerControl - ContainerControl property are used to parent control, usually the form, that contains the data-bound controls on which the errorprovider can display error icon. The Windows Forms ErrorProvider component is used to validate user input on a form or control. It is typically used in conjunction with validating user input on a form, or displaying errors within a dataset. An error provider is a better alternative than displaying an error message in a message box, because once a message box is dismissed, the error message is no longer visible. TheErrorProvider component displays an error icon ( ) next to the relevant control, such as a text box; when the user positions the mouse pointer over the error icon, a ToolTip appears, showing the error message string.
  • 47. The ErrorProvider component's key properties are DataSource, ContainerControl, and Icon. The ContainerControl property must be set to the appropriate container (usually the Windows Form) in order for the ErrorProvider component to display an error icon on the form. When the component is added in the designer, the ContainerControl property is set to the containing form; if you add the control in code, you must set it yourself. Displaying Error Icons for Form Validation with the Windows Forms ErrorProvider Component You can use a Windows Forms ErrorProvider component to display an error icon when the user enters invalid data. You must have at least two controls on the form in order to tab between them and thereby invoke the validation code. To display an error icon when a control's value is invalid 1. Add two controls - for example, text boxes - to a Windows Form. 2. Add an ErrorProvider component to the form. 3. Select the first control and add code to its Validating event handler. In order for this code to run properly, the procedure must be connected to the event. For more information, seeCreating Event Handlers on the Windows Forms Designer, Creating Event Handlers at Run Time for Windows Forms, and Creating Event Handlers in the Visual Basic Code Editor. The following code tests the validity of the data the user has entered; if the data is invalid, the SetError method is called. The first argument of the SetError method specifies which control to display the icon next to. The second argument is the error text to display. Private Sub TextBox1_Validating (ByVal Sender As Object, _ ByVal e As System.ComponentModel.CancelEventArgs) Handles _ TextBox1.Validating If Not IsNumeric(TextBox1.Text) Then ErrorProvider1.SetError(TextBox1, "Not a numeric value.") Else ' Clear the error. ErrorProvider1.SetError(TextBox1, "") End If End Sub