Tddd49 Lecture 04
Tddd49 Lecture 04
C# and .NET
Programming
(Lecture 04)
Sahand Sadjadee
Linköping University
Outline
● Batching
● Binary Large Objects (BLOBs)
● Connections
● Data Format
● Exception Management
● Object Relational Mapping ( http://nhibernate.info/ as an example)
● Queries
● Stored Procedures
● Stored Procedures vs. Dynamic SQL
● Transactions
● Validation
● XML
Performance Considerations https://msdn.microsoft.com/en-us/library/ee658127.aspx
● Use connection pooling and tune performance based on results obtained by running simulated load scenarios.
a. https://msdn.microsoft.com/en-us/library/bb399543(v=vs.110).aspx
● Consider tuning isolation levels for data queries. If you are building an application with high-throughput
requirements, special data operations may be performed at lower isolation levels than the rest of the transaction.
Combining isolation levels can have a negative impact on data consistency, so you must carefully analyze this
option on a case by case basis.
● Consider batching commands to reduce the number of round trips to the database server.
● Consider using optimistic concurrency with nonvolatile data to mitigate the cost of locking data in the database.
This avoids the overhead of locking database rows, including the connection that must be kept open during a lock.
● If using a DataReader, use ordinal lookups for faster performance.
a. https://msdn.microsoft.com/en-us/library/haa3afyz(v=vs.110).aspx
Security Considerations https://msdn.microsoft.com/en-us/library/ee658127.aspx
● When storing passwords, use a salted hash instead of an encrypted version of the password.
● Require that callers send identity information to the data layer for auditing purposes.
● Use parameterized SQL queries and typed parameters to mitigate security issues and reduce the chance of
SQL injection attacks succeeding. Do not use string concatenation to build dynamic queries from user
input data.
What is LINQ? https://msdn.microsoft.com/en-us/library/bb308959.aspx
General-purpose query facilities added to the .NET Framework apply to all sources of information, not just relational or XML data. This
facility is called .NET Language-Integrated Query (LINQ).
Language Integrated Query (LINQ, pronounced "link") is a Microsoft .NET Framework component that adds native data querying
capabilities to .NET languages, although ports exist for PHP (PHPLinq),JavaScript (linq.js), TypeScript (linq.ts), and ActionScript
(ActionLinq) - but none of these ports are strictly equivalent to LINQ in C# for example (where it is a part of the language, not an external
library, and where it often addresses a wider range of needs).
IEnumerable
https://msdn.microsoft.com/en-us/library/system.collections.ienumerable(v=vs.110).aspx
File.WriteAllText(@"c:\videogames.json", videogameRatings.ToString());
var postTitles =
from p in rss["channel"]["item"]
select (string)p["title"];
var categories =
from c in rss["channel"]["item"].SelectMany(i => i["categories"]).Values<string>()
group c by c
into g
orderby g.Count() descending
select new { Category = g.Key, Count = g.Count() };
using System;
using System.Linq;
using System.Collections.Generic;
class app {
static void Main() {
string[] names = { "Burke", "Connor", "Frank",
"Everett", "Albert", "George",
"Harris", "David" };
sqlConnection1.Open();
reader = cmd.ExecuteReader();
// Data is accessible through the DataReader object here.
//In order to use linq to access the data, it first needs to be stored as a list.
sqlConnection1.Close();
SQLDataReader
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader(v=vs.110).aspx
Provides a way of reading a forward-only stream of rows from a SQL Server database. This class cannot
be inherited.
Using an ORM and LINQ https://www.devart.com/dotconnect/mysql/articles/tutorial_linq.html
Console.ReadLine();
Linq - example 01/Group By
string[] words = { "blueberry", "chimpanzee", "abacus", Words that start with the letter 'b':
"banana", "apple", "cheese" }; blueberry
banana
Words that start with the letter 'c':
var wordGroups = chimpanzee
cheese
from w in words Words that start with the letter 'a':
group w by w[0] into g abacus
select new { FirstLetter = g.Key, Words = g }; apple
var orderGroups =
from p in products
group p by p.Category into g
select new { Category = g.Key, Products = g };
ObjectDumper.Write(orderGroups, 1);
Linq - example 04/GroupBy - Nested
List<Customer> customers = GetCustomerList();
var customerOrderGroups =
from c in customers
select
new
{
c.CompanyName,
YearGroups =
from o in c.Orders
group o by o.OrderDate.Year into yg
select
new
{
Year = yg.Key,
MonthGroups =
from o in yg
group o by o.OrderDate.Month into mg
select new { Month = mg.Key, Orders = mg }
}
};
ObjectDumper.Write(customerOrderGroups, 3);
Linq - example 05/GroupBy - Comparer
public void Linq44() public class AnagramEqualityComparer : IEqualityComparer<string>
{ {
string[] anagrams = { "from ", " salt", " earn ", public bool Equals(string x, string y)
" last ", " near ", " form " }; {
return getCanonicalString(x) == getCanonicalString(y);
var orderGroups = anagrams.GroupBy(w => }
w.Trim(), new AnagramEqualityComparer());
public int GetHashCode(string obj)
ObjectDumper.Write(orderGroups, 1); {
} return getCanonicalString(obj).GetHashCode();
}
Product product12 = (
from p in products
where p.ProductID == 12
select p)
.First();
ObjectDumper.Write(product12);
Linq - example 07/Element operator
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
int fourthLowNum = (
from n in numbers
where n > 5
select n)
.ElementAt(1); // second number is index 1 because sequences use 0-based indexing
var sortedWords =
from w in words
orderby w
select w;
var sortedWords =
from w in words
orderby w.Length
select w;
var sortedProducts =
from p in products
orderby p.ProductName
select p;
ObjectDumper.Write(sortedProducts);
Linq - example 11/Ordering
public void Linq31()
{
string[] words = { "aPPLE", "AbAcUs", "bRaNcH", "BlUeBeRrY", "ClOvEr", "cHeRry" };
ObjectDumper.Write(sortedWords);
}
var sortedDoubles =
from d in doubles
orderby d descending
select d;
var sortedDigits =
from d in digits
orderby d.Length, d
select d;
Console.WriteLine("Sorted digits:");
foreach (var d in sortedDigits)
{
Console.WriteLine(d);
}
Linq - example 14/Aggregate
var numbers = new List<int> { 6, 2, 8, 3 };
int sum = numbers.Aggregate((result, item) => result + item);
// sum: (((6+2)+8)+3) = 19
Linq - example 15/Aggregate
double[] doubles = { 1.7, 2.3, 1.9, 4.1, 2.9 };
var q =
from c in categories
join p in products on c equals p.Category
select new { Category = c, p.ProductName };
foreach (var v in q)
{
Console.WriteLine(v.ProductName + ": " + v.Category);
}
Linq - example 17/Group Join
string[] categories = new string[]{
"Beverages",
"Condiments",
"Vegetables",
"Dairy Products",
"Seafood" };
var q =
from c in categories
join p in products on c equals p.Category into ps
select new { Category = c, Products = ps };
foreach (var v in q)
{
Console.WriteLine(v.Category + ":");
foreach (var p in v.Products)
{
Console.WriteLine(" " + p.ProductName);
}
}
Linq - example 18/Left Outer Join
string[] categories = new string[]{
"Beverages",
"Condiments",
"Vegetables",
"Dairy Products",
"Seafood" };
var q =
from c in categories
join p in products on c equals p.Category into ps
from p in ps.DefaultIfEmpty()
select new { Category = c, ProductName = p == null ? "(No products)" : p.ProductName };
foreach (var v in q)
{
Console.WriteLine(v.ProductName + ": " + v.Category);
}
More examples @
https://code.msdn.microsoft.com/101-LINQ-Samples-3fb9811b
LINQ to SQL
Interesting tutorial...
https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/linq/
Repository Pattern* https://msdn.microsoft.com/en-us/library/ff649690.aspx
Thanks for listening!