Java vs. .Net Livslang Uddannelse August 20th, 2004 Bent Thomsen PhD, DIC, Cand.Scient, EurIng, CEng, FBCS, MACM, MIEEE bt@cs.auc.dk Department of Computer Science Aalborg University 1 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 2 A Unified Programming Model Consistent API availability regardless of language and programming model .NET Framework RAD, Composition and Delegation VB Object Model Subclassing, Power and Expressiveness MFC/ATL Stateless, code embedded in HTML pages ASP Windows API 3 .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 4 Microsoft .NET Web services support across the Microsoft platform Services Servers Experiences & Solutions Tools Clients 5 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. 6 .NET Framework Common 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 Common Language Runtime Operating System 7 .NET Framework Base Class Library – Object-oriented collection of reusable types – Collections, I/O, Strings, … .NET Framework (Base Class Library) Common Language Runtime Operating System 8 .NET Framework Data Access Layer – Access relational databases – Disconnected data model – Work with XML ADO .NET and XML .NET Framework (Base Class Library) Common Language Runtime Operating System 9 .NET Framework ASP.NET & Windows Forms – Create application’s front-end – Web-based user interface, Windows GUI, Web services, … ASP .NET Web Forms Web Services Mobile Internet Toolkit Windows Forms ADO .NET and XML .NET Framework (Base Class Library) Common Language Runtime Operating System 10 .NET Framework System.Web Services Description Discovery Protocols System.Windows.Forms UI Design Component Model HTML Controls Web Controls System.Drawing Cache Security Drawing 2D Printing Configuration Session State Imaging Text System.XML System.Data ADO.NET Design SQL Client SQL ServerCE XML Document Xslt/XPath Serialization Reader/Writers System Collections Security IO Net Configuration Service Process Text Reflection Diagnostics Globalization Resources Threading Runtime Interop Services Remoting Serialization 11 .NET Framework Programming Languages – Use your favorite language C++ C# VB.NET Perl … J# ASP .NET Web Forms Web Services Mobile Internet Toolkit Windows Forms ADO .NET and XML .NET Framework (Base Class Library) Common Language Runtime Operating System 12 .NET Framework Common Language Specification C++ VB Common Language C# Perl Specification J# … ASP .NET Web Forms Web Services Mobile Internet Toolkit Windows Forms ADO .NET and XML .NET Framework (Base Class Library) Common Language Runtime Operating System 13 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 14 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 15 .NET Languages • Languages provided by Microsoft – • Third-parties languages – • Cross-language inheritance and exceptions handling Object system is built in, not bolted on – • Perl, Python, Pascal, APL, COBOL, Eiffel, Haskell, ML, Oberon, Scheme, Smalltalk… Advanced multi-language features – • C++, C#, J#, VB.NET, JScript No additional rules or API to learn All compile to .Net Assemblies – Contains MSIL and metadata 16 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 17 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 18 .Net Assemblies Compilation Assembly Source Code Compiler csc.exe or vbc.exe C++, C#, VB or any .NET language DLL or EXE 19 .Net Execution Model Common Language Runtime Source code Managed code VB C# C++ Compiler Compiler Compiler Assembly IL Code Assembly IL Code Assembly IL Code Common Language Runtime JIT Compiler Native Code Operating System Services 20 Managed Code Execution DEVELOPMENT Source code 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); public static void Main(String[] args ) w.WriteLine(usr); { String usr; FileStream f; StreamWriter w; w.Close(); try { } catch (Exceptionusr=Environment.GetEnvironmentVariable("USERNAME"); e){ Console.WriteLine("Exception:"+e.ToString()); 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()); } } Compiler Evidence Host Policy Manager DEPLOYMENT Assembly PE header + MSIL + Metadata + EH Table Assembly Loader 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 permissio ns and forms the root of the code group tree."> <IMembershipCondition clas s="AllMembershipCondition" version="1"/> <CodeGroup class="UnionCodeGroup" version="1" PermissionSetName="FullTrust" Granted permissions GAC, app. directory, download cache Permission request (class) (method) Class Loader NGEN EXECUTION Assembly info Module + Class list PEVerify Vtable + Class info JIT + verification CLR Services GC Exception Native code Class init + GC table Security 21 .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 22 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 23 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 24 Visual C++ .NET Continue 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 25 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# 26 C# • Hello world using System; class HelloWorld { public static void Main() { Console.WriteLine(“Hello World!"); } } >csc HelloWorld.cs >Hello World! 27 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; 28 C# • Parameter Passing By Value By Reference public static void Swap(ref int x, ref int y) { int z = x; x = y; y = z; } 29 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) { . . . 30 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 31 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 () { . . . 32 C# 2.0 Language Enhancements • • • • Generics Anonymous methods Iterators Partial types 33 Generics public class List<T> { private T[] elements; private int count; public void Add(T element) { if (count == elements.Length) Resize(count * 2); elements[count++] = element; } public T this[int index] { get { return elements[index]; } List<int> intList set { elements[index] = value; } = new List<int>(); } intList.Add(1); // No boxing intList.Add(2); // No boxing public int Count { // Compile-time error get { return count; intList.Add("Three"); } } int i = intList[0]; // No cast required } 34 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 35 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 36 Visual Studio .NET 37 Referencing the Framework 38 .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… 39 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 40 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 41 Web Services Open Standards & Protocols • XML – Universal data format – Standards-based integration – User-customizable • HTTP – Ubiquitous protocol – Universally understood 42 VS.NET and Web Services • Expose functionality as service – – – • Reuse existing Web Services – – • No need to learn XML, SOAP, or WSDL Interface is automatically generated Seamless deployment VS.NET generates the plumbing Full IntelliSense support Build and consume with any VS language 43 Software as a Service Visual Studio .Net and the Net Framework • 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 [WebMethod] Public Function HelloWorld() as String return “Hello World” End Function WSDL Compiler Test Page Web Service Object 44 Windows Forms • Rich, powerful client UI – – – • Secure – – • Control anchoring, visual inheritance Shared across all .NET languages No-touch deployment Semi-trusted browser component Fully-trusted local application Full Web Service integration 45 .Net on other Platforms • .Net Compact Framework – PocketPC, XScale, ARM, … • SSCLI – BSD Unix, Mac OS X • Mono – Linux 46 .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 47 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 – – – 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 – • • • P/Invoke – PlatformInvoke enables calls to Win32 DLLs Client web services is fully supported No Generic Serialization – – Datasets can be serialized to XML No binary Serialization 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 50 .NET Framework System.Web Services Description Discovery Protocols System.Windows.Forms UI Design Component Model HTML Controls Web Controls System.Drawing Cache Security Drawing 2D Printing Configuration Session State Imaging Text System.XML System.Data ADO.NET Design SQL Client SQL ServerCE XML Document Xslt/XPath Serialization Reader/Writers System Collections Security IO Net Configuration Service Process Text Reflection Diagnostics Globalization Resources Threading Runtime Interop Services Remoting Serialization 51 .NET Compact Framework System.Web Services Description Discovery Protocols System.Windows.Forms UI Design Component Model HTML Controls Web Controls System.Drawing Cache Security Drawing 2D Printing Configuration Session State Imaging Text System.XML System.Data ADO.NET SQL Client XML Document Serialization Design SQL ServerCE Xslt/XPath Reader/Writers System Collections IO Configuration Security Net Service Process Text Reflection Diagnostics Globalization Resources Threading Runtime Interop Services Remoting Serialization 52 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 53 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# 54 .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 55 .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 56 .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 57 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 58