SlideShare a Scribd company logo
Usman Farooq
Exceptions and Exception Handling:
Exception: An exception is a problem that arises during the execution of a program. A C# exception is a
response to an exceptional circumstance that arises while a program is running, such as an attempt to
divide by zero. Exceptions provide a way to transfer control from one part of a program to another. C#
exception handling is built upon four keywords: try, catch, finally and throw.
 Try: A try block identifies a block of code for which particular exceptions will be activated. It's
followed by one or more catch blocks.
 Catch: A program catches an exception with an exception handler at the place in a program
where you want to handle the problem. The catch keyword indicates the catching of an exception.
 Finally: The finally block is used to execute a given set of statements, whether an exception is
thrown or not thrown. For example, if you open a file, it must be closed whether an exception is
raised or not.
 Throw: A program throws an exception when a problem shows up. This is done using a throw
keyword.
Types of Exception Classes in C#: C# exceptions are represented by classes. The exception classes in C#
are mainly directly or indirectly derived from the System.Exception class. Some of the exception classes
derived from the System. Exception class are the System.ApplicationException and
System.SystemException classes.
 The System.ApplicationException class supports exceptions generated by application programs.
So the exceptions defined by the programmers should derive from this class.
 The System.SystemException class is the base class for all predefined system exception.
Exception Class Description
System.IO.IOException Handles I/O errors.
System.IndexOutOfRangeException
Handles errors generated when a method refers to
an array index out of range.
System.ArrayTypeMismatchException
Handles errors generated when type is mismatched
with the array type.
System.NullReferenceException
Handles errors generated from referencing a null
object.
System.DivideByZeroException
Handles errors generated from dividing a dividend
with zero.
System.InvalidCastException Handles errors generated during typecasting.
System.OutOfMemoryException
Handles errors generated from insufficient free
Usman Farooq
memory.
System.StackOverflowException Handles errors generated from stack overflow.
Handling C# Exceptions: C# provides a structured solution to the exception handling problems in the
form of try and catch blocks. Using these blocks the core program statements are separated from the
error-handling statements. These error handling blocks are implemented using the try, catch and finally
keywords.
//Program Goes Here
Rapid Application Development Model: RAD model is Rapid Application Development model. It is a type
of incremental model. In RAD model the components or functions are developed in parallel as if they
were mini projects. The developments are time boxed, delivered and then assembled into a working
prototype. This can quickly give the customer something to see and use and to provide feedback
regarding the delivery and their requirements.
Advantages of the RAD model:
 Reduced development time.
 Increases reusability of components
 Quick initial reviews occur
 Encourages customer feedback
 Integration from very beginning solves a lot of integration issues.
Disadvantages of RAD model:
 Depends on strong team and individual performances for identifying business requirements.
Usman Farooq
 Only system that can be modularized can be built using RAD
 Requires highly skilled developers/designers.
 High dependency on modeling skills
 Inapplicable to cheaper projects as cost of modeling and automated code generation is very high.
When to use RAD model:
 RAD should be used when there is a need to create a system that can be modularized in 2-3
months of time.
 It should be used if there’s high availability of designers for modeling and the budget is high
enough to afford their cost along with the cost of automated code generating tools.
 RAD SDLC model should be chosen only if resources with high business knowledge are available
and there is a need to produce the system in a short span of time (2-3 months).
C# Connection to Database *(Theory): You can connect your C# application to data in a SQL Server
database using the .NET Framework Data Provider for SQL Server. The first step in a C# application is to
create an instance of the Server object and to establish its connection to an instance of Microsoft SQL
Server.
The SqlConnection Object is Handling the part of physical communication between the C# application
and the SQL Server Database. An instance of the SqlConnection class in C# is supported the Data Provider
for SQL Server Database. The SqlConnection instance takes Connection String as argument and pass the
value to the Constructor statement.
You can connect to your database by either:
1. Graphically connection to your database (by defining a DataSet in Visual Studio)
2. You can simply specify your connection string in your main form. That will serve as the default
trans-connection to your database.
Steps to connect to Database:
1. On the File menu, point to New and then click Project.
2. In the New Project dialog box, click Windows Forms Application, and then click OK.
A new Windows Forms project opens.
3. Double click on your form (the backend CS class will be opened and you will be redirected to the
Form_Load Event Handle method)
4. Import SQL References
5. Create a new Connection object
a. If you are use SQL Server, use SqlConnection
b. For MS Access, use OledbConnection
6. Once connection object is initialized, specify connection string
7. After specifying connection string, open your connection to your DB Server with
ConnectionObject.Open() command.
Connection Strings in C#: C# provides you the facility to either create your connection string separately
(old way), when your form loads connection object created, or you can use Configuration file of your
project to store your connection.
Usman Farooq
C# Connection String for MS Access DB: Assume that Database name is : “ TestDB ” and DB Location is :
localdisk D:/
Connection string would be as follow:
connectionString="Provider=Microsoft.ACE.OLEDB.12.0;DataSource=D:TestDB.accdb”;
Connection String for an SQL Instance will be as follow:
connectionString="Data Source=<ServerInstanceName>;Initial Catalog=<DB>;Integrated Security=True";
Creating a connection object for SQL Server DB:
private void Form1_Load(object sender, EventArgs e)
{
stringconString = "Data Source=<Server Instance>;Initial Catalog=<DB>;Integrated
Security=True;";
SqlConnection con = new SqlConnection();
con.ConnectionString = conString;
con.Open();
MessageBox.Show("Opened");
}
ADO.NET:ADO.NET provides a bridge between the front end controls and the back end database. The
ADO.NET objects encapsulate all the data access operations and the controls interact with these objects
to display data, thus hiding the details of movement of data.
The following figure shows the ADO.NET objects at a glance:
ADO.NET
Usman Farooq
Objects: ADO.NET includes many objects you can use to work with data. The objects below are the ones
you must know
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.
To create a connection, you must specify the connection string to the database, usually the connection
string consist of few parameters described below:
Connection String Parameter
Name
Description
Data Source
Identifies the server. Could be local machine, machine domain
name, or IP Address.
Initial Catalog Database name.
Integrated Security Set to SSPI to make connection with user's Windows login
User ID Name of user configured in SQL Server.
Password Password matching SQL Server User ID.
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 aSqlDataAdapter, which holds a set of commands that work on a group
of data.
Creating a SqlCommand Object: Similar to other C# objects, you instantiate a SqlCommand object via the
new instance declaration, as follows:
SqlCommandcmd = new SqlCommand("SELECTCategoryNameFROM Categories", con);
The line above is typical for instantiating a SqlCommand object. It takes a string parameter that holds the
command you want to execute and a reference to a SqlConnection object.
Querying Data: When using a SQL select command, you retrieve a data set for viewing. To accomplish this
with a SqlCommand object, you would use the ExecuteReader method, which returns a SqlDataReader
object.
1. Instantiate a new command with a query and connection
SqlCommandcmd = new SqlCommand("select CategoryName from Categories", conn);
2. Call Execute reader to get query results
SqlDataReaderrdr = cmd.ExecuteReader();
Usman Farooq
Inserting Data: To insert data into a database, use the ExecuteNonQuery method of the SqlCommand
object. The following code shows how to insert data into a database table:
SqlConnectioncon =new SqlConnection( “INSERT INTO Table1(Name,Contact) VALUES (‘”+txtName+”,
’”+txtContact+”’)”),con;
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 Providers, which is why it does not have a
Data Provider specific prefix.
The SqlDataAdapter Object: Sometimes the data you work with is primarily read-only and you rarely need
to make changes to the underlying data source Some situations also call for caching data in memory to
minimize the number of database calls for data that does not change. The data adapter makes it easy for
you to accomplish these things by helping to manage data in a disconnected mode. The data adapter fills
a DataSet object when reading the data and writes in a single batch when persisting changes back to the
database. A data adapter contains a reference to the connection object and opens and closes the
connection automatically when reading from or writing to the database. Additionally, the data adapter
contains command object references for SELECT, INSERT, UPDATE, and DELETE operations on the data.
You will have a data adapter defined for each table in a DataSet and it will take care of all communication
with the database for you. All you need to do is tell the data adapter when to load from or write to the
database.
Object Oriented Programming: Object Oriented Programming (OOP) concepts in C#: Abstraction,
Encapsulation, Inheritance and Polymorphism.
OOP Features:
 Object Oriented Programming (OOP) is a programming model where programs are organized
around objects and data rather than action and logic.
 OOP allows decomposition of a problem into a number of entities called objects and then builds
data and functions around these objects.
 The software is divided into a number of small units called objects. The data and functions are
built around these objects.
 The data of the objects can be accessed only by the functions associated with that object.
 The functions of one object can access the functions of another object.
Usman Farooq
Basic Concepts
Class:
 A class is the core of any modern Object Oriented Programming language such as C#.
 In OOP languages it is mandatory to create a class for representing data.
 A class is a blueprint of an object that contains variables for storing data and functions to perform
operations on the data.
 A class will not occupy any memory space and hence it is only a logical representation of data.
 To create a class, you simply use the keyword "class" followed by the class name:
class Employee
{
}
Object:
 Objects are the basic run-time entities of an object oriented system. They may represent a person,
a place or any item that the program must handle.
 "An object is a software bundle of related variable and methods."
 "An object is an instance of a class"
 A class will not occupy any memory space. Hence to work with the data represented by the class
you must create a variable for the class, that is called an object.
 When an object is created using the new operator, memory is allocated for the class in the heap,
the object is called an instance and its starting address will be stored in the object in stack
memory.
 When an object is created without the new operator, memory will not be allocated in the heap, in
other words an instance will not be created and the object in the stack contains the value null.
 When an object contains null, then it is not possible to access the members of the class using that
object.
 Syntax to create an object of class Employee:
Employee objEmp = new Employee();
All the programming languages supporting Object Oriented Programming will be supporting these three
main concepts:
1. Encapsulation
2. Inheritance
3. Polymorphism
Abstraction
 Abstraction is "To represent the essential feature without representing the background details."
 Abstraction lets you focus on what the object does instead of how it does it.
 Abstraction provides you a generalized view of your classes or objects by providing relevant
information.
Usman Farooq
 Abstraction is the process of hiding the working style of an object, and showing the information
of an object in an understandable manner.
Encapsulation
 Wrapping up a data member and a method together into a single unit (in other words class) is
called Encapsulation.
 Encapsulation is like enclosing in a capsule. That is enclosing the related operations and data
related to an object into that object.
 Encapsulation is like your bag in which you can keep your pen, book etcetera. It means this is the
property of encapsulating members and functions.
class Bag
{
book;
pen;
ReadBook();
}
 Encapsulation means hiding the internal details of an object, in other words how an object does
something.
 Encapsulation prevents clients from seeing its inside view, where the behaviour of the abstraction
is implemented.
 Encapsulation is a technique used to protect the information in an object from another object.
 Hide the data for security such as making the variables private, and expose the property to access
the private data that will be public.
 So, when you access the property you can validate the data and set it.
Polymorphism
 The word polymorphism means having many forms.
 In object-oriented programming paradigm, polymorphism is often expressed as 'one interface,
multiple functions'.
 Polymorphism can be static or dynamic.
 In static polymorphism the response to a function is determined at the compile time.
 In dynamic polymorphism, it is decided at run-time.
Static Polymorphism:The mechanism of linking a function with an object during compile time is called
early binding. It is also called static binding. C# provides two techniques to implement static
polymorphism. These are:
1. Function overloading
2. Operator overloading
Usman Farooq
1: Function Overloading:You can have multiple definitions for the same function name in the same scope.
The definition of the function must differ from each other by the types and/or the number of arguments
in the argument list. You cannot overload function declarations that differ only by return type.
Eg:
Class A {
Public void Show ( ){
MessageBox.Show(“Hello”);
}
Public void Show (String param1){
MessageBox.Show(“Hello ” +param1);
}
Public string Show (string param1){
Return “Hello ”+param1;
}
}
Dynamic Polymorphism: C# allows you to create abstract classes that are used to provide partial class
implementation of an interface. Implementation is completed when a derived class inherits from it.
Abstract classes contain abstract methods, which are implemented by the derived class. The derived
classes have more specialized functionality.
Please note the following rules about abstract classes:
 You cannot create an instance of an abstract class
 You cannot declare an abstract method outside an abstract class
 When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared sealed.
Inner Class (Program):
class Demo
{
public static void Main()
{
System.Console.WriteLine("Demo");
OuterClass.NestedClass.abc();
}
}
class OuterClass
{
private int y = 100;
public class NestedClass : OuterClass
{
public static void abc()
{
OuterClassoc = new OuterClass();
System.Console.WriteLine(oc.y);
}
}}
Usman Farooq
User Controls: User controls are a way of making a custom, reusable component. A user control can
contain other controls but must be hosted by a form. Windows forms are the container for controls,
including user controls
Steps to Create a User Control DLL:
1. Open the Visual Studio and start a new project. Your project must be based on the Windows
Control Library template. Call your project by any name and click OK.
2. Once you have your project open, add a new User Control to your project.
3. Visually design your user control (you have to use the standard control library to design your
custom user control)
4. Once completed, Start Debug your project
5. If no error occurs, your dllshoul be compiled
6. Now open new project template
7. On Toolbox, right click and select “ Choose Items “
8. Browse the opened dialog to the location where your user control project is saved
9. Browse to Project/Debug, and select the <UserControlName>.dll file
10. Click OK.
Partial Classes in C#:It is possible to split the definition of a class or a struct, an interface or a method over
two or more source files. Each source file contains a section of the type or method definition, and all parts
are combined when the application is compiled.
Advantage of using Partial Classes:
 The biggest use of partial classes is make life easier on code generators / designers. Partial classes
allow the generator to simply emit the code they need to emit and do not have to deal with user
edits to the file. Users are likewise free to annotate the class with new members by having a
second partial class. This provides a very clean framework for separation of concerns.
Database Handling code
using System.Data.OleDb;
String connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=C:UsersAliDocumentsVisual Studio
2012ProjectsWindowsFormsApplication2first.accdb";
String tableName = "mytable";
String query = "INSERT INTO " + tableName + "(fname,lname) VALUES (" + "'" +
textBox1.Text + "'" + " , " + "'" + textBox2.Text + "'" + ")";
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
OleDbCommand ob = new OleDbCommand(query, conn);
Usman Farooq
ob.ExecuteNonQuery();
conn.Close();
MessageBox.Show("The value is inserted Successfully");
/////////////////////////////////////////////////////
Data Retrieval
//////////////////////////////////////////////////////
String connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=C:UsersAliDocumentsVisual Studio
2012ProjectsWindowsFormsApplication2first.accdb";
String tableName = "mytable";
String query = String.Format("select * from [{0}]", tableName);
DataSet ds = new DataSet();
OleDbConnection conn = new OleDbConnection(connectionString);
conn.Open();
OleDbDataAdapter da = new OleDbDataAdapter(query, conn);
da.Fill(ds, tableName);
conn.Close();
MessageBox.Show("Total Rows = " + ds.Tables["mytable"].Rows.Count+ "n" +
ds.Tables["mytable"].Rows[2][2]);// + "n"+ ds.Tables["mytable"].Rows[0]["fname"] + "n" +
ds.Tables["mytable"].Rows[0]["lname"]);
//////////////////////////////////////////////////////////////////
Course Out line from which paper can be set
The above notes are made by Usman Farooq(BSCS 7-A).These notes are not the course outline.
The actual course outline is following in the form of pics. The course before mid is not included.
The course for your final starts from "Menu's".
(Syed Ali Raza)
Course Instructor
Visual Programming
Usman Farooq
Usman Farooq
Usman Farooq

More Related Content

DOCX
Simple ado program by visual studio
DOCX
Repository Pattern in MVC3 Application with Entity Framework
DOCX
Rhino Mocks
PDF
Mvc acchitecture
PPTX
DOCX
Test Driven Development
PPTX
ADO.NET by ASP.NET Development Company in india
PPT
Java jdbc
Simple ado program by visual studio
Repository Pattern in MVC3 Application with Entity Framework
Rhino Mocks
Mvc acchitecture
Test Driven Development
ADO.NET by ASP.NET Development Company in india
Java jdbc

What's hot (19)

PDF
Mvc interview questions – deep dive jinal desai
PPT
Advanced SQL Injection
PDF
Oracle to vb 6.0 connectivity
PPT
Ado.net
PPTX
Back-2-Basics: .NET Coding Standards For The Real World
PPTX
Easy mock
PPTX
Sql injection
PDF
Spring Certification Questions
DOCX
Cis 355 i lab 6 of 6
PDF
Analyzing source code of WPF examples by the Infragistics Company
DOCX
Cis 355 i lab 6 of 6
PDF
Beginning linq
PDF
SQL injection: Not only AND 1=1
PDF
Sql Injection Myths and Fallacies
PPT
ADO.NET
PPTX
L2624 labriola
PPT
ASP.NET Session 11 12
PDF
02 basic java programming and operators
PPT
SQL Injection
Mvc interview questions – deep dive jinal desai
Advanced SQL Injection
Oracle to vb 6.0 connectivity
Ado.net
Back-2-Basics: .NET Coding Standards For The Real World
Easy mock
Sql injection
Spring Certification Questions
Cis 355 i lab 6 of 6
Analyzing source code of WPF examples by the Infragistics Company
Cis 355 i lab 6 of 6
Beginning linq
SQL injection: Not only AND 1=1
Sql Injection Myths and Fallacies
ADO.NET
L2624 labriola
ASP.NET Session 11 12
02 basic java programming and operators
SQL Injection
Ad

Similar to MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP (20)

PPTX
Ado.net
PPTX
PATTERNS07 - Data Representation in C#
DOCX
Simple ado program by visual studio
PPT
Chap14 ado.net
PPTX
ADO architecture of XML andd Windows form
PPTX
Chapter 3: ado.net
PPT
For Beginers - ADO.Net
PDF
Ado.Net Architecture
PDF
Using sql server in c sharp
PPT
Synapseindia dot net development chapter 8 asp dot net
PPTX
PDF
C# classes
DOCX
unit 3.docx
PDF
PPT
How to ace your .NET technical interview :: .Net Technical Check Tuneup
PPTX
LECTURE 14 Data Access.pptx
PPT
Lecture 6. ADO.NET Overview.
DOCX
Ado dot net complete meterial (1)
PPTX
C# and ASP.NET Code and Data-Access Security
Ado.net
PATTERNS07 - Data Representation in C#
Simple ado program by visual studio
Chap14 ado.net
ADO architecture of XML andd Windows form
Chapter 3: ado.net
For Beginers - ADO.Net
Ado.Net Architecture
Using sql server in c sharp
Synapseindia dot net development chapter 8 asp dot net
C# classes
unit 3.docx
How to ace your .NET technical interview :: .Net Technical Check Tuneup
LECTURE 14 Data Access.pptx
Lecture 6. ADO.NET Overview.
Ado dot net complete meterial (1)
C# and ASP.NET Code and Data-Access Security
Ad

Recently uploaded (20)

PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
Piense y hagase Rico - Napoleon Hill Ccesa007.pdf
PDF
Electrolyte Disturbances and Fluid Management A clinical and physiological ap...
PPTX
Open Quiz Monsoon Mind Game Final Set.pptx
PDF
English Language Teaching from Post-.pdf
PPTX
UNDER FIVE CLINICS OR WELL BABY CLINICS.pptx
PDF
Pre independence Education in Inndia.pdf
PPTX
Cardiovascular Pharmacology for pharmacy students.pptx
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Open folder Downloads.pdf yes yes ges yes
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PPTX
Revamp in MTO Odoo 18 Inventory - Odoo Slides
PDF
From loneliness to social connection charting
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
Piense y hagase Rico - Napoleon Hill Ccesa007.pdf
Electrolyte Disturbances and Fluid Management A clinical and physiological ap...
Open Quiz Monsoon Mind Game Final Set.pptx
English Language Teaching from Post-.pdf
UNDER FIVE CLINICS OR WELL BABY CLINICS.pptx
Pre independence Education in Inndia.pdf
Cardiovascular Pharmacology for pharmacy students.pptx
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
human mycosis Human fungal infections are called human mycosis..pptx
Abdominal Access Techniques with Prof. Dr. R K Mishra
Open folder Downloads.pdf yes yes ges yes
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Revamp in MTO Odoo 18 Inventory - Odoo Slides
From loneliness to social connection charting
Week 4 Term 3 Study Techniques revisited.pptx

MCS,BCS-7(A,B) Visual programming Syllabus for Final exams @ ISP

  • 1. Usman Farooq Exceptions and Exception Handling: Exception: An exception is a problem that arises during the execution of a program. A C# exception is a response to an exceptional circumstance that arises while a program is running, such as an attempt to divide by zero. Exceptions provide a way to transfer control from one part of a program to another. C# exception handling is built upon four keywords: try, catch, finally and throw.  Try: A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch blocks.  Catch: A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception.  Finally: The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For example, if you open a file, it must be closed whether an exception is raised or not.  Throw: A program throws an exception when a problem shows up. This is done using a throw keyword. Types of Exception Classes in C#: C# exceptions are represented by classes. The exception classes in C# are mainly directly or indirectly derived from the System.Exception class. Some of the exception classes derived from the System. Exception class are the System.ApplicationException and System.SystemException classes.  The System.ApplicationException class supports exceptions generated by application programs. So the exceptions defined by the programmers should derive from this class.  The System.SystemException class is the base class for all predefined system exception. Exception Class Description System.IO.IOException Handles I/O errors. System.IndexOutOfRangeException Handles errors generated when a method refers to an array index out of range. System.ArrayTypeMismatchException Handles errors generated when type is mismatched with the array type. System.NullReferenceException Handles errors generated from referencing a null object. System.DivideByZeroException Handles errors generated from dividing a dividend with zero. System.InvalidCastException Handles errors generated during typecasting. System.OutOfMemoryException Handles errors generated from insufficient free
  • 2. Usman Farooq memory. System.StackOverflowException Handles errors generated from stack overflow. Handling C# Exceptions: C# provides a structured solution to the exception handling problems in the form of try and catch blocks. Using these blocks the core program statements are separated from the error-handling statements. These error handling blocks are implemented using the try, catch and finally keywords. //Program Goes Here Rapid Application Development Model: RAD model is Rapid Application Development model. It is a type of incremental model. In RAD model the components or functions are developed in parallel as if they were mini projects. The developments are time boxed, delivered and then assembled into a working prototype. This can quickly give the customer something to see and use and to provide feedback regarding the delivery and their requirements. Advantages of the RAD model:  Reduced development time.  Increases reusability of components  Quick initial reviews occur  Encourages customer feedback  Integration from very beginning solves a lot of integration issues. Disadvantages of RAD model:  Depends on strong team and individual performances for identifying business requirements.
  • 3. Usman Farooq  Only system that can be modularized can be built using RAD  Requires highly skilled developers/designers.  High dependency on modeling skills  Inapplicable to cheaper projects as cost of modeling and automated code generation is very high. When to use RAD model:  RAD should be used when there is a need to create a system that can be modularized in 2-3 months of time.  It should be used if there’s high availability of designers for modeling and the budget is high enough to afford their cost along with the cost of automated code generating tools.  RAD SDLC model should be chosen only if resources with high business knowledge are available and there is a need to produce the system in a short span of time (2-3 months). C# Connection to Database *(Theory): You can connect your C# application to data in a SQL Server database using the .NET Framework Data Provider for SQL Server. The first step in a C# application is to create an instance of the Server object and to establish its connection to an instance of Microsoft SQL Server. The SqlConnection Object is Handling the part of physical communication between the C# application and the SQL Server Database. An instance of the SqlConnection class in C# is supported the Data Provider for SQL Server Database. The SqlConnection instance takes Connection String as argument and pass the value to the Constructor statement. You can connect to your database by either: 1. Graphically connection to your database (by defining a DataSet in Visual Studio) 2. You can simply specify your connection string in your main form. That will serve as the default trans-connection to your database. Steps to connect to Database: 1. On the File menu, point to New and then click Project. 2. In the New Project dialog box, click Windows Forms Application, and then click OK. A new Windows Forms project opens. 3. Double click on your form (the backend CS class will be opened and you will be redirected to the Form_Load Event Handle method) 4. Import SQL References 5. Create a new Connection object a. If you are use SQL Server, use SqlConnection b. For MS Access, use OledbConnection 6. Once connection object is initialized, specify connection string 7. After specifying connection string, open your connection to your DB Server with ConnectionObject.Open() command. Connection Strings in C#: C# provides you the facility to either create your connection string separately (old way), when your form loads connection object created, or you can use Configuration file of your project to store your connection.
  • 4. Usman Farooq C# Connection String for MS Access DB: Assume that Database name is : “ TestDB ” and DB Location is : localdisk D:/ Connection string would be as follow: connectionString="Provider=Microsoft.ACE.OLEDB.12.0;DataSource=D:TestDB.accdb”; Connection String for an SQL Instance will be as follow: connectionString="Data Source=<ServerInstanceName>;Initial Catalog=<DB>;Integrated Security=True"; Creating a connection object for SQL Server DB: private void Form1_Load(object sender, EventArgs e) { stringconString = "Data Source=<Server Instance>;Initial Catalog=<DB>;Integrated Security=True;"; SqlConnection con = new SqlConnection(); con.ConnectionString = conString; con.Open(); MessageBox.Show("Opened"); } ADO.NET:ADO.NET provides a bridge between the front end controls and the back end database. The ADO.NET objects encapsulate all the data access operations and the controls interact with these objects to display data, thus hiding the details of movement of data. The following figure shows the ADO.NET objects at a glance: ADO.NET
  • 5. Usman Farooq Objects: ADO.NET includes many objects you can use to work with data. The objects below are the ones you must know 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. To create a connection, you must specify the connection string to the database, usually the connection string consist of few parameters described below: Connection String Parameter Name Description Data Source Identifies the server. Could be local machine, machine domain name, or IP Address. Initial Catalog Database name. Integrated Security Set to SSPI to make connection with user's Windows login User ID Name of user configured in SQL Server. Password Password matching SQL Server User ID. 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 aSqlDataAdapter, which holds a set of commands that work on a group of data. Creating a SqlCommand Object: Similar to other C# objects, you instantiate a SqlCommand object via the new instance declaration, as follows: SqlCommandcmd = new SqlCommand("SELECTCategoryNameFROM Categories", con); The line above is typical for instantiating a SqlCommand object. It takes a string parameter that holds the command you want to execute and a reference to a SqlConnection object. Querying Data: When using a SQL select command, you retrieve a data set for viewing. To accomplish this with a SqlCommand object, you would use the ExecuteReader method, which returns a SqlDataReader object. 1. Instantiate a new command with a query and connection SqlCommandcmd = new SqlCommand("select CategoryName from Categories", conn); 2. Call Execute reader to get query results SqlDataReaderrdr = cmd.ExecuteReader();
  • 6. Usman Farooq Inserting Data: To insert data into a database, use the ExecuteNonQuery method of the SqlCommand object. The following code shows how to insert data into a database table: SqlConnectioncon =new SqlConnection( “INSERT INTO Table1(Name,Contact) VALUES (‘”+txtName+”, ’”+txtContact+”’)”),con; 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 Providers, which is why it does not have a Data Provider specific prefix. The SqlDataAdapter Object: Sometimes the data you work with is primarily read-only and you rarely need to make changes to the underlying data source Some situations also call for caching data in memory to minimize the number of database calls for data that does not change. The data adapter makes it easy for you to accomplish these things by helping to manage data in a disconnected mode. The data adapter fills a DataSet object when reading the data and writes in a single batch when persisting changes back to the database. A data adapter contains a reference to the connection object and opens and closes the connection automatically when reading from or writing to the database. Additionally, the data adapter contains command object references for SELECT, INSERT, UPDATE, and DELETE operations on the data. You will have a data adapter defined for each table in a DataSet and it will take care of all communication with the database for you. All you need to do is tell the data adapter when to load from or write to the database. Object Oriented Programming: Object Oriented Programming (OOP) concepts in C#: Abstraction, Encapsulation, Inheritance and Polymorphism. OOP Features:  Object Oriented Programming (OOP) is a programming model where programs are organized around objects and data rather than action and logic.  OOP allows decomposition of a problem into a number of entities called objects and then builds data and functions around these objects.  The software is divided into a number of small units called objects. The data and functions are built around these objects.  The data of the objects can be accessed only by the functions associated with that object.  The functions of one object can access the functions of another object.
  • 7. Usman Farooq Basic Concepts Class:  A class is the core of any modern Object Oriented Programming language such as C#.  In OOP languages it is mandatory to create a class for representing data.  A class is a blueprint of an object that contains variables for storing data and functions to perform operations on the data.  A class will not occupy any memory space and hence it is only a logical representation of data.  To create a class, you simply use the keyword "class" followed by the class name: class Employee { } Object:  Objects are the basic run-time entities of an object oriented system. They may represent a person, a place or any item that the program must handle.  "An object is a software bundle of related variable and methods."  "An object is an instance of a class"  A class will not occupy any memory space. Hence to work with the data represented by the class you must create a variable for the class, that is called an object.  When an object is created using the new operator, memory is allocated for the class in the heap, the object is called an instance and its starting address will be stored in the object in stack memory.  When an object is created without the new operator, memory will not be allocated in the heap, in other words an instance will not be created and the object in the stack contains the value null.  When an object contains null, then it is not possible to access the members of the class using that object.  Syntax to create an object of class Employee: Employee objEmp = new Employee(); All the programming languages supporting Object Oriented Programming will be supporting these three main concepts: 1. Encapsulation 2. Inheritance 3. Polymorphism Abstraction  Abstraction is "To represent the essential feature without representing the background details."  Abstraction lets you focus on what the object does instead of how it does it.  Abstraction provides you a generalized view of your classes or objects by providing relevant information.
  • 8. Usman Farooq  Abstraction is the process of hiding the working style of an object, and showing the information of an object in an understandable manner. Encapsulation  Wrapping up a data member and a method together into a single unit (in other words class) is called Encapsulation.  Encapsulation is like enclosing in a capsule. That is enclosing the related operations and data related to an object into that object.  Encapsulation is like your bag in which you can keep your pen, book etcetera. It means this is the property of encapsulating members and functions. class Bag { book; pen; ReadBook(); }  Encapsulation means hiding the internal details of an object, in other words how an object does something.  Encapsulation prevents clients from seeing its inside view, where the behaviour of the abstraction is implemented.  Encapsulation is a technique used to protect the information in an object from another object.  Hide the data for security such as making the variables private, and expose the property to access the private data that will be public.  So, when you access the property you can validate the data and set it. Polymorphism  The word polymorphism means having many forms.  In object-oriented programming paradigm, polymorphism is often expressed as 'one interface, multiple functions'.  Polymorphism can be static or dynamic.  In static polymorphism the response to a function is determined at the compile time.  In dynamic polymorphism, it is decided at run-time. Static Polymorphism:The mechanism of linking a function with an object during compile time is called early binding. It is also called static binding. C# provides two techniques to implement static polymorphism. These are: 1. Function overloading 2. Operator overloading
  • 9. Usman Farooq 1: Function Overloading:You can have multiple definitions for the same function name in the same scope. The definition of the function must differ from each other by the types and/or the number of arguments in the argument list. You cannot overload function declarations that differ only by return type. Eg: Class A { Public void Show ( ){ MessageBox.Show(“Hello”); } Public void Show (String param1){ MessageBox.Show(“Hello ” +param1); } Public string Show (string param1){ Return “Hello ”+param1; } } Dynamic Polymorphism: C# allows you to create abstract classes that are used to provide partial class implementation of an interface. Implementation is completed when a derived class inherits from it. Abstract classes contain abstract methods, which are implemented by the derived class. The derived classes have more specialized functionality. Please note the following rules about abstract classes:  You cannot create an instance of an abstract class  You cannot declare an abstract method outside an abstract class  When a class is declared sealed, it cannot be inherited, abstract classes cannot be declared sealed. Inner Class (Program): class Demo { public static void Main() { System.Console.WriteLine("Demo"); OuterClass.NestedClass.abc(); } } class OuterClass { private int y = 100; public class NestedClass : OuterClass { public static void abc() { OuterClassoc = new OuterClass(); System.Console.WriteLine(oc.y); } }}
  • 10. Usman Farooq User Controls: User controls are a way of making a custom, reusable component. A user control can contain other controls but must be hosted by a form. Windows forms are the container for controls, including user controls Steps to Create a User Control DLL: 1. Open the Visual Studio and start a new project. Your project must be based on the Windows Control Library template. Call your project by any name and click OK. 2. Once you have your project open, add a new User Control to your project. 3. Visually design your user control (you have to use the standard control library to design your custom user control) 4. Once completed, Start Debug your project 5. If no error occurs, your dllshoul be compiled 6. Now open new project template 7. On Toolbox, right click and select “ Choose Items “ 8. Browse the opened dialog to the location where your user control project is saved 9. Browse to Project/Debug, and select the <UserControlName>.dll file 10. Click OK. Partial Classes in C#:It is possible to split the definition of a class or a struct, an interface or a method over two or more source files. Each source file contains a section of the type or method definition, and all parts are combined when the application is compiled. Advantage of using Partial Classes:  The biggest use of partial classes is make life easier on code generators / designers. Partial classes allow the generator to simply emit the code they need to emit and do not have to deal with user edits to the file. Users are likewise free to annotate the class with new members by having a second partial class. This provides a very clean framework for separation of concerns. Database Handling code using System.Data.OleDb; String connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:UsersAliDocumentsVisual Studio 2012ProjectsWindowsFormsApplication2first.accdb"; String tableName = "mytable"; String query = "INSERT INTO " + tableName + "(fname,lname) VALUES (" + "'" + textBox1.Text + "'" + " , " + "'" + textBox2.Text + "'" + ")"; OleDbConnection conn = new OleDbConnection(connectionString); conn.Open(); OleDbCommand ob = new OleDbCommand(query, conn);
  • 11. Usman Farooq ob.ExecuteNonQuery(); conn.Close(); MessageBox.Show("The value is inserted Successfully"); ///////////////////////////////////////////////////// Data Retrieval ////////////////////////////////////////////////////// String connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:UsersAliDocumentsVisual Studio 2012ProjectsWindowsFormsApplication2first.accdb"; String tableName = "mytable"; String query = String.Format("select * from [{0}]", tableName); DataSet ds = new DataSet(); OleDbConnection conn = new OleDbConnection(connectionString); conn.Open(); OleDbDataAdapter da = new OleDbDataAdapter(query, conn); da.Fill(ds, tableName); conn.Close(); MessageBox.Show("Total Rows = " + ds.Tables["mytable"].Rows.Count+ "n" + ds.Tables["mytable"].Rows[2][2]);// + "n"+ ds.Tables["mytable"].Rows[0]["fname"] + "n" + ds.Tables["mytable"].Rows[0]["lname"]); ////////////////////////////////////////////////////////////////// Course Out line from which paper can be set The above notes are made by Usman Farooq(BSCS 7-A).These notes are not the course outline. The actual course outline is following in the form of pics. The course before mid is not included. The course for your final starts from "Menu's". (Syed Ali Raza) Course Instructor Visual Programming