NET Core 3 and Unit Testing

Total Page:16

File Type:pdf, Size:1020Kb

NET Core 3 and Unit Testing Learn C# Programming A guide to building a solid foundation in C# language for writing efcient programs Marius Bancila Rafaele Rialdi Ankit Sharma BIRMINGHAM—MUMBAI Learn C# Programming Copyright © 2020 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 efort 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 authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been 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. Commissioning Editor: Richa Tripathi Acquisition Editor: Alok Dhuri Senior Editor: Storm Mann Content Development Editor: Ruvika Rao Technical Editor: Pradeep Sahu Copy Editor: Safs Editing Language Support Editor: Safs Editing Project Coordinator: Francy Puthiry Proofreader: Safs Editing Indexer: Pratik Shirodkar Production Designer: Jyoti Chauhan First published: April 2020 Production reference: 1280420 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78980-586-4 www.packt.com To my smart boys, Cristian and Bogdan, who love learning new things every day. – Marius To my mom and dad, who ignited my passion with a Sinclair ZX81 when I was a child, and to my beautiful wife, Valeria, who has always supported me in my adventures. I love you! – Rafaele To my mother, Vibha Sharma, for everything she did for me. – Ankit Packt.com Subscribe to our online digital library for full access to over 7,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website. Why subscribe? • Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals • Improve your learning with Skill Plans built especially for you • Get a free eBook or video every month • Fully searchable for easy access to vital information • Copy and paste, print, and bookmark content Did you know that Packt ofers eBook versions of every book published, with PDF and ePub fles available? You can upgrade to the eBook version at packt.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.packt.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and ofers on Packt books and eBooks. Foreword As a developer of the 2020s, it's hard to believe that there was a time in which the choice of programming language was crucial for the success of a sofware project, with each programming language coming with its own set of libraries defning the range of possible actions. Data access, for example, was a no-brainer in Visual Basic but hard to do in C++, for example. By the same token, calling into low-level Windows API functions was easy in C but sometimes impossible in Visual Basic. Ten came the .NET platform made of two distinct pillars. One pillar was an object- oriented framework defning a wide range of predefned behaviors. Te other pillar was a language runtime able to support a variety of programming languages, including Visual Basic and the new C#. Over the years, C# has then become the primary language for the whole .NET platform. So, what does it mean to learn C# today, two decades afer .NET 1.0? Learning the sole syntax and semantics of a programming language makes little to no sense these days, whether it is C#, Java, or Python. A programming language is a largely interchangeable tool with limited real programming power without the backbone of a solid framework. Subsequently, learning the plain syntax of a programming language is a small fraction of the job and a book that intends to cover any programming language has to go well beyond data types, operators, and control statements. Tis is precisely what this book does and in addition, in it, you will also explore the authors' well-known obsession through clear and precise topics. Tis book is not simply a technical guide about using the C# language. It covers statements, data types, classes, generics, concurrency, and even functional and dynamic programming, plus the array of new features in the latest C# language. However, if you are only armed with these tools, you won't go too far even with building toy applications. It is also important for you to know about the foundational aspects of the .NET platform, such as refection, collections, regular expressions, fles, streams, serialization, and LINQ. Anything else? You bet! Error handling, exceptions, garbage collection, and memory management also have a reserved chapter, before ending with an overview of C#8 in the context of .NET Core 3 and unit testing. In spite of the title, this is not simply the umpteenth book on a popular programming language. It is a book about how to use a popular programming language to its fullest for building .NET applications on a solid foundation. Dino Esposito Digital Strategist, Youbiquitous.net Contributors About the authors Marius Bancila is a sofware engineer with almost two decades of experience in developing solutions for the industrial and fnancial sectors. He is the author of Modern C++ Programming Cookbook and Te Modern C++ Challenge. He works as a sofware architect and is focused on Microsof technologies, mainly developing desktop applications with C++ and C#, but not solely. He is passionate about sharing his technical expertise with others and, for that reason, he has been recognized as a Microsof MVP for C++ and later developer technologies since 2006. I would like to thank everybody that made this book possible. To Rafaele and Ankit for laboring on this project together and making it a great book. To Omprakash for his useful comments. To Ruvika for all her support and patience during the project. To Alok, Storm, and all the other people at Packt that helped turn this book from an idea to reality. Rafaele Rialdi is a senior sofware architect working as a consultant, speaker, and trainer. Since 2003, he is a Microsof MVP in the Developer Security category. His passion for the community leads him to be a member of the board of UGIdotNET, president of DotNetLiguria, and co-founder of the Italian C++ user group. Currently, he is working as an architect and developer on the backend of an enterprise project with a specifc focus on code generation, and working on cross-platform mobile and IoT development in both C# and C++. You can fnd him on Twitter with the handle @raffaeler. A big thank you goes to my fellow co-authors, Marius and Ankit, for their great work; Omprakash for his valuable reviews; the entire Packt team, who did a great job in letting me work with peace of mind; and, last but not least, Ruvika for her great patience in coordinating with all of us. Ankit Sharma is a sofware engineer currently working as Senior Member Technical with ADP in Hyderabad, India. He has over six years of extensive experience with Microsof technologies, including C#, ASP.NET, and SQL Server, and UI technologies such as jQuery, Angular, and Blazor. Ankit is a technical author and speaker and loves to contribute to the open source community. He writes articles for multiple platforms, including c-sharpcorner, Dzone, Medium, and freeCodeCamp. For his dedicated contribution to the developer's community, he has been recognized as c-sharpcorner MVP, Dzone MVB, and a top contributor in the technology category on Medium. He is also the author of the frst ever book on Blazor – Blazor Quick Start Guide. You can tweet him at @ankitsharma_007. I would like to thank my mother for her continuous support throughout the process of writing this book. I would also like to thank my co-authors, Marius and Rafaele, for their constructive feedback throughout the writing process, which was crucial in enhancing the quality of the content. About the reviewer Omprakash Pandey is a seasoned sofware technology professional associated with Synergetics. He has provided innovative solutions on C, C++, Java (Core, Intermediate, and Advanced), .NET (Basic), ADO.NET, WCF, WF, ASP.NET MVC, Microsof 365, Microsof Azure, infrastructure management for portal development and deployment, and services development. Packt is searching for authors like you If you're interested in becoming an author for Packt, please visit authors. packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specifc hot topic that we are recruiting an author for, or submit your own idea. Table of Contents Preface 1 Starting with the Building Blocks of C# The history of C# 18 Xamarin 32 Understanding the CLI 20 Assemblies in .NET 33 Common Type System (CTS) 22 Global Assembly Cache (GAC) 33 Common Language Specifcation (CLS) 22 Runtime package store
Recommended publications
  • Non-Invasive Software Transactional Memory on Top of the Common Language Runtime
    University of Neuchâtel Computer Science Department (IIUN) Master of Science in Computer Science Non-Invasive Software Transactional Memory on top of the Common Language Runtime Florian George Supervised by Prof. Pascal Felber Assisted by Patrick Marlier August 16, 2010 This page is intentionally left blank Table of contents 1 Abstract ................................................................................................................................................. 3 2 Introduction ........................................................................................................................................ 4 3 State of the art .................................................................................................................................... 6 4 The Common Language Infrastructure .................................................................................. 7 4.1 Overview of the Common Language Infrastructure ................................... 8 4.2 Common Language Runtime.................................................................................. 9 4.3 Virtual Execution System ........................................................................................ 9 4.4 Common Type System ........................................................................................... 10 4.5 Common Intermediate Language ..................................................................... 12 4.6 Common Language Specification.....................................................................
    [Show full text]
  • Common Language Infrastructure (CLI) Partitions I to IV
    Standard ECMA-335 December 2001 Standardizing Information and Communication Systems Common Language Infrastructure (CLI) Partitions I to IV Phone: +41 22 849.60.00 - Fax: +41 22 849.60.01 - URL: http://www.ecma.ch - Internet: [email protected] Standard ECMA-335 December 2001 Standardizing Information and Communication Systems Common Language Infrastructure (CLI) Partitions I to IV Partition I : Concepts and Architecture Partition II : Metadata Definition and Semantics Partition III : CLI Instruction Set Partition IV : Profiles and Libraries Phone: +41 22 849.60.00 - Fax: +41 22 849.60.01 - URL: http://www.ecma.ch - Internet: [email protected] mb - Ecma-335-Part-I-IV.doc - 16.01.2002 16:02 Common Language Infrastructure (CLI) Partition I: Concepts and Architecture - i - Table of Contents 1Scope 1 2 Conformance 2 3 References 3 4 Glossary 4 5 Overview of the Common Language Infrastructure 19 5.1 Relationship to Type Safety 19 5.2 Relationship to Managed Metadata-driven Execution 20 5.2.1 Managed Code 20 5.2.2 Managed Data 21 5.2.3 Summary 21 6 Common Language Specification (CLS) 22 6.1 Introduction 22 6.2 Views of CLS Compliance 22 6.2.1 CLS Framework 22 6.2.2 CLS Consumer 22 6.2.3 CLS Extender 23 6.3 CLS Compliance 23 6.3.1 Marking Items as CLS-Compliant 24 7 Common Type System 25 7.1 Relationship to Object-Oriented Programming 27 7.2 Values and Types 27 7.2.1 Value Types and Reference Types 27 7.2.2 Built-in Types 27 7.2.3 Classes, Interfaces and Objects 28 7.2.4 Boxing and Unboxing of Values 29 7.2.5 Identity and Equality of Values 29
    [Show full text]
  • Python Guide Documentation 0.0.1
    Python Guide Documentation 0.0.1 Kenneth Reitz 2015 11 07 Contents 1 3 1.1......................................................3 1.2 Python..................................................5 1.3 Mac OS XPython.............................................5 1.4 WindowsPython.............................................6 1.5 LinuxPython...............................................8 2 9 2.1......................................................9 2.2...................................................... 15 2.3...................................................... 24 2.4...................................................... 25 2.5...................................................... 27 2.6 Logging.................................................. 31 2.7...................................................... 34 2.8...................................................... 37 3 / 39 3.1...................................................... 39 3.2 Web................................................... 40 3.3 HTML.................................................. 47 3.4...................................................... 48 3.5 GUI.................................................... 49 3.6...................................................... 51 3.7...................................................... 52 3.8...................................................... 53 3.9...................................................... 58 3.10...................................................... 59 3.11...................................................... 62
    [Show full text]
  • Programming with Windows Forms
    A P P E N D I X A ■ ■ ■ Programming with Windows Forms Since the release of the .NET platform (circa 2001), the base class libraries have included a particular API named Windows Forms, represented primarily by the System.Windows.Forms.dll assembly. The Windows Forms toolkit provides the types necessary to build desktop graphical user interfaces (GUIs), create custom controls, manage resources (e.g., string tables and icons), and perform other desktop- centric programming tasks. In addition, a separate API named GDI+ (represented by the System.Drawing.dll assembly) provides additional types that allow programmers to generate 2D graphics, interact with networked printers, and manipulate image data. The Windows Forms (and GDI+) APIs remain alive and well within the .NET 4.0 platform, and they will exist within the base class library for quite some time (arguably forever). However, Microsoft has shipped a brand new GUI toolkit called Windows Presentation Foundation (WPF) since the release of .NET 3.0. As you saw in Chapters 27-31, WPF provides a massive amount of horsepower that you can use to build bleeding-edge user interfaces, and it has become the preferred desktop API for today’s .NET graphical user interfaces. The point of this appendix, however, is to provide a tour of the traditional Windows Forms API. One reason it is helpful to understand the original programming model: you can find many existing Windows Forms applications out there that will need to be maintained for some time to come. Also, many desktop GUIs simply might not require the horsepower offered by WPF.
    [Show full text]
  • 0672325756 A020601
    .NET Refresher A020601 .NET is the latest version of the component-based architec- ture that Microsoft has been developing for a number of years to support its applications and operating systems. As the name suggests, .NET provides a range of technologies specially designed to enable applications to be integrated across a network, often using XML as the glue between the different components. In turn, this helps it support many of the emerging standards for application in development, including UDDI, SOAP Messaging, WSDL, and other Web services standards to enable you to build XML Web services applications. The .NET Framework consists of the main technology components and libraries that support .NET application development. By using .NET, it’s possible to build a desktop application, a desktop interface to a Web applica- tion, or a Web application and still use the same toolkits and libraries. It’s even possible to convert a desktop appli- cation to a Web-based one and provide both application types by using the same core code base. The real benefit of .NET, however, is how it integrates with other applications and, more importantly, with other components within the .NET system. Existing application development models rely on compiling an application written in one language into a native format directly executable by the operating system and the underlying hardware. With .NET, application components are compiled from their native language (C++, Java, Perl) to run in the Common Language Runtime (CLR). This means that a single application can be made up of components written in a number of different languages—each component using the strengths of each language while simultaneously contributing toward a common goal.
    [Show full text]
  • PV178: Programming for .NET Framework Introduction to .NET and C
    Introduction to .NET Framework Introduction to C# References PV178: Programming for .NET Framework Introduction to .NET and C# VojtˇechForejt, forejt@fi.muni.cz Martin Osovsk´y,[email protected] Faculty of Informatics and Institute of Computer Science Masaryk University March 14, 2010 Introduction to .NET Framework Introduction to C# References Overveiw Microsoft.Net Technology Suite standards (CLI) and their implementations (CLR) programming languages (C# among others) development tools (Microsoft Visual Studio, Microsoft .Net Framework SDK) runtime (Microsoft .Net Framework) application toolkits (ASP.Net, ADO.Net,. ) Introduction to .NET Framework Introduction to C# References CLI Overview Common Language Infrastructure international standard (ECMA #335, ISO/IEC 23271:2003), see [7] a standard base for creating execution and development environments interoperability { languages and libraries conforming to the standard should work together seamlessly Introduction to .NET Framework Introduction to C# References CLI Overview CLI Components CLI itself defines the Common Type System (CTS) the Common Language Specification (CLS) metadata (description of the code units, such as visibility, security requirements, etc.) portable and platform-agnostic file format for managed code common Intermediate Language (CIL) instruction set basic requirements on the Virtual Execution System a programming framework (a class library) Introduction to .NET Framework Introduction to C# References Common Type System CTS: the Common Type System The Complete set of types available to a CLI-compliant language based both on representation of values and their behaviour designed for language interoperability designed via set of rules { types are extensible (by derivation), type system is not designed for broad coverage: object-oriented, procedural and functional languages (C#, JScript, C++, F#, COBOL, J#, etc.
    [Show full text]
  • Pdf for a Detailed Explanation, Along with Various Techniques for Debouncing
    MicroPython Documentation Release 1.11 Damien P. George, Paul Sokolovsky, and contributors May 29, 2019 CONTENTS i ii CHAPTER ONE MICROPYTHON LIBRARIES Warning: Important summary of this section • MicroPython implements a subset of Python functionality for each module. • To ease extensibility, MicroPython versions of standard Python modules usually have u (“micro”) prefix. • Any particular MicroPython variant or port may miss any feature/function described in this general docu- mentation (due to resource constraints or other limitations). This chapter describes modules (function and class libraries) which are built into MicroPython. There are a few categories of such modules: • Modules which implement a subset of standard Python functionality and are not intended to be extended by the user. • Modules which implement a subset of Python functionality, with a provision for extension by the user (via Python code). • Modules which implement MicroPython extensions to the Python standard libraries. • Modules specific to a particular MicroPython port and thus not portable. Note about the availability of the modules and their contents: This documentation in general aspires to describe all modules and functions/classes which are implemented in MicroPython project. However, MicroPython is highly configurable, and each port to a particular board/embedded system makes available only a subset of MicroPython libraries. For officially supported ports, there is an effort to either filter out non-applicable items, or mark individual descriptions with “Availability:” clauses describing which ports provide a given feature. With that in mind, please still be warned that some functions/classes in a module (or even the entire module) described in this documentation may be unavailable in a particular build of MicroPython on a particular system.
    [Show full text]
  • Comparison of C++ and C
    Comparison of C++ and C# Jim Fawcett CSE681 – Software Modeling and analysis Summer 2005 Table of Contents • Object Models • C# Language • C# Object Model • Common Type System • C# Object Type • Type Class • Class Browser in IDE • Delegates • Events • Threads • Assemblies • C# Libraries Both are Important • C++ has a huge installed base. • Your next employer is very likely to be a C++ house. • C# is gaining popularity very quickly. • But, your next employer may not yet do C#. • CSE681 – Software Modeling and Analysis • Focuses almost exclusively on C# and .Net. • CSE687 – Object Oriented Design: • Focuses almost exclusively on C++ and the Standard Library. Comparison of Object Models Contents • C++ Object Model • .Net Object Model • All objects share a rich memory model: • More Spartan memory model: • Static, stack, and heap • Value types are stack-based only. • Rich object life-time model: • Reference types (all user defined types • Static objects live of the duration of the and library types) live on the heap. program. • Non-deterministic life-time model: • Objects on stack live within a scope defined • All reference types are garbage collected. by { and }. • That’s the good news. • Objects on heap live at the designer’s • That’s the bad news. descretion. • Semantics based on a shallow reference • Semantics based on a deep copy model. model. • That’s the good news. • For compilation, client’s use their • That’s the bad news. server’s meta-data. • For compilation, clients carry their • That is great news. server’s type information. • It is this property that makes .Net • That’s definitely bad news.
    [Show full text]
  • Discovering Ironpython
    PART I Introducing IronPython ⊲⊲ CHAPTER 1: Discovering IronPython ⊲⊲ CHAPTER 2: Understanding the IronPython Basics COPYRIGHTED MATERIAL 548592c01.indd 1 2/24/10 12:47:07 PM 548592c01.indd 2 2/24/10 12:47:08 PM 1 Discovering IronPython WHAT’S IN THIS CHAPTER? ➤➤ Understanding why you want to add IronPython to your developer toolbox ➤➤ Obtaining and installing IronPython on your machine ➤➤ Understanding some underlying basics of how IronPython works ➤➤ Using IronPython at the console and within a window ➤➤ Designing and building a simple application IronPython: It sounds like some kind of metal snake infesting your computer, but it isn’t. IronPython is the .NET version of the open source Python language (http://www .python.org/). Python is a dynamic language that can greatly enhance your programming experience, help you create applications in less time, and make the applications you create significantly more responsive to user needs. Of course, you’ve heard these promises before from other languages. This chapter helps you understand how IronPython delivers on these promises in specific situations. The smart developer soon learns that every language serves specific needs and might not work well in others. So this chapter isn’t here to blow smoke at you — ​once you complete it, you’ll understand the strengths and weaknesses of IronPython. Of course, you’ll need to obtain a copy of IronPython before you can use it because Visual Studio doesn’t include IronPython as part of the default installation. This chapter helps you get IronPython installed on your system and tells you about some options you may want to install as well.
    [Show full text]
  • Comparative Studies of Six Programming Languages
    Comparative Studies of Six Programming Languages Zakaria Alomari Oualid El Halimi Kaushik Sivaprasad Chitrang Pandit Concordia University Concordia University Concordia University Concordia University Montreal, Canada Montreal, Canada Montreal, Canada Montreal, Canada [email protected] [email protected] [email protected] [email protected] Abstract Comparison of programming languages is a common topic of discussion among software engineers. Multiple programming languages are designed, specified, and implemented every year in order to keep up with the changing programming paradigms, hardware evolution, etc. In this paper we present a comparative study between six programming languages: C++, PHP, C#, Java, Python, VB ; These languages are compared under the characteristics of reusability, reliability, portability, availability of compilers and tools, readability, efficiency, familiarity and expressiveness. 1. Introduction: Programming languages are fascinating and interesting field of study. Computer scientists tend to create new programming language. Thousand different languages have been created in the last few years. Some languages enjoy wide popularity and others introduce new features. Each language has its advantages and drawbacks. The present work provides a comparison of various properties, paradigms, and features used by a couple of popular programming languages: C++, PHP, C#, Java, Python, VB. With these variety of languages and their widespread use, software designer and programmers should to be aware
    [Show full text]
  • Introducing .NET Standard @Dotnet @Aspnet September 26, 2016 by Immo Landwerth [MSFT] // 199 Comments
    Server & Tools Blogs > Developer Tools Blogs > .NET Blog Sign in .NET Blog A first-hand look from the .NET engineering teams Introducing .NET Standard @dotnet @aspnet September 26, 2016 by Immo Landwerth [MSFT] // 199 Comments Share 2K 1622 1175 Search MSDN with Bing Questions? Check out the .NET Standard FAQ. You can find the latest version of the Search this blog compatibility matrix here. Search all blogs In my last post, I talked about how we want to make porting to .NET Core easier. In this post, I’ll Tags focus on how we’re making this plan a reality with .NET Standard. We’ll cover which APIs we plan to include, how cross-framework compatibility will work, and what all of this means for .NET Core. .NET .NET Core If you’re interested in details, this post is for you. But don’t worry if you don’t have time or you’re not interested in details: you can just read the TL;DR section. .net framework .NET Update For the impatient: TL;DR announcement .NET Standard solves the code sharing problem for .NET developers across all platforms by bringing asp.net ASP.NET Core open in browser PRO version Are you a developer? Try out the HTML to PDF API pdfcrowd.com asp.net all the APIs that you expect and love across the environments that you need: desktop applications, async azure c# clr mobile apps & games, and cloud services: bcl codegen .NET Standard is a set of APIs that all .NET platforms have to implement. This unifies the community .NET platforms and prevents future fragmentation.
    [Show full text]
  • Points-To and Side-Effect Analyses for Programs Built with Precompiled
    Points-to and Side-effect Analyses for Programs Built with Precompiled Libraries Atanas Rountev and Barbara G. Ryder Department of Computer Science, Rutgers University, Piscataway, NJ 08854, USA {rountev,ryder}@cs.rutgers.edu Abstract. Large programs are typically built from separate modules. Traditional whole-program analysis cannot be used in the context of such modular development. In this paper we consider analysis for programs that combine client modules with precompiled library modules. We define separate analyses that allow library modules and client modules to be analyzed separately from each other. Our target analyses are Andersen’s points-to analysis for C [1] and a side-effect analysis based on it. We perform separate points-to and side-effect analyses of a library module by using worst-case assumptions about the rest of the program. We also show how to construct summary information about a library module and how to use it for separate analysis of client modules. Our empirical results show that the separate points-to analyses are practical even for large modules, and that the cost of constructing and storing library summaries is low. This work is a step toward incorporating practical points-to and side-effect analyses in realistic compilers and software productivity tools. 1 Introduction Large programs are typically built from separate modules. Such modular devel- opment allows better software management and provides a practical compilation model: instead of (re)compiling large programs from scratch, compilers can per- form separate compilation of individual modules. This approach allows sharing of modules between programs; for example, an already compiled library module can be reused with no implementation or compilation cost.
    [Show full text]