Building CLI Applications with C# and .NET: A step-by-step guide to developing cross-platform CLI apps-from coding and testing to deployment

Building CLI Applications with C# and .NET: A step-by-step guide to developing cross-platform CLI apps-from coding and testing to deployment

Building CLI Applications with C# and .NET: A step-by-step guide to developing cross-platform CLI apps-from coding and testing to deployment
Автор: Belmansour Tidjani
Дата выхода: 2025
Издательство: Packt Publishing Limited
Количество страниц: 293
Размер файла: 8.0 MB
Тип файла: PDF
Добавил: Aleks-5
 Проверить на вирусы  Дополнительные материалы 

Building CLI Applications with C# and .NET....2

Foreword....5

Contributors....6

About the author....6

About the reviewer....7

Learn more on Discord....8

Preface....24

Who this book is for....25

What this book covers....26

To get the most out of this book....26

Download the example code files....27

Conventions used....27

Get in touch....28

Share Your Thoughts....28

Download a free PDF copy of this book....28

Part 1: Getting Started with CLI Applications....30

Chapter 1: Introduction to CLI Applications....31

A day in the life of an IT professional....31

Why care about CLI applications?....32

To CLI or not to CLI?....33

CLI applications as the building block for creating workstation profiles....33

Even heavy graphical applications have a CLI tool!....34

Even ChatGPT has a CLI!....34

Summary....34

Chapter 2: Setting Up the Development Environment....36

Technical requirements....36

Installing Visual Studio Code....36

Installing the required extensions....38

Installing the .NET SDK....41

Installing and configuring Git....44

Summary....49

Your turn!....49

Chapter 3: Basic Concepts of Console Applications in .NET....50

Technical requirements....50

Creating (and executing) a simple console application....50

Working with the System.Console class....58

Useful properties....58

Useful methods....59

Useful event....63

One more thing....65

Summary....67

Your turn!....68

Part 2: Foundations of Building CLI Applications....69

Chapter 4: Command-Line Parsing....70

Technical requirements....70

Creating the console application....70

Parsing the arguments of a console application....72

From console to CLI – parsing the arguments using an existing library....75

Adding the root command....76

Adding the link command....78

About commands....79

Do all commands need to have a handler method?....79

Adding options to the link command....79

What other types of options can we use?....81

Getting help....81

Getting the application’s version number....84

Summary....85

Your turn!....85

Task #1 – Delete an existing bookmark....86

Task #2 – Update an existing bookmark....86

Task #3 – List all existing bookmarks....86

Chapter 5: Input/Output and File Handling....88

Technical requirements....88

Controlling input values for an option....88

Required versus non-required options....88

What about arguments?....94

Setting a default value for an option....94

Controlling the allowed values for an option....96

Validating input values....99

Adding multiple elements in one go....101

Working with files passed in as options values....105

Summary....110

Your turn!....110

Task #1 – validating the format and the ability to access the input file....111

Task #2 – merging existing links from the input file....111

Chapter 6: Error Handling and Logging....112

Technical requirements....112

Handling errors in CLI applications....112

Handling exceptions....112

Handling errors doesn’t necessarily mean handling exceptions....116

Handling program termination....117

Logging in CLI applications....119

Why JSON?....120

Why Serilog?....120

Accessing IServiceCollection....121

Adding Serilog to IServiceCollection....121

Adding (and configuring) the required Serilog sinks....121

Configuring sinks in appsettings.json....122

Let’s log something!....125

Closing and gracefully disposing of Serilog....127

Summary....128

Your turn!....128

Task #1 – Handling errors for the Import command....128

Task #2 – Logging errors to a file....128

Part 3: Advanced Topics in CLI Application Development....130

Chapter 7: Interactive CLI Applications....131

Technical requirements....131

Building interactive command-line applications....131

Adding a FIGlet....132

Designing user-friendly CLI applications....134

Enhancing text display using markup....134

Offering choices to the user using selection prompts....137

Showing live progress of the export command....139

Displaying bookmarks in a tree view....141

To be or not to be interactive?....143

Summary....143

Your turn!....144

Task 1 – present a bookmark in a user-friendly way....144

Task 2 – change the category of a bookmark interactively....144

Chapter 8: Building Modular and Extensible CLI Applications....145

Technical requirements....145

Step 1 – building a code map of the application....145

Using the Help menu to build the code map....146

Step 2 – deciding where to start....148

Step 3 – designing the project structure....148

Step 4 – refactoring the export command....149

Step 5 – applying the dependency inversion principle....151

Step 6 – refactoring the Program class....153

Step 7 – running the program....155

Taking refactoring to new heights....156

Updating the project structure....158

Summary....160

Your turn!....160

Task #1 – refactor the remaining commands....160

Chapter 9: Working with External APIs and Services....161

Technical requirements....161

Why consume external APIs?....161

How to consume an external API....162

Benefits of using IHttpClientFactory....162

Bookmarkr: your bookmarks, anywhere!....163

The sync command....163

Registering the sync command....165

Running the program....166

Reducing the coupling between our application and the external dependency....167

About the Service Agent pattern....168

Implementing the Service Agent pattern....168

Rerunning the program....171

Summary....172

Your turn!....172

Task #1 – adding SQLite as a data store....172

Task #2 – retrieving the web page name based on its URL....173

Part 4: Testing and Deployment....174

Chapter 10: Testing CLI Applications....175

Technical requirements....175

Why is testing so important?....175

Types of tests....176

About usability tests....177

The pyramid of (software) testing....178

What should we test?....179

What not to test....181

Testing is a safety net....181

When should we run tests?....181

Adding a test project to Bookmarkr....182

Structuring the test project....183

Code artifacts that should not be tested....185

Writing effective tests....186

Running our tests....187

Mocking external dependencies....188

The role of mocking....189

How to mock an external dependency....189

Mocking the BookmarkService service....190

Using the mock version of the BookmarkService service....190

Changes to the code must be made!....191

Going back to implementing the test cases....192

Internals visibility....194

Centralizing test initialization....195

How to hunt a bug....196

Summary....196

Your turn!....196

Task #1 – Write the required unit tests for the remaining functionalities....197

Task #2 – Write integration tests for the sync command....197

Chapter 11: Packaging and Deployment....198

Technical requirements....198

A bit of terminology....198

Packaging and distribution options for CLI applications....199

Packaging and distributing a CLI application....200

Option #1 – as a .NET tool....200

Option #2 – as a Docker container....206

Option #3 – as a WinGet package....210

Managing versions of the application....215

Semantic versioning primer....215

Managing versions of a .NET tool....216

Managing versions of a Docker container....217

Managing versions of a WinGet package....220

Summary....221

Your turn!....222

Task #1 – allowing Linux users to install Bookmarkr using apt-get....222

Task #2 – allowing macOS users to install Bookmarkr using Homebrew....222

Part 5: Advanced Techniques and Best Practices....223

Chapter 12: Performance Optimization and Tuning....224

Technical requirements....224

Performance optimization areas....224

Instrumenting .NET applications....225

Hot spots versus hot paths....226

Identifying the application’s hot spots and hot paths....226

Profiling Bookmarkr with BenchmarkDotNet....227

Monitoring BookmarkrSyncr with Azure Application Insights....232

Common performance optimization techniques....232

Optimizing Bookmarkr’s performance....234

Summary....236

Your turn!....237

Task #1 – Write more benchmarks....237

Task #2 – Fine-tune Bookmarkr for optimal performance....237

Chapter 13: Security Considerations for CLI Applications....238

Technical requirements....238

Security areas....238

Assessing the security posture of a CLI application....240

Securing remote communications using authentication....243

Why is authentication important?....243

How to perform authentication....243

Implementing authentication....244

Authenticating external services using a PAT....244

Passing the PAT from the CLI application to the external service....246

Summary....251

Your turn!....251

Task #1 – Update dependency versions....251

Task #2 – Use Mend Bolt to scan the code for vulnerabilities....252

Task #3 – Allow BookmarkrSyncr to manage multiple users....252

Chapter 14: Additional Resources and Libraries....253

Further reading and resources....253

C# 12 and .NET 8, by Mark J. Price....253

Refactoring with C#, by Matt Eland....254

Pragmatic Test-Driven Development in C# and .NET, by Adam Tibi....257

C# 7 and .NET Core 2.0 High Performance, by Ovais Mehboob Ahmed Khan....259

Useful libraries for CLI application development....261

Polly....261

HangFire....261

StackExchange.Redis....262

MediatR....262

MassTransit....262

BenchmarkDotNet....262

Portable.BouncyCastle....262

NSubstitute....263

AutoFixture....263

RichardSzalay.MockHttp....263

Summary....263

Your turn!....263

Task #1 – List additional features for Bookmarkr....264

Task #2 – List the skills and libraries you need to implement a feature....264

Index....265

Why subscribe?....280

Other Books You May Enjoy....280

Packt is searching for authors like you....284

Share Your Thoughts....284

Download a free PDF copy of this book....284

Unlock the potential of .NET to design, test, and deploy robust CLI applications, including development, security, and monitoring

Key Features

  • Receive expert guidance on building CLI applications with .NET
  • Implement advanced techniques for creating cross-platform, modular, and robust CLI applications
  • Put your knowledge into practice through hands-on exercises and real-world projects
  • Purchase of the print or Kindle book includes a free PDF eBook

Book Description

Developers and system administrators often face challenges like inefficient workflows, complex system operations, and the growing demand for robust automation tools. CLI applications provide a powerful solution by enhancing flexibility, efficiency, and productivity in various environments. This book will guide you through mastering the development of robust command-line tools using .NET.

Written by a Microsoft Azure MVP, the book’s hands-on approach ensures practical experience with real-world projects. You’ll start with an overview of foundational principles, essential concepts, and best practices for CLI application development. From there, you’ll advance to creating interactive interfaces, integrating with external APIs and services, and implementing security measures to safeguard your applications. Each chapter will build progressively from basic to advanced topics.

Beyond development, you’ll learn how to enhance application quality through testing, package for efficient distribution, and deploy effectively. The book also teaches strategies to optimize performance to ensure your applications run efficiently under heavy usage.

By the end of this book, you’ll have gained a deep understanding of CLI application development with .NET to build modular, extensible, and easy-to-maintain applications.

What you will learn

  • Master CLI application development principles to enhance productivity
  • Build modular and extensible CLI applications that adapt to evolving needs
  • Develop interactive CLI applications for engaging user experiences
  • Integrate external APIs and services to extend functionality
  • Implement robust security measures to ensure data protection
  • Improve quality and reliability through comprehensive testing
  • Package and deploy CLI applications efficiently for smooth releases
  • Optimize performance to achieve high efficiency and effectiveness

Who this book is for

This book is for software developers, architects, and DevOps engineers aiming to enhance their existing SaaS platforms or optimize system operations. It focuses on providing users with CLI applications that automate and streamline workflows, unlocking operational efficiency. A basic understanding of programming concepts and prior experience with .NET and C# is expected, as this book doesn't cover introductory material.


Похожее:

Список отзывов:

Нет отзывов к книге.