Linq and XML for Microsoft Visual Basic Developer

Transcription

Linq and XML for Microsoft Visual Basic Developer
Multi targeting - .NET FX 2.0 / 3.0 / 3.5
Code Snippet
Funny Short cuts
자동완성 창 Transparency
Ctrl + Tab : Open 된 창 목록 Access / 바로 가기
Property
DebuggerDisplay
EditorBrowsable
Scenario
Build a large project (using background
compilation)
VB2008 takes
VB2008 is x
x% as much
times faster
VB2005 TimeVB2008 Time
time as
than VB2005
(ms)
(ms)
VB2005 (100%
(2005 time/
* 2008 time/
2008 time)
2005 time)
222206.25
1352.88
164.25
0.61%
Build a large multi-project solution (explicit build
1618604.75
operation)
57542.75
28.13
3.56%
Build a large multi-project solution (using
background compilation)
222925.50
19861.88
11.22
8.91%
327.00
36.50
8.96
11.16%
255551.25
38769.38
6.59
15.17%
1192.50
530.5
2.25
44.49%
Edit-and-Continue in a solution with xml
comments (first time)
441.25
210.5
2.10
47.71%
Responsiveness after changing a method
statement
390.25
236.38
1.65
60.57%
Responsiveness after adding a member to a
class
Responsiveness after opening a project
Invoke Intellisense to see a list of types (first
time)
Scenario
10 Steps in the debugger (subsequent times)
VB2008 takes
VB2008 is x
x% as much
times faster
VB2005 TimeVB2008 Time
time as
than VB2005
(ms)
(ms)
VB2005 (100%
(2005 time/
* 2008 time/
2008 time)
2005 time)
1850.75
1167.13
1.59
63.06%
79.25
51.5
1.54
64.98%
F5 when the solution is already built
(subsequent times)
385.20
278.7
1.38
72.35%
Item gets added to the Error List after making
an error
531.25
394.5
1.35
74.26%
10 Steps in the debugger (first time)
1336.50
1150
1.16
86.05%
Responsiveness while background compiling
on an open solution
4803.00
4284.75
1.12
89.21%
Load a large solution (subsequent times)
13667.5
12407.25
1.10
90.78%
19946.25
18222
1.09
91.36%
Invoke Intellisense to see a list of types
(subsequent times)
Load a large solution (first time)
(Note: This is the improvement on XP. Vista
has seen about twice as much improvement
for the Load Solution scenario than XP. )
Query expressions
XML literals
XML element access
Object initializers
Local type inference
Lambda expressions
Extension methods
Anonymous types
Relaxed delegates
Partial methods
Nullable types
Expression trees
암시적 타입 벾수선언
확장 메소드
람다식
객체 생성자
익명 타입
Nullable types
쿼리식
Dim x = 5
<Extension>
Sub Randomize(col As Collection)
Function(c) c.Name
New Point With { .x = 1, .y = 2 }
New With { c.Name, c.Phone }
Dim aVar as Integer?
From … Where … Select
Variable type 은 초기화를 통해 유추된다
Integer
String
Double
모든
타입들은
Object!
Dim x = 5
Dim s = "Hello"
Dim d = 1.0
Dim numbers = New Integer() {1, 2, 3}
Dim orders = new Dictionary(Of Integer, Order)()
기졲 타입들을 새로운 메서드로 확장
Namespace ArrayExtensions
Module IntArrExtensions
<Extension()> _
Function Sort(i As Integer()) As Integer()
…
obj.Foo(x, y)
End Function
Imports ArrayExtensions

XXX.Foo(obj, x, y)
<Extension()> _
DimReverseInPlace(ByRef
values() As Integer =i {5,
2, 1, 3}
Sub
As 4,
Integer())
Console.WriteLine(IntegerArrExtensions.ReverseInPlace(
_
…
IntegerArrExtensions.Sort(values))
End Sub
End Module
Dim values() As Integer = GetValues()
End Namespace
Console.WriteLine(values.Sort().ReverseInPlace())
Return _
Process.GetProcesses(). _
Where( Function(proc As Process) proc.Threads.Count > 10). _
Select( Function(proc As Process) _
New With { .Name = proc.ProcessName, _
.ThreadCount = proc.Threads.Count } )
Function _Filter1(proc As Process) As Boolean
Return proc.Threads.Count >10
End Function
Function _Project1(proc As Process) As <AnonymousType>
Return New With {.Name = proc.ProcessName, _
.ThreadCount = proc.Threads.Count }
End Function
Class ProcInfo
Public ProcessName As String
Public Count As Integer
End Class
What goes
here?
procs==__
Dim procs
Process.GetProcesses( )__
From proc In Process.GetProcesses()
New
proc.ProcessName,
ProcInfo With {proc.Threads.Count
.ProcessName = proc.ProcessName, _
Select ???
.Count =proc.Threads.Count }
결과 타입은?
Dim procs= _
From proc In Process.GetProcesses( ) _
객체 초기자로proc.Threads.Count
Select proc.ProcessName,
타입 선언을
생략한다
Dim procs= _
From proc In Process.GetProcesses(
)_
Anonymous
Select New With { .ProcessName
= proc.ProcessName, _
type
.Count = proc.Threads.Count
Class $Anonymous1
Public ProcessName As String
Public Count As Integer
End Class
Dim bytes = _
From Page In pages _
Select New $Anonymous1 With { .ProcessName = proc.ProcessName, _
.Count = proc.Threads.Count }
System.Nullable(Of T)
Value 타입에 Null 값을 허용시킨다
T 와 a Boolean으로 이뤄짂 Structure
Public Structure Nullable(Of T As Structure)
Integer
Private value As T
Private hasValue As Boolean
123
Public ReadOnly Property Value As T Value
…
End Property
Nullable(Of Integer)
123
???
Public ReadOnly Property HasValue As Boolean
…
End Property
True
False
End Structure
Non-null
Null
designer generated code 같은 스타읷
부가적읶 구현을 가능하도록 해 줌
선언에는 코드가 졲재하지 않음
Partial Class DataContainer
오직 구현될 경우에만 호출됨,
그렇지 않을 경우에는 유효하지
Private Partial Sub OnValueChange(value
않음 As String)
End Sub
Public Sub ChangeValue(newValue As String)
Me.OnValueChange(newValue)
Me._value = newValue
End Sub
End Class
Partial Class DataContainer
Private Sub OnValueChanged(value As String)
„ Code to react to value changing
End Sub
End Class
사용자는 부가적읶 구현
코드를 제공한다
“난 개읶적으로 Visual Basic이 Object-Oriented
언어들 보다 프로그래밍적으로 우수하다고
생각한다. 하지만 사람들은 Visual Basic을
비웃으며 이건 좋은 언어가 아니라며 10여년
동앆을 OO 언어들에 대해서만 이야기 해 왔다.
Visual Basic이 훌륭한 언어는 아니였다. 하지만
Visual Basic 이 가짂 DB Interfacing의 용이함은
Object Oriented 자체 보다 근본적으로 중요한
것이라 생각한다”
데이터 쿼리의 갂결화
쿼리와 데이터 벾경작업의 통합
객체, RDB, XML 데이터의 통합
XML 작업의 단순화
스키마와 관계없이 XML 구조 파악
XML 문서를 빠르게 생성
XML 구성요소들에 대한 쉬운 접근
XML is first citizen in VB.net !
Language-INtegrated Query (LINQ)
언어적 특징들(LINQ to Objects)
LINQ to Data
LINQ to DataSet
LINQ to SQL
LINQ to Entities
LINQ to XML 과 XML 통합
Visual Basic
Others…
C#
.NET Language-Integrated Query
LINQ enabled data sources
LINQ-enabled ADO.NET
LINQ
To Objects
LINQ
To Datasets
LINQ
To
SQL
LINQ
To Entities
LINQ
To XML
<book>
<title/>
<author/>
<price/>
</book>
Objects
Relational
XML
Dim 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 > 10
End 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
Filter
Select <expr>
Where <expr>, Distinct
Test
Any(<expr>), All(<expr>)
Join
<expr> Join <expr> On <expr> Equals <expr>
Group
Group By <expr>, <expr> Into <expr>, <expr>
Group Join <decl> On <expr> Equals <expr>
` Into <expr>
Aggregat
e
Count([<expr>]), Sum(<expr>), Min(<expr>),
Max(<expr>), Avg(<expr>)
Partition
Skip [ While ] <expr>, Take [ While ] <expr>
Set
Order
Union, Intersect, Except
Order By <expr>, <expr> [ Ascending | Descending ]
Dim custs() As Customer = SampleData.GetCustomers()
Dim q = From c In custs Where c.State = "WA“ Select c.City
Dim q = custs.Where(Function(c) c.State = “WA”).Select(Function(c) c.City)
Dim names() As String = q.ToArray()
custs
ID
Name
names
Phone
Where
Function(c) c.State= “WA”
Select
Function(c) c.City
오늘날의 쿼리 및 데이터 액세스
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 While
r.Close()
따옴표로 쿼리
만들기
Loosely bound
arguments
Loosely typed
result sets
컴파읷 할 때
체크할 수 없음
LINQ 로 데이터 액세스
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
각 테이블은
컬렉션으로
From 이 Select 보다 앞선다
읶텔리센스가
가능해짂다
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
가능
Dim aCustomers = _
From cust In customers _
Where cust.Name.StartsWith(“A”) _
Select cust.Name, cust.City
조작은 줄 단위로
이뤄짂다
명시적읶 Aggregation
Grouping key
명시적읶
aggregation
Dim customers = _
From o In Orders _
Group By o.CustomerID _
Into OrderTotal = Sum(o.Amount * o.Price) _
Select CustomerID, OrderTotal
계층형 데이터를 위해 연산자를그룹이
포함한다
이미
졲재
Dim procs= _
From proc In System.Diagnostics.Process.GetProcesses( ) _
Aggregate thread In proc.Threads _
Into AvgThreadPriority = Average(thread.CurrentPriority) _
Select Name = proc.ProcessName, AvgThreadPriority
명령형 모델
Dim doc As New XmlDocument()
Dim contacts As XMLElement = doc.CreateElement("contacts") Document
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) <contacts>
집중됨
End If
<contact>
Next
<name>Great Lakes Food</name>
<phone>(503) 555-7123</phone>
doc.AppendChild(contacts)
</contact>
…
</contacts>
선언형 모델
Dim contacts As New XElement("contacts", _
From cust in customers _
Where cust.Country = "USA“ _
Element 중심적
Select New XElement("contact", _
New XElement("name", cust.CompanyName), _
New XElement("phone", cust.Phone) _
)
)
통합된 쿼리
작고 가벼움
Only VB!!
Xml.Linq 의
Xelement로
유추됨
Dim contacts = _
<contacts>
<%= _
직관적
From cust In customers _
Where cust.Country = "USA" _
Select <contact>
<name><%= cust.CompanyName %></name>
<phone><%= cust.Phone %></phone>
</contact> _
%>
</contacts>
연산 결과를 채워
넣을 수 있는 공갂
객체 생성을 단순화
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)))
모든 Element XML 구성 요소들에 쉽게 접근한다
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)
Attributes
Descendents
Elements
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)
XML 을 위한 Language integrated query(Linq)
XPath/XQuery 에서 사용되는 강력한 구문
Visual Basic as programming language!
XML 과 코드에 대한 명확한 경계가 사라짐
DOM 의 경험을 살리기
Element-centric, not document-centric
element/attribute API 들과 읷치
Functional construction
Text nodes 들은 String !
Simplified XML namespace support
Faster and smaller than DOM
OOP에 대한 이해 부족
코드 부재로 읶한 개발 생산성 저하
리소스 부재?
소스벾홖
컴포넌트 재홗용
Fusion
재 개발
PrintForm, Printer Compatibility Library
Line and Shape Controls
Interop Forms Toolkit 1.0 & 2.0
2.0 includes MDI & user controls
업그레이드 젂략 – Interop을 통한 단계적 Upgrade
Form 단위로 젂홖, 위험을 줄읶다
기졲 개발된 어플리케이션들을 VB.net 으로 확장한다
Microsoft Interop Forms Toolkit (v2.0)
업그레이드를 이용하게 해 주는 가이드, 도구, 코드 제공
코드 벾홖기가 아님!!
VB6 Application
VB6
Form(s)
Interop
(COM)
VB.NET
Form(s)

Similar documents

Altevo FS4500/FS4100

Altevo FS4500/FS4100 공간지원, 랙마운트(Rackmount) 또는 페데스탈(Pedestal) 랙마운트(Rackmount) 또는 페데스탈(Pedestal)구성 구성 --각 각드라이브의 드라이브의듀얼 듀얼포트 포트엑세스를 엑세스를위해 위해독립적으로 독립적으로 고안된 Mutliplexor Technology 고안된 Mutliplexor Technology --직관적 직관적및 및...

More information

Windows Registry Artifacts - Kevin`s Attic for Security Research

Windows Registry Artifacts - Kevin`s Attic for Security Research • What is registry?  광활한 Microsoft Windows 운영체제 정보 저장소  운영체제와 프로그램 구성 데이터의 계층형 데이터베이스 (Hierarchical Database in binary)  Drawbacks: 단일 실패점 (SPoF, Single Point of Failure)

More information

Mobile RFID Technologies and Standards

Mobile RFID Technologies and Standards – BREW, J2ME, WIPI 등과 같은 다양한 platform이 존재하므로 ISO/IEC 29179에서는 추상화된 API만을 정의함 – 구현 수준의 API는 각 platform에서 별도로 정의해야 함 • 국내에는 이를 위해 WIPI APIs가 정의되어 있음

More information