1
Java vs. .Net
Livslang UddannelseAugust 20th, 2004
Bent ThomsenPhD, DIC, Cand.Scient, EurIng, CEng, FBCS, MACM, MIEEE
[email protected] of Computer Science
Aalborg University
2
What is Microsoft .Net?
• It is a vision– The platform for the digital future– ‘.NET is Microsoft’s platform for a new computing model
built around XML Web Services’Microsoft Corporation Annual Report, 2001
• It is a brand name– Applied to many things
• It is a set of products and technologies– Infrastructure– Tools– Servers– Services
• .Net is Microsoft’s core business Strategy
3
A Unified Programming Model
Windows API
.NET Framework
Consistent API availability regardless oflanguage and programming model
ASP
Stateless,code embeddedin HTML pages
MFC/ATL
Subclassing,Power and
Expressiveness
VB Object Model
RAD,Composition and
Delegation
4
.NET Technologies
• The .NET Framework– The CLR with support for XML Web services and more
– Supporting Visual Basic.NET, C#, C++, and more
• The .Net development tools– Visual Studio.Net
• The .NET Enterprise Servers– BizTalk Server 2003, SQL Server 2003, Commerce Server 2003 and
more
• The .Net Services– Passport, My Services, bCentral, expedia and more
5
Microsoft .NET
Web services support across the Microsoft platform Web services support across the Microsoft platform
To
ols
To
ols
ClientsClients
ServicesServices
ServersServers
Ex
pe
rien
ces
E
xp
erie
nce
s
& S
olu
tion
s&
So
lutio
ns
6
The Core of .NET Framework: FCL & CLR
• Common Language Runtime– Garbage collection
– Language integration
– Multiple versioning support (no more DLL hell!)
– Integrated security
• Framework Class Library– Provides the core functionality:
ASP.NET, Web Services, ADO.NET, Windows Forms, IO, XML, etc.
7
.NET Framework Common Language Runtime
Operating SystemOperating System
Common Language RuntimeCommon Language Runtime
– CLR manages code execution at runtime
– Memory management
• Kills entire classes of bugs (e.g., memory corruption, ref counting)
– Thread management, etc.
– Auto-versioning, no more DLL Hell
8
.NET Framework Base Class Library
Operating SystemOperating System
Common Language RuntimeCommon Language Runtime
.NET Framework (Base Class Library).NET Framework (Base Class Library)
– Object-oriented collection of reusable types
– Collections, I/O, Strings, …
9
.NET Framework Data Access Layer
Operating SystemOperating System
Common Language RuntimeCommon Language Runtime
.NET Framework (Base Class Library).NET Framework (Base Class Library)
ADO .NET and XMLADO .NET and XML
– Access relational databases
– Disconnected data model
– Work with XML
10
.NET Framework ASP.NET & Windows Forms
Operating SystemOperating System
Common Language RuntimeCommon Language Runtime
.NET Framework (Base Class Library).NET Framework (Base Class Library)
ADO .NET and XMLADO .NET and XML
ASP .NETASP .NETWeb Forms Web ServicesWeb Forms Web Services
Mobile Internet ToolkitMobile Internet Toolkit
WindowsWindowsFormsForms
– Create application’s front-end – Web-based user interface, Windows GUI, Web services, …
11
.NET FrameworkSystem.WebSystem.Web System.Windows.FormsSystem.Windows.Forms
System.DrawingSystem.Drawing
System.XMLSystem.XMLSystem.DataSystem.Data
SystemSystem
ServicesDescriptionDiscoveryProtocols
UIHTML ControlsWeb Controls
Security
Session StateConfiguration
Cache
SQL Client
SQL ServerCEDesign
ADO.NET
IO
Net
Collections
Security
Reflection
Resources
Text
Globalization
Configuration
Service Process
Diagnostics
Threading
RuntimeInterop ServicesRemotingSerialization
Design
Drawing 2D
Imaging
XML Document
Xslt/XPath
Serialization
Reader/Writers
Printing
Text
Component Model
12
.NET Framework Programming Languages
Operating SystemOperating System
Common Language RuntimeCommon Language Runtime
.NET Framework (Base Class Library).NET Framework (Base Class Library)
ADO .NET and XMLADO .NET and XML
ASP .NETASP .NETWeb Forms Web ServicesWeb Forms Web Services
Mobile Internet ToolkitMobile Internet Toolkit
WindowsWindowsFormsForms
C++C++ C#C# VB.NETVB.NET PerlPerl J#J# ……
– Use your favorite language
13
.NET Framework Common Language Specification
Operating SystemOperating System
Common Language RuntimeCommon Language Runtime
.NET Framework (Base Class Library).NET Framework (Base Class Library)
ADO .NET and XMLADO .NET and XML
ASP .NETASP .NETWeb Forms Web ServicesWeb Forms Web Services
Mobile Internet ToolkitMobile Internet Toolkit
WindowsWindowsFormsForms
Common Language SpecificationCommon Language SpecificationC++C++ C#C# VBVB PerlPerl J#J# ……
14
Common Type System (CTS)
• All .NET languages have the same primitive data types. An int in C# is the same as an int in VB.NET, COBOL.Net, Haskell, …
• When communicating between modules written in any .NET language, the types are guaranteed to be compatible on the binary level
• Types can be:– Value types – passed by value, stored in the stack– Reference types – passed by reference, stored in the heap
• Strings are a primitive data type now
15
Common Language Specification (CLS)
• Any language that conforms to the CLS is a .NET language
• A language that conforms to the CLS has the ability to take full advantage of the Framework Class Library (FCL)
• CLS is standardized by ECMA
16
.NET Languages
• Languages provided by Microsoft– C++, C#, J#, VB.NET, JScript
• Third-parties languages– Perl, Python, Pascal, APL, COBOL, Eiffel, Haskell, ML,
Oberon, Scheme, Smalltalk…
• Advanced multi-language features– Cross-language inheritance and exceptions handling
• Object system is built in, not bolted on– No additional rules or API to learn
• All compile to .Net Assemblies– Contains MSIL and metadata
17
Intermediate Language
• .NET languages are compiled to an Intermediate Language (IL)
• IL is also known as MSIL or CIL• CLR compiles IL in just-in-time (JIT) manner –
each function is compiled just before execution• The JIT code stays in memory for subsequent
calls• Recompilations of assemblies are also possible
18
Example of MSIL Code
.method private hidebysig static void Main() cil managed
{ .entrypoint // Code size 11 (0xb) .maxstack 8 IL_0000: ldstr "Hello, world!" IL_0005: call void
[mscorlib]System.Console::WriteLine(string) IL_000a: ret} // end of method HelloWorld::Main
19
Source CodeSource Code
C++, C#, VB or C++, C#, VB or any .NET any .NET languagelanguage
csc.exe or vbc.execsc.exe or vbc.exeCompilerCompiler
AssemblyAssembly
DLL or EXEDLL or EXE
.Net AssembliesCompilation
20
VBVBSource Source codecode
CompilerCompiler
C++C++C#C#
CompilerCompilerCompilerCompiler
Operating System ServicesOperating System Services
Common Language RuntimeCommon Language Runtime
JIT CompilerJIT Compiler
Native CodeNative Code
ManagedManagedcodecode
AssemblyAssemblyIL CodeIL Code
AssemblyAssemblyIL CodeIL Code
AssemblyAssemblyIL CodeIL Code
.Net Execution ModelCommon Language Runtime
21
Managed Code Execution
PEVerifyPEVerify
NGENNGEN
DEPLOYMENTDEPLOYMENT
GAC, GAC, app. directory, app. directory,
download cachedownload cache
GAC, GAC, app. directory, app. directory,
download cachedownload cache
public static void Main(String[] args ){ String usr; FileStream f; StreamWriter w; try { usr=Environment.GetEnvironmentVariable("USERNAME"); f=new FileStream(“C:\\test.txt",FileMode.Create); w=new StreamWriter(f); w.WriteLine(usr); w.Close(); } catch (Exception e){ Console.WriteLine("Exception:"+e.ToString()); }} CompilerCompiler
DEVELOPMENTDEVELOPMENT
public static void Main(String[] args ){ String usr; FileStream f; StreamWriter w; try { usr=Environment.GetEnvironmentVariable("USERNAME"); f=new FileStream(“C:\\test.txt",FileMode.Create); w=new StreamWriter(f); w.WriteLine(usr); w.Close(); } catch (Exception e){ Console.WriteLine("Exception:"+e.ToString()); }}
Source codeSource code AssemblyAssemblyPE header + MSIL + PE header + MSIL + Metadata + EH TableMetadata + EH Table
AssemblyAssemblyPE header + MSIL + PE header + MSIL + Metadata + EH TableMetadata + EH Table
EXECUTIONEXECUTIONAssembly infoAssembly info
Module Module + Class list+ Class list
Assembly infoAssembly infoModule Module
+ Class list+ Class listPolicy Policy
ManagerManager
HostHost
Policy<?xml version="1.0" encoding="utf-8" ?><configuration> <mscorlib> <security> <policy> <PolicyLevel version="1"> <CodeGroup class="UnionCodeGroup" version="1" PermissionSetName="Nothing" Name="All_Code" Description="Code group grants no permissions and forms the root of the code group tree."> <IMembershipCondition class="AllMembershipCondition" version="1"/> <CodeGroup class="UnionCodeGroup" version="1" PermissionSetName="FullTrust"
ClassClassLoaderLoader
Granted Granted permissionspermissions
Granted Granted permissionspermissions
Vtable +Vtable +Class infoClass infoVtable +Vtable +
Class infoClass infoJIT +JIT +
verificationverificationNative codeNative code+ GC table+ GC table
Native codeNative code+ GC table+ GC table
CLR ServicesCLR ServicesGCGCExceptionExceptionClass initClass initSecuritySecurity
(assembly
(assembly))
((classclass))
((methodmethod))
AssemblyAssemblyLoaderLoader
EvidenceEvidence
Permission requestPermission request
22
.NET Security
• Role-based Security– What the user is allowed to do within the application
– .NET Roles = Windows Active Directory® groups
• Code Access Security– What the code is allowed to do on this machine
– Evidence Based (Policies, Permissions, Evidence)
• Cryptography Built In to .NET FX
23
Visual Basic .NET
• Evolution, not revolution, of language used by developers worldwide
• Builds on existing technology while adding power– True OOP
– Multithreading
– NT Services
– Web Services
• The fastest way to build scalable applications for industry
24
Visual J# .NET
• Native support for XML Web services • Fully integrated with Visual Studio .NET
development environment• Full access to the .NET Framework
– ASP.NET, ADO.NET, Windows Forms
– Integration with >20 other languages
• Protection of existing investments– Use java language syntax on .NET
– Move applications and skills forward
25
Visual C++ .NETContinue to provide most powerful
and flexible language
• Better ANSI/ISO conformance
• Enable seamless, incremental use of .NET Framework
• Enhanced ATL Servers
• Improved ATL and MFC Clients
• Enhanced STL
26
Visual C# .NET Component Oriented Language
• C# is the first “component oriented” language in the C/C++ family
• Component concepts are first class:– Properties, methods, events
– Design-time and run-time attributes
– Integrated documentation using XML
• Enables one-stop programming– No header files, IDL, etc.
– C++ heritage – simplification with no unnecessary sacrifices
• If you are serious about .Net you need to learn C#
27
C#
• Hello world
using System;
class HelloWorld { public static void Main() { Console.WriteLine(“Hello World!"); }}
>csc HelloWorld.cs>Hello World!
28
C#
• Properties
public class button { private string caption;
public string Caption { get { return caption; } set { if (value != null) caption = value; } }}
button b = new button();
b.Caption = “abc”string s = b.Caption;
29
C#
• Parameter Passing
By Value
public static void Swap(ref int x, ref int y) { int z = x; x = y; y = z;}
By Reference
30
C#
• Pointers– Not recommended for use
public struct Node { public int value; public unsafe Node* next;}
public unsafe class A { . . .
public class A { public unsafe void B (char *p) { . . .
31
C#
• Boxing / Unboxing– Allows value types to be converted to and from objects automatically
ArrayList list = new ArrayList();int z = 100;
list.Add(1); list.Add(13.12); list.Add(z); //integers are automatically boxed //when they are added to the list
32
C#
• Versioning– C# requires developers to clearly state their intent
• Use of the keyword ‘new’ and ‘override’
Class Derived B { new public void x () { . . .
Class Derived B { public override void x () { . . .
33
C# 2.0 Language Enhancements
• Generics• Anonymous methods• Iterators• Partial types
34
Generics
public class Listpublic class List<<TT>> {{ private private TT[] elements;[] elements; private int count;private int count;
public void Add(public void Add(TT element) { element) { if (count == elements.Length) if (count == elements.Length) Resize(count * 2);Resize(count * 2); elements[count++] = element;elements[count++] = element; }}
public public TT this[int index] { this[int index] { get { return elements[index]; }get { return elements[index]; } set { elements[index] = value; }set { elements[index] = value; } }}
public int Count {public int Count { get { return count; }get { return count; } }}}}
ListList<int><int> intList = new List intList = new List<int><int>();();
intList.Add(1);intList.Add(1); // No boxing// No boxingintList.Add(2);intList.Add(2); // No boxing// No boxingintList.Add("Three");intList.Add("Three"); // Compile-time // Compile-time errorerror
int i = intList[0];int i = intList[0]; // No cast required// No cast required
35
Visual Studio .NET
• Development tool that contains a rich set of productivity and debugging features– Supports managed and unmanaged applications– Supports C#, C++, VB.NET, …– Many useful tools and wizards– Windows Forms Designer– ASP.NET Web Forms Designer– Web Services support– SQL Server integration with ADO.NET and XML
• VS.NET is not part of the .NET Framework– Not necessary to build or run managed code– The .NET Framework SDK includes command line compilers
36
VS.NET – Single Development Environment
• From Visual Studio.NET you can:– Write code
– Design user interface
– Study documentation
– Debug
– Test
– Deploy
• Same tools for all languages• Same tools for all platforms
37
Visual Studio .NET
38
Referencing the Framework
39
.NET Applications
• Web Form – Next Generation ASP Page• Win Form – Next Generation Win32 App• Web Services – Key to Interoperability• Others –
– Server Objects
– Console Applications
– Window Services
– Mobile Clients
– Many more…
40
ASP.NET
• Server-side Web Forms and Web Services components separate code from content– Developer productivity increases– Tools easily use ASP.NET– Any programming language: full VB, JScript, C++, COBOL, Perl,
etc.– 40% to 70% reduction in lines of code
• Compiled• No-touch deployment system• Intelligent state management• Backwards compatible with ASP• Controls sense client and adapt output: HTML, DHTML,
WML
41
What Is an XML Web Service?
• A Component That Uses XML & HTTP To Define and Deliver A Service– Global reach
– Based on open set of standards
– Reuse across platforms
– Works with any operating system, programming language, or network
– Expose legacy code
• Different systems can actually talk
42
Web ServicesOpen Standards & Protocols
• XML– Universal data format
– Standards-based integration
– User-customizable
• HTTP– Ubiquitous protocol
– Universally understood
43
VS.NET and Web Services
• Expose functionality as service– No need to learn XML, SOAP, or WSDL
– Interface is automatically generated
– Seamless deployment
• Reuse existing Web Services– VS.NET generates the plumbing
– Full IntelliSense support
• Build and consume with any VS language
44
• Built-in Support for Developing and Consuming Web Services– Based entirely on open standards
– Automatically generates WSDL
– Automatically provides test page
– Attribute based – No heavy coding needed
Software as a ServiceVisual Studio .Net and the Net Framework
Public Function HelloWorld() as String
return “Hello World”
End Function
[WebMethod]WSDLWSDL
WebServiceObject
WebServiceObject
TestPage
TestPage
Compiler
45
Windows Forms
• Rich, powerful client UI– Control anchoring, visual inheritance
– Shared across all .NET languages
– No-touch deployment
• Secure– Semi-trusted browser component
– Fully-trusted local application
• Full Web Service integration
46
.Net on other Platforms
• .Net Compact Framework– PocketPC, XScale, ARM, …
• SSCLI– BSD Unix, Mac OS X
• Mono– Linux
47
.Net CF
• Target mobile and embedded devices• Portable subset of .NET Framework
– No new ‘compact’ namespaces– Visual Basic .NET and C# compiler
support in v1• Leverage Visual Studio .NET
– Run managed .EXEs and .DLLs directly– Debug with Visual Studio .NET
• Peacefully co-exist with host OS– Run on native threads, P/Invoke to call native code
Execution Engine Commonalities
• Verifiable type safe execution– No uninitialized variables, unsafe casts, bad array indexing,
bad pointer math• Garbage Collection
– No ref-counting, no leaks• JIT compilation• Error handling with exceptions• Common type system
– Call, inherit, and source-level debug across different languages
Execution Engine Differences
• No ASP.NET• COM Interop
– Good support for calling native DLLs• • P/Invoke – PlatformInvoke enables calls to Win32
DLLs– Support for calling COM objects using dll wrappers– No support for writing COM/ActiveX objects– No Install-time JIT (nGen)
• No Reflection Emit• No Remoting
– Client web services is fully supported• No Generic Serialization
– Datasets can be serialized to XML– No binary Serialization
50
Other Differences
• Class libraries are a subset (about 25%)
• Different size and scalability characteristics• Compact Additions
– IrDA support
– SQL Server CE managed classes
– Device-specific controls
51
.NET FrameworkSystem.WebSystem.Web System.Windows.FormsSystem.Windows.Forms
System.DrawingSystem.Drawing
System.XMLSystem.XMLSystem.DataSystem.Data
SystemSystem
ServicesDescriptionDiscoveryProtocols
UIHTML ControlsWeb Controls
Security
Session StateConfiguration
Cache
SQL Client
SQL ServerCEDesign
ADO.NET
IO
Net
Collections
Security
Reflection
Resources
Text
Globalization
Configuration
Service Process
Diagnostics
Threading
RuntimeInterop ServicesRemotingSerialization
Design
Drawing 2D
Imaging
XML Document
Xslt/XPath
Serialization
Reader/Writers
Printing
Text
Component Model
52
.NET Compact FrameworkSystem.WebSystem.Web System.Windows.FormsSystem.Windows.Forms
System.DrawingSystem.Drawing
System.XMLSystem.XMLSystem.DataSystem.Data
SystemSystem
ServicesDescriptionDiscoveryProtocols
UIHTML ControlsWeb Controls
Security
Session StateConfiguration
Cache
SQL Client
SQL ServerCEDesign
ADO.NET
IO
Net
Collections
Security
Reflection
Resources
Text
Globalization
Configuration
Service Process
Diagnostics
Threading
RuntimeInterop ServicesRemotingSerialization
Design
Drawing 2D
Imaging
XML Document
Xslt/XPath
Serialization
Reader/Writers
Printing
Text
Component Model
53
How to Create a Smart Device Application
• Create a New Smart Device Application Project
• Choose the platform and type of project
• Add additional forms, controls, and code
54
What Are Smart Device Projects?
• Smart Device Projects are used to develop applications that target the .NET Compact Framework
• Supported devices include:– Pocket PC 2000, 2002 and 2003– Pocket PC 2002 Phone Edition– SmartPhone 2003– Custom-designed embedded devices built with the Windows
CE .NET 4.1 operating system• Supported languages are Visual Basic and C#
55
.NET Framework on Linux
• Mono Project– Open Source C# compiler, CLR and Framework Class Library
– Runs on various platforms and hardware:
• Linux, Unix, FreeBSD, Windows – JIT-compiler for x86
• s390, SPARC, PowerPC – interpreter for these hardware architectures
– Supports also:
• ADO.NET and XML
• Windows Forms (not fully)
• ASP.NET
• Web Services
56
.NET Framework on Linux (2)
• Mono Project
– Runs .NET portable executables on Linux, e.g.
mono myapp.exe– Compiles .NET applications to portable executables, e.g.
mcs myapp.cs– The obtained .exe file can taken and run on Windows
• DotGNU Portable.NET
– Build and execute .NET applications on GNU/Linux, Windows, Solaris, NetBSD, FreeBSD, and MacOS X
57
.NET (R)Evolutionary
• Evolutionary– Existing Skills Migrate Smoothly
– Interoperates with Existing Applications
– Extension of WinDNA Architecture
• Revolutionary– Common Language Runtime
– Deployment / Versioning (Ends DLL Hell)
– Web Services & XML Integration
– Evidence Base Code Access Security
58
Future of .Net
– .Net is Microsoft’s core strategy
• .Net will be part of OS in the next generation of Windows
• Lot’s of innovation in Longhorn – Avalon, indigo, WinFS
Top Related