PPT/2

PPT/2

Web programming and advanced development techniques Layering LINQ approach XML handling, XLINQ Exercise V 1.0 1 Web programming and advanced development techniques Layering LINQ approach

XML handling, XLINQ Exercise V 1.0 2 Layering Aim: hiding the implementation details so that the upper layer will not depend on other layers not-immediately below Similar principle: layered structure of operating systems V 1.0 3 Tier vs Layer

Layer: logical separation of classes All classes belonging to one layer serve the common higher purpose (e.g. display, data management, business logic) It is clearly defined which classes can be accessed from the outside The external (provided and used) functionalities are described using interfaces We have a well-designed application if a given layer can be replaced with a differently implemented other component that implements the same interface Tier: physical separation of the components of the application Software- or hardware components that execute the layer classes Not necessarily have the same separation as the layers V 1.0 4

Application layers Every layer can be separated to internal layers Connecting them: using interfaces V 1.0 5 Web programming and advanced development techniques Layering LINQ approach XML handling, XLINQ Exercise

V 1.0 6 LINQ (Language Integrated Queries) Allows a simple syntax to handle source-independent management of various collections Simple syntax: simple methods that solve everyday common tasks (that can typically be solved using loops/conditions) Source-independent: array, list, XML, database, LINQ To Objects, LINQ To XML, LINQ to Entities, ... Parts LINQ operator methods LINQ query syntax (from, where, select, join, orderby...), query parser + Lambda expressions + Extension methods

+ var keyword, anonymous instances V 1.0 7 Adding methods We want to add new methods to existing collections, BUT changing the interface definition can have unwanted side effects we cant add implemented full methods to interfaces V 1.0

? 8 Extension methods V 1.0 9 Lambda expressions with LINQ methods The lambda expressions Are parameters for the LINQ extension methods Automatically called for every element of the collection If we work with IEnumerable, then the input is T Various possible output types (e.g. WhereFilterbool; OrderBySortIComparable)

The lambda outputs are used to determine the output of the LINQ method, which can be IEnumerable, IEnumerable, T, int With databases Same syntax, IQueryable extensions expression lambda can be merged/optimized! V 1.0 10 With extension methods We have to call the same LINQ method for common tasks, independent from the actual type of the collection The collection is often an interface-typed method or constructor parameter, so the business logic layer doesnt even know what type it is exactly working with (DEPENDENCY INJECTION, detailed later)

The called method is actually an extension method for the interface, that executes the operation (filter/sort/etc) independent from the actual collection type List, XML file this week Database next week XML format? Soon V 1.0 11 Language constructs Lambda expressions: to shorten the code, and to avoid writing a new method/delegate for every different filter / sort / calculation var type (from C#3): can be only used inside methods; the type of the variable will be deducted by the compiler. We can use it if we do not care about the real type of the variable (The variable is NOT typeless! The variable is NOT dynamic!)

We have to instantly assign a value to a var typed variable, and from this point, the usage of the variable is the same (for us and for the Intellisense as well!) var x = 6; var z = new Student(); V 1.0 12 Language constructs Class initializer: if a class has a zero-parameter constructor: Student joe = new Student() { Credits = 23, Name = "Joe" }; Anonymous classes (when using temporary, small, data-oriented, single-usage classes) : var NameAgeAddress = new {

Name="Joe", Age=23, Address="Budapest Bcsi t 96/B" }; Best part: the intellisense will follow this as well! V 1.0 13 LINQ collections class Student { public string Name { get; set; } public int Credits { get; set; } public Student(string name, int credits) { Name = name; Credits = credits; } public override string ToString()

{ return Name + " - " + Credits; } } V 1.0 14 LINQ collections int[] arr1 = new int[] { 2, 4, 6, 8, 2, 1, 2, 3 }; int[] arr2 = new int[] { 1, 3, 5, 7, 1, 1, 2, 3 }; string[] arrStr = new string[] { "Bla", "Joln", "Bill", "Shakespeare", "Verne", "Jkai" }; List students = new List();

students.Add(new Student("Els Egon", 52)); students.Add(new Student("Msodik Miksa", 97)); students.Add(new Student("Harmadik Huba", 10)); students Add(new Student("Negyedik Nr", 89)); students.Add(new Student("tdik dn", 69)); V 1.0 15 LINQ Operators Set operators: Concat concatenation, Contains check for existance, Distinct filter repeated values, Intersect set intersection, Union set union, Except set difference Sort: OrderBy using an arbitrary order, Reverse reverse order Filter: Where Calculations (Aggregate methods): Average, Count, Max, Min,

Sum Grouping: GroupBy create groups using a common property In the examples, we use arrays/lists V 1.0 16 LINQ Operators 1. Sets Check for existence of an element: bool isInside=arr1.Contains(4); Concatenate (same elements are not filtered!): var output = arr1.Concat(arr2); Filter out repetitions (convert to set): var output = arr1.Distinct(); Intersection: var output = arr1.Intersect(arr2);

Union: var output = arr1.Union(arr2); Difference (elements in arr1 that are not in arr2) var output = arr1.Except(arr2); V 1.0 17 LINQ Operators 2. Reverse In this case, the input of the collection is int[] Even if we filter/reverse we know the output should be int[] Despite this, we CAN NOT use int[], because the LINQ methods are written as a general approach for all collections We use IEnumerable or simply var Can be converted: result.ToArray(); result.ToList(); var output = arr1.Reverse(); foreach (var akt in output)

{ Console.Write(akt + ", "); } Console.ReadLine(); 3, 2, 1, 2, 8, 6, 4, 2 V 1.0 18 LINQ Operators 3. Sort OrderBy The Lambda expression in the parameter must extract the (IComparable) key from a collection element (which will be used to sort the elements) We could also specify a self-made IComparer Int array, sort the data itself: var output = arr1.OrderBy(x => x);

String array, sort according to the length of the elements: var output = arrStr.OrderBy(x => x.Length); List of students, sort by names: var output = students.OrderBy(x => x.Name); V 1.0 19 LINQ Operators 4. Filter, Count Where / Count The lambda expression in the parameter must return a bool value The result of the Where is the collection where the lambda returns true. The result of the Count is an int The Count can be called without parameters full count Int array, odd numbers:

var output = arr1.Where(x => x % 2 == 1); String array, number of names with four letters: int num = arrStr.Count(x => x.Length == 4); V 1.0 20 LINQ Operators 5. Filter, property selection List of students, where the credits is a prime number: var output = students.Where(x => { if (x.Credits<=1) return false; for (int i = 2; i <= Math.Sqrt(x.Credits); i++) if (x.Credits % i == 0) return false;

return true; }); // Msodik Miksa - 97, Negyedik Nr - 89 Property selection / conversion: var nameList = students.Select(x => x.Name); V 1.0 21 LINQ Operators 6. Multiple List of students, the uppercase name of the ones with odd credits, operators sorted by the name, descending: var output = students.Where(x => x.Credits %2==1) .OrderBy(x => x.Name)

.Reverse() .Select(x => x.Name.ToUpper()); // or: OrderByDescending // TDIK DN, NEGYEDIK NR, MSODIK MIKSA Same result, same IL code (procedural vs declarative syntax): var output = from x in students where x.Credits % 2 == 1 orderby x.Name descending V 1.0 22 LINQ Operators 7. Aggregation Aggregate methods int mySum = arr1.Sum(); //28 double myAvg = arr2.Average(); //2.875 int sumEven = arr1.

Where(x => x % 2 == 0).Sum(); //24 int summOdd = arr1. Where(x => x % 2 == 1).Sum(); //4 The example above happens quite often: we have a Where filter for a flag, and then we execute the same operation for every flag values => execute same calculation for every group One where+calculation per group slow automatic calculation: GroupBy V 1.0 23 LINQ Opertorok 8. Group By Group by, according to parity: var myGroup = arr1.GroupBy(x => x % 2); foreach (var g in myGroup) {

Console.WriteLine(Remainder: " + g.Key + ", Number of elements: " + g.Count()); } var output = from x in arr1 group x by x%2 into g V 1.0 select new {Remainder=g.Key, Num=g.Count()}; 24 Web programming and advanced development techniques Layering

LINQ methods XML handling, XLINQ Exercise V 1.0 25 XML structure (w3schools.com) Everyday Italian Giada De Laurentiis 2005 30.00

Learning XML Erik T. Ray 2003 39.95 Hierarchical way to describe data XML declaration + nodes + attributes Nodes/tags: , = Attributes: In category= V 1.0 26 XML structure

Strict rules First line: optional format specification, with character encoding: Every node can have: Textual value Sub-nodes Attributes One root element must be specified that surrounds the whole document Every tag must be closed ( or ) The nesting of tags must be perfect Bad: Good: Capitalization matters V 1.0 27

XML structure attribute vs sub-node There is no rule, but use common sense when choosing between attributes or tags. This solution is well-formed, but not logical: Suggestion: attributes are quite rare, usually only id="0001", everything else goes into a sub-tag (attributes are hard to extend) V 1.0 28

XML rules Capitalization matters When defining attributes, quotation or apostrophes are required Use entities for special characters: Karakter < > & " V 1.0 Entity < > &

' " 29 XML + .NET XmlReader, XmlWriter Fast, using few memory One-way operation Complicated to create complex XML files XML transformation is HORRIBLE (replacing, exchanging nodes, changing nodes...) XmlDocument, XmlNode, XmlElement, Xml* Slow, uses a lot of memory (builds up the whole XML tree) Algorithms are not necessarily simple (easy for those who are familiar with DOM document operations) Useful for XML transformations

XML Serialization Fast, but very limited usage Strict document class rules V 1.0 30 X* classes Aim: Fast Clean design Support the standard XML tools (XQuery, XSLT) Replace XPath XDocument, XElement, XAttribute, XDeclaration, X* Very easy to create/read XML files in .NET System.Xml.Linq namespace Automatic string conversion (with tag names!)

We have to typecast after reading the Value property V 1.0 31 XElement The constructor is flexible (params keyword) almost any XML can be created with a single constructor call var xe = new XElement("person", "Joe"); Joe var xe2 = new XElement("person", new XElement("name", "Joe"), new XElement("age", 25)); Joe 25

V 1.0 32 XAttribute With constructor: var xe = new XElement("person", new XAttribute("id", 43984), new XElement("name", "Joe"), new XElement("age", 25)); After the XElement creation: var xe2 = new XElement("person", new XElement("name", "Joe"), new XElement("age", 25)); xe2.SetAttributeValue("id", 43984);

V 1.0 Joe 25 33 To save an XDocument XDocument outDoc = new XDocument( new XElement("people", new XElement("person", new XAttribute("id", 0), new XElement("name", "Joe"), new XElement("age", 22)), new XElement("person", new XAttribute("id", 1),

new XElement("name", "Quagmire"), new XElement("age", 34)))); outDoc.Save("people.xml"); Customizable: outDoc.WriteTo() + XmlWriter V 1.0 34 Simple data processing Joe 25 0618515133

.Element(name) .Attribute(name) .Elements(name) .Attributes(name) string name = xDoc.Element("people").Element("human") .Element("name").Value; int id = int.Parse(xDoc.Element("people").Element("human") .Attribute("id").Value); ... OR ... (typecasting works with attributes and elements too) int id = (int)(xDoc.Element("people").Element("human") .Attribute("id")); V 1.0 35

LINQ to XML X* classes: strong LINQ-support! A lot of methods return IEnumerable, T is usually XElement / XAttribute Pl. XElement xe2: xe2.Descendants() Every descendants (including sub-descendants) xe2.Descendants("note") Every descendants with a given tag name (including sub-descendants) xe2.Elements() Immediate descendants xe2.Elements("note") Immediate descendants with a given tag name

xe2.Attributes(), xe2.Ancestors() V 1.0 36 LINQ to XML Joe 25 0618515133 XDocument XDoc = ...

var q = from x in XDoc.Root.Descendants("person") where x.Element("name").Value.StartsWith("Jo") select x; V 1.0 37 Web programming and advanced development techniques Layering LINQ methods XML handling, XLINQ Exercise

V 1.0 38 Load XML XDocument inDoc = XDocument.Parse(stringWithFullXML); XDocument inDoc = XDocument.Load("Joe.xml"); XDocument XDoc = XDocument.Load ("http://users.nik.uni-obuda.hu/prog3/_data/people.xml"); V 1.0 39 Example List those who do not work in the building BA (We work with String data we always have to typecast to the good

type if this is not good)! Extra keyword: LET to define local variables for the LINQ query XDocument XDoc = XDocument.Load("http://users.nik.uni-obuda.hu/prog3/_ data/people.xml"); var q0 = from akt in XDoc.Descendants("person") let room=akt.Element("room").Value where !room.StartsWith("BA") select akt; foreach (var akt in q0) { Console.WriteLine(akt.ToString()); V 1.0 } 40 Exercise

The XElement class can be processed using the .Element() and .Attribute() methods... Using those, import the XML into a list! 1. Determine the number of workers who work in the AII department! 2. Display those who live in the third floor in a paginated list, we should press ENTER after every 15 elements 3. Who have the shortest or the longest names? 4. Determine the number of workers for every department! 5. Determine the biggest department! 6. List the workers for the biggest department! 7. List the people who work in the third biggest department ordered by their room number in descending order! V 1.0 41 2nd Exercise

http://users.nik.uni-obuda.hu/prog3/_data/war_of_westeros.xml V 1.0 42 2nd Exercise In the war of five kings 1. How many houses participated? 2. List the battles with the ambush type! 3. How many battles are there where the defending army won and there was a major capture? 4. How many battles were won by the Stark house? 5. Which battles had more than 2 participating houses? 6. Which are the 3 most violent regions? 7. Which one is the most violent region? 8. In the 3 most violent region, which battles had more than 2

participating houses? (Q5 join Q6) 9. List the houses ordered descending by the number of battles won! 10. Which battle had the biggest known army? 11. List the three commanders who attacked the most often! V 1.0 43 Sources

V 1.0 Lambda expressions: http://msdn.microsoft.com/en-us/library/bb397687.aspx Lambda expressions: http://geekswithblogs.net/michelotti/archive/2007/08/15/114702.aspx Why use Lambda expressions: http://stackoverflow.com/questions/167343/c-lambda-expressionwhy-should-i-use-this Recursive lambda expressions: http://blogs.msdn.com/b/madst/archive/2007/05/11/recursivelambda-expressions.aspx Standard query operators: http://msdn.microsoft.com/en-us/library/bb738551.aspx Linq introduction: http://msdn.microsoft.com/library/bb308959.aspx 101 Linq samples: http://msdn.microsoft.com/en-us/vcsharp/aa336746 Lambda: Reiter Istvn: C# jegyzet (http://devportal.hu/content/CSharpjegyzet.aspx) , 186-187. oldal

Linq: Reiter Istvn: C# jegyzet (http://devportal.hu/content/CSharpjegyzet.aspx) , 250-269. oldal Flp Dvid XLinq prezentcija Linq to XML in 5 minutes: http://www.hookedonlinq.com/LINQtoXML5MinuteOverview.ashx Access XML data using Linq: http://www.techrepublic.com/blog/programming-and-development/access-xml-data-using-linq-toxml/594 Simple XML parsing examples: http://omegacoder.com/?p=254 , http://gnaresh.wordpress.com/2010/04/08/linq-using-xdocument/ XML: Reiter Istvn: C# jegyzet (http://devportal.hu/content/CSharpjegyzet.aspx) , 224. oldal (A knyv az XMLReader/Writer, illetve az XmlDocument hasznlatt mutatja be) 44 V 1.0 45 V 1.0

46

Recently Viewed Presentations

  • Effect of Certain Agonists &amp; Antagonists on Isolated Guinea ...

    Effect of Certain Agonists & Antagonists on Isolated Guinea ...

    Effect of Certain Agonists & their Antagonists on Isolated Guinea-pig Ileum Guinea pig ileum is a smooth muscle receive dual nerve supply from autonomic nervous system (sympathetic and parasympathetic) . Parasympathetic tone is dominant in ileum which Ach cause contraction...
  • Second Sunday in Lent - Lectionary

    Second Sunday in Lent - Lectionary

    For those who want to save their life will lose it, and those who lose their life for my sake, and for the sake of the gospel, will save it. Mark 8:35
  • Acute asthma in emergency departments in France A multicenter ...

    Acute asthma in emergency departments in France A multicenter ...

    Caractéristiques au SAU N = 780 72 ans, H = 70% Tabac = 80%, BPCO connue = 84% FR = 26/ β2+ = 90% aux Urgences 10% sortis du SAU 11% admis en réa 7% de décès amélioration de la...
  • Phase Velocity & Group Velocity Sinusoidal waves  They

    Phase Velocity & Group Velocity Sinusoidal waves They

    Title: PowerPoint Presentation Author: S.P.Khastagir Last modified by: roycp Created Date: 11/2/2005 2:22:27 PM Document presentation format: On-screen Show (4:3)
  • Presentation for Directors

    Presentation for Directors

    Previously - Quality and Risk Profiles (QRPs) for acute hospitals. advanced statistical modelling. New model - Intelligent monitoring informs programme of inspections (Sept 2013) Clarity about indicators they will prioritise, rather than a model that claims to scan all information...
  • A Midsummer night&#x27;s dream

    A Midsummer night's dream

    A Midsummer night's dream. Today: Understanding Shakespeare. Understanding the interaction of the characters and how this advances the plot. Identify topics from the story and compare/contrast them to modern day media
  • Operationalizing an ARV/FDC Patent Pool Warren A. Kaplan,

    Operationalizing an ARV/FDC Patent Pool Warren A. Kaplan,

    Warren A. Kaplan, PhD, JD, MPH. Boston University School of Public Health. Assistant Professor of International Health. Boston, MA. Definition: the multiparty agreement between two or more patent owners by which their patents are licensed as a package to one...
  • Everyone is a reader. . . Some just

    Everyone is a reader. . . Some just

    Global Read Aloud. 2013. Geoff Herbach. Sharon M. Draper. Kate Messner. Eric Carle