20
ADO.NET (and more LINQ) Entity Framework (and more LINQ) Verification (CodeContracts) TPL (Task Parallel Library) Other .NET/C# topics

Other .NET/C# topics

  • Upload
    jesus

  • View
    41

  • Download
    7

Embed Size (px)

DESCRIPTION

Other .NET/C# topics. ADO.NET (and more LINQ) Entity Framework (and more LINQ) Verification ( CodeContracts ) TPL (Task Parallel Library). ADO.NET. To måder at tilgå DB på: Connected Åbn connection Læse-/Skrivetilgang ( select , insert , update og delete ) via Command-objekt - PowerPoint PPT Presentation

Citation preview

Page 1: Other .NET/C# topics

ADO.NET (and more LINQ)Entity Framework (and more LINQ)Verification (CodeContracts)TPL (Task Parallel Library)

Other .NET/C# topics

Page 2: Other .NET/C# topics

ADO.NET

To måder at tilgå DB på:Connected

Åbn connectionLæse-/Skrivetilgang (select, insert, update og delete) via Command-objektVed læsetilgang (select) returneres et DataReader-objektLuk Connection

DisconnectedFyld et DataSet-objekt (kopi af dele af db) vha. en DataAdapterDataAdapter indpakker SQL-statement(s)DataSet-objekt indeholder DataTable-objekterDataTable-objekter indeholder collections af rækker og kolonner

Page 3: Other .NET/C# topics

Connection vs. Connectionless

Connection:Open ConnectionUdfør db-operationerLuk ConnectionDer arbejdes på aktuelle dataAndre applikationer lukkes evt. ude

Domæneklasser

SQL

Dataklasser

DB

Page 4: Other .NET/C# topics

Domæneklasser

SQL

Dataklasser

DB

• Connectionless:– Tag en kopi af et

databaseudsnit– Udfør db-operationer

på kopien– Andre applikationer

kan ændre data– Der arbejdes evt. på

en uaktuel kopi af data

Connection vs. Connectionless

• Data ændres i den lokale kopi:– ved update checkes om andre har

ændret dataene i kopien– i så fald afvises opdateringen

(ConcurrencyException)

Page 5: Other .NET/C# topics

Hvis DB skal opdateresTilføj et commandobjekt til dataadapteren

InsertCommandUpdateCommandDeleteCommand

Gøres vha. parametriserede queries, fx:

da.InsertCommand = new OleDbCommand("INSERT INTO ” +

Ansat (løn, navn, stilling) VALUES (?, ?, ?)",dbconn);

da.Update(ds, ”Ansat”);

1. parameter:

sql

2. parameter: connection

Her opdateres DB. Kan fejle (ConcurrencyException)

Page 6: Other .NET/C# topics

Transaction - Definition

A transaction is an operation on data in the database.A transaction may be composed of several database operations, but is viewed as a logical unit of workA transaction must be done completely or not done at allA transaction must have the ACID properties:

A: Either it is done in total or it is not done at all (Atomicity)C: The database moves from one consistent state to an other consistent state (Consistency)I: If more operations are accessing the same data, they are not to disturb each other – they must execute as if they executed alone (Isolation)D: When a transaction completes, its changes to the database are permanent (Durability)

Page 7: Other .NET/C# topics

Transactions – example:T1 and T2 are executing concurrently

T1: Transfers N DKKs from account X to account Y:

read_item(X);X:= X-N;write_item(X);read_item(Y);Y:= Y+N;write_item(Y);

T2: Deposits M DKK on account Y:

read_item(Y);Y:= Y+M;write_item(Y);

Any possible problems?

time

Page 8: Other .NET/C# topics

Transactions – Problems

We want several transactions to execute concurrently (Why?)Three types of problems:

lost updateuncommitted dependency (temporary update)inconsistent analysis (incorrect summary)

Crash during execution of a transaction must be handled

Page 9: Other .NET/C# topics

Lost Update

Page 10: Other .NET/C# topics

Uncommitted Dependency

Page 11: Other .NET/C# topics

Inconsistent Analysis

Page 12: Other .NET/C# topics

SQL Support for Transactions

By default any SQL statement is considered to be atomic, that is: a transaction.Transactions involving more than one SQL statement must be opened by BeginTransaction() and terminated by either Commit() or Rollback().It is possible to specify the isolation level of a transaction:

Read UncommittedRead Committed (Default on MS SQL Server)Repeatable Read Serializable

Page 13: Other .NET/C# topics

Isolation Levels

READ UNCOMMITTEDIn this isolation level, dirty reads are allowed. One transaction may see uncommitted changes made by some other transaction.

READ COMMITTEDData records retrieved by a query are not prevented from modification by some other transaction. Non-repeatable reads may occur, meaning data retrieved in a SELECT statement may be modified by some other transaction when it commits. In this isolation level, read locks are acquired on selected data but they are released immediately whereas write locks are released at the end of the transaction.

Page 14: Other .NET/C# topics

Isolation Levels

REPEATABLE READAll data records read by a SELECT statement cannot be changed; however, if the SELECT statement contains any ranged WHERE clauses, phantom reads can occur. In this isolation level, the transaction acquires read locks on all retrieved data, but does not acquire range locks.

SERIALIZABLEThis isolation level specifies that all transactions occur in a completely isolated fashion; i.e., as if all transactions in the system had executed serially, one after the other. The DBMS may execute two or more transactions at the same time only if the illusion of serial execution can be maintained. At this isolation level, phantom reads cannot occur.

Page 15: Other .NET/C# topics

Entity FrameworkData menu >> Add New Data Source…

select Database, Entity Data Model, …

VS generates persistent model ― entities, collections, etc.

var query = from doctor in _db.Doctors orderby doctor.LastName, doctor.FirstName select doctor;

foreach (Doctor d in query){ string name = string.Format("{0}, {1}", d.LastName, d.FirstName); lstDoctors.Items.Add(name);}

SchedulingEntities _db = new SchedulingEntities();

From Joe Hummel

Page 16: Other .NET/C# topics

Specifikationer: Code Contracts

Metoder specificeres vha. pre- og postbetingelser:Prebetingelse:Et udsagn om programmets tilstand (værdier af variable) som skal være sandt inden metoden må kaldes.Postbetingelse:Et udsagn om programmets tilstand (værdier af variable) som skal være sandt når metoden returnerer.

Invarianter specificerer krav, som går på tværs af metoder.

Page 17: Other .NET/C# topics

Eksempel: Dictionary (Map – værdibaseret container, lagrer par af (key, value))

public interface Dictionary {/*@ invariant count()>=0; @*/ // Basic queries public /*@ pure @*/ int count();

/*@ ensures (count()==0) ==> (!\result); @*/ public /*@ pure @*/ boolean has(Object key);

/*@ requires has(key); @*/ public /*@ pure @*/ Object valueFor(Object key);

// Derived queries /*@ ensures \result == (count()==0); @*/ public boolean isEmpty();

// Commands /*@ requires !has(key); @ ensures has(key); @ ensures valueFor(key)==value; @ ensures count()==(\old(count())+1); @*/ public void put(Object key, Object value);

/*@ requires has(key); @ ensures !has(key); @ ensures count()==(\old(count())-1); @*/ public void remove(Object key);}

Her specifikation som kommentarer

Understøttes i .NET af CodeContracts

Page 18: Other .NET/C# topics

TPL: Task Parallel Library

Vi får næppe bedre performance pga. øget clock- frekvens (More’s lov holder ikke længere).Derimod får vi flere processorer – fire er allerede ved at være standard på almindelige lap-tops.Derfor bliver parallelprogrammering mere og mere interessant.

TPL er .NET 4’s bud en API til parallelprogrammering.

Page 19: Other .NET/C# topics

Taskusing System.Threading.Tasks; Task T = new Task( code );T.Start();if…

while…

tells .NET that task *can* start, then returns immediately

original code

task"code"

Program “forks” and now 2 code streams are executing concurrently

― original, and T.

computation to perform…

From Joe Hummel

Page 20: Other .NET/C# topics

Language support

TPL takes advantage of .NET language featuresLambda expressionsClosures

Parallel.For(0, N,

(i) => { C[i] = A[i] + B[i]; }

);

int[] A, B, C; . . .

for(i=0; i<N; i++){ C[i] = A[i] + B[i];}

lambda expression

close over data (by ref!)

From Joe Hummel