Transcript Lecture 4

DT265-2
Object Oriented Software
Development 2
Lecture 4 : C# language features &
Databases
Lecturer Pat Browne
[email protected]
C# Language Features
1. Generics
2. Delegates
3. Covariance & Contravariance
4. Attributes
5. Database connectivity
C# Generics
• Generics are the most powerful feature of C# 2.0.
Generics allow you to define type-safe data structures,
without committing to actual data types. This results in
a significant performance boost and higher quality
code, because you get to reuse data processing
algorithms without duplicating type-specific code. The
benefits of the programming model, and unique
innovations, such as constrains, generic methods and
delegates, and generic inheritance. Generics are
utilized in other areas of the .NET Framework such as
reflection, arrays, collections, serialization, and
remoting, and how to improve on the basic offering.
List<T>
using System.Collections.Generic;
class Program {
static void Main() {
List<int> list = new List<int>();
list.Add(2);
list.Add(3);
list.Add(5);
list.Add(7); } }
Generic Method OutputThing < T >
// Define generic method
static void OutputThing < T > (T thing)
{
Console.WriteLine(“Thing: {0}”, thing);
}
// Run method for string and Int.
OutputThing < string > (“A string”);
OutputThing < int > (42);
Generic Class
public class Stack<T> {
int position;
T[] data = new T[100];
public void Push (T obj) {
data[position++] = obj; }
public T Pop() {
return data[--position]; }}
-- Stack<T> can be used as follows:
Stack<int> stack = new Stack<int>();
stack.Push(5);
stack.Push(10);
int x = stack.Pop(); // x is 10
int y = stack.Pop(); // y is 5
IEnumerable<T> IEnumerator<T>
First we will look at the non-generic
IEnumerable and IEnumerator.
http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspx
http://www.dotnetperls.com/ienumerable
IEnumerable
•
•
•
•
•
•
•
•
•
•
•
•
•
•
•
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{ static void Main()
IEnumerable<int> result = from value in Enumerable.Range(0, 2) select value;
// Loop.
foreach (int value in result){
Console.WriteLine(value); }
// We can use extension methods on IEnumerable<int>
double average = result.Average();
// Extension methods can convert IEnumerable<int>
List<int> list = result.ToList();
int[] array = result.ToArray();
}}
IEnumerable<T>
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
Display(new List<bool> { true, false, true });
}
static void Display(IEnumerable<bool> argument)
{
foreach (bool value in argument)
Console.WriteLine(value);
}
}
Delegates
• A delegate is a type that references a method.
Once a delegate is assigned a method, it
behaves exactly like that method. The
delegate method can be used like any other
method, with parameters and a return value.
– Tasks:
– Type in examples from hand-out.
– Change the Square function to Double that
doubles its argument.
Covariance & Contravariance
• Covariance Example: Manager and Employee types.
Because there’s an inheritance relationship between
these classes, there’s an implicit reference conversion
from Manager to Employee:
• Manager → Employee
• And now, because of the annotation of T in
IEnumerable<out T>, there’s also an implicit reference
conversion from IEnumerable<Manager> to
IEnumerable<Employee>.
• IEnumerable<Manager> → IEnumerable<Employee>
Covariance & Contravariance
• Covariance Example: The arrow are reversed:
• Manager → Employee
•
IComparable<Manager> ← IComparable<Employee>
C# Attributes
• Attributes add metadata to certain parts of the
source code (classes, properties, fields,
methods, parameters, etc.) . The compiler takes
the information in the attribute and places it in
the C# Intermediate Language (IL).
• Attributes by themselves don't do anything
unless they are consumed. They remain in the IL
until they are found and acted upon, which is
usually done is using reflection.
• Do C# Attribute Tutorial
•
http://msdn.microsoft.com/en-us/library/aa288454%28v=vs.71%29.aspx
C# Attributes
• Attributes represent declarative information.
Programmers can attach attributes to various
program entities, and retrieve attribute
information in a run-time environment. For
instance, a framework might define a
HelpAttribute attribute that can be
placed on certain program elements (such as
classes and methods) to provide a mapping
from those program elements to their
documentation.
Compiling at command line
• Find where csc.exe is on your machine
• You can add this location you the PATH system
variable.
• csc.exe file.cs
Database Connectivity
• A database connection is a facility that allows client
software to communicate with database server
software, whether on the same machine or not. A
connection is required to send commands and receive
answers.
• A database driver is a piece of software for accessing a
database. There are various DB and language specific
database drivers.
• A JDBC driver is a software component enabling a Java
application to interact with a database. JDBC drivers
are analogous to ODBC drivers, ADO.NET data
providers, and OLE DB providers.
Different ways to connect to a db
• For C# there are alternative ways to connect
to a database:
– ODBC
– OLE
– ADO.NET
Connecting C# program SQL Server
2008R2 Database
• Download and load Northwind database as
instructed at:
• http://www.codeproject.com/Articles/42837/Ho
wTo-Install-the-Northwind-and-Pubs-SampleDataba
• Do a sample queries:
SELECT LastName
FROM Employees
ORDER BY LastName;
Connecting C# program SQL Server
2008R2 Database
• Run queries in C# based on:
• http://www.codeproject.com/Articles/4416/B
eginners-guide-to-accessing-SQL-Serverthrough-C
• Run code in notes section (below) using your
own user name and server name:
• “Id=YOUR-USER-NAME;" +
• "Server=YOUR-SERVER-NAME;" +
Adding Data Source in Visual Studio
• Visual Studio provides tools to connect
applications to data from many different sources,
such as databases, Web services, and objects. In
Visual Studio connection objects can be created
as a result of completing one of the data wizards
or of dragging data objects onto your form. To
connect an application to data in a database,
Web service, or object, use the Data Source
Configuration Wizard. From the main menu
choose, Add New Data Source from the Data
Sources Window.
Connect SQL server 2008 databases to
you Visual Studio 2010 application.
• To connect an Application from Visual Studio 2010 to
SQL Server by using wizard:
• a) Click on Tools menu from menu
• b) click on "Connect to Database" it will open "Choose
Data Source" dialog
• c) select your SQL server 2008 as "Microsoft SQL
Server" out of all installed Data Source on your System
• e) press Continue button, after that it will give you
option to put your Server name, user ID and password.
You should not need a password on your own machine.
Adding a Data Source to Visual Studio
Using the Data Source in C#
• The program in the notes section uses the
Employee Table from the Northwind database.
• SQL Server should be running.
• SqlDataAdapter interacts with the
DataTable type. It fills the DataTable with
the query results from the Employees table and
displays data using DataGridView.
• See
• http://www.dotnetperls.com/sqldataadapter
Connecting C# program to PostgreSQL
• A particular database driver that can be used
with C# and PostgreSQL is called Npgsql.
• Npgsql is a .Net Data Provider for PostgreSQL. It
allows any program developed for .Net
framework to access a PostgreSQL database
server. It is implemented in C#.
• Npgsql allows a .Net client application (Console,
WinForms, ASP.NET, Web Services...) to send and
receive data to & from a PostgreSQL server.
A Npgsql Database Connection
•
•
•
•
•
•
Download from:
http://pgfoundry.org/frs/?group_id=1000140
Unzip to say:
C:\Npgsql2.0.12.0-bin-ms.net4.0
You might need a different .NET version
In Project add Reference. Click the ‘Browse’ tab
and select the Npqsql dll only.
• Then you should include using Npgsql; in
applications that access PostgreSQL.
A Npgsql Database Connection
• Run this program:
• The area of each county is held in a column called
km2. Add this column to the SQL query in the
above form.
A Npgsql Database Connection
• IP address for http://cork.ict.ad.dit.ie
• 147.252.234.32
• PostgreSQL Port: 5432
Database Projects
•
•
•
•
•
Database1: SQL Client
Database2: Data source
Database3: PostgreSQL
More detailed example at:
http://www.codeproject.com/Articles/8477/U
sing-ADO-NET-for-beginners
Draw line with mouse
• Run this program