0% found this document useful (0 votes)
21 views23 pages

Ado Unit 3

The document provides an introduction to C# Windows Forms, detailing its purpose as a GUI class library for developing desktop applications. It explains how to create a Windows Forms application using Visual Studio, including the use of various controls and data binding techniques. Additionally, it covers ADO.NET for data access, its architecture, features, and applications, along with examples of binding data to a DataGridView.

Uploaded by

Nitin Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views23 pages

Ado Unit 3

The document provides an introduction to C# Windows Forms, detailing its purpose as a GUI class library for developing desktop applications. It explains how to create a Windows Forms application using Visual Studio, including the use of various controls and data binding techniques. Additionally, it covers ADO.NET for data access, its architecture, features, and applications, along with examples of binding data to a DataGridView.

Uploaded by

Nitin Sharma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Introduction to C# Windows Forms

Windows Forms is a Graphical User Interface (GUI) class library which is bundled in .Net Framework.
Its main purpose is to provide an easier interface to develop the applications for desktop, tablet, PCs.
It is also termed as the WinForms. The applications which are developed by using Windows Forms or
WinForms are known as the Windows Forms Applications that runs on the desktop computer.
WinForms can be used only to develop the Windows Forms Applications not web applications.
WinForms applications can contain the different type of controls like labels, list boxes, tooltip etc.

Creating a Windows Forms Application Using Visual Studio 2017

 First, open the Visual Studio then Go to File -> New -> Project to create a new project and
then select the language as Visual C# from the left menu. Click on Windows Forms App(.NET
Framework) in the middle of current window. After that give the project name and Click OK.

Here the solution is like a container which contains the projects and files that may be
required by the program.

 After that following window will display which will be divided into three parts as follows:

1. Editor Window or Main Window: Here, you will work with forms and code editing.
You can notice the layout of form which is now blank. You will double click the form
then it will open the code for that.

2. Solution Explorer Window: It is used to navigate between all items in solution. For
example, if you will select a file form this window then particular information will be
display in the property window.

3. Properties Window: This window is used to change the different properties of the
selected item in the Solution Explorer. Also, you can change the properties of
components or controls that you will add to the forms.

 Now to add the controls to your WinForms application go to Toolbox tab present in the
extreme left side of Visual Studio. Here, you can see a list of controls. To access the most
commonly used controls go to Common Controls present in Toolbox tab.

 Now drag and drop the controls that you needed on created Form. For example, if you can
add TextBox, ListBox, Button etc. as shown below. By clicking on the particular dropped
control you can see and change its properties present in the right most corner of Visual
Studio.

In the above image, you can see the TextBox is selected and its properties like TextAlign,
MaxLength etc. are opened in right most corner. You can change its properties’ values as per
the application need. The code of controls will be automatically added in the background.
You can check the Form1.Designer.cs file present in the Solution Explorer Window.

 To run the program you can use an F5 key or Play button present in the toolbar of Visual
Studio. To stop the program you can use pause button present in the ToolBar. You can also
run the program by going to Debug->Start Debugging menu in the menubar.

C# Windows Forms is a graphical user interface (GUI) framework that enables developers to create
desktop applications for the Windows operating system. Windows Forms applications are created
using the C# programming language and the .NET framework. They are built by dragging and
dropping controls such as buttons, text boxes, labels, and other user interface elements onto a form.

1. The Windows Forms framework provides a rich set of controls that developers can use to
build applications with. These controls are designed to provide a consistent and familiar user
interface for Windows users. Developers can customize the appearance and behavior of
these controls by setting various properties and handling events.

2. To create a Windows Forms application in C#, you can use Microsoft Visual Studio, which is
an integrated development environment (IDE) that provides a visual designer to create and
layout the user interface elements. The visual designer is a drag-and-drop interface for
building your UI, and you can easily configure each control’s properties through a user-
friendly interface.

3. In addition to the visual designer, Visual Studio also provides a code editor that enables
developers to write the C# code for the application’s logic. Developers can handle events and
perform tasks such as data validation, data manipulation, and business logic implementation.

4. Windows Forms applications are versatile and can be used to create various types of
applications such as data entry, management, and reporting applications, as well as games
and multimedia applications.

Introduction to ADO.NET

The .NET Framework includes its own data access technology i.e. ADO.NET. ADO.NET is the latest
implementation of Microsoft’s Universal Data Access strategy. ADO.NET consists of managed classes
that allows .NET applications to connect to data sources such as Microsoft SQL Server, Microsoft
Access, Oracle, XML, etc., execute commands and manage disconnected data..t

Microsoft ADO.NET is the latest improvement after ADO. Firstly, ADO.NET was introduced in the
10th version of the .NET framework, which helps in providing an extensive array of various features to
handle data in different modes, such as connected mode and disconnected mode. In connected
mode, we are dealing with live data and in disconnected mode, data is provided from the data store.
ADO.NET was primarily developed to address two ways to work with data that we are getting from
data sources. The two ways are as follows :
1. The first is to do with the user’s need to access data once and to iterate through a collection
of data in a single instance i.e caching the data in runtime memory.

2. The second way to work with data is in connected way which is we do not cache data. And
we always go to database to retrieve it

Architecture of ADO.NET :
ADO.NET uses a multilayered architecture that revolves around a few key concepts as –

 asConnection

 Command

 DataSet objects

The ADO.NET architecture is a little bit different from the ADO, which can be shown from the
following figure of the architecture of ADO.NET.

Architecture of ADO.NET

One of the key differences between ADO and ADO.NET is how they deal with the challenge of
different data sources. In ADO.NET, programmers always use a generic set of objects, no matter what
the underlying data source is. For example, if we want to retrieve a record from an Oracle Database,
we use the same connection class that we use to tackle the same task with SQL Server. This is not the
case with ADO.NET, which uses a data provider model and the DataSet.

Features of ADO.NET :
The following are the features of ADO.NET –

 Interoperability-
We know that XML documents are text-based formats. So, one can edit and edit XML
documents using standard text-editing tools. ADO.NET uses XML in all data exchanges and
for internal representation of data.

 Maintainability –
ADO.NET is built around the idea of separation of data logic and user interface. It means that
we can create our application in independent layers.

 Programmability (Typed Programming) –


It is a programming style in which user words are used to construct statements or evaluate
expressions. For example: If we want to select the “Marks” column from “Kawal” from the
“Student” table, the following is the way to do so:
DataSet.Student("Kawal").Marks;

 Performance –
It uses disconnected data architecture which is easy to scale as it reduces the load on the
database. Everything is handled on the client-side, so it improves performance.

 Scalability –
It means meeting the needs of the growing number of clients, which degrading performance.
As it uses disconnected data access, applications do not retain database lock connections for
a longer time. Thus, it accommodates scalability by encouraging programmers to conserve
limited resources and allow users to access data simultaneously.

What Types of Applications Use ADO.NET?

ADO.NET is used in various applications where data access and manipulation are crucial. Here are
some types of applications that commonly use ADO.NET:

 Desktop Applications: Traditional desktop applications like Windows Forms and WPF
applications often need to interact with databases or other data sources. ADO.NET provides
the necessary tools to connect to databases, retrieve data, and update records.

 Web Applications: Web applications, including ASP.NET Web Forms and ASP.NET MVC
applications, require data access to display, collect, and manage information. ADO.NET
enables these applications to connect to databases and present data to users.

 Console Applications: Console applications might need to perform data-related tasks, like
importing/exporting data, data analysis, or reporting. ADO.NET can facilitate these tasks by
providing efficient data access.

 Service Applications: Background or Windows services that process data often rely on
ADO.NET to connect to databases and handle data-related operations.

C# Grid Control

SourceGrid is a Windows Forms control written entirely in C#, my goal is to create a simple but
flexible grid to use in all of the cases in which it is necessary to visualize or to change a series of data
in a table format. There are a lot of controls of this type available, but often are expensive, difficult to
be customize or not compatible with. NET. The Microsoft DataGrid for me is too DataSet orientated
and therefore results often complicated to use in the cases in which the source data isn't a DataSet
and often is not enough customizable.

In C#, binding a DataGridView to a data source involves setting the DataSource property to
an IEnumerable implementation (like a DataTable or List), and optionally specifying a DataMember if
the source has multiple tables/lists.

Lecture Notes: Binding DataGridView to a Data Source

1. Understanding Data Binding

 Purpose:

Data binding allows a DataGridView control to display and interact with data from various sources
(databases, collections, etc.).

 Mechanism:

The DataGridView control is bound to a data source using


the DataSource and DataMember properties.

 Data Source Types:

 DataTable

 DataSet
 List<T>

 BindingSource

 Data Binding Events:

The DataGridView can be configured to respond to events related to data changes (e.g., row added,
cell changed).

2. Binding to a DataTable

example.

// Create a DataTable

DataTable dt = new DataTable();

dt.Columns.Add("ID", typeof(int));

dt.Columns.Add("Name", typeof(string));

dt.Columns.Add("Age", typeof(int));

// Add some data

dt.Rows.Add(1, "Alice", 30);

dt.Rows.Add(2, "Bob", 25);

// Bind the DataGridView to the DataTable

dataGridView1.DataSource = dt;

 Explanation:

o A DataTable is created and populated with data.

o The DataSource property of the DataGridView is set to the dt object.

o The DataGridView automatically displays the data from the DataTable.

3. Binding to a List

example.

// Create a List of objects

List<Person> people = new List<Person>();

people.Add(new Person { ID = 1, Name = "Alice", Age = 30 });

people.Add(new Person { ID = 2, Name = "Bob", Age = 25 });

// Bind the DataGridView to the List

dataGridView1.DataSource = people;

 Explanation:

o A List of custom objects (Person) is created.

o The DataSource property of the DataGridView is set to the people object.

o The DataGridView displays the properties of the Person objects as columns.


4. Binding to a BindingSource

example.

// Create a BindingSource

BindingSource bs = new BindingSource();

// Create a DataTable

DataTable dt = new DataTable();

dt.Columns.Add("ID", typeof(int));

dt.Columns.Add("Name", typeof(string));

dt.Columns.Add("Age", typeof(int));

// Add some data

dt.Rows.Add(1, "Alice", 30);

dt.Rows.Add(2, "Bob", 25);

// Set the BindingSource's DataSource

bs.DataSource = dt;

// Bind the DataGridView to the BindingSource

dataGridView1.DataSource = bs;

 Explanation:

o A BindingSource is used as an intermediary between the DataGridView and the data


source.

o The BindingSource's DataSource property is set to the dt object.

o The DataGridView is bound to the BindingSource.

5. Customizing the DataGridView

 Column Headers: The DataGridView automatically creates column headers based on the
data source's column names. You can customize these headers by setting
the HeaderText property of the DataGridViewColumn objects.

 Column Formatting: You can format the data displayed in each column using
the DefaultCellStyle property of the DataGridViewColumn objects.

 Sorting and Filtering: The DataGridView provides built-in sorting and filtering capabilities.

Data Binding
Every ASP.NET web form control inherits the DataBind method from its parent Control class, which
gives it an inherent capability to bind data to at least one of its properties. This is known as simple
data binding or inline data binding.
Simple data binding involves attaching any collection (item collection) which implements the
IEnumerable interface, or the DataSet and DataTable classes to the DataSource property of the
control.
On the other hand, some controls can bind records, lists, or columns of data into their structure
through a DataSource control. These controls derive from the BaseDataBoundControl class. This is
called declarative data binding.
The data source controls help the data-bound controls implement functionalities such as, sorting,
paging, and editing data collections.
The BaseDataBoundControl is an abstract class, which is inherited by two more abstract classes:
DataBoundControl
HierarchicalDataBoundControl
The abstract class DataBoundControl is again inherited by two more abstract classes:
ListControl
CompositeDataBoundControl
The controls capable of simple data binding are derived from the ListControl abstract class and these
controls are:
BulletedList
CheckBoxList
DropDownList
ListBox
RadioButtonList
The controls capable of declarative data binding (a more complex data binding) are derived from the
abstract class CompositeDataBoundControl. These controls are:
DetailsView
FormView
GridView
RecordList
Simple Data Binding
Simple data binding involves the read-only selection lists. These controls can bind to an array list or
fields from a database. Selection lists takes two values from the database or the data source; one
value is displayed by the list and the other is considered as the value corresponding to the display.
Let us take up a small example to understand the concept. Create a web site with a bulleted list and a
SqlDataSource control on it. Configure the data source control to retrieve two values from your
database (we use the same DotNetReferences table as in the previous chapter).
Choosing a data source for the bulleted list control involves:
Selecting the data source control
Selecting a field to display, which is called the data field
Selecting a field for the value

When the application is executed, check that the entire title column is bound to the bulleted list and
displayed.
Declarative Data Binding
We have already used declarative data binding in the previous tutorial using GridView control. The
other composite data bound controls capable of displaying and manipulating data in a tabular
manner are the DetailsView, FormView, and RecordList control.
In the next tutorial, we will look into the technology for handling database, i.e, ADO.NET.
However, the data binding involves the following objects:

A dataset that stores the data retrieved from the database.


The data provider, which retrieves data from the database by using a command over a connection.
The data adapter that issues the select statement stored in the command object; it is also capable of
update the data in a database by issuing Insert, Delete, and Update statements.
Relation between the data binding objects:

Example
Let us take the following steps:
Step (1) : Create a new website. Add a class named booklist by right clicking on the solution name in
the Solution Explorer and choosing the item 'Class' from the 'Add Item' dialog box. Name it as
booklist.cs.
using System;
using System.Data;
using System.Configuration;
using System.Linq;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;
namespace databinding
{
public class booklist
{
protected String bookname;
protected String authorname;
public booklist(String bname, String aname)
{
this.bookname = bname;
this.authorname = aname;

public String Book


{
get
{
return this.bookname;
}
set
{
this.bookname = value;
}
}

public String Author


{
get
{
return this.authorname;
}
set
{
this.authorname = value;
}
}
}
}
Step (2) : Add four list controls on the page a list box control, a radio button list, a check box list, and
a drop down list and four labels along with these list controls. The page should look like this in design
view:

The source file should look as the following:


<form id="form1" runat="server">
<div>

<table style="width: 559px">


<tr>
<td style="width: 228px; height: 157px;">
<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True"
OnSelectedIndexChanged="ListBox1_SelectedIndexChanged">
</asp:ListBox>
</td>

<td style="height: 157px">


<asp:DropDownList ID="DropDownList1" runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>
</td>
</tr>

<tr>
<td style="width: 228px; height: 40px;">
<asp:Label ID="lbllistbox" runat="server"></asp:Label>
</td>

<td style="height: 40px">


<asp:Label ID="lbldrpdown" runat="server">
</asp:Label>
</td>
</tr>

<tr>
<td style="width: 228px; height: 21px">
</td>

<td style="height: 21px">


</td>
</tr>

<tr>
<td style="width: 228px; height: 21px">
<asp:RadioButtonList ID="RadioButtonList1" runat="server"
AutoPostBack="True"
OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
</asp:RadioButtonList>
</td>

<td style="height: 21px">


<asp:CheckBoxList ID="CheckBoxList1" runat="server"
AutoPostBack="True" OnSelectedIndexChanged="CheckBoxList1_SelectedIndexChanged">
</asp:CheckBoxList>
</td>
</tr>

<tr>
<td style="width: 228px; height: 21px">
<asp:Label ID="lblrdlist" runat="server">
</asp:Label>
</td>

<td style="height: 21px">


<asp:Label ID="lblchklist" runat="server">
</asp:Label>
</td>
</tr>
</table>

</div>
</form>
Step (3) : Finally, write the following code behind routines of the application:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
IList bklist = createbooklist();

if (!this.IsPostBack)
{
this.ListBox1.DataSource = bklist;
this.ListBox1.DataTextField = "Book";
this.ListBox1.DataValueField = "Author";

this.DropDownList1.DataSource = bklist;
this.DropDownList1.DataTextField = "Book";
this.DropDownList1.DataValueField = "Author";

this.RadioButtonList1.DataSource = bklist;
this.RadioButtonList1.DataTextField = "Book";
this.RadioButtonList1.DataValueField = "Author";

this.CheckBoxList1.DataSource = bklist;
this.CheckBoxList1.DataTextField = "Book";
this.CheckBoxList1.DataValueField = "Author";

this.DataBind();
}
}

protected IList createbooklist()


{
ArrayList allbooks = new ArrayList();
booklist bl;

bl = new booklist("UNIX CONCEPTS", "SUMITABHA DAS");


allbooks.Add(bl);

bl = new booklist("PROGRAMMING IN C", "RICHI KERNIGHAN");


allbooks.Add(bl);

bl = new booklist("DATA STRUCTURE", "TANENBAUM");


allbooks.Add(bl);

bl = new booklist("NETWORKING CONCEPTS", "FOROUZAN");


allbooks.Add(bl);

bl = new booklist("PROGRAMMING IN C++", "B. STROUSTROUP");


allbooks.Add(bl);

bl = new booklist("ADVANCED JAVA", "SUMITABHA DAS");


allbooks.Add(bl);

return allbooks;
}

protected void ListBox1_SelectedIndexChanged(object sender, EventArgs e)


{
this.lbllistbox.Text = this.ListBox1.SelectedValue;
}

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)


{
this.lbldrpdown.Text = this.DropDownList1.SelectedValue;
}

protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)


{
this.lblrdlist.Text = this.RadioButtonList1.SelectedValue;
}

protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)


{
this.lblchklist.Text = this.CheckBoxList1.SelectedValue;
}
}
Observe the following:
The booklist class has two properties: bookname and authorname.
The createbooklist method is a user defined method that creates an array of booklist objects named
allbooks.The Page_Load event handler ensures that a list of books is created. The list is of IList type,
which implements the IEnumerable interface and capable of being bound to the list controls. The
page load event handler binds the IList object 'bklist' with the list controls. The bookname property is
to be displayed and the authorname property is considered as the value.
When the page is run, if the user selects a book, its name is selected and displayed by the list
controls whereas the corresponding labels display the author name, which is the corresponding
value for the selected index of the list control.

Adapter Design Pattern in C# with Examples

The Adapter Design Pattern is a structural pattern that allows objects with incompatible interfaces to
work together. It acts as a bridge between two incompatible interfaces. This pattern is useful when
you want to use existing classes, but their interfaces do not match the one you need.
The Adapter Design Pattern acts as a bridge between two incompatible objects. Let’s say the first
object is A and the second object is B. Object A wants to consume some of object B’s services.
However, these two objects are incompatible and cannot communicate directly. In this case, the
Adapter will come into the picture and act as a middleman or bridge between objects A and B. Now,
object A will call the Adapter, and the Adapter will do the necessary transformations or conversions,
and then it will call object B.

Let us understand the Adapter Design Pattern with an Example, and then we will see the UML
Diagram of the Adapter Design Pattern by comparing it with our Example. Please have a look at the
following image. Here, you can see two interfaces, or you can say two systems. On the right-hand
side, you can see the Third Party Billing System; on the left-hand side, you can see the Client, i.e., the
Existing HR System. Now, we will see how these two systems are incompatible, and we will also see
how we will make them compatible using Adapter Design Patterns in C#.
Now, the HR System will send the employee information as a String Array to the Adapter. Then, what
this Adapter will do is it will read the employee information from the string array, populate the
employee object, and then put each employee object into the List<Employee> collection. Then, the
Adapter will send the List<Employee> to the ProcessSalary method of the Third Party Billing System.
Then, the ProcessSalary method calculates each employee’s salary and deposits the salary into the
Employee’s bank account.
So, in this way, we can make two incompatible interfaces work together with the help of the Adapter
Design Pattern in C#. Again, the Adapter Design Pattern in C# can be implemented in two ways. They
are as follows.
1. Object Adapter Pattern
2. Class Adapter Pattern
Implementation of Object Adapter Design Pattern in C#:
Let us implement the example we discussed using the Object Adapter Design Pattern in C# step by
step. Once we discuss the Example, we will see the UML Diagram of the Object Adapter Design
Pattern by comparing it with our Examples. So, let us proceed and see how we can implement the
Object Adapter Design Pattern in C#.
Step 1: Creating Employee Class
Create a class file named Employee.cs and copy and paste the following code. This class is going to be
used by ThirdPartyBillingSystem (i.e., Adaptee) as well as by the Adapter. Here, we created the
Employee with the required properties and then initialize the properties using the class constructor.

namespace AdapterDesignPattern
{
public class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public string Designation { get; set; }
public decimal Salary { get; set; }

public Employee(int id, string name, string designation, decimal salary)


{
ID = id;
Name = name;
Designation = designation;
Salary = salary;
}
}
}

Step2: Creating Adaptee


This is going to be a class that contains the functionality that the client requires.
However, this interface is not compatible with the client. So, create a class file
named ThirdPartyBillingSystem.cs and copy and paste the following code. This class
has the ProcessSalary method, which takes a list of employees as an input parameter
and then processes each employee’s salary.
using System;
using System.Collections.Generic;
namespace AdapterDesignPattern
{
// The Adaptee contains some functionality that is required by the client.
// But this interface is not compatible with the client code.
public class ThirdPartyBillingSystem
{
//ThirdPartyBillingSystem accepts employee's information as a List to process each employee's
salary
public void ProcessSalary(List<Employee> listEmployee)
{
foreach (Employee employee in listEmployee)
{
Console.WriteLine("Rs." + employee.Salary + " Salary Credited to " + employee.Name + "
Account");
}
}
}
}
Step3: Creating ITarget interface
This is going to be the domain-specific interface that is going to be used by the client. So, create an
interface with the name ITarget.cs and then copy and paste the following code into it. This class
defines the abstract ProcessCompanySalary method, which is going to be implemented by the
Adapter. Again, the client will use this method to process the salary.
namespace AdapterDesignPattern
{
// The ITarget defines the domain-specific interface used by the client code.
// This interface needs to be implemented by the Adapter.
// The client can only see this interface i.e. the class which implements the ITarget interface.
public interface ITarget
{
void ProcessCompanySalary(string[,] employeesArray);
}
}
Step4: Create an Adapter
This will be the class that implements the ITarget interface and has a reference to the Adaptee
(ThirdPartyBillingSystem) object as we are using the Object Adapter Design Pattern. This class is
responsible for communication between the Client and the Adaptee.
So, create a class file named EmployeeAdapter.cs and copy and paste the following code. This class
implements the ITarget interface and provides the implementation for
the ProcessCompanySalary method. This class also has a reference to the ThirdPartyBillingSystem
(Adaptee) object. The ProcessCompanySalary method receives the employee information as a string
array, converts the string array to a list of Employees, and then calls the ProcessSalary method on the
ThirdPartyBillingSystem (Adaptee) object by providing the list of employees as an argument.
using System;
using System.Collections.Generic;
namespace AdapterDesignPattern
{
// This is the class that makes two incompatible interfaces or systems work together.
// The Adapter makes the Adaptee's interface compatible with the Target's interface.
public class EmployeeAdapter : ITarget
{
//To use Object Adapter Design Pattern, we need to create an object of ThirdPartyBillingSystem
ThirdPartyBillingSystem thirdPartyBillingSystem = new ThirdPartyBillingSystem();

//The following will accept the employees in the form of string array
//Then convert the employee string array to List of Employees
//After conversation, it will call the Adaptee's Method to Process the Salaries
public void ProcessCompanySalary(string[,] employeesArray)
{
string Id = null;
string Name = null;
string Designation = null;
string Salary = null;

List<Employee> listEmployee = new List<Employee>();

for (int i = 0; i < employeesArray.GetLength(0); i++)


{
for (int j = 0; j < employeesArray.GetLength(1); j++)
{
if (j == 0)
{
Id = employeesArray[i, j];
}
else if (j == 1)
{
Name = employeesArray[i, j];
}
else if (j == 2)
{
Designation = employeesArray[i, j];
}
else
{
Salary = employeesArray[i, j];
}
}

listEmployee.Add(new Employee(Convert.ToInt32(Id), Name, Designation,


Convert.ToDecimal(Salary)));
}

Console.WriteLine("Adapter converted Array of Employee to List of Employee");


Console.WriteLine("Then delegate to the ThirdPartyBillingSystem for processing the employee
salary\n");
thirdPartyBillingSystem.ProcessSalary(listEmployee);
}
}
}
Step5: Client
Here, the client will be our HR System (i.e., the Main method of the Program class). Please modify
the Main method as shown below. Notice that we have the employee information as a string array
here. Then, we create an instance of EmployeeAdapter and call the ProcessCompanySalary method
by passing the string array as an argument. So, with the help of the Adapter (i.e., EmployeeAdapter
object), the Client and the Third Party Billing System now work together.
using System;
namespace AdapterDesignPattern
{
//Client
//The Client is Incompatible with ThirdPartyBillingSystem
class Program
{
static void Main(string[] args)
{
//Storing the Employees Data in a String Array
string[,] employeesArray = new string[5, 4]
{
{"101","John","SE","10000"},
{"102","Smith","SE","20000"},
{"103","Dev","SSE","30000"},
{"104","Pam","SE","40000"},
{"105","Sara","SSE","50000"}
};

//The EmployeeAdapter Makes it possible to work with Two Incompatible Interfaces


Console.WriteLine("HR system passes employee string array to Adapter\n");
ITarget target = new EmployeeAdapter();
target.ProcessCompanySalary(employeesArray);

Console.Read();
}
}
}
Output:

UML Diagram of Object Adapter Design Pattern in C#:


Let us understand the UML Diagram of the Object Adapter Design Pattern by comparing the
components with our example. To understand the Class or UML diagram and the different
components of the Object Adapter Design Pattern, please look at the following diagram. As you can
see, the client uses the ITarget Interface and creates an instance of the Adapter, and using the
Adapter instance, the client communicates with the Adaptee. The Adapter is the component that
makes it possible to work with two different incompatible interfaces.

The Adapter Design Pattern is composed of four components. They are as follows:
1. Client: The Client class can only see the ITarget interface, i.e., the class that implements the
ITarget interface, i.e., the Adapter (in our example, it is the EmployeeAdapter). Using that
Adapter (EmployeeAdapter) object, the client will communicate with the Adaptee, which is
incompatible with the client.
2. ITarget: This is going to be an interface that needs to be implemented by the Adapter. The
client can only see this interface, i.e., the class which implements this interface.
3. Adapter: This class makes two incompatible interfaces or systems work together. The
Adapter class implements the ITrager interface and provides the implementation for the
interface method. This class is also composed of the Adaptee, i.e., it has a reference to the
Adaptee object as we are using the Object Adapter Design Pattern. In our example, the
EmployeeAdapter class implements the ITarget Interface and provides implementations to
the ProcessCompanySalary method of the ITarget Interface. This class also has a reference to
the ThirdPartyBillingSystem object.
4. Adaptee: This class contains the client’s required functionality but is incompatible with the
existing client code. So, it requires some adaptation or transformation before the client can
use it. It means the client will call the Adapter, and the Adapter will do the required
conversions and then make a call to the Adaptee.
This is all about the Object Adapter Design Pattern in C#. Let us proceed and see how to achieve the
same using the Class Adapter Design Pattern in C#.
Understanding Class Adapter Design Pattern in C#:
This is another approach to implementing the Adapter Design Pattern in C#. In this approach, the
Adapter calls will implement the ITarget interface and inherit from the Adaptee class. That means the
Adapter class will now be a child of the Adaptee class. So, instead of creating a reference variable of
Adaptee to call the Adaptee method, it can call that method directly as it is available via inheritance.
Before implementing the same example using the Class Adapter Design Pattern, let us first
understand the class diagram of the Class Adapter Design Pattern. Please have a look at the following
image.

The class diagram is identical to the Object Adapter Design Pattern class diagram. The only difference
is that the Adapter class now implements the Target interface and is inherited from the Adaptee
class. In the case of the Object Adapter Design Pattern, the adapter has a reference to the Adaptee
object, and using that reference, it will call the adaptee methods. But in the case of the Class Adapter
Design Pattern, the adapter will call the inherited method of the Adaptee class directly.
Implementation of Class Adapter Design Pattern in C#:
Let us implement the previous example using the Class Adapter Design Pattern in C# step by step.
The implementation is exactly the same as the Object Adapter Design Pattern Implementation. The
only difference is in the EmployeeAdapter class. Now, in the EmployeeAdapter class, instead of
Creating a reference variable of the ThirdPartyBillingSystem class, we will make this
EmployeeAdapter class inherit from the ThirdPartyBillingSystem. After the required transformation
or conversations, we need to call the ProcessSalary method.
So, please modify the EmployeeAdapter class as shown below to use the Class Adapter Design
Pattern in C#. The EmployeeAdapter class is now inherited from the Adaptee, i.e., the
ThirdPartyBillingSystem class, and implements the ITarget interface.
using System;
using System.Collections.Generic;
namespace AdapterDesignPattern
{
// This is the class that makes two incompatible interfaces or systems work together.
// The Adapter makes the Adaptee's interface compatible with the Target's interface.
// To use Class Adapter Pattern, we need to inherit the Adapter class from the Adaptee class
public class EmployeeAdapter : ThirdPartyBillingSystem, ITarget
{
//The following will accept the employees in the form of string array
//Then convert the employee string array to List of Employees
//After conversation, it will call the Adaptee's Method to Process the Salaries
public void ProcessCompanySalary(string[,] employeesArray)
{
string Id = null;
string Name = null;
string Designation = null;
string Salary = null;

List<Employee> listEmployee = new List<Employee>();

for (int i = 0; i < employeesArray.GetLength(0); i++)


{
for (int j = 0; j < employeesArray.GetLength(1); j++)
{
if (j == 0)
{
Id = employeesArray[i, j];
}
else if (j == 1)
{
Name = employeesArray[i, j];
}
else if (j == 2)
{
Designation = employeesArray[i, j];
}
else
{
Salary = employeesArray[i, j];
}
}

listEmployee.Add(new Employee(Convert.ToInt32(Id), Name, Designation,


Convert.ToDecimal(Salary)));
}

Console.WriteLine("Adapter converted Array of Employee to List of Employee");


Console.WriteLine("Then delegate to the ThirdPartyBillingSystem for processing the employee
salary\n");
//Call the Base Class ProcessSalary Method to Process the Salary
ProcessSalary(listEmployee);
}
}
}
Output:
When to use the Object Adapter Pattern and Class Adapter Pattern in C#?
It is completely based on the situation. For example, if you have a Java class and want to make it
compatible with the dot net class, then you need to use the Object Adapter Design Pattern because
it is not possible to make the inheritance. On the other hand, if both the classes are within the same
project and using the same programming language, and if inheritance is possible. then you need to
go for the Class Adapter Design Pattern.
When to use the Adapter Design Pattern in Real-Time Applications?
The Adapter Design Pattern in C# is particularly useful in the following scenarios:
 Integration with Third-party or Legacy Systems: When your application needs to interact
with an external system or a legacy system, and the interfaces of the external systems are
not compatible with your application’s interfaces.
 Reusing Existing Code: If you have existing classes with functionality that you need to use,
but their interfaces don’t match the ones your system currently uses, an adapter can bridge
this gap.
 Creating a Common Interface for Different Classes: When you have several classes with
different interfaces but want to treat them uniformly through a common interface.
 Supporting Multiple Data Sources: When your application needs to handle data from
different sources (like databases, file systems, web services) but wants to process them in a
uniform manner.
 Testing and Mocking: Adapters can be used to create stubs or mocks for unit testing,
especially when the actual objects are cumbersome to use in a test environment (like
database connections or external services).
 Providing Backward Compatibility: When updating an application or library, adapters can be
used to maintain backward compatibility with the old versions of APIs or data models.
 Cross-Platform Compatibility: In scenarios where you need to provide support for different
platforms or environments while keeping the rest of the application code consistent.

DataReader C#
Data reader is an object that is used to read data from the data sources. This can only perform read
operation and not update operation on the data source. The data is retrieved as a data stream from
the data source. Though the data reader is restricted in terms of only reading operation, it is highly
effective and optimized as it is read only and forward only. There are two types of providers in
the .Net Framework, they are SQLDataReader and OleDbDataReader. The data reader increases the
application performance by reducing system overhead as it stores the only row in memory at a given
point of time. This article will cover in detail the data reader in c# along with appropriate examples.
Syntax:
The sql data reader is available in the namespace System.Data.SqlClient and the corresponding
assembly is System.Data.SqlClient.dll. A SQL data reader is initialized as follows.

SqlDataReadersqlReader = sqlCmd.ExecuteReader();

The execute reader is used to pass the SQL statements or procedure to the sqlconnection object and
the corresponding result is stored in the sqlreader object of SqlDataReader. Before reading from any
data reader, it should always be open and should point to the first record. The read() method of data
reader is used to read and it moves forward to the next row.
The oledb data reader also behaves in the same way. It is available in the name space
System.Data.OleDb and the corresponding assembly is System.Data.OleDb.dll. An oledbDataReader
object is used to connect to OLEDB data sources and fetch data from them. Like SQLDataReader,
oledbdata reader should also be open before performing read operation. An oledb data reader is
initialized as follows.
OleDbDataReaderoledbReader = oledbCmd.ExecuteReader();
Accessing Data Reader Results
The data reader object has a read method that can be used to access rows from the result set. Each
column value can be accessed either using their name or using their column order in which they
appear on the result set. To improve efficiency, a set of pre-defined type conversion methods to
access values as such. Data reader is advised to use when working large sets of data as the data is not
stored in cache memory. It is always advisable to close the data reader object once it is used. If the
command has some return values or output parameters, it is only available once the data reader is
closed. Another important thing to keep in mind while using data reader is that when a connection is
used by a data reader another data reader or any other operation can’t be performed on that
connection. Also, one important thing to remember is only forward accessing the dataset is possible.
We can iterate to the next record only and not to the previous one.
Working with Multiple Sets
If data reader returns multiple result sets, the NextResult method of data reader can be used to
access them. During implementation, it should be noted and taken care that all the result sets are
being iterated and each column inside the result set is accessible.

Examples to Implement of DataReader C#


Below are the examples of DataReader C#:
Example #1
Typically, data is read from the result set returned by the data reader is to iterate each row using a
while loop. The read method return value is of bool type, if the next row is present then true is
returned and for the last record, false is returned. The while loop will be executed until the condition
becomes false.
Syntax:
while(rdr.Read())
{
// operation to be performed
// Access columns
// Data manipulation
}
Like closing a SQL connection, it is always a best practice to close the Data reader. All the while part
can be in enclosed in a try block and the data reader connection can be closed in the finally block.
Syntax:
try
{
// operation to be performed
// Access columns
// Data manipulation
}
Catch
{
//Handle exception here
}
finally
{
//close the data reader connection
if (reader != null)
{
reader.Close();
}
// close thesql connection
}
Code:
using System;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace test
{
public partial class test1 : Form
{
public test1()
{
InitializeComponent();
}
Public static void main()
{
string constr = null;
SqlConnectionscon ;
SqlCommandscmd ;
string sstat = null;
constr = "Data Source=testserver;Initial Catalog=testdb;User ID=test;Password=test";
sstat = "Select * from test";
scon = new SqlConnection(constr);
try
{
scon.Open();
scmd = new SqlCommand(sstat, scon);
SqlDataReadersstatReader = scmd.ExecuteReader();
while (sstatReader.Read())
{
Console.WriteLine("Name:" sstatReader.GetValue(0) + "age:" sstatReader.GetValue(1) );
}
sstatReader.Close();
scmd.Dispose();
scon.Close();
}
catch (Exception ex)
{
}
}
}
}
Output:

Example #2
Code:
using System;
using System.Windows.Forms;
using System.Data.OleDb;
namespace test
{
public partial class test : Form
{
public test()
{
InitializeComponent();
}
Public static void main()
{
string constr = null;
OleDbConnectionocon ;
OleDbCommandocmd ;
string sql = null;
constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=test.mdb";
sql = "select * from emp";
ocon = new OleDbConnection(constr);
try
{
ocon.Open();
ocmd = new OleDbCommand(sql, ocon);
OleDbDataReaderordr = ocmd.ExecuteReader();
while (ordr.Read ())
{
Console.WriteLine("EmpName:" ordr.GetValue(0) + "Empage:" ordr.GetValue(1) + "Esalary"
ordr.GetValue(2) );
}
ordr.Close();
ocmd.Dispose();
ocon.Close();
}
catch (Exception ex)
{
Console.WriteLine("Connection Failed");
}
}
}
}
Output:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy