Mastering C# and .NET Framework - Marino Posadas - E-Book

Mastering C# and .NET Framework E-Book

Marino Posadas

0,0
38,39 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Deep dive into C# and .NET architecture to build efficient, powerful applications

About This Book

  • Uniquely structured content to help you understand what goes on under the hood of .NET's managed code platform to master .NET programming
  • Deep dive into C# programming and how the code executes via the CLR
  • Packed with hands-on practical examples, you'll understand how to write applications to make full use of the new features of .NET 4.6, .NET Core and C# 6/7

Who This Book Is For

This book was written exclusively for .NET developers. If you've been creating C# applications for your clients, at work or at home, this book will help you develop the skills you need to create modern, powerful, and efficient applications in C#.

No knowledge of C# 6/7 or .NET 4.6 is needed to follow along—all the latest features are included to help you start writing cross-platform applications immediately. You will need to be familiar with Visual Studio, though all the new features in Visual Studio 2015 will also be covered.

What You Will Learn

  • Understand C# core concepts in depth, from sorting algorithms to the Big O notation
  • Get up to speed with the latest changes in C# 6/7
  • Interface SQL Server and NoSQL databases with .NET
  • Learn SOLID principles and the most relevant GoF Patterns with practical examples in C# 6.0
  • Defend C# applications against attacks
  • Use Roslyn, a self-hosted framework to compile and advanced edition in both C# and Visual basic .NET languages
  • Discern LINQ and associated Lambda expressions, generics, and delegates
  • Design a .NET application from the ground up
  • Understand the internals of a .NET assembly
  • Grasp some useful advanced features in optimization and parallelism

In Detail

Mastering C# and .NET Framework will take you in to the depths of C# 6.0/7.0 and .NET 4.6, so you can understand how the platform works when it runs your code, and how you can use this knowledge to write efficient applications. Take full advantage of the new revolution in .NET development, including open source status and cross-platform capability, and get to grips with the architectural changes of CoreCLR.

Start with how the CLR executes code, and discover the niche and advanced aspects of C# programming – from delegates and generics, through to asynchronous programming. Run through new forms of type declarations and assignments, source code callers, static using syntax, auto-property initializers, dictionary initializers, null conditional operators, and many others. Then unlock the true potential of the .NET platform. Learn how to write OWASP-compliant applications, how to properly implement design patterns in C#, and how to follow the general SOLID principles and its implementations in C# code.

We finish by focusing on tips and tricks that you'll need to get the most from C# and .NET.

This book also covers .NET Core 1.1 concepts as per the latest RTM release in the last chapter.

Style and approach

This book uses hands-on practical code examples that will take you into the depths of C# and .NET. Packed with hands-on practical examples, it is great as a tutorial, or as a reference guide.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 658

Veröffentlichungsjahr: 2016

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Table of Contents

Mastering C# and .NET Framework
Credits
About the Author
Acknowledgements
About the Reviewer
www.PacktPub.com
eBooks, discount offers, and more
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Inside the CLR
An annotated reminder of some important computing terms
Context
The OS multitask execution model
Context types
Thread safety
State
Program state
Serialization
Process
Thread
SysInternals
Static versus dynamic memory
Garbage collector
Concurrent computing
Parallel computing
Imperative programming
Declarative programming
The evolution of .NET
.NET as a reaction to the Java World
The open source movement and .NET Core
Common Language Runtime
Common Intermediate Language
Managed execution
Components and languages
Structure of an assembly file
Program execution
Metadata
Introducing metadata with a basic Hello World
PreJIT, JIT, EconoJIT, and RyuJIT
Common Type System
Naming conventions, rules, and type access modes
Members of a type
A quick tip on the execution and memory analysis of an assembly in Visual Studio 2015
The stack and the heap
Garbage collection
Implementing algorithms with the CLR
Data structures, algorithms, and complexity
Big O Notation
An approach to performance in the most common sorting algorithms
Relevant features appearing in versions 4.5x, 4.6, and .NET Core 1.0 and 1.1
.NET 4.5.x
.NET 4.6 (aligned with Visual Studio 2015)
.NET Core 1.0
.NET Core 1.1
Summary
2. Core Concepts of C# and .NET
C# – what's different in the language?
Languages: strongly typed, weakly typed, dynamic, and static
The main differences
The true reason for delegates
The evolution in versions 2.0 and 3.0
Generics
Creating custom generic types and methods
Lambda expressions and anonymous types
Lambda expressions
It's all about signatures
The LINQ syntax
LINQ syntax is based on the SQL language
Deferred execution
Joining and grouping collections
Type projections
Extension methods
Summary
3. Advanced Concepts of C# and .NET
C# 4 and .NET framework 4.0
Covariance and contravariance
Covariance in interfaces
Covariance in generic types
Covariance in LINQ
Contravariance
Tuples: a remembrance
Tuples: implementation in C#
Tuples: support for structural equality
Tuples versus anonymous types
Lazy initialization and instantiation
Dynamic programming
Dynamic typing
The ExpandoObject object
Optional and named parameters
The Task object and asynchronous calls
C# 5.0: async/await declarations
What's new in C# 6.0
String interpolation
Exception filters
The nameof operator
The null-conditional operator
Auto-property initializers
Static using declarations
Expression bodied methods
Index initializers
What's new in C# 7.0
Binary literals and digit separators
Pattern matching and switch statements
Tuples
Decomposition
Local functions
Ref return values
Summary
4. Comparing Approaches for Programming
Functional languages
F# 4 and .NET Framework
The inevitable Hello World demo
Identifiers and scope
Lists
Function declarations
The pipeline operator
Pattern matching
Classes and types
Casting
The TypeScript language
The new JavaScript
TypeScript: a superset of JavaScript
So, what exactly is TypeScript?
Main features and coalitions
Installing the tools
Transpiling to different versions
Advantages in the IDE
A note on TypeScript's object-oriented syntax
More details and functionality
Summary
5. Reflection and Dynamic Programming
Reflection in the .NET Framework
Calling external assemblies
Generic Reflection
Emitting code at runtime
The System.CodeDOM namespace
The Reflection.Emit namespace
Interoperability
Primary Interop Assemblies
Formatting cells
Inserting multimedia in a sheet
Interop with Microsoft Word
Office apps
The Office app default project
Architectural differences
Summary
6. SQL Database Programming
The relational model
Properties of relational tables
The tools – SQL Server 2014
The SQL language
SQL Server from Visual Studio
Data access in Visual Studio
.NET data access
Using ADO.NET basic objects
Configuring the user interface
The Entity Framework data model
Summary
7. NoSQL Database Programming
A brief historical context
The NoSQL world
Architectural changes with respect to RDBMS
Querying multiple queries
The problem of nonnormalized data
Data nesting
About CRUD operations
MongoDB on Windows
File structure and default configuration
Some useful commands
Operators
Altering data – the rest of CRUD operations
Text indexes
MongoDB from Visual Studio
First demo: a simple query from Visual Studio
CRUD operations
Deletion
Insertion
Modifications and replacements
Summary
8. Open Source Programming
Historical open source movements
Other projects and initiatives
Open source code for the programmer
Other languages
The Roslyn project
Differences from traditional compilers
Getting started with Roslyn
A first look at Microsoft Code Analysis Services
Code Analyzers
An entire open source sample for you to check: ScriptCS
A basic project using Microsoft.CodeAnalysis
The first approach to code refactoring
Debugging and testing the demo
TypeScript
Debugging TypeScript
Debugging TypeScript with Chrome
Interfaces and strong typing
Implementing namespaces
Declarations, scope, and Intellisense
Scope and encapsulation
Classes and class inheritance
Functions
Arrays and interfaces
More TypeScript in action
The DOM connection
Summary
9. Architecture
The election of an architecture
The Microsoft platform
A universal platform
The MSF application model
The Team Model
The Governance Model
The Risk Model
Risk evaluation
Risk assessment
Risk action plans
CASE tools
The role of Visio
A first example
The database design
Creating the demo application in Visual Studio
Website design
Reports
Many other options
BPMN 2.0 (Business Process Model and Notation)
UML standard support
Visual Studio architecture, testing, and analysis tools
Application's architecture using Visual Studio
Class diagrams
Testing
Testing our application in Visual Studio
The Analyze menu
The end of the life cycle – publishing the solution
Summary
10. Design Patterns
The origins
The SOLID principles
Single Responsibility principle
An example
Open/Closed principle
Back to our sample
Liskov Substitution principle
Back to the code again
Other implementations of LSP in .NET (Generics)
Interface Segregation principle
Dependency Inversion principle
A final version of the sample
Design patterns
Singleton
The Factory pattern
The Adapter pattern
The Façade pattern
The Decorator pattern
The Command pattern
An example already implemented in .NET
The Observer pattern
The Strategy pattern
Other software patterns
Other patterns
Summary
11. Security
The OWASP initiative
The OWASP Top 10
A1 – injection
SQL injection
Prevention
The case for NoSQL databases
A2 – Broken Authentication and Session Management
The causes
Prevention
.NET coding for A2
Desktop applications
Web applications
A3 – Cross-Site Scripting (XSS)
Prevention
A4 – Insecure Direct Object References
Prevention
A5 – Security Misconfiguration
Possible examples of attacks
Prevention – aspects to consider
Prevention – measures
A6 – Sensitive Data Exposure
A7 – Missing Function-level Access Control
Prevention
A8 – Cross-Site Request Forgery
Prevention
A9 – Using components with known vulnerabilities
A10 – Invalidated redirects and forwards
Summary
12. Performance
Application Performance Engineering
The tools
Advanced options in Visual Studio 2015
Advanced options in the Diagnostic Tools menu
Other tools
The process of performance tuning
Performance Counters
Bottleneck detection
Bottleneck detection in practice
Using code to evaluate performance
Optimizing web applications
IIS optimization
ASP.NET optimization
General and configuration
Caching
Data access
Load balancing
Client side
Summary
13. Advanced Topics
The Windows messaging subsystem
The MSG structure
Sub-classing techniques
Some useful tools
Platform/Invoke: calling the OS from .NET
The process of platform invocation
Windows Management Instrumentation
CIM searchable tables
Parallel programming
Difference between multithreading and parallel programming
Parallel LINQ
Dealing with other issues
Canceling execution
The Parallel class
The Parallel.ForEach version
Task Parallel
Communication between threads
.NET Core 1.0
The list of supported environments
Core FX
Core CLR
Core RT
Core CLI
Installation of .NET Core
The CLI interface
ASP.NET Core 1.0
What's new
A first approach
Configuration and Startup settings
Self-hosted applications
ASP.NET Core 1.0 MVC
Managing scripts
NET Core 1.1
Summary
Index

Mastering C# and .NET Framework

Mastering C# and .NET Framework

Copyright © 2016 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

First published: December 2016

Production reference: 1091216

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham B3 2PB, UK.

ISBN 978-1-78588-437-5

www.packtpub.com

Credits

Author

Marino Posadas

Reviewers

Fabio Claudio Ferracchiati

Commissioning Editor

Edward Gordon

Acquisition Editor

Denim Pinto

Content Development Editor

Priyanka Mehta

Technical Editor

Dhiraj Chandanshive

Copy Editor

Stuti Srivastava

Project Coordinator

Izzat Contractor

Proofreader

Safis Editing

Indexer

Rekha Nair

Graphics

Disha Haria

Production Coordinator

Aparna Bhagat

Cover Work

Aparna Bhagat

About the Author

Marino Posadas is an independent senior trainer, writer, and consultant in Microsoft Technologies and Web Standards. He is a Microsoft MVP in C#, Visual Studio, and Development Technologies; an MCT, MAP (2013), MCPD, MCTS, MCAD, MCSD, and MCP. Additionally, he was the former director for development in Spain and Portugal for Solid Quality Mentors.

He's published 14 books and more than 500 articles on development technologies in several magazines. Topics covered in his books range from Clipper and Visual Basic 5.0/6.0 to C #, .NET-safe programming, Silverlight 2.0 and 4.0, and Web Standards. The Guide to Programming in HTML5, CSS3 and JavaScript with Visual Studio is his latest book.

He is also a speaker at Microsoft events, having lectured in Spain, Portugal, England, the USA, Costa Rica, and Mexico.

You can find him on LinkedIn at https://es.linkedin.com/in/mposadas.

His website, http//elavefenix.net, also contains developer's resources and videos, in English and Spanish, interviewing representatives of the Microsoft and Web Standards development world.

Acknowledgements

I'd like to thank Denim Pinto, Priyanka Mehta, and Fabio Claudio Ferracchiati from Packt Publishing for their continuous support and confidence while writing this book.

Special thanks to some professionals and technology evangelists whose work inspired different parts of this book, in particular, Mark Russinowich, Scott Hanselman, Scott Hunter (the "lesser" Scotts), Daniel Roth, Lluis Franco, Luis Ruiz Pavón, Dino Esposito, Miguel Katrib, James Gray, Paul Cotton, Stephen Toub, and Troy Hunt.

Also, I would like to remember my MVP lead, Cristina González Herrero, for her continuous encouragement and help, and other people at Microsoft who have always supported my activities. My memories go here to Alfonso Rodríguez, David Carmona, David Salgado, José Bonnín, César de la Torre, Andy Gonzalez, and Leon Welicki.

My appreciation also goes to my mates at Netmind, Alex and Bernat Palau, Miquel Rodriguez, Israel Zorrilla, and Angel Rayo, for their support in this initiative from the beginning.

About the Reviewer

Fabio Claudio Ferracchiati is a senior consultant and a senior analyst/developer using Microsoft technologies. He works for React Consulting (www.reactconsulting.it) as Microsoft Dynamics 365 Solution Architect. He is a Microsoft Certified Solution Developer for .NET, a Microsoft Certified Application Developer for .NET, a Microsoft Certified Professional, and a prolific author and technical reviewer. Over the past 10 years, he's written articles for Italian and international magazines and coauthored more than 10 books on a variety of computer topics.

www.PacktPub.com

eBooks, discount offers, and more

Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at <[email protected]> for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why subscribe?

Fully searchable across every book published by PacktCopy and paste, print, and bookmark contentOn demand and accessible via a web browser

I dedicate this book to my wife, Milagros, and my family, with a special mention to my nephews and nieces: Fernando, Sarah, Ana, Paula, Pablo, Javier, Adrian, Irene, Luis, and Juan.

Preface

.NET and the C# language have continuously grown in adoption since its release in early 2001. C#'s main author, Anders Hejlsberg, has lead several groups of developers in constant growing and improvement, until reaching the current version, .NET 4.6, and the very important .NET Core 1.0/1.1, and keeps on going with this work, also linked to the new TypeScript language, which we will also cover in this book.

This book is a journey through the different options and possibilities .NET Framework in general, and C# in particular, provide to developers to build applications that run on Windows and, as seen in the last chapter, on other platforms and devices.

I believe that it can be a reference for programmers wanting to update their knowledge to the latest versions of this set of technologies, but also for those who, coming from other environments, would like to approach .NET and the C# language to extend their skills and programming toolset.

All the main points discussed in here are illustrated with examples, and the important parts of these demos are explained in detail, so you can easily follow this route.

What this book covers

Chapter 1, Inside the CLR, goes through the internal structure of .NET, the way assemblies are built, the tools and resources we have to work with them, and the way .NET integrates with the operating system.

Chapter 2, Core Concepts of C# and .NET, reviews the foundations of the language, its main characteristics, and some of the true reasons for the appearance of certain features, such as delegates.

Chapter 3, Advanced Concepts of C# and .NET, starts with version 4.0, viewing some common practices new to the language and Framework libraries, especially those related to synchronicity, execution threads, and dynamic programming. Finally, we can find many new aspects that appeared in versions 6.0 and 7.0, intended to simplify the way we write code.

Chapter 4, Comparing Approaches for Programming, deals with two members of the .NET language ecosystem: F# and TypeScript (also called functional languages), which are gaining momentum among the programmer's community.

Chapter 5, Reflection and Dynamic Programming, covers the ability of a .NET program to examine, introspect, and modify its own structure and behavior, and also how to interoperate with other programs, such as the Office Suite.

Chapter 6, SQL Database Programming, deals with access to databases built according to the principles of the Relational Model, and in particular to SQL databases. It covers Entity Framework 6.0 and gives a brief reminder of ADO.NET.

Chapter 7, NoSQL Database Programming, reviews the emerging database paradigm called NoSQL databases. We will use MongoDB, the most popular of its kind, and see how to manage it from C# code.

Chapter 8, Open Source Programming, goes through the current state of open source programming with Microsoft technologies, the open source ecosystem. We will review Node.js, Roselyn, and also TypeScript, although with a slightly different point of view.

Chapter 9, Architecture, goes through the structure of an application and the tools available in its construction, such as MSF, good practices, and so on.

Chapter 10, Design Patterns, focuses on the quality of the code and its structures in terms of efficacy, precision, and maintainability. It deals with SOLID principles, the Gang of Four patterns, and other proposals.

Chapter 11, Security, analyzes the OWASP Top 10 security recommendations from the point of view of the .NET developer.

Chapter 12, Performance, deals with common issues that a developer encounters in relation to an application's performance, and which techniques and tips are commonly suggested in order to obtain flexible, responsive, and well-behaved software, with a special emphasis on web performance.

Chapter 13, Advanced Topics, covers interaction with the OS via subclassing and platform/invoke, system data retrieval through WMI, parallel programming, and an introduction to the new .NET Core and ASP.NET Core multiplatform technologies.

What you need for this book

As this book is dedicated to C# and .NET, the main tool to use is Visual Studio. However, you can use several versions to follow the majority of the sections in this book.

I've used Visual Studio 2015 Ultimate Update 3, but you can also use the free Community Edition for more than 90% of its contents. Other available options are Visual Studio 2015 Express Edition, which is also free, and Visual Studio Code, which is also free and multiplatform.

Additionally, a basic installation of SQL Server Express 2014, which is free, is required together with the SQL Server Management Studio (version 2016 works equally well with the topics covered here).

For the NoSQL part, MongoDB is also required in its basic installation.

To debug websites, it's good to have Chrome Canary or Firefox Developer Edition, for they have extended capabilities for developers.

Other tools and utilities can be installed from the Extensions and Updates menu option, linked to the Tools menu in the different versions of Visual Studio.

Finally, in some cases, there are tools that you can download from the sites indicated in this book; although, they're not an absolute requirement for the full comprehension of this book's contents.

Who this book is for

This book was written exclusively for .NET developers. If you're creating C# applications for your clients, at work or at home, this book will help you develop the skills you need to create modern, powerful, and efficient applications in C#.

No knowledge of C# 6/7 or .NET 4.6 is needed to follow along—all the latest features are included to help you start writing cross-platform applications immediately. You will need to be familiar with Visual Studio, although all the new features in Visual Studio 2015 will also be covered.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.Hover the mouse pointer on the SUPPORT tab at the top.Click on Code Downloads & Errata.Enter the name of the book in the Search box.Select the book for which you're looking to download the code files.Choose from the drop-down menu where you purchased this book from.Click on Code Download.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for WindowsZipeg / iZip / UnRarX for Mac7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Mastering-C-Sharp-and-.NET-Framework. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at <[email protected]> with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

The evolution of .NET

Until the arrival of .NET, the Microsoft programming ecosystem had been ruled by a few classic languages, Visual Basic and C++ (with the Microsoft Foundation classes) being typical examples of this.

Note

Also known as MFC, Microsoft Foundation Classes is a library that wraps portions of the Windows API in C++ classes, including functionalities that enable them to use a default application framework. Classes are defined for many of the handle-managed Windows objects and also for predefined windows and common controls. It was introduced in 1992 with Microsoft's C/C++ 7.0 compiler for use with 16-bit versions of Windows as an extremely thin object-oriented C++ wrapper for the Windows API.

However, the big changes proposed by .NET were started using a totally different component model approach. Up until 2002, when .NET officially appeared, such a component model was COM (Component Object Model), introduced by the company in 1993. COM is the basis for several other Microsoft technologies and frameworks, including OLE, OLE automation, ActiveX, COM+, DCOM, the Windows shell, DirectX, UMDF (User-Mode Driver Framework), and Windows runtime.

Note

A device-driver development platform (Windows Driver Development Kit) first introduced with Microsoft's Windows Vista operating system is also available for Windows XP. It facilitates the creation of drivers for certain classes of devices.

At the time of writing this, COM is a competitor with another specification named CORBA (Common Object Request Broker Architecture), a standard defined by theObject Management Group (OMG), designed to facilitate the communication of systems that are deployed on diverse platforms. CORBA enables collaboration between systems on different operating systems, programming languages, and computing hardware. In its life cycle, it has received a lot of criticism, mainly because of poor implementations of the standard.

.NET as a reaction to the Java World

In 1995, a new model was conceived to supersede COM and the unwanted effects related to it, especially versions and the use of the Windows Registry on which COM depends to define accessible interfaces or contracts; a corruption or modified fragment of the registry could indicate that a component was not accessible at runtime. Also, in order to install applications, elevated permissions were required, since the Windows Registry is a sensible part of the system.

A year later, various quarters of Microsoft started making contacts with some of the most distinguished software engineers, and these contacts remained active over the years. These included architects such as Anders Hejlsberg (who became the main author of C# and the principal architect of .NET framework), Jean Paoli (one of the signatures in the XML Standard and the former ideologist of AJAX technologies), Don Box (who participated in the creation of SOAP and XML Schemas), Stan Lippman (one of the fathers of C++, who was working at the time at Disney), Don Syme (the architect for generics and the principal author of the F# language), and so on.

The purpose of this project was to create a new execution platform, free from the caveats of COM and one that was able to hold a set of languages to execute in a secure and extensible manner. The new platform should be able to program and integrate the new world of web services, which had just appeared—based on XML—along with other technologies. The initial name of the new proposal was Next Generation Windows Services (NGWS).

By late 2000, the first betas of .NET framework were released, and the first version appeared on February 13, 2002. Since then, .NET has been always aligned with new versions of the IDE (Visual Studio). The current version of the classic .NET framework at the time of writing this is 4.6.1, but we will get into more detail on this later in the chapter.

An alternative .NET appeared in 2015 for the first time. In the //BUILD/ event, Microsoft announced the creation and availability of another version of .NET, called .NET Core.

The open source movement and .NET Core

Part of an idea for the open source movement and .NET Core comes from a deep change in the way software creation and availability is conceived in Redmond nowadays. When Satya Nadella took over as the CEO at Microsoft, they clearly shifted to a new mantra: mobile-first, cloud-first. They also redefined themselves as a company of software and services.

This meant embracing the open source idea with all its consequences. As a result, a lot of the NET Framework has already been opened to the community, and this movement will continue until the whole platform is opened, some say. Besides, a second purpose (clearly stated several times at the //BUILD/ event) was to create a programming ecosystem powerful enough to allow anyone to program any type of application for any platform or device. So, they started to support Mac OX and Linux as well as several tools to build applications for Android and iOS.

However, the implications run deeper. If you want to build applications for Mac OS and Linux, you need a different Common Language Runtime (CLR) that is able to execute in these platforms without losing out on performance. This is where .NET Core comes into play.

At the time writing this, Microsoft has published several (ambitious) improvements to the .NET ecosystem, mainly based on two different flavors of .NET:

The first one is the version that was last available—.NET (.NET framework 4.6.x)—and the second one is the new version, intended to allow compilations that are valid not only for Windows platforms, but also for Linux and Mac OSes.

NET Core is the generic name for a new open source version of the CLR made available in 2015 (updated last November to version 1.1) intended to support multiple flexible .NET implementations. In addition, the team is working on something called .NET Native, which compiles to native code in every destination platform.

However, let's keep on going with the main concepts behind the CLR, from a version-independent point of view.

Note

The whole project is available on GitHub at https://github.com/dotnet/coreclr.

Common Language Runtime

To address some of the problems of COM and introduce the bunch of new capabilities that were requested as part of the new platform, a team at Microsoft started to evolve prior ideas (and the names associated with the platform as well). So, the framework was soon renamed to Component Object Runtime (COR) prior to the first public beta, when it was finally given the name of Common Language Runtime in order to drive the fact that the new platform was not associated with a single language.

Actually, there are dozens of compilers available for use with the .NET framework, and all of them generate a type intermediate code, which—in turn—is converted into native code at execution time, as shown in the following figure:

The CLR, as well as COM, focuses on contracts between components, and these contracts are based on types, but that's where the similarities end. Unlike COM, the CLR establishes a well-defined form to specify contracts, which is generally known as metadata.

Also, the CLR includes the possibility of reading metadata without any knowledge of the underlying file format. Furthermore, such metadata is extensible by means of custom attributes, which are strongly typed themselves. Other interesting information included in the metadata includes the version information (remember, there should be no dependencies of the Registry) and component dependencies.

Besides, for any component (called assembly), the presence of metadata is mandatory, which means that it's not possible to deploy the access of a component without reading its metadata. In the initial versions, implementations of security were mainly based on some evidence included in the metadata. Furthermore, such metadata is available for any other program inside or outside the CLR through a process called Reflection.

Another important difference is that .NET contracts, above all, describe the logical structure of types. There are no in-memory representations, reading order sequences, alignment or parameter conventions, among other things, as Don Box explains in detail in his magnificent Essential .NET.

Common Intermediate Language

The way these previous conventions and protocols are resolved in CLR is by means of a technique called contract virtualization. This implies that most of the code (if not all) written for the CLR doesn't contain the machine code but an intermediate language called Common Intermediate Language (CIL), or just Intermediate Language (IL).

CLR never executes CIL directly. Instead, CIL is always translated into native machine code prior to its execution by means of a technique called JIT (Just-In-Time) compilation. This is to say that the JIT process always adapts the resulting executable code to the destination machine (independent from the developer). There are several modes of performing a JIT process, and we'll look at them in more detail later in this chapter.

Thus, CLR is what we might call a type-centered framework. For CLR, everything is a type, an object, or a value.

Managed execution

Another critical factor in the behavior of CLR is the fact that programmers are encouraged to forget about the explicit management of memory and the manual management of threads (especially associated with languages such as C and C++) to adopt the new way of execution that the CLR proposes: managed execution.

Under managed execution, CLR has complete knowledge of everything that happens in its execution context. This includes every variable, method, type, event, and so on. This encourages and fosters productivity and eases the path to debugging in many ways.

Additionally, CLR supports the creation of runtime code (or generative programming) by means of a utility called CodeDOM. With this feature, you can emit code in different languages and compile it (and execute it) directly in the memory.

All this drives us to the next logical questions: which languages are available to be used with this infrastructure, which are the common points among them, how is the resulting code assembled and prepared for execution, what are the units of stored information (as I said, they're called assemblies), and finally, how is all this information organized and structured into one of these assemblies?

Components and languages

Every execution environment has a notion of software components. For CLR, such components must be written in a CLI-compliant language and compiled accordingly. You can read a list of CLI languages on Wikipedia. But the question is what is a CLI-compliant language?

CLI stands for Common Language Infrastructure, and it's a software specification standardized by ISO and ECMA describing the executable code and a runtime environment that allows multiple high-level languages to be used on different computer platforms without being rewritten for specific architectures. The .NET framework and the free and open source Mono are implementations of CLI.

Note

Note that the official sites for these terms and entities are as follows:

ISO: http://www.iso.org/iso/home.html

ECMA: http://www.ecma-international.org/

MONO: http://www.mono-project.com/

CLI languages: https://en.wikipedia.org/wiki/List_of_CLI_languages

The most relevant points in the CLI would be as follows (according to Wikipedia):

First, to substitute COM, metadata is key and provides information on the architecture of assemblies, such as a menu or an index of what you can find inside. Since it doesn't depend on the language, any program can read this information.That established, there should be a common set of rules to comply in terms of data types and operations. This is the Common Type System (CTS). All languages that adhere to CTS can work with a set of rules.For minimal interoperation between languages, there is another set of rules, and this should be common to all programming languages in this group, so a DLL made with one language and then compiled can be used by another DLL compiled in a different CTS language, for example.Finally, we have a Virtual Execution System, which is responsible for running this application and many other tasks, such as managing the memory requested by the program, organizing execution blocks, and so on.

With all this in mind, when we use a .NET compiler (from now on, compiler), we generate a byte stream, usually stored as a file in the local filesystem or on a web server.

Structure of an assembly file

Files generated by a compilation process are called assemblies, and any assembly follows the basic rules of any other executable file in Windows and adds a few extensions and information suitable and mandatory for the execution in a managed environment.

In short, we understand that an assembly is just a set of modules containing the IL code and metadata, which serve as the primary unit of a software component in CLI. Security, versioning, type resolution, processes (application domains), and so on, all work on a per-assembly basis.

The significance of this implies changes in the structure of executable files. This leads to a new file architecture represented in the following figure:

Note that a PE file is one that conforms to the Portable/Executable format: a file format for executables, object code, DLLs, FON (Font) files, and others used in 32-bit and 64-bit versions of Windows operating systems. It was first introduced by Microsoft in Windows NT 3.1, and all later versions of Windows support this file structure.

This is why we find a PE/COFF header in the format, which contains compatible information required by the system. However, from the point of view of a .NET programmer, what really matters is that an assembly holds three main areas: the CLR header, the IL code, and a section with resources (Native Image Section in the figure).

Tip

A detailed description of the PE format is available at http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx.

Program execution

Among the libraries linked with CLR, we found a few responsible for loading assemblies in the memory and starting and initializing the execution context. They're generally referenced as CLR Loader. Together with some other utilities, they provide the following:

Automatic memory managementUse of garbage collectorMetadata access to find information on typesLoading modulesAnalyzing managed libraries and programsA robust exception management subsystem to enable programs to communicate and respond to failures in structured waysNative and legacy code interoperabilityA JIT compilation of managed code into native codeA sophisticated security infrastructure

This loader uses OS services to facilitate the loading, compilation, and execution of an assembly. As we've mentioned previously, CLR serves as an execution abstraction for .NET languages. To achieve this, it uses a set of DLLs, which acts as a middle layer between the OS and the application program. Remember that CLR itself is a collection of DLLs, and these DLLs work together to define the virtual execution environment. The most relevant ones are as follows:

mscoree.dll (sometimes called shim because it is simply a facade in front of the actual DLLs that the CLR comprises)clr.dllmscorsvr.dll (multiprocessor) or mscorwks.dll (uniprocessor)

In practice, one of the main roles of mscoree.dll is to select the appropriate build (uniprocessor or multiprocessor) based on any number of factors, including (but not limited to) the underlying hardware.

The clr.dll is the real manager, and the rest are utilities for different purposes. This library is the only one of the CLRs that is located at $System.Root$, as we can find through a simple search:

My system is showing two versions (there are some more), each one ready to launch programs compiled for 32-bit or 64-bit versions. The rest of the DLLs are located at another place: a secure set of directories generally called Global Assembly Cache (GAC).

Actually, the latest edition of Windows 10 installs files for all versions of such GAC, corresponding to versions 1.0, 1.1, 2.0, 3.0, 3.5, and 4.0, although several are just placeholders with minimum information, and we only find complete versions of .NET 2.0, .NET 3.5 (only partially), and .NET 4.0.

Also, note that these placeholders (for the versions not fully installed) admit further installations if some old software requires them to. This is to say that the execution of a .NET program relies on the version indicated in its metadata and nothing else.

You can check which versions of .NET are installed in a system using the CLRver.exe utility, as shown in the following figure:

Internally, several operations take place before execution. When we launch a .NET program, we'll proceed just as usual, as if it were just another standard executable of Windows.

Behind the scenes, the system will read the header in which it will be instructed to launch mscore.dll, which—in turn—will start the whole running process in a managed environment. Here, we'll omit all the intricacies inherent to this process since it goes far beyond the scope of this book.

Metadata

We've mentioned that the key aspect of the new programming model is the heavy reliance on metadata. Furthermore, the ability to reflect against metadata enables programming techniques in which programs are generated by other programs, not humans, and this is where CodeDOM comes into play.

We'll cover some aspects of CodeDOM and its usages when dealing with the language, and we'll look at how the IDE itself uses this feature frequently every time it creates source code from a template.

In order to help the CLR find the various pieces of an assembly, every assembly has exactly one module whose metadata contains the assembly manifest: an additional piece of CLR metadata that acts as a directory of adjunct files that contain additional type definitions and code. Furthermore, CLR can directly load modules that contain an assembly manifest.

So, what is the aspect of a manifest in a real program and how can we examine its content? Fortunately, we have a bunch of .NET utilities (which, technically, don't belong to CLR but to the .NET framework ecosystem) that allow us to visualize this information easily.

Introducing metadata with a basic Hello World

Let's build a typical Hello World program and analyze its contents once it is compiled so that we can inspect how it's converted into Intermediate Language (IL) and where the meta-information that we're talking about is.

Along the course of this book, I'll use Visual Studio 2015 Community Edition Update 1 (or higher if an updated version appears) for reasons that I'll explain later. You can install it for free; it's a fully capable version with tons of project types, utilities, and so on.

Note

Visual Studio 2015 CE update 1 is available at https://www.visualstudio.com/vs/community/.

The only requirement is to register for free in order to get a developer's license that Microsoft uses for statistical purposes—that's all.

After launching Visual Studio, in the main menu, select New Project and go to the Visual C# templates, where the IDE offers several project types, and select a console application, as shown in the following screenshot:

Visual Studio will create a basic code structure composed of several references to libraries (more about that later) as well as a namespace block that includes the program class. Inside that class, we will find an application entry point in a fashion similar to what we would find in C++ or Java languages.

To produce some kind of output, we're going to use two static methods of the Console class: WriteLine, which outputs a string adding a carriage return, and ReadLine, which forces the program to stop until the user introduces a character and presses the return key so that we can see the output that is produced.

After cleaning these references that we're not going to use, and including the couple of sentences mentioned previously, the code will look like this:

using System; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { Console.WriteLine("Hello! I'm executing in the CLR context."); Console.ReadLine(); } } }

To test it, we just have to press F5 or the Start button and we'll see the corresponding output (nothing amazing, so we're not including the capture).

At the time of editing the code, you will have noticed several useful characteristics of the IDE's editor: the colorizing of sentences (distinguishing the different purposes: classes, methods, arguments, literals, and so on); IntelliSense, which offers what makes sense to write for every class' member; Tooltips, indicating every return type for methods; the value type for literals or constants; and the number of references made to every member of the program that could be found in your code.

Technically, there are hundreds of other useful features, but that's something we will have the chance to test starting from the next chapter, when we get into the C# aspects and discover how to prove them.

As for this little program, it's a bit more interesting to check what produced such output, which we'll find in the Bin/Debug folder of our project. (Remember to press the Show all files button at the head of Solution Explorer, by the way):

As we can see, two executables are generated. The first one is the standalone executable that you can launch directly from its folder. The other, with the .vshost prefix before the extension, is the one Visual Studio uses at debug time and that contains some extra information required by the IDE. Both produce the same results.

Once we have an executable, it is time to link the .NET tool – that will let us view the metadata that we're talking about – to Visual Studio.

To do this, we go to the Tools | External Tools option in the main menu, and we'll see a configuration dialog window, presenting several (and already tuned) external tools available; press the New button and change the title to IL Disassembler, as shown in the following screenshot:

Next, we need to configure the arguments that we're going to pass to the new entry: the name of the tool and the required parameters.

You'll notice that there are several versions of this tool. These depend on your machine.

For our purposes, it will suffice to include the following information:

The root of the tool (named ILDASM.exe, and located in my machine at C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools)The path of the executable generated, for which I'm using a predefined macro expressed by $targetpath

Given that our program is already compiled, we can go back to the Tools menu and find a new entry for IL Disassembler. Once launched, a window will appear, showing the IL code of our program, plus a reference called Manifest (which shows the metadata), and we can also double-click to show another window with this information, as shown in the following screenshot:

Note

Note that I've modified ILDASM's font size for clarity.

The information included in the manifest comes from two sources: the IDE itself, configured to prepare the assembly for execution (we can view most of the lines if we take a more detailed look at the window's content), and customizable information that we can embed in the executable's manifest, such as descriptions, the assembly title, the company information, trademark, culture, and so on. We'll explore how to configure that information in the next chapter.

In the same manner, we can keep on analyzing the contents of every single node shown in the main ILDASM window. For instance, if we want to see the IL code linked to our Main entry point, the tool will show us another window where we can appreciate the aspect of the IL code (note the presence of the text cil managed next to the declaration of main):