Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 10

INT452: Modern Web Programming Tools and Techniques - I

Homework # 4
Based on:
( ADO.NET: understanding Databases, Connected and disconnected Databases, DataSets,
Datatables, Dataviews,DataBinding Controls: Repeater, DataList, DataGrid View, Security with
ASP.NET )

Note: Attempt all questions from Part A and Part B


Part-A

1. If you need to create a user interface in ASP.NET that allows a user to display,
filter, edit and delete data coming from a database, what is the best control to use?
How will you hook up that control to the database?

Sol.:- The best control to use for display, filter, edit and delete data coming from
a database is Gridveiw.
The code for gridview in asp.net :-

<%@ Page Language="VB" %>


<html>
<head>
  <title>Introducing the ASP.NET 2.0 GridView - Editing</title>
</head>
<body>

<form runat="server">

  <asp:SqlDataSource ID="mySqlDataSource" runat="server"


    ConnectionString = "Server=(local);Database=pubs;User
Id=sa;Password=password;"
    SelectCommand = "SELECT * FROM authors;"
    DeleteCommand = "DELETE FROM authors WHERE au_id=@au_id;"
    UpdateCommand = "UPDATE authors SET au_fname=@au_fname,
au_lname=@au_lname,
      address=@address, city=@city, state=@state, zip=@zip,
phone=@phone,
      contract=@contract WHERE au_id=@au_id;"
  >
    <DeleteParameters>
      <asp:Parameter Name="au_id" Type="String" />
    </DeleteParameters>
    <UpdateParameters>
      <asp:Parameter Name="au_id"    Type="String" />
      <asp:Parameter Name="au_fname" Type="String" />
      <asp:Parameter Name="au_lname" Type="String" />
      <asp:Parameter Name="address"  Type="String" />
      <asp:Parameter Name="city"     Type="String" />
      <asp:Parameter Name="state"    Type="String" />
      <asp:Parameter Name="zip"      Type="String" />
      <asp:Parameter Name="phone"    Type="String" />
      <asp:Parameter Name="contract" Type="Boolean" />
    </UpdateParameters>
  </asp:SqlDataSource>

  <asp:GridView ID="myGridView" DataSourceID="mySqlDataSource"


runat="server"
    AutoGenerateColumns = "False"
    AllowPaging  = "True"
    AllowSorting = "True"
    DataKeyNames = "au_id"
    CellPadding  = "4"
    ForeColor    = "#333333"
    GridLines    = "None"
  >
    <Columns>
      <asp:BoundField    HeaderText="ID"        
DataField="au_id"    SortExpression="au_id"    ReadOnly="True" />
      <asp:BoundField    HeaderText="First Name"
DataField="au_fname" SortExpression="au_fname" />
      <asp:BoundField    HeaderText="Last Name" 
DataField="au_lname" SortExpression="au_lname" />
      <asp:BoundField    HeaderText="Address"   
DataField="address"  SortExpression="address" />
      <asp:BoundField    HeaderText="City"      
DataField="city"     SortExpression="city" />
      <asp:BoundField    HeaderText="State"     
DataField="state"    SortExpression="state" />
      <asp:BoundField    HeaderText="Zip Code"  
DataField="zip"      SortExpression="zip" />
      <asp:BoundField    HeaderText="Phone"     
DataField="phone"    SortExpression="phone" />
      <asp:CheckBoxField HeaderText="Contract"  
DataField="contract" SortExpression="contract" />
      <asp:CommandField
        ButtonType       = "Button"
        ShowEditButton   = "True"
        ShowDeleteButton = "True"
      />
    </Columns>
    <HeaderStyle         BackColor="#333399" ForeColor="#FFFFFF"
Font-Bold="True" />
    <RowStyle            BackColor="#CCCCCC" />
    <AlternatingRowStyle BackColor="#FFFFFF" />
    <PagerStyle          BackColor="#333399" ForeColor="#FFFFFF"
HorizontalAlign="Center" />
  </asp:GridView>

</form>

</body>
</html>

2. How can you use ADO.NET features in ASP.NET Web applications?


Sol.:- ADO.NET is a set of classes that expose data access services to the .NET
programmer. ADO.NET provides a rich set of components for creating distributed, data-
sharing applications. It is an integral part of the .NET Framework, providing access to
relational, XML, and application data. ADO.NET supports a variety of development
needs, including the creation of front-end database clients and middle-tier business
objects used by applications, tools, languages, or Internet browsers.
ADO.NET objects, such as the SqlConnection, SqlCommand, and SqlDataAdapter
instances are used to retrive data from database.For example :-
public IEnumerable GetSubscribers()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = @"Data Source=.\SQLExpress;Integrated
Security=True;AttachDBFilename=D:\Application\Data\Database.mdf";

SqlCommand com = new SqlCommand();


com.Connection = con;
com.CommandText = "Select * From Subscribers";
com.CommandType = CommandType.Text;
DataSet ds = new DataSet();
SqlDataAdapter ad = new SqlDataAdapter();
ad.SelectCommand = com;

con.Open();
ad.Fill(ds);
con.Close();

return ds.Tables[0].DefaultView;
}

3. Describe the following ADO.NET objects with appropriate code snippet :


a. Connection Objects
i. OleDbConnection
An OleDbConnection object represents a unique connection to a
data source. In the case of a client/server database system, it is
equivalent to a network connection to the server. Depending on the
functionality supported by the native OLE DB provider, some
methods, or properties of an OleDbConnection object may not be
available. Ex.:-

public sealed class OleDbConnection : Component,


ICloneable, IDbConnection

ii. OdbcConnection
An OdbcConnection object represents a unique connection to a
data source created by using a connection string or ODBC data
source name (DSN). In the case of a client/server database system,
it is equivalent to a network connection to the server. Depending
on the functionality supported by the native ODBC driver, some
methods or properties of an OdbcConnection object may not be
available.
The OdbcConnection object uses native resources such as ODBC
environment and connection handles. You should always explicitly
close any open OdbcConnection objects by calling Close or
Dispose before the OdbcConnection object goes out of scope. Not
doing so leaves the freeing of these native resources to garbage
collection, which may not free them immediately. This, in turn,
may eventually cause the underlying driver to run out of resources
or reach a maximum limit, resulting in sporadic failures. For
example, you might encounter Maximum Connections-related
errors while a number of connections are waiting to be deleted by
the garbage collector. Explicitly closing the connections by calling
Close or Dispose allows a more efficient use of native resources,
enhancing scalability and improving overall application
performance. Example:-
public __gc __sealed class OdbcConnection : public Component,
ICloneable, IDbConnection
iii. OracleConnection
An OracleConnection object represents a unique connection to a
database created by using a connection string. In the case of a
client/server database system, it is equivalent to a network
connection to the server.
You should always explicitly close any open OracleConnection
objects by calling Close or Dispose before the OracleConnection
object goes out of scope. Not doing so leaves the freeing of these
native resources to garbage collection, which may not free them
immediately. For example, you might encounter Maximum
Connections-related errors while a number of connections are
waiting to be deleted by the garbage collector. Explicitly closing
the connections by calling Close or Dispose allows a more
efficient use of native resources, enhancing scalability and
improving overall application performance.
Example :- public sealed class OracleConnection :
Component, ICloneable,IDbConnection

iv. SqlConnection
A SqlConnection object represents a unique session to a SQL
Server data source. In the case of a client/server database system, it
is equivalent to a network connection to the server. SqlConnection
is used in conjunction with SqlDataAdapter and SqlCommand to
increase performance when connecting to a Microsoft SQL Server
database. For all third-party SQL server products, as well as other
OLE DB-supported data sources, use OleDbConnection.
When you create an instance of SqlConnection, all properties are
set to their initial values. For a list of these values, see the
SqlConnection constructor.
If the SqlConnection goes out of scope, it is not closed. Therefore,
you must explicitly close the connection by calling Close or
Dispose. Example:-
public sealed class SqlConnection : Component,
IDbConnection, ICloneable

b. Command Object
i. SelectCommand
The SelectCommand property represents an SQL query or the
name of a stored procedure, and is used by the Select method to
retrieve data from a SQL Server database.
Example:-SelectCommand="SELECT FirstName, LastName,
Title FROM Employees">

ii. InsertCommand
The InsertCommand represents either an SQL query or the name of
a stored procedure, and is used to insert data in database.
Example:- insertcommand="INSERT INTO Shippers (
CompanyName,Phone) VALUES (@CoName,@Phone)">

iii. UpdateCommand
Gets or sets the SQL string that the SqlDataSource control uses to
update data in the underlying database.
When an application calls the Update method, the DataAdapter
examines the RowState property, and executes the required
INSERT, UPDATE, or DELETE statements iteratively for each
row, based on the order of the indexes configured in the DataSet.
For example, Update might execute a DELETE statement,
followed by an INSERT statement, and then another DELETE
statement, due to the ordering of the rows in the DataTable.
Example:- UPDATE CustTest SET CustID = @p1 , CustName
= @p2 WHERE ( CustID = @p3 AND CustName = @p4 )

iv. DeleteCommand
It is used to delete records in the data source that correspond to
deleted rows in the DataSet.
DELETE [Target] FROM [FORCE] Table_List [[,
Table_List ...] | [JOIN [ Table_List]]]
[WHERE FilterCondition1 [AND | OR FilterCondition2]]

Example:- command = new OleDbCommand(


"DELETE * FROM Customers WHERE CustomerID = ?",
connection);

Part-B
4. Write steps to create a table in SQL Server Database through ASP.NET web
environment, enter values in the table and then display that data in a DataGrid
control on the run time after establishing a connection of database with the grid.

Sol.:-
// Establish the database server
string connectionString = "...";
SqlConnection connection =
new SqlConnection(connectionString);
Server server =
new Server(new ServerConnection(connection));

// Create table in my personal database


Database db = server.Databases["davidhayden"];

// Create new table, called TestTable


Table newTable = new Table(db, "TestTable");

// Add "ID" Column, which will be PK


Column idColumn = new Column(newTable, "ID");
idColumn.DataType = DataType.Int;
idColumn.Nullable = false;
idColumn.Identity = true;
idColumn.IdentitySeed = 1;
idColumn.IdentityIncrement = 1;

// Add "Title" Column


Column titleColumn = new Column(newTable, "Title");
titleColumn.DataType = DataType.VarChar(50);
titleColumn.Nullable = false;

// Add Columns to Table Object


newTable.Columns.Add(idColumn);
newTable.Columns.Add(titleColumn);

// Create a PK Index for the table


Index index = new Index(newTable, "PK_TestTable");
index.IndexKeyType = IndexKeyType.DriPrimaryKey;

// The PK index will consist of 1 column, "ID"


index.IndexedColumns.Add(new IndexedColumn(index,"ID"));

// Add the new index to the table.


newTable.Indexes.Add(index);

// Physically create the table in the database


newTable.Create();

5. Describe various data-bound controls such as:


a. DataList

The DetailsView control is used to display a single record from a data source in a
table, where each field of the record is displayed in a row of the table. It can be used
in combination with a GridView control for master-detail scenarios. The DetailsView
control supports the following features:

Binding to data source controls, such as SqlDataSource.

Built-in inserting capabilities.

Built-in updating and deleting capabilities.

Built-in paging capabilities.

Programmatic access to the DetailsView object model to dynamically set properties,


handle events, and so on.

Customizable appearance through themes and styles.

b. FormView
The FormView control gives you the ability to work with a single record
from a data source, similar to the DetailsView control. The difference
between the FormView and the DetailsView controls is that the
DetailsView control uses a tabular layout where each field of the record is
displayed as a row of its own. In contrast, the FormView control does not
specify a pre-defined layout for displaying the record. Instead, you create
a template containing controls to display individual fields from the record.
The template contains the formatting, controls, and binding expressions
used to create the form.
The FormView control is typically used for updating and inserting new
records, and is often used in master/detail scenarios where the selected
record of the master control determines the record to display in the
FormView control. For more information and an example, see Modifying
Data Using a FormView Web Server Control.

c. ListView
A ListView control allows you to display a list of items with item text
and, optionally, an icon to identify the type of item. For example, the
Windows Explorer list of files is similar in appearance to a ListView
control. It displays a list of the files and folders currently selected in the
tree. Each file and folder displays an icon associated with it to help
identify the type of file or folder. The ListViewItem class represents an
item within a ListView control.

6. Create a web form to enter a student data into a database created in SQL Server.
Then generate a report based on the data fetched from that database.
Sol.:- using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using ContosoUniversity.Models;

namespace ContosoUniversity.DAL
{
    public class SchoolInitializer :
DropCreateDatabaseIfModelChanges<SchoolContext>
    {
        protected override void Seed(SchoolContext context)
        {
            var students = new List<Student>
            {
                new Student { FirstMidName = "Carson",   LastName =
"Alexander", EnrollmentDate = DateTime.Parse("2005-09-01") },
                new Student { FirstMidName = "Meredith", LastName =
"Alonso",    EnrollmentDate = DateTime.Parse("2002-09-01") },
                new Student { FirstMidName = "Arturo",   LastName =
"Anand",     EnrollmentDate = DateTime.Parse("2003-09-01") },
                new Student { FirstMidName = "Gytis",    LastName =
"Barzdukas", EnrollmentDate = DateTime.Parse("2002-09-01") },
                new Student { FirstMidName = "Yan",      LastName =
"Li",        EnrollmentDate = DateTime.Parse("2002-09-01") },
                new Student { FirstMidName = "Peggy",    LastName =
"Justice",   EnrollmentDate = DateTime.Parse("2001-09-01") },
                new Student { FirstMidName = "Laura",    LastName =
"Norman",    EnrollmentDate = DateTime.Parse("2003-09-01") },
                new Student { FirstMidName = "Nino",     LastName =
"Olivetto",  EnrollmentDate = DateTime.Parse("2005-09-01") }
            };
            students.ForEach(s => context.Students.Add(s));
            context.SaveChanges();

            var enrollments = new List<Enrollment>


            {
                new Enrollment { StudentID = 1, CourseID = 1050, Grade =
1 },
                new Enrollment { StudentID = 1, CourseID = 4022, Grade =
3 },
                new Enrollment { StudentID = 1, CourseID = 4041, Grade =
1 },
                new Enrollment { StudentID = 2, CourseID = 1045, Grade =
2 },
                new Enrollment { StudentID = 2, CourseID = 3141, Grade =
4 },
                new Enrollment { StudentID = 2, CourseID = 2021, Grade =
4 },
                new Enrollment { StudentID = 3, CourseID = 1050        
},
                new Enrollment { StudentID = 4, CourseID = 1050,        
},
                new Enrollment { StudentID = 4, CourseID = 4022, Grade =
4 },
                new Enrollment { StudentID = 5, CourseID = 4041, Grade =
3 },
                new Enrollment { StudentID = 6, CourseID = 1045        
},
                new Enrollment { StudentID = 7, CourseID = 3141, Grade =
2 },
            };
            enrollments.ForEach(s => context.Enrollments.Add(s));
            context.SaveChanges();

            context.SaveChanges();
        }
    }
}

You might also like