📄 Page
1
M A N N I N G Dustin Metzgar Foreword by Scott Hanselman SECOND EDITION
📄 Page
2
Praise for the first edition A great on ramp to the world of .NET and .NET Core. You’ll learn the why, what, and how of building sys- tems on this new platform. —From the foreword by Scott Hanselman, Microsoft Covers valuable use cases such as data access, web app development, and deployment to multiple plat- forms. —Viorel Moisei, Gabriels Technology Solutions Teaches you to write code that ports across all platforms; also includes tips for porting legacy code to .NET Core. —Eddy Vluggen, Cadac Covers all the new tools and features of .NET Core. Brain-friendly. —Tiklu Ganguly, ITC Infotech I highly recommend to all of my colleagues, beginners or experienced. —Renil Abdulkader, KPMG LLP I’ve never worked with .NET before, but this book makes it easy to pick up . . . and makes it feel as cool as node.js. —Daut Morina, Livingdocs AG Just what I needed to start using .NET Core. —Daniel Vásquez, Raet
📄 Page
3
(This page has no text content)
📄 Page
4
.NET in Action SECOND EDITION DUSTIN METZGAR FOREWORD BY SCOTT HANSELMAN M A N N I N G SHELTER ISLAND
📄 Page
5
For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: orders@manning.com ©2024 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. The author and publisher have made every effort to ensure that the information in this book was correct at press time. The author and publisher do not assume and hereby disclaim any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from negligence, accident, or any other cause, or from any usage of the information herein. Manning Publications Co. Development editor: Dustin Archibald 20 Baldwin Road Technical editor: Gerald Versluis PO Box 761 Review editors: Adriana Sabo and Dunja Nikitović Shelter Island, NY 11964 Production editor: Kathy Rossland Copy editor: Keir Simpson Proofreader: Jason Everett Technical proofreader: Ricardo Peres Typesetter: Gordan Salinovic Cover designer: Marija Tudor ISBN 9781633439313 Printed in the United States of America
📄 Page
6
v brief contents PART 1 THE BASICS .....................................................................1 1 ■ Why .NET? 3 2 ■ Building a console application 16 3 ■ Creating web services and applications with ASP.NET Core 36 PART 2 DATA ...........................................................................57 4 ■ File and network I/O 59 5 ■ Using Entity Framework Core with relational databases 86 PART 3 TESTING .....................................................................117 6 ■ Unit-testing fundamentals 119 7 ■ Substituting dependencies in tests 139 8 ■ Integration testing 161
📄 Page
7
BRIEF CONTENTSvi PART 4 GETTING READY FOR RELEASE..........................................187 9 ■ Security 189 10 ■ Performance and profiling 218 11 ■ Handling failures 239 12 ■ Building world-ready applications 261 13 ■ Working with containers 280
📄 Page
8
vii contents foreword xii preface xiv acknowledgments xvi about this book xviii about the author xxi about the cover illustration xxii PART 1 THE BASICS............................................................1 1 Why .NET? 3 1.1 What is .NET? 4 1.2 Where is .NET used? 6 .NET in gaming and 3D graphics 6 ■ Popular .NET open source projects 7 1.3 When to use .NET 8 1.4 What will I learn from this book? 9 1.5 What is in the .NET runtime? 10 Intermediate language 11 ■ JIT compilation 12 ■ Garbage collection 13
📄 Page
9
CONTENTSviii 2 Building a console application 16 2.1 Creating new applications from templates 17 2.2 Building and running 17 2.3 Writing code 18 2.4 Namespaces and conventions 20 2.5 Global using statements 23 2.6 Static using statements 24 2.7 Handling more command-line arguments 25 2.8 C# properties 27 Reflection 33 ■ Interpolated strings 34 ■ Null operators 34 Casting objects to types 35 3 Creating web services and applications with ASP.NET Core 36 3.1 Web services 36 Adding a service that responds with a collection of data 41 ■ Controlling the response 46 3.2 Web applications 49 Razor pages 51 ■ Code-behind 52 PART 2 DATA..................................................................57 4 File and network I/O 59 4.1 Reading and writing files 59 Building a custom template 60 ■ Finding files in folders 62 Finding text in a file 64 ■ Disposing the StreamReader with using 66 ■ Parsing command-line arguments 67 4.2 Working with JSON 68 Reading JSON documents 69 ■ Writing JSON documents 73 JSON serialization 74 4.3 Making HTTP requests 76 4.4 Unblocking programs with asynchronous programming 79 5 Using Entity Framework Core with relational databases 86 5.1 Storing application data 87 5.2 Building your first EF Core application 88 Object-creation shorthand 92 ■ Cleaning up the compiler warnings 92 ■ Creating a relationship 93
📄 Page
10
CONTENTS ix 5.3 Accessing data asynchronously 98 5.4 Using EF Core with ASP.NET Core 102 Request methods 102 5.5 Exposing your API via Swagger/OpenAPI 108 PART 3 TESTING ...........................................................117 6 Unit-testing fundamentals 119 6.1 Writing code that’s easier to test 119 6.2 SOLID principles 120 S: Single responsibility principle 120 ■ O: Open/closed principle 121 ■ L: Liskov substitution principle 122 I: Interface segregation principle 123 ■ D: Dependency inversion principle 123 6.3 An example test application: Sodoku 125 6.4 Building your first xUnit test project 126 6.5 Fact tests 128 6.6 Theory tests 129 Applying SOLID principles to SudokuSolver 131 ■ Testing for exceptions 134 ■ Theory testing with MemberData 135 7 Substituting dependencies in tests 139 7.1 Testing code that relies on the current time 140 7.2 Testing code that uses Streams 144 Memory stream 145 ■ File stream from copied files 145 Manifest resource streams 146 7.3 Finding easier ways to write large strings 147 7.4 Replacing dependencies with fakes 150 Considering an example repository design pattern 150 ■ Setting up the unit-test class 155 ■ Validating faked method calls 156 Verifying the number and order of calls 159 ■ Throwing exceptions from fakes 159 8 Integration testing 161 8.1 Applications with many dependencies 162 8.2 Testing with an in-memory database 164 8.3 Testing HTTP calls 171
📄 Page
11
CONTENTSx 8.4 Broader integration tests 175 8.5 Integration-testing ASP.NET Core APIs 179 PART 4 GETTING READY FOR RELEASE................................187 9 Security 189 9.1 Securing applications 190 9.2 Threat modeling 191 9.3 Setting up HTTPS 193 9.4 Checking for SQL injection vulnerability 195 Adding an interceptor 196 ■ Configuring the connection string safely 202 9.5 ASP.NET Core Identity 203 Setting up Microsoft authentication 206 ■ Authenticating with Swagger UI 209 9.6 Authorization 213 10 Performance and profiling 218 10.1 Why test performance? 219 10.2 Introduction to BenchmarkDotNet 220 10.3 Profiles 224 Capturing profiles with BenchmarkDotNet 225 ■ Analyzing profiles 225 ■ Using PerfView 227 ■ Understanding garbage collection 230 10.4 Web performance testing 235 11 Handling failures 239 11.1 Operating in the real world 239 11.2 EF Core 240 Database transactions 240 ■ Retrying on transient faults 252 11.3 Polly 255 Simulating HTTP errors 257 ■ Other Polly capabilities 259 12 Building world-ready applications 261 12.1 Creating the sample application 262 12.2 Getting resource strings 266
📄 Page
12
CONTENTS xi 12.3 Adding resource languages 269 12.4 ASP.NET Core’s built-in culture support 271 12.5 Internationalization 273 Globalization 273 ■ Localizability review 276 ■ Testing right- to-left languages 276 ■ Other considerations for globalization 277 13 Working with containers 280 13.1 Why use containers? 280 13.2 Container landscape 281 13.3 Building a container image 282 Using .NET 6 and earlier or custom Dockerfile 283 ■ Using .NET 7 and later 289 13.4 Configuration 291 Controlling the .NET environment 292 ■ Configuration order 293 ■ Hierarchical configuration 294 ■ Applying configuration in Docker Desktop 294 ■ Mapping configuration to objects 295 13.5 Secrets 298 appendix A .NET history 301 appendix B Setting up your development environment 305 appendix C MAUI and Blazor 307 appendix D The async state machine 314 appendix E Testing internal members 319 appendix F xUnit supplement 322 index 325
📄 Page
13
xii foreword Six years have passed since I wrote the foreword for the first edition of what was then .NET Core in Action. You’re holding in your hands (or digitally) the massively revised and improved second edition, now titled .NET in Action. The word Core has gone from the branding, as cross-platform .NET is no longer thought of as a less-than-full ver- sion, but today, .NET is recognized as a robust, full-featured, incredibly powerful eco- system. Today, we’re shipping and enjoying .NET 8, with .NET 9 coming reliably at the end of 2024. The community enjoys long-term support versions, and millions of devel- opers and enterprises trust .NET to run their software every day. Modern .NET is in action every day, and it’s fast, it’s portable, and it’s awesome. As Dustin called out in the first edition of his book, you’ll be able to use a host of open source libraries to test your code, access databases, build microservices, and go live, either on your own hardware or in the cloud. Cross-platform GUI apps? .NET can make them happen for you. WebAssembly (WASM)? Check. Today, .NET powers games on your Xbox and Steam Deck, runs massive distributed applications in con- tainers or orchestrated with Kubernetes, but also powers Internet of Things (IoT) devices and microcontrollers with technologies such as Wilderness Labs Meadow and .NET nanoFramework. You’d be hard-pressed to find a computer or system that doesn’t run today’s .NET. This improved second edition includes a ton of new samples, chapters, and revi- sions with more than 300 pages of goodness! Dustin is sure to shout out many of the amazing open source libraries that make the .NET community successful. Whether they’re games and graphics, databases and testing utilities, distributed systems, build
📄 Page
14
FOREWORD xiii tools, or workflows, a ton of fantastic projects out there are pushing .NET to the edges and beyond. Finally, I want to call out the fact that you could hardly find a better guide to the .NET space than Dustin Metzgar. With more than 20 years of experience shipping software, he not only offers deep expertise on .NET, but also provides an inside look with important historical context as someone who worked on the .NET team at Micro- soft. I appreciate Dustin as an open source advocate, community member, technolo- gist, and writer. I hope you enjoy reading, exploring, and learning from this fantastic .NET in Action, Second Edition as much as I did! —SCOTT HANSELMAN, VICE PRESIDENT, DEVELOPER COMMUNITY, MICROSOFT
📄 Page
15
xiv preface Software developers learn throughout their entire careers, which is part of the appeal. The more I learn, the more I discover how much I don’t know (the known unknown). The times when I learned most were the times when an unknown became a known unknown, such as when a whole category of development that I’d never heard of was revealed to me. Subjects such as performance profiling and localization never occurred to me when I started, yet they play important roles in professional software development. With so much information available through blogs, tweets, Stack Overflow, confer- ences, and online documentation, you might wonder whether physical books can still be relevant, especially books about a subject like .NET that might be outdated by the time they reach print. Learning a new software environment is like being dropped into an unfamiliar landscape. You can wander around certain parts that interest you and never see the whole area. A book is like a map and travel guide; it can give you a sense of the whole area and introduce places you may not have explored on your own. By the end of the book, you should feel confident in this new area. I’ve spent a significant portion of my career on .NET. My introduction to .NET happened in Framework 1.0, thanks to a salesperson who didn’t know (or care) that our product was written in Java when the customer wanted .NET. The project to con- vert to .NET and implement it at the customer site turned out to be my favorite con- sulting job. Years later, I was fortunate enough to be hired by Microsoft, where I worked on the .NET Framework and .NET Core. I got to work with many talented
📄 Page
16
PREFACE xv developers and write code that’s now used by countless applications. I still use .NET today even after leaving Microsoft, which has further enriched my understanding. My goal for this book is to provide an overview of the .NET environment so that you’ll feel confident enough about .NET to write and maintain real-world applications. You’ll get more out of this book if you write the code from the chapters and try the exer- cises. In this second edition, I’ve endeavored to make a book that’s not only a great learning resource, but also a handy text to keep on your desk for quick reference.
📄 Page
17
xvi acknowledgments Thanks to the editors at Manning who kept the bar high and helped me write the book I wanted to write. Thanks to Dustin Archibald for guiding me through the whole process. Also, thanks to Melissa Ice for making sure that everything was delivered and to Ivan Martinović and Benjamin Berg for fixing all my AsciiDoc mistakes. A big thanks goes to Scott Hanselman. Scott is a great developer, blogger, and speaker who has worked for many years to advance and evangelize .NET. I’m honored that he wrote the foreword for this book. I’m also grateful to technical editor Gerald Versluis for helping make the manu- script what it is today. Gerald is a senior software engineer at Microsoft, working on .NET MAUI. Since 2009, he’s worked on a variety of projects, ranging from frontend to backend and anything in between that involves C#, .NET, Azure, ASP.NET, and all kinds of other .NET technologies. At some point, he fell in love with cross-platform and mobile development with Xamarin, now .NET MAUI. Since then, he has become an active community member, producing content online and presenting about all things tech at conferences around the world. I’d also like to thank Samer Alameer for his help with the localization chapter. He helped me with the Arabic and also taught me some important points about localization. Finally, thank you to everyone who bought the early-access version of this book and to all the reviewers who provided invaluable feedback along the way: Adhir Ramjiawan, Andrei Tarutin, Barry L. Wallis, Cesar Aguirre, Chad Miars, Chris H. Shin, Dan Sheikh, Daniel McAlister, Daniel Vásquez, Dmitrii Slabko, Ernesto Cardenas, Georg Piwonka, George Onofrei, Jason Hales, Jonathan Reeves, Joe Cuevas, Krishna Chaitanya
📄 Page
18
ACKNOWLEDGMENTS xvii Anipindi, Lakshminarayanan Sampath, Luigi Zambetti, Marios Solomou, Michael Williams, Mitchell Fox, Nikos Kanakaris, Oliver Korten, Renato Gentile, Tom Madden, Viktoria Dolzhenko, and Vladislav Bilay. Your suggestions helped make this book better.
📄 Page
19
xviii about this book .NET in Action was written to help you build applications and services in .NET. It takes you through many important aspects of developing high-quality software for release. Concepts and language features are introduced in action, with examples to show their practical application. Who should read this book Whether you’re new to .NET and C# or a seasoned .NET Framework developer, this book has plenty of useful information for you. Although all this information may be available online through documentation, blogs, and the like, this book compiles and organizes everything in a format that’s clear and easy to follow. The book assumes that you have working knowledge of imperative, object-oriented programming languages such as C++ and Java. Although the book isn’t an instructional guide to C#, it explains key concepts of C# to aid the reader. This book also assumes that you have some profi- ciency with terminals or command lines and text editors. How this book is organized: A road map This book has 13 chapters: ■ Chapter 1 introduces .NET—what it is and why you want to learn it. ■ Chapter 2 gets you started creating .NET console applications. ■ Chapter 3 expands to building web services and applications. ■ Chapter 4 acquaints you with input/output (I/O) fundamentals such as files and HTTP requests.
📄 Page
20
ABOUT THIS BOOK xix ■ Chapter 5 introduces Entity Framework Core (EF Core), a popular way to access databases. ■ Chapter 6 covers how to unit-test. ■ Chapter 7 further enhances your unit-testing prowess by showing you how to use substitutes. ■ Chapter 8 expands into integration testing, which is particularly useful for test- ing web services. ■ Chapter 9 helps you secure your .NET applications. ■ Chapter 10 looks at how to detect and understand performance issues. ■ Chapter 11 shows various ways to recover from failures. ■ Chapter 12 covers the internationalization process and shows you how to make applications world-ready. ■ Chapter 13 walks you through putting your application in containers and han- dling configuration. About the code This book contains many examples of source code, both in numbered listings and inline with normal text. In both cases, source code is formatted in a fixed-width font like this to separate it from ordinary text. Sometimes, code is also in bold to high- light code that has changed from previous steps in the chapter, such as when a new feature adds to an existing line of code. In many cases, the original source code has been reformatted; we’ve added line breaks and reworked indentation to accommodate the available page space in the book. In rare cases, even this was not enough, and listings include line-continuation markers (➥). Additionally, comments in the source code have been removed from the listings when the code is described in the text. Code annotations accompany many of the listings, highlighting important concepts. The source code for the book is located at https://github.com/dmetzgar/ dotnet-in-action-code. This GitHub repository contains all the source code from the book. The complete code for the examples in the book is also available for download from the Manning website at https://www.manning.com/books/dotnet-in-action-second-edition. You can get executable snippets of code from the liveBook (online) version of this book at https://livebook.manning.com/book/dotnet-in-action-second-edition. liveBook discussion forum Purchase of .NET in Action, Second Edition, includes free access to liveBook, Manning’s online reading platform. Using liveBook’s exclusive discussion features, you can attach comments to the book globally or to specific sections or paragraphs. It’s a snap to make notes for yourself, ask and answer technical questions, and receive help from the author and other users. To access the forum, go to https://livebook.manning.com/book/ dotnet-in-action-second-edition/discussion. You can also learn more about Manning’s forums and the rules of conduct at https://livebook.manning.com/discussion.