Paul Yuknewicz paulyuk@microsoft.com Lead Program Manager Microsoft Visual Basic DEV 319

Preview:

Citation preview

LINQ and XML for the Microsoft Visual Basic DeveloperPaul Yuknewiczpaulyuk@microsoft.comLead Program ManagerMicrosoft Visual Basic

DEV 319

Linus Torvalds on Visual Basic“For example, I personally believe that

Visual Basic did more for programming than “Object-Oriented Languages” did. Yet people laugh at Visual Basic and say it’s a bad language, and they’ve been talking about OO languages for decades.

And no, Visual Basic wasn’t a great language, but I think the easy DB interfaces in Visual Basic were fundamentally more important than object orientation is, for example.”

Aaron Finkelstein
SPEAKER: Yes, I know he used "VB" in the original quote but I can't...

Microsoft Visual Basic 9.0

Simplify querying dataIntegrate query and transform operationsUnify query of object, relational, and XML data

Simplify working with XMLImpose structure on XML w/no schemaProduce XML documents quicklyAccess XML members easily

Visual Basic 9.0 Overview

Language-INtegrated Query (LINQ)Language Features (through LINQ to Objects) LINQ to Relational Data

LINQ to DataSetLINQ to SQLLINQ to Entities

LINQ to XML and XML Integration

… and of course lots of demos!

Language-Integrated Query

LINQ enabled data sources

LINQTo

Objects

Objects

LINQTo XML

<book> <title/> <author/> <price/></book>

XML

LINQ-enabled ADO.NET

LINQTo

Datasets

LINQTo

SQL

LINQTo

Entities

Relational

Others…Visual Basic C#

.NET Language-Integrated Query

Language-Integrated Query

demo

Query ExpressionsDim highThreadProcs = _ From proc In Process.GetProcesses _ Where proc.Threads.Count > 10 _ Select proc.ProcessName, proc.Threads.Count

Dim highThreadProcs = Process.GetProcesses(). _ Where(Function(proc As Process) proc.Threads.Count > 10). _ Select (Function(proc As Process) _

New With {.ProcessName = proc.ProcessName _

.Count = proc.Threads.Count)Function _Filter1(proc As Process) As Boolean Return proc.Threads.Count > 10End Function

Function _Projection1(proc As Process) As <Anonymous Type> Dim projection As New <AnonymousType> projection.ProcessName = proc.ProcessName projection.Count = proc.Threads.Count Return projection End Function

Project Select <expr>

Filter Where <expr>, Distinct

Test Any(<expr>), All(<expr>)

Join <expr> Join <expr> On <expr> Equals <expr>

GroupGroup By <expr>, <expr> Into <expr>, <expr>Group Join <decl> On <expr> Equals <expr>` Into <expr>

Aggregate

Count([<expr>]), Sum(<expr>), Min(<expr>), Max(<expr>), Avg(<expr>)

Partition Skip [ While ] <expr>, Take [ While ] <expr>

Set Union, Intersect, Except

Order Order By <expr>, <expr> [ Ascending | Descending ]

Query Expressions

Querying Relational Data

Dim c As New SqlConnection(…)c.Open()Dim cmd As SqlCommand( _ "SELECT c.Name, c.Phone “ & _ "FROM Customers c” & _ "WHERE c.City = @p0")cmd.Parameters("@p0“) = "London"Dim dr As DataReader= c.Execute(cmd)While (dr.Read()) Dim name As String = r.GetString(0) Dim phone As String= r.GetString(1) Dim date As DateTime = r.GetDateTime(2)End Whiler.Close()

Accessing data today

Queries in quotes

Loosely bound

arguments

Loosely typed result sets

No compile time checks

Public Class Customer …

Public Class Northwind Inherits DataContext

Public Property Customers As Table(Of Customer)

…End Class

Dim db As New Northwind(…)Dim contacts = _ From cust in db.Customers _ Where cust.City = "London" Select cust.Name, cust.Phone

For Each custInfo in contacts ColdCall(custInfo.Name, custInfo.Phone)Next

Querying Relational DataAccessing data with LINQ

Classes describe data

Strongly typed

connection

Integrated query syntax

Strongly typed results

Tables are like collections

Linq for Relational Data

demo

Not Your Father’s SQL…

From before Select

Fully composable

Dim customers = _ From cust In db.Customers _ Select cust.Name, cust.City, cust.State, cust.ZIP

Dim customers = _ From cust In db.Customers _ Select cust.Name, cust.City, cust.State, cust.ZIP _ Order By ZIP _ Select Name, City, State

Operations are “built up” line-by-line and…

Enables good IntelliSense

Dim aCustomers = _ From cust In customers _ Where cust.Name.StartsWith(“A”) _ Select cust.Name, cust.City

…across statements

Not Your Father’s SQL…

Aggregation is explicit

Dim customers = _ From o In Orders _ Group By o.CustomerID _ Into OrderTotal = Sum(o.Amount * o.Price) _ Select CustomerID, OrderTotal

Grouping key Explicit aggregation

Includes operators for hierarchical data

Dim procs= _ From proc In System.Diagnostics.Process.GetProcesses( ) _ Aggregate thread In proc.Threads _ Into AvgThreadPriority = Average(thread.CurrentPriority) _ Select Name = proc.ProcessName, AvgThreadPriority

Group already exists

Programming XML Today

Dim doc As New XmlDocument()Dim contacts As XMLElement = doc.CreateElement("contacts")For Each Dim c in Customers If (c.Country = "USA") Dim e As XMLElement = doc.CreateElement("contact") Dim name As XMLElement = doc.CreateElement("name") name.InnerText = c.CompanyName e.AppendChild(name) Dim phone As XMLElement = doc.CreateElement("phone") phone.InnerText = c.Phone e.AppendChild(phone) contacts.AppendChild(e) End IfNextdoc.AppendChild(contacts)

<contacts> <contact> <name>Great Lakes Food</name> <phone>(503) 555-7123</phone> </contact> …</contacts>

Imperative model

Document-centric

No integrated queries

Memory-intensive

LINQ to XML

Dim contacts As New XElement("contacts", _ From cust in customers _ Where cust.Country = "USA“ _ Select New XElement("contact", _ New XElement("name", cust.CompanyName), _ New XElement("phone", cust.Phone) _ ))

Declarative model

Element-centric

Integrated queries

Smaller and faster

Integrated XML in Visual Basic

Dim contacts = _ <contacts> <%= _ From cust In customers _ Where cust.Country = "USA" _ Select <contact> <name><%= cust.CompanyName %></name> <phone><%= cust.Phone %></phone> </contact> _ %> </contacts>

Infers Xml.Linq XElement

No conceptual

barrier

Expression holes for computed

values

Linq to XML

demo

XML Literals

Shorthand for object creation

Dim emp = _ <employee> <name>Joe</name> <age>28</age> <department id="432"> <deptname>Engineering</deptname> </department> </employee>

Dim emp = _ New XElement("employee", _ New XElement("name", "Joe"), _ New XElement("age", 28), _ New XElement("department", _ New XElement("name", "Engineering"), _ New XAttribute("id", 432)))

XML Element Access

Element access covers all XML axes

Dim employees As XElement = GetCurrentEmployeesByDept(“IT”)Dim deptID As Integer = CInt(employees.Attribute(“DeptID"))Dim emp As XElement = First(employees.Descendents(“Employee"))Dim empDOB As Date = CDate(item.Element(“DateOfBirth“).Value)Dim employees As XElement = GetCurrentEmployeesByDept(“IT”)Dim deptID As Integer = CInt(employees.@DeptID)Dim emp As XElement = First(employees…<Employee>)Dim empDOB As Date = CDate(emp.<DateOfBirth>.Value)

Attributes

DescendentsElements

LINQ to XML

Language integrated query for XMLExpressive power of XPath/XQueryBut with Visual Basic as programming languageNo conceptual barrier between XML and code

Leverages experience with DOMElement-centric, not document-centricSymmetry in element/attribute APIsFunctional constructionText nodes are just stringsSimplified XML namespace supportFaster and smaller than DOM

Visual Basic 9.0 Features

Query expressionsXML literalsXML element accessNullable typesObject initializersLocal type inferenceLambda expressions

Extension methodsExpression treesAnonymous typesTernary operatorCoalesce operatorRelaxed delegatesPartial methods

…and many other bug fixes and small features!

Related Sessions, HOLs, etc.

DEV318 - Strategies for Moving Your Microsoft Visual Basic 6 Investments to .NET

    14/08/2007 10:45 AM - 12:00 PM 

DEV319 - LINQ and XML for the Microsoft Visual Basic Developer

    14/08/2007 2:20 PM - 3:35 PM 

DEV317 - Microsoft Visual Basic: Tips and Tricks for the Microsoft Visual Studio 2008 IDE

    15/08/2007 9:00 AM - 10:15 AM 

Resources

VB Team Bloghttp://blogs.msdn.com/vbteam

Visual C# Developer Centerhttp://msdn2.microsoft.com/en-us/vcsharp/default.aspx

Visual Studio Orcas Beta2 Download Pagehttp://msdn2.microsoft.com/en-us/vstudio/aa700831.aspx

Visual Basic Developer Center & Contenthttp://msdn.com/vbasic

Evaluation Forms

Questions?

© 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.

The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after

the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.

Recommended