SlideShare a Scribd company logo
ADO .NET
Typing and
Validation
Michael Heron
Introduction
 Our coverage of the ADO .NET framework
in the last lecture focussed on the use of
the data set.
 Disconnected, memory resident
representations of underlying data
structures.
 In this lecture we are going to look at the
data reader.
 Real time query of data.
Data Set Problems
 Data sets are not an ideal system of
accessing underlying databases.
 But then, there’s no such thing as an ideal
solution.
 Data sets are memory hungry.
 The data you have accessed remains resident
in memory as long as your data set is in scope.
 Data sets can be wasteful.
 They execute a full query each time, when you
may not actually need that.
 Data sets are blocking.
 They need to fully complete before you can do
anything else.
Data Readers
 Whereas a dataset is a disconnected
representation, data readers allow for
real-time querying of the underlying
database.
 However, at a cost of flexibility.
 Data readers are forward only, and read
only.
 It accesses data a record at a time.
 Stream-based I/O
Data Readers
 Data readers are platform specific.
 They aren’t generic representations like a data
set.
 As such, they vary depending on whether
there is a managed provider framework.
 As in, is there a supported database engine.
 It cannot access data in more abstract
formats.
 It doesn’t allow for access to XML, or allow you
to build your own representation if you needed
it.
Using A Data Reader
 Data readers can take over the step
where we normally create a data
adapter and data set.
 As usual, it’s created from an SQL
command:
 OleDbCommand
 SqlCommand
 The object you will need is a Data Reader
object:
 OleDbDataReader
 SqlDataReader
Example Code
private void Form1_Load(object sender, EventArgs e)
{
string query;
OleDbConnection oleDbConnection1 =
new OleDbConnection (
"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=computer_store.mdb;" +
"User Id=admin;Password=;");
OleDbCommand myCommand;
OleDbDataReader myReader;
oleDbConnection1.Open();
query = "select * from Customer";
myCommand = new OleDbCommand(query, oleDbConnection1);
myReader = myCommand.ExecuteReader();
}
Reading From A Reader
 We use the read method of a data
reader to have it read the next record in
the query.
 This returns a true or a false to indicate success.
myReader.read();
 Once we’ve read in a record, we access
it in the reader directly:
txtId.Text =
myReader[“customer id”];
Reading From A Reader
 If we need to read all records, we put it in
a loop:
while(myReader.Read())
{
cmbItems.Items.Add
(myReader["CustomerName"]);
}
Data Reader Mechanics
 Data readers only ever go forward.
 Each invocation of the read method moves
us on one record through the results.
 The data stream persists until the data
reader is disposed of.
 Data readers are useful for quick and
easy access to data.
 And for circumstances where real time
access is important.
Data Sets Revisited
 In our examples to data, we have been
used what are known as untyped
datasets.
 These are data-sets with no compile-time
sanity checks.
 These often cause problems:
 Array out of bounds
 Misspelled fields
Typed Data Sets
 We can actually make .NET handle a lot
of these problems for us at compile time.
 We use Typed Data Sets for this.
 These are a little more complicated to set
up than simple data sets.
 They require us to use the server explorer.
 When we use connection strings, we don’t
need to do that.
Untyped Data Sets
 This is perfectly valid in an untyped Data Set:
myData.Tables[1].Rows[6]
[“Customer Name”]
 What if there’s only one table?
 What if there are only five rows?
 What if there’s no customer name
field?
Typed Data Sets
 Typed data sets put a compile-time check on
element access.
 Plus, you get to use intellisense on them!
 Right click on your project, and choose ‘add new
item’:
Typed Data Sets
 Typed data sets have an extension of xsd.
 Xml Schema Data
 Once you have added that to the
project, you can drag and drop tables
onto the xsd file to create the schema.
 You can also add necessary data relations to
the schema if needed, via the toolbox.
 This creates a class that represents a data
set.
 You use it in place of DataSet.
 This is what happens when you create a data
connection through the wizard.
 Hence why all your data sets end with a number.
Using A Typed Data Set
 Once you’ve gone through the steps of
setting up a type-safe data set, you use it
like a normal data set:
MyDataSet myData;
myAdapter.fill (myData);
 It gets more useful when you actually
come to access the data...
Using a Typed Data Set
 Now, your data set will contain an
enumeration representing the table:
myData.Customer[0];
 And each element of that enumeration
will have a property reflecting a field
name:
myData.Customer[0].CustomerName;
Typed Data Set
 Typed data sets also expose a range of
other useful methods.
 Specifically, each field gets an ‘is null’ method:
for (int i = 0; i < myData.Customer.Count - 1; i++)
{
if (myData.Customer[0].IsCustomerNameNull()
== false)
{
cmbItems.Items.Add
(myData.Customer[i].CustomerName);
}
}
Disadvantages of Strong
Typing
 A typed data set is a layer on top of an
untyped data set.
 As such, it comes with a small performance hit.
 However, this comes with a corresponding
increase in productivity.
 You shouldn’t have to do things that a compiler can
do for you – if a compiler can do them, they are
trivial.
 They are limited by their implementation.
 You don’t want to have to roll one by hand!
 Some people don’t like strong typing.
 These people are wrong.
Advantages of Strong Typing
 Compile-time sanity checking.
 You trade run-time errors for compile-time
errors.
 That’s always a smart trade.
 Intellisense support.
 Seriously, this is major.
 Provision of standard functionality.
 Ease of data access
 Ease of data comparison
Data Readers versus Typed
Datasets
 Which do you want to use?
 Data readers offer performance improvements.
 Data sets are implemented internally with a data
reader.
 This performance gain is usually marginal.
 Data readers require you to build a data
representation yourself.
 When manipulating data, a data set is
more appropriate.
 When doing a quick ‘query then forget’ a
data reader may suffice.
 Your needs will dictate which is best.
Data Validation
 Data validation serves to meet two
requirements.
 Ensure that invalid changes to the
database can be stopped before they are
committed.
 Deal with run-time errors to provide a
seamless user interaction experience.
 Data is valuable.
 Indeed, usually more valuable than any
other element of a system.
Two Mechanics
 Two mechanics exist to allow you to
control data as it enters the system.
 Give the user a chance to validate
information for correctness.
 Validate editing as it is done.
 The data set object gives you a number
of methods for commiting changes.
 RejectChanges
 AcceptChanges
Reject Changes
if (myData.HasChanges()) {
response = MessageBox.Show("Do you want to
“+ “commit these changes?", "Commit
Changes?",
MessageBoxButtons.YesNo);
if (response == DialogResult.No)
{
myData.RejectChanges();
}
else
{
myData.AcceptChanges();
}
}
Change Committal
 Committing changes to the database
is done using update().
 This requires the HasChanges method to
evaluate as true.
 Otherwise, nothing happens.
 We can call it on the data set itself.
 Or on a specific data row if we need finer
grained control.
 Calling it on the data set trickles down
to all internal objects.
 Each DataRow has a RowState
property that holds its internal state.
Accepting Changes
 When you call update, as part of its
standard Operating Procedure, it calls
Accept Changes.
 And this sets the RowState property
appropriately.
 One or the other should be used, rather
than both.
 They don’t Play Nicely together.
Accepting Changes
 Changes must be committed to be
persistent.
 If you have a function that adds a new row
each time you click the button, every time
you click it you’ll lose the last changes.
 This is handled internally by a Data
Versioning system.
 Each row in a table has a property which
handles its current ‘version’.
Data Versioning
 Each row of a table contains multiple
versions of the changed data.
 This is useful for revision control.
 Each row contains the following
properties:
 Current – the current version of the data (after
your changes)
 Original – the data before you started meddlin’
 Proposed – The data that you have modified.
This is only available temporarily
 Default – The default value for the data (usually
the original, or set from the data structure).
Version Control
 This gives you fairly fine-grained control over
committing data to a database.
 You can attach event handlers to various controls
to allow you to control this.
 We can register an event for a changing
row like so:
myTable.RowChanged += new
DataRowChangeEventHandler(Change_
Row);
 Change_Row is the method that will be
executed when this event is triggered.
Event Handlers
 Each event has a special event handler
class to deal with it.
 It serves as a wrapper around a method.
 They stem from either DataRow or
DataColumn
 DataColumnChangeEventHandler
 DataRowChangeEventHandler
 Throw exceptions in these methods if you
want to prevent data being committed.
Event Handler
private static void Change_Row(object sender,
DataRowChangeEventArgs e) {
if ((int)e.Row["CustomerId"] < 0)
{
throw new ArgumentException("Customer ID must “ +
“be positive");
}
}
 Why do this?
 Why not let the database itself handle it?
 This way we can provide meaningful user
feedback.
 And take advantage of strong typing to provide
context and convenience.
Triggering Code
try
{
myTable.Rows.Add(myRow);
}
catch (ArgumentException ex)
{
MessageBox.Show("Customer ID “
“must be positive.");
myTable.RejectChanges();
return;
}
Preventing or Compensating
 Exceptions allow you to catch errors that
you don’t have any explicit control over.
 Users typing into a data grid, for example.
 You also have the chance to validate
within code before you ever trigger an
exception.
 Deal with things in if statements or validation
functions before they get that far.
 There are plusses and minuses to both
approaches.
Conclusion
 ADO .NET gives us the best of both worlds with
database driven applications.
 Strong syntactically correct typing.
 Fine-grained control over updating, removing
and changing data.
 As part of good interface design in any
language, you must commit yourself to
meaningful error messages.
 These are only possible if you have fine-grained
control over validation.

More Related Content

What's hot

Vb.net session 05
Vb.net session 05Vb.net session 05
Vb.net session 05
Niit Care
 
CQRS introduction
CQRS introductionCQRS introduction
CQRS introduction
Yura Taras
 
CaseStudy-MohammedImranAlam-Xcelsius
CaseStudy-MohammedImranAlam-XcelsiusCaseStudy-MohammedImranAlam-Xcelsius
CaseStudy-MohammedImranAlam-Xcelsius
Mohammed Imran Alam
 

What's hot (15)

Data Binding and Data Grid View Classes
Data Binding and Data Grid View ClassesData Binding and Data Grid View Classes
Data Binding and Data Grid View Classes
 
Visual Basic.Net & Ado.Net
Visual Basic.Net & Ado.NetVisual Basic.Net & Ado.Net
Visual Basic.Net & Ado.Net
 
Backup your tables to SQL Azure using SQL Stretch
Backup your tables to SQL Azure using SQL StretchBackup your tables to SQL Azure using SQL Stretch
Backup your tables to SQL Azure using SQL Stretch
 
Grid Vew Control VB
Grid Vew Control VBGrid Vew Control VB
Grid Vew Control VB
 
Disconnected Architecture and Crystal report in VB.NET
Disconnected Architecture and Crystal report in VB.NETDisconnected Architecture and Crystal report in VB.NET
Disconnected Architecture and Crystal report in VB.NET
 
Vb.net session 05
Vb.net session 05Vb.net session 05
Vb.net session 05
 
Excel Datamining Addin Advanced
Excel Datamining Addin AdvancedExcel Datamining Addin Advanced
Excel Datamining Addin Advanced
 
Step by Step Asp.Net GridView Tutorials
Step by Step Asp.Net GridView TutorialsStep by Step Asp.Net GridView Tutorials
Step by Step Asp.Net GridView Tutorials
 
GRID VIEW PPT
GRID VIEW PPTGRID VIEW PPT
GRID VIEW PPT
 
MS SQL SERVER: Data mining concepts and dmx
MS SQL SERVER: Data mining concepts and dmxMS SQL SERVER: Data mining concepts and dmx
MS SQL SERVER: Data mining concepts and dmx
 
2310 b 09
2310 b 092310 b 09
2310 b 09
 
Data Integration and Transformation in Data mining
Data Integration and Transformation in Data miningData Integration and Transformation in Data mining
Data Integration and Transformation in Data mining
 
Android sql examples
Android sql examplesAndroid sql examples
Android sql examples
 
CQRS introduction
CQRS introductionCQRS introduction
CQRS introduction
 
CaseStudy-MohammedImranAlam-Xcelsius
CaseStudy-MohammedImranAlam-XcelsiusCaseStudy-MohammedImranAlam-Xcelsius
CaseStudy-MohammedImranAlam-Xcelsius
 

Viewers also liked (6)

ETHICS05 - Intellectual Property
ETHICS05 - Intellectual PropertyETHICS05 - Intellectual Property
ETHICS05 - Intellectual Property
 
PATTERNS07 - Data Representation in C#
PATTERNS07 - Data Representation in C#PATTERNS07 - Data Representation in C#
PATTERNS07 - Data Representation in C#
 
CPP13 - Object Orientation
CPP13 - Object OrientationCPP13 - Object Orientation
CPP13 - Object Orientation
 
ETHICS09 - Case Study - The Cuckoo's Egg
ETHICS09 - Case Study - The Cuckoo's EggETHICS09 - Case Study - The Cuckoo's Egg
ETHICS09 - Case Study - The Cuckoo's Egg
 
ETHICS03 - Equity Funding Scandal - Case Study
ETHICS03 - Equity Funding Scandal - Case StudyETHICS03 - Equity Funding Scandal - Case Study
ETHICS03 - Equity Funding Scandal - Case Study
 
2CPP14 - Abstraction
2CPP14 - Abstraction2CPP14 - Abstraction
2CPP14 - Abstraction
 

Similar to PATTERNS08 - Strong Typing and Data Validation in .NET

Asp net interview_questions
Asp net interview_questionsAsp net interview_questions
Asp net interview_questions
Bilam
 
topic 2 data flow daigram topic-converted.pdf
topic 2 data flow daigram topic-converted.pdftopic 2 data flow daigram topic-converted.pdf
topic 2 data flow daigram topic-converted.pdf
tahir427002
 
App Grid Dev With Coherence
App Grid Dev With CoherenceApp Grid Dev With Coherence
App Grid Dev With Coherence
James Bayer
 

Similar to PATTERNS08 - Strong Typing and Data Validation in .NET (20)

White Paper On ConCurrency For PCMS Application Architecture
White Paper On ConCurrency For PCMS Application ArchitectureWhite Paper On ConCurrency For PCMS Application Architecture
White Paper On ConCurrency For PCMS Application Architecture
 
Ado
AdoAdo
Ado
 
Ado.Net Architecture
Ado.Net ArchitectureAdo.Net Architecture
Ado.Net Architecture
 
Tableau Basic Questions
Tableau Basic QuestionsTableau Basic Questions
Tableau Basic Questions
 
End-to-End Machine Learning Project
End-to-End Machine Learning ProjectEnd-to-End Machine Learning Project
End-to-End Machine Learning Project
 
Excel Datamining Addin Beginner
Excel Datamining Addin BeginnerExcel Datamining Addin Beginner
Excel Datamining Addin Beginner
 
Data warehousing interview_questionsandanswers
Data warehousing interview_questionsandanswersData warehousing interview_questionsandanswers
Data warehousing interview_questionsandanswers
 
Asp net interview_questions
Asp net interview_questionsAsp net interview_questions
Asp net interview_questions
 
Asp net interview_questions
Asp net interview_questionsAsp net interview_questions
Asp net interview_questions
 
Chapter 15
Chapter 15Chapter 15
Chapter 15
 
Test data generation
Test data generationTest data generation
Test data generation
 
topic 2 data flow daigram topic-converted.pdf
topic 2 data flow daigram topic-converted.pdftopic 2 data flow daigram topic-converted.pdf
topic 2 data flow daigram topic-converted.pdf
 
Test Driven Database Development With Data Dude
Test Driven Database Development With Data DudeTest Driven Database Development With Data Dude
Test Driven Database Development With Data Dude
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
 
App Grid Dev With Coherence
App Grid Dev With CoherenceApp Grid Dev With Coherence
App Grid Dev With Coherence
 
Application Grid Dev with Coherence
Application Grid Dev with CoherenceApplication Grid Dev with Coherence
Application Grid Dev with Coherence
 
App Grid Dev With Coherence
App Grid Dev With CoherenceApp Grid Dev With Coherence
App Grid Dev With Coherence
 
Tableau interview questions and answers
Tableau interview questions and answersTableau interview questions and answers
Tableau interview questions and answers
 
Introduction to database with ms access(DBMS)
Introduction to database with ms access(DBMS)Introduction to database with ms access(DBMS)
Introduction to database with ms access(DBMS)
 

More from Michael Heron

More from Michael Heron (20)

Meeple centred design - Board Game Accessibility
Meeple centred design - Board Game AccessibilityMeeple centred design - Board Game Accessibility
Meeple centred design - Board Game Accessibility
 
Musings on misconduct
Musings on misconductMusings on misconduct
Musings on misconduct
 
Accessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS FrameworkAccessibility Support with the ACCESS Framework
Accessibility Support with the ACCESS Framework
 
ACCESS: A Technical Framework for Adaptive Accessibility Support
ACCESS:  A Technical Framework for Adaptive Accessibility SupportACCESS:  A Technical Framework for Adaptive Accessibility Support
ACCESS: A Technical Framework for Adaptive Accessibility Support
 
Authorship and Autership
Authorship and AutershipAuthorship and Autership
Authorship and Autership
 
Text parser based interaction
Text parser based interactionText parser based interaction
Text parser based interaction
 
SAD04 - Inheritance
SAD04 - InheritanceSAD04 - Inheritance
SAD04 - Inheritance
 
GRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and RadiosityGRPHICS08 - Raytracing and Radiosity
GRPHICS08 - Raytracing and Radiosity
 
GRPHICS07 - Textures
GRPHICS07 - TexturesGRPHICS07 - Textures
GRPHICS07 - Textures
 
GRPHICS06 - Shading
GRPHICS06 - ShadingGRPHICS06 - Shading
GRPHICS06 - Shading
 
GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)GRPHICS05 - Rendering (2)
GRPHICS05 - Rendering (2)
 
GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)GRPHICS04 - Rendering (1)
GRPHICS04 - Rendering (1)
 
GRPHICS03 - Graphical Representation
GRPHICS03 - Graphical RepresentationGRPHICS03 - Graphical Representation
GRPHICS03 - Graphical Representation
 
GRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D GraphicsGRPHICS02 - Creating 3D Graphics
GRPHICS02 - Creating 3D Graphics
 
GRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D GraphicsGRPHICS01 - Introduction to 3D Graphics
GRPHICS01 - Introduction to 3D Graphics
 
GRPHICS09 - Art Appreciation
GRPHICS09 - Art AppreciationGRPHICS09 - Art Appreciation
GRPHICS09 - Art Appreciation
 
2CPP18 - Modifiers
2CPP18 - Modifiers2CPP18 - Modifiers
2CPP18 - Modifiers
 
2CPP17 - File IO
2CPP17 - File IO2CPP17 - File IO
2CPP17 - File IO
 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
 
2CPP15 - Templates
2CPP15 - Templates2CPP15 - Templates
2CPP15 - Templates
 

Recently uploaded

Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 

Recently uploaded (20)

OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Studiovity film pre-production and screenwriting software
Studiovity film pre-production and screenwriting softwareStudiovity film pre-production and screenwriting software
Studiovity film pre-production and screenwriting software
 
Agnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in KrakówAgnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in Kraków
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
 
Software Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdfSoftware Testing Exam imp Ques Notes.pdf
Software Testing Exam imp Ques Notes.pdf
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 

PATTERNS08 - Strong Typing and Data Validation in .NET

  • 2. Introduction  Our coverage of the ADO .NET framework in the last lecture focussed on the use of the data set.  Disconnected, memory resident representations of underlying data structures.  In this lecture we are going to look at the data reader.  Real time query of data.
  • 3. Data Set Problems  Data sets are not an ideal system of accessing underlying databases.  But then, there’s no such thing as an ideal solution.  Data sets are memory hungry.  The data you have accessed remains resident in memory as long as your data set is in scope.  Data sets can be wasteful.  They execute a full query each time, when you may not actually need that.  Data sets are blocking.  They need to fully complete before you can do anything else.
  • 4. Data Readers  Whereas a dataset is a disconnected representation, data readers allow for real-time querying of the underlying database.  However, at a cost of flexibility.  Data readers are forward only, and read only.  It accesses data a record at a time.  Stream-based I/O
  • 5. Data Readers  Data readers are platform specific.  They aren’t generic representations like a data set.  As such, they vary depending on whether there is a managed provider framework.  As in, is there a supported database engine.  It cannot access data in more abstract formats.  It doesn’t allow for access to XML, or allow you to build your own representation if you needed it.
  • 6. Using A Data Reader  Data readers can take over the step where we normally create a data adapter and data set.  As usual, it’s created from an SQL command:  OleDbCommand  SqlCommand  The object you will need is a Data Reader object:  OleDbDataReader  SqlDataReader
  • 7. Example Code private void Form1_Load(object sender, EventArgs e) { string query; OleDbConnection oleDbConnection1 = new OleDbConnection ( "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=computer_store.mdb;" + "User Id=admin;Password=;"); OleDbCommand myCommand; OleDbDataReader myReader; oleDbConnection1.Open(); query = "select * from Customer"; myCommand = new OleDbCommand(query, oleDbConnection1); myReader = myCommand.ExecuteReader(); }
  • 8. Reading From A Reader  We use the read method of a data reader to have it read the next record in the query.  This returns a true or a false to indicate success. myReader.read();  Once we’ve read in a record, we access it in the reader directly: txtId.Text = myReader[“customer id”];
  • 9. Reading From A Reader  If we need to read all records, we put it in a loop: while(myReader.Read()) { cmbItems.Items.Add (myReader["CustomerName"]); }
  • 10. Data Reader Mechanics  Data readers only ever go forward.  Each invocation of the read method moves us on one record through the results.  The data stream persists until the data reader is disposed of.  Data readers are useful for quick and easy access to data.  And for circumstances where real time access is important.
  • 11. Data Sets Revisited  In our examples to data, we have been used what are known as untyped datasets.  These are data-sets with no compile-time sanity checks.  These often cause problems:  Array out of bounds  Misspelled fields
  • 12. Typed Data Sets  We can actually make .NET handle a lot of these problems for us at compile time.  We use Typed Data Sets for this.  These are a little more complicated to set up than simple data sets.  They require us to use the server explorer.  When we use connection strings, we don’t need to do that.
  • 13. Untyped Data Sets  This is perfectly valid in an untyped Data Set: myData.Tables[1].Rows[6] [“Customer Name”]  What if there’s only one table?  What if there are only five rows?  What if there’s no customer name field?
  • 14. Typed Data Sets  Typed data sets put a compile-time check on element access.  Plus, you get to use intellisense on them!  Right click on your project, and choose ‘add new item’:
  • 15. Typed Data Sets  Typed data sets have an extension of xsd.  Xml Schema Data  Once you have added that to the project, you can drag and drop tables onto the xsd file to create the schema.  You can also add necessary data relations to the schema if needed, via the toolbox.  This creates a class that represents a data set.  You use it in place of DataSet.  This is what happens when you create a data connection through the wizard.  Hence why all your data sets end with a number.
  • 16. Using A Typed Data Set  Once you’ve gone through the steps of setting up a type-safe data set, you use it like a normal data set: MyDataSet myData; myAdapter.fill (myData);  It gets more useful when you actually come to access the data...
  • 17. Using a Typed Data Set  Now, your data set will contain an enumeration representing the table: myData.Customer[0];  And each element of that enumeration will have a property reflecting a field name: myData.Customer[0].CustomerName;
  • 18. Typed Data Set  Typed data sets also expose a range of other useful methods.  Specifically, each field gets an ‘is null’ method: for (int i = 0; i < myData.Customer.Count - 1; i++) { if (myData.Customer[0].IsCustomerNameNull() == false) { cmbItems.Items.Add (myData.Customer[i].CustomerName); } }
  • 19. Disadvantages of Strong Typing  A typed data set is a layer on top of an untyped data set.  As such, it comes with a small performance hit.  However, this comes with a corresponding increase in productivity.  You shouldn’t have to do things that a compiler can do for you – if a compiler can do them, they are trivial.  They are limited by their implementation.  You don’t want to have to roll one by hand!  Some people don’t like strong typing.  These people are wrong.
  • 20. Advantages of Strong Typing  Compile-time sanity checking.  You trade run-time errors for compile-time errors.  That’s always a smart trade.  Intellisense support.  Seriously, this is major.  Provision of standard functionality.  Ease of data access  Ease of data comparison
  • 21. Data Readers versus Typed Datasets  Which do you want to use?  Data readers offer performance improvements.  Data sets are implemented internally with a data reader.  This performance gain is usually marginal.  Data readers require you to build a data representation yourself.  When manipulating data, a data set is more appropriate.  When doing a quick ‘query then forget’ a data reader may suffice.  Your needs will dictate which is best.
  • 22. Data Validation  Data validation serves to meet two requirements.  Ensure that invalid changes to the database can be stopped before they are committed.  Deal with run-time errors to provide a seamless user interaction experience.  Data is valuable.  Indeed, usually more valuable than any other element of a system.
  • 23. Two Mechanics  Two mechanics exist to allow you to control data as it enters the system.  Give the user a chance to validate information for correctness.  Validate editing as it is done.  The data set object gives you a number of methods for commiting changes.  RejectChanges  AcceptChanges
  • 24. Reject Changes if (myData.HasChanges()) { response = MessageBox.Show("Do you want to “+ “commit these changes?", "Commit Changes?", MessageBoxButtons.YesNo); if (response == DialogResult.No) { myData.RejectChanges(); } else { myData.AcceptChanges(); } }
  • 25. Change Committal  Committing changes to the database is done using update().  This requires the HasChanges method to evaluate as true.  Otherwise, nothing happens.  We can call it on the data set itself.  Or on a specific data row if we need finer grained control.  Calling it on the data set trickles down to all internal objects.  Each DataRow has a RowState property that holds its internal state.
  • 26. Accepting Changes  When you call update, as part of its standard Operating Procedure, it calls Accept Changes.  And this sets the RowState property appropriately.  One or the other should be used, rather than both.  They don’t Play Nicely together.
  • 27. Accepting Changes  Changes must be committed to be persistent.  If you have a function that adds a new row each time you click the button, every time you click it you’ll lose the last changes.  This is handled internally by a Data Versioning system.  Each row in a table has a property which handles its current ‘version’.
  • 28. Data Versioning  Each row of a table contains multiple versions of the changed data.  This is useful for revision control.  Each row contains the following properties:  Current – the current version of the data (after your changes)  Original – the data before you started meddlin’  Proposed – The data that you have modified. This is only available temporarily  Default – The default value for the data (usually the original, or set from the data structure).
  • 29. Version Control  This gives you fairly fine-grained control over committing data to a database.  You can attach event handlers to various controls to allow you to control this.  We can register an event for a changing row like so: myTable.RowChanged += new DataRowChangeEventHandler(Change_ Row);  Change_Row is the method that will be executed when this event is triggered.
  • 30. Event Handlers  Each event has a special event handler class to deal with it.  It serves as a wrapper around a method.  They stem from either DataRow or DataColumn  DataColumnChangeEventHandler  DataRowChangeEventHandler  Throw exceptions in these methods if you want to prevent data being committed.
  • 31. Event Handler private static void Change_Row(object sender, DataRowChangeEventArgs e) { if ((int)e.Row["CustomerId"] < 0) { throw new ArgumentException("Customer ID must “ + “be positive"); } }  Why do this?  Why not let the database itself handle it?  This way we can provide meaningful user feedback.  And take advantage of strong typing to provide context and convenience.
  • 32. Triggering Code try { myTable.Rows.Add(myRow); } catch (ArgumentException ex) { MessageBox.Show("Customer ID “ “must be positive."); myTable.RejectChanges(); return; }
  • 33. Preventing or Compensating  Exceptions allow you to catch errors that you don’t have any explicit control over.  Users typing into a data grid, for example.  You also have the chance to validate within code before you ever trigger an exception.  Deal with things in if statements or validation functions before they get that far.  There are plusses and minuses to both approaches.
  • 34. Conclusion  ADO .NET gives us the best of both worlds with database driven applications.  Strong syntactically correct typing.  Fine-grained control over updating, removing and changing data.  As part of good interface design in any language, you must commit yourself to meaningful error messages.  These are only possible if you have fine-grained control over validation.