Software Engineering I Lecture 9 Reminder of what is left for this - - PowerPoint PPT Presentation

software engineering i
SMART_READER_LITE
LIVE PREVIEW

Software Engineering I Lecture 9 Reminder of what is left for this - - PowerPoint PPT Presentation

Software Engineering I Lecture 9 Reminder of what is left for this semester Today: Databases 11-23: Asynchronous programming 11-30: Web services 12-07: Middleware, filters, testing 12-14: UI 12-21: Design patterns with .net


slide-1
SLIDE 1

Software Engineering I

Lecture 9

slide-2
SLIDE 2

Reminder of what is left for this semester

  • Today: Databases
  • 11-23: Asynchronous programming
  • 11-30: Web services
  • 12-07: Middleware, filters, testing
  • 12-14: UI
  • 12-21: Design patterns with .net
  • 01-04: Summary and overview of exam
slide-3
SLIDE 3

.NET 5.0 is released!

  • C# 9 language version as well
  • Entity framework core 5.0 released
  • More info: https://docs.microsoft.com/en-

us/dotnet/core/dotnet-five

slide-4
SLIDE 4

Socrative – how are we doing?

  • Go to Socrative.com
  • Student login
  • Enter: DOTNET2020
  • 5mins;
slide-5
SLIDE 5

Overview

  • Intro to MSSQL

– Overview – Working with database

  • Main classes for working with Database:

– Connection – Command – DataSet, DataTable, and DataAdapter

  • Intro to ORM
slide-6
SLIDE 6

Why?

  • 90% of applications have a need to store data
  • Storing to file is inefficient and difficult to use
  • Practical assignments: each application should store users info

(login), any specific data (books that are in library, people/cars that are missing, people that are in your social network)

  • .NET applications have multiple ways to work with database –

today we’re going to explore it

slide-7
SLIDE 7

Intro to MSSQL

  • Microsoft SQL Server
  • Base: Transact-SQL (TSQL)
  • T-SQL expands standard SQL by adding:

– Procedural programming – Local variables – Functions for working with strings – Math functions – Changes to UPDATE and DELETE statements

  • This makes Transact-SQL Turing complete
slide-8
SLIDE 8

Turing complete

  • A Turing Complete system means a system in which a program

can be written that will find an answer (although with no guarantees regarding runtime or memory).

– So, if somebody says "my new thing is Turing Complete" that means in principle (although often not in practice) it could be used to solve any computation problem.

  • A Turing Complete system means a system in which a program

can be written that will find an answer.

slide-9
SLIDE 9

T-SQL few notes

  • from with join:
  • Try/catch (starting 2005, before - @@ERROR):
slide-10
SLIDE 10

Database creation

  • View → Server Explorer
  • Data Connections → Add Data Connection
  • Data source:

– Microsoft Access Database file – Microsoft ODBC Data source – Microsoft SQL server – Microsoft SQL Server Compact – Microsoft SQL Server Database file (good for tests) – Oracle Database – Other (live demo).

slide-11
SLIDE 11

ADO.NET

  • ADO.NET is a collection of classes in .NET framework, which

allows to work with databases while using:

– DML commands: insert/update/select/delete. – DDL commands: create tables, functions, etc.

  • ADO.NET is considered to be continuation of ActiveX Data

Objects

slide-12
SLIDE 12

Connection

  • Object of Connection class is used to establish a bridge between

program and database.

  • SqlConnection - to connect to SQL Server

(namespace: System.Data.SqlClient).

– Derives System.Data.Common. DBConnection.

slide-13
SLIDE 13

Connection

  • System.Data.Common.DBConnection

has many methods (MSDN), but main ones:

Method Description Close Closes connection type obejct (disconnect) Open Opens Connection type object (connect)

slide-14
SLIDE 14

Connection

Property Description ConnectionString Gets or sets the string used to open a connection to a database. Example: Server=myServerAddress; Database=myDataBase; User Id=myUsername; Password=myPassword More: http://www.ConnectionStrings.com ConnectionTimeout Gets the time in seconds that the system should wait while establishing a connection to the database before generating an error. Database Gets the name of the database DataSource Gets the name of the database server ServerVersion Gets the server version for the database State Gets a string that represents the state of the connection such as Open

  • r Closed
slide-15
SLIDE 15

Command

  • Is used to execute statements against a database.
  • Both – DML and DDL.
  • Main class: System.Data.Common.DBCommand
  • SQL Server: System.Data.SqlClient.SqlCommand
  • Methods:

– ExecuteNonQuery – ExecuteReader – ExecuteScalar – ExecuteXmlReader

slide-16
SLIDE 16

Command: ExecuteNonQuery

  • ExecuteNonQuery used for commands which does not return

results.

  • For example: insert, update, delete:
slide-17
SLIDE 17

Command: ExecuteNonQuery

  • To call a database procedure:
  • Call:
slide-18
SLIDE 18

Command: ExecuteNonQuery

slide-19
SLIDE 19

Command: ExecuteReader

  • ExecuteReader method is designed to select multi-column records from

database (SELECT)

  • ExecuteReader returns DBDataReader type object.
  • DBDataReader

is a forward-only result collection, which remains connected to database while reader is open.

slide-20
SLIDE 20

Command: ExecuteReader

slide-21
SLIDE 21

Command: ExecuteScalar

  • ExecuteScalar() is used when it is known, that result is

a single value (a row).

  • Used for aggregate functions like SUM/AVG .
slide-22
SLIDE 22

Common rules

  • Don't write „select * ...“!!!
  • Close() is a must for both - DBDataReader and

Connection.

  • Without

Close()

  • pen

connections might remain, which might be very painful.

  • Try use using:
slide-23
SLIDE 23

DEMO – look at SqlDemo.rar

slide-24
SLIDE 24

DataSet/DataTable

  • DBDataReader: minuses?
  • One solution: DataSet and DataTable
  • DataTable differs from DBDataReader:

– Not constantly connected to DB. Meaning that it is possible to connect, load data, disconnect, modify, connect, update. – Data can be manipulated in more directions.

  • DataSet is a container, containing DataTable objects.
slide-25
SLIDE 25

DataAdapter

  • DataAdapter is used to:

– Load data to DataSet (meanig to DataTable(s)) – Perform CRUD operations

  • SQL sentance can be passed in constructor.
  • Even after closing cn, ds.Tables[0] is accessable.
slide-26
SLIDE 26

DataTable

  • DataSet has property Tables.
  • Tables has a collection of DataTable type objects, which were returned by

query.

  • DataTable

has Rows propery, which has collection

  • f

DataRow type objects. – Rows can be iterated or looked at through index. – Rows has property Count.

  • DataAdapter class allows insert/update/delete as well.
slide-27
SLIDE 27

DataAdapter: Select

slide-28
SLIDE 28

DataAdapter: Insert

slide-29
SLIDE 29

DataAdapter: Update

slide-30
SLIDE 30

DataAdapter: Delete

slide-31
SLIDE 31

DataAdapter

  • NewRow() method (in DataTable class object) is used to create new lines.

– New values are added via column names – And then DataTable.Rows.Add() method is used.

  • DataAdapter object Update() method call forces ADO.NET to:

– Look at what operations were performed – Call needed commands (in this case - InsertCommand)

slide-32
SLIDE 32

DataAdapter

  • UpdateCommand and DeleteCommand have different Command type
  • bjects, which have different logic behind them.
  • DbDataAdapter.Update()

will execute corresponding commands, depending on what happened with DataTable object.

  • DbDataAdapter tries to execute the commands without checking if they

make sense.

slide-33
SLIDE 33

DataGridView

  • Class for displaying table(s) data in UI.
  • Allows to run CRUD operations.
  • Realization:

– Via code: DataGridView.cs – Visual Studio: MSDN: How to: Display Related Data in a Windows Forms Application

  • Capabilities: it is possible to display master / detail tables (e.g. clients and
  • rders).
slide-34
SLIDE 34

When should you use ADO.NET?

NEVER

slide-35
SLIDE 35

Well, actually..

  • If you want to execute simple SQL queries, and there is no need

to manipulate data;

  • If you want your application to have the best performance (this

can be gained with ORM too, but it is difficult);

  • Legacy code support;
  • And that is why it is in requirements for third assignement
slide-36
SLIDE 36

ORM

  • ADO.NET classes allowing manipulating data:

– SqlCommand, SqlDataReader, SqlDataAdapter and DataSet.

  • MS recommendation:

– Low (however, not too low) level work with data should be handled via ORM (Object-Relational Mapper).

  • ORM – programming technique for converting data between incompatible

type systems using object-oriented programming languages.

– ORM hides work with ADO.NET data providers. – Creates "virtual object database" that can be used from within the programming language.

slide-37
SLIDE 37

ORM

  • ORM: to use or not to use?
  • Example: school database, having:

– Instructor and Course tables – Many-to-Many saved in CourseInstructor table.

  • Task: display all instructors and courses that they have.
slide-38
SLIDE 38
slide-39
SLIDE 39

ORM way

  • SchoolContext:

– DBContext type object – Namespace: System.Data.Entity – Works with DB.

slide-40
SLIDE 40

Some ORMs

  • ADO.NET Entity Framework is main one in NET.
  • LINQ to SQL is a bit legacy ORM.
  • NHibernate another popular one.
  • Some others:

– micro ORM such as Dapper or Massive, – Enterprise Library Data Access Application Block.

slide-41
SLIDE 41

ORM advantages

  • Less code to be written (code is testable).
  • Code is not DB-specific.

– Entity Framework allows to migrate between databases without changing application code (-ish).

  • Software is easier to expand and maintain

– However, maybe a bit slower.

  • Real world is so complicated, since:

– Migrations – Entities – Relations...

slide-42
SLIDE 42

Tip of the day

  • LINQPAD - The .NET Programmer’s Playground
  • Download link - https://www.linqpad.net/Download.aspx
  • Basic functionality is free
  • A lot of material on how to use – check next slide
slide-43
SLIDE 43
slide-44
SLIDE 44
slide-45
SLIDE 45

Database first

  • Project → Add new item → „ADO.NET Entity Data Model“
  • Choose existing DB.
  • Class in the code is find via:

– If file with name [fileName].dbml – Then DBContext will be [fileNameDataContext]

slide-46
SLIDE 46

Database first

  • Minuses:

– Code is generated from DB, which sometimes is not OK. – If we create DB by ourselves as well, we do double job. – POCO (plain old CLD objects) classes can be changed only in partial classes or T4 files.

  • Plusses:

– Very OK, if DB is created by DBA or similar. – EDM (entity data model) wizard takes care about hierarchies and relationships – less error prone. – DB is open for changes – model can be updated afterwards.

slide-47
SLIDE 47

T4 files

  • File [name].edmx has [name].tt file.

– Text Transformation Template Toolkit – Called "T4 template".

  • Auto-generated: a mix of text and control blocks, which allows to generate

entity-related code.

  • Has a collection of entities, as separate files.
slide-48
SLIDE 48

Context: HashSet class

  • Same as List, only...

– Unique values – Insert returns false, if it failed. – Inner structure allows faster search (unique) – Set operations possible:

  • Union/Intersection/IsSubsetOf ....

– Insert order not saved – To select value one iterates or uses Contains()

slide-49
SLIDE 49

Model first

  • Project → Add new item → „ADO.NET Entity Data Model“
  • Choose „Empty Model“.
  • API window used to create

– On your own:

  • Entity Framework → Get Started → Model First
  • After all that: „Generate Database from Model“.
slide-50
SLIDE 50

Model first

  • Visual creation (might be useful for DBA and similar)
  • Similar to DB-first
  • Plusses:

– Everything is aimed at point'n'click.

  • Minuses:

– Hard to control both – entity and DB code (updates are extra complicated).

  • That's why it's used rarely, mostly for small projects (with accurate design).

– DB changes are not welcomed, because DB is updated according to model. – POCO classes changed through partial classes or T4 files only.

slide-51
SLIDE 51

Code first

  • Everything happens through the classes:
  • "virtual" keyword is used to mark navigational properties and to enable

Lazy Loading.

  • Allows working in OOP, without looking at DB.
  • Focus to app and it's development, rather than DB.
slide-52
SLIDE 52

Code first

  • Plusses

– Most flexible – No magic which is hard to control (model and DB first) – OK to use with having DB as well – Powerfull migration mechanism

  • Minus:

– No manual changes in DB.

  • More: in the literature
slide-53
SLIDE 53

DEMO - Look at EntityFramework.rar

slide-54
SLIDE 54

Instructions for using code first with entity framework core

  • Install these nugget packages:

– Microsoft.EntityFrameworkCore – Microsoft.EntityFrameworkCore.Relational – Microsoft.EntityFrameworkCore.SqlServer – Microsoft.EntityFrameworkCore.Tools

  • Define your database context

– Must inherit from DbContext – Must have constructor without parameters, if you are using OnConfigruing method to configure database (no DI)

slide-55
SLIDE 55

Instructions for using code first with entity framework core

  • Define your DBSets that will represent the tables
  • Override OnModelCreating method, to use fluent api, so that you could define how to

create your tables

  • For console app, override OnConfiguring and provide connection string
  • Set the project that your DBContext is defined in to be a startup project
  • Add migration: open package manger console, select your project where db context is

defined as default one and type command add-migraiton YourMigrationName

  • If you're happy with generated migration (you can find it in created Migrations folder),

then run update-database in package manager console

  • You have a database and table created, you can go and check it using your IDE
slide-56
SLIDE 56

Lazy vs Eager

  • 4 SQL (lazy) vs one (eager)
slide-57
SLIDE 57

When ORM speed is not enough

  • Manual SQL queries are created and executed. Example:

– A table that has many rows. – Update command needed for a single column (all values in it) – EF would do that for each line, SQL would have the option doing it at once.

slide-58
SLIDE 58

When ORM speed is not enough

  • Changing EF execution configuration logic. Example:

– EF determines, which fields have changed in the program (meaning which ones have to be updated in DB), when silently checking them with original ones (!!!)

  • Imagine having iteration-type environment where that happens!
  • Solution: disable tracking in that cycle:

– property AutoDetectChangesEnabled in DbContext.Configuration

slide-59
SLIDE 59

Literature

  • MCSD toolkit:

– Chapter 9: Working with ADO.NET (DataSet/ DataTable/ DataAdapter)

  • MSDN:

– How to: Bind Data to the Windows Forms DataGridView Control – ASP.NET Data Access Options – Extra: How to: Display Related Data in a Windows Forms Application

  • Web:

– http://www.ConnectionStrings.com

slide-60
SLIDE 60

Next time

  • Asynchrounous programming

– Thread – Task – Async/await – Real examples

slide-61
SLIDE 61

Questions