200 likes | 335 Views
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
E N D
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 • Ved læsetilgang (select) returneres et DataReader-objekt • Luk Connection • Disconnected • Fyld et DataSet-objekt (kopi af dele af db) vha. en DataAdapter • DataAdapter indpakker SQL-statement(s) • DataSet-objekt indeholder DataTable-objekter • DataTable-objekter indeholder collections af rækker og kolonner
Connection vs. Connectionless • Connection: • Open Connection • Udfør db-operationer • Luk Connection • Der arbejdes på aktuelle data • Andre applikationer lukkes evt. ude
Connection vs. Connectionless • Connectionless: • Tag en kopi af et databaseudsnit • Udfør db-operationerpåkopien • Andre applikationerkanændre data • Derarbejdesevt. på en uaktuel kopi af data • Data ændres i den lokale kopi: • ved update checkes om andre har ændret dataene i kopien • i så fald afvises opdateringen (ConcurrencyException)
Hvis DB skal opdateres • Tilføj et commandobjekt til dataadapteren • InsertCommand • UpdateCommand • DeleteCommand • Gøres vha. parametriserede queries, fx: 1. parameter: sql da.InsertCommand = new OleDbCommand("INSERT INTO ” + Ansat (løn, navn, stilling) VALUES (?, ?, ?)",dbconn); da.Update(ds, ”Ansat”); Her opdateres DB. Kan fejle (ConcurrencyException) 2. parameter: connection
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 work • A transaction must be done completely or not done at all • A 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)
time Transactions – example:T1 and T2 are executing concurrently Any possible problems? 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);
Transactions – Problems • We want several transactions to execute concurrently (Why?) • Three types of problems: • lost update • uncommitted dependency (temporary update) • inconsistent analysis (incorrect summary) • Crash during execution of a transaction must be handled
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 Uncommitted • Read Committed (Default on MS SQL Server) • Repeatable Read • Serializable
Isolation Levels • READ UNCOMMITTED • In this isolation level, dirty reads are allowed. One transaction may see uncommitted changes made by some other transaction. • READ COMMITTED • Data 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.
Isolation Levels • REPEATABLE READ • All data records read by a SELECTstatement cannot be changed; however, if the SELECTstatement 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. • SERIALIZABLE • This 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.
Entity Framework • Data menu >> Add New Data Source… • select Database, Entity Data Model, … • VS generates persistent model ― entities, collections, etc. SchedulingEntities_db = new SchedulingEntities(); var query = from doctor in _db.Doctors orderbydoctor.LastName, doctor.FirstName select doctor; foreach (Doctor d in query) { string name = string.Format("{0}, {1}", d.LastName, d.FirstName); lstDoctors.Items.Add(name); } From Joe Hummel
Specifikationer: CodeContracts • 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.
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); } Eksempel: Dictionary(Map – værdibaseret container, lagrer par af (key, value)) Her specifikation som kommentarer Understøttes i .NET af CodeContracts
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.
Task using System.Threading.Tasks; Task T = new Task(code); T.Start(); if… while… tells .NET that task *can* start, then returns immediately computation to perform… original code task "code" Program “forks” and now 2 code streams are executing concurrently ― original, and T. From Joe Hummel
Language support • TPL takes advantage of .NET language features • Lambda expressions • Closures close over data (by ref!) int[] A, B, C; . . . for(i=0; i<N; i++) { C[i] = A[i] + B[i]; } Parallel.For(0, N, (i) => { C[i] = A[i] + B[i]; } ); lambda expression From Joe Hummel