Metaprogramming in C# - Einar Ingerbrigsten - E-Book

Metaprogramming in C# E-Book

Einar Ingerbrigsten

0,0
32,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

Metaprogramming is an advanced technique that helps developers to automate repetitive tasks, generate scalable code, and enhance productivity in software development. Metaprogramming in C# is a comprehensive guide that will help you reap the full potential of metaprogramming in .NET runtime.
You’ll start by learning about the .NET runtime environment and how you can use it to become a more productive developer. You'll learn how to infer types using reflection, use attributes, and create dynamic proxies. You’ll also explore the use of expressions to create and execute code and how to take advantage of Dynamic Language Runtime.
But that's not all! You’ll also learn to go beyond inheritance and use method signature conventions to create easily maintainable code. Finally, you’ll dive into the world of compiler magic with Roslyn, where you'll discover how to use Roslyn to generate code, perform static code analysis, and write your own compiler extensions.
By the end of this book, you’ll have a deep understanding of metaprogramming concepts and how to apply them to your C# code. You’ll be able to think about types, use attributes and expressions to generate code, and apply crosscutting concerns to improve code quality.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB

Seitenzahl: 398

Veröffentlichungsjahr: 2023

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.



Metaprogramming in C#

Automate your .NET development and simplify overcomplicated code

Einar Ingebrigtsen

BIRMINGHAM—MUMBAI

Metaprogramming in C#

Copyright © 2023 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 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.

Associate Group Product Manager: Kunal Sawant

Publishing Product Manager: Akash Sharma

Content Development Editor: Rosal Colaco

Technical Editor: Maran Fernandes

Copy Editor: Safis Editing

Project Coordinator: Deeksha Thakkar

Proofreader: Safis Editing

Indexer: Manju Arasan

Production Designer: Shyam Sundar Korumilli

Business Development Executive: Debadrita Chatterjee

Developer Relations Marketing Executives: Rayyan Khan and Sonia Chauhan

First published: June 2023

Production reference: 1090623

Published by Packt Publishing Ltd.

Livery Place

35 Livery Street

Birmingham

B3 2PB, UK.

ISBN 978-1-83763-542-9

www.packtpub.com

Contributors

About the author

Einar Ingebrigtsen works as chief architect at Aksio InsurTech, a company focusing on building insurance and pension solutions. His heart is in architecture and improving the lives of developers and he loves to create solutions that make other developers more productive and help in delivering great products to end users. Einar has been developing software professionally since 1994 and has done so in everything from games on different platforms to broadcast TV software, to telecom software, to line of business software within multiple different verticals. Of all of his experiences, he has fallen in love with a specific flavor of architecture, mindset, and approach – namely, event sourcing. Most of his time at work (and spare time) is devoted to building out a platform that has the goal of democratizing event sourcing called Cratis (https://cratis.io).

I want to thank everyone who has been patient with me while writing this book, especially my wife, Anne Grethe, and my two kids, Mia and Herman. It has taken up a lot of my spare time to get this done. I also want to thank everyone at Packt who has been part of the project, giving me pointers and guidance throughout the process. It’s been absolutely invaluable.

About the reviewer

Marius Iulian Mihailescu is an associate lecturer at Spiru Haret University and co-founder/chief research officer at Dapyx Solution, Bucharest, Romania. His work is focused on applied/theoretical cryptography and information security, dealing with the identification process of threats and vulnerabilities using artificial intelligence and machine learning. He is currently also working as an IT project manager at the Institute for Computers, Romania, where he is responsible for the development process of several projects.

His research interests are extended to areas such as computer vision, biometrics, machine learning, artificial intelligence, and deep learning. The goal of his research is focused on understanding the real requirements of complex systems (cloud computing, big data, IoT, etc.) and their applications in different domains (such as computer forensics, behavioral psychology, and financial derivatives), and to provide real and practical solutions for guaranteeing the Confidentiality, Integrity, and Availability (CIA) of the processes.

Marius completed his Ph.D. studies in computer science on improving the security techniques for guaranteeing the confidentiality and integrity of the biometrics data at the Faculty of Mathematics and Computer Science at the University of Bucharest, Romania. During this time, he was also a part-time research associate for the ATHOS (short for, Automated System of Authentication through Biometric Signature) project from S.C. Softwin S.R.L., where he worked on improving the load balancing mechanisms in a parallel computing system.

Table of Contents

Preface

Part 1: Why Metaprogramming?

1

How Can Metaprogramming Benefit You?

Reasoning about your code

Developer concerns

Automation

Metaprogramming

Removing manual structure and process

Maintaining software

Generating code

Compile time safety

Summary

2

Metaprogramming Concepts

Technical requirements

Implicit – using what is already there

Leveraging the power of reflection

Explicit – additional adornment of code

Creating custom attributes

Domain-specific languages

Gherkin – technical sample

Summary

3

Demystifying through Existing Real-World Examples

Technical requirements

Prerequisites for your system

ASP.NET controllers

Custom HTTP Get handler

Controller

ASP.NET validation

Automatically hooking up model state handling

Summary

Part 2: Leveraging the Runtime

4

Reasoning about Types Using Reflection

Technical requirements

Assembly discovery in the running process

Assembly

Leveraging library metadata to get project referenced assemblies

Reusable fundamentals

Business app

Discovering types

Back to business

Domain concepts

Cross-cutting concerns

Open/closed principle applied

Summary

5

Leveraging Attributes

Technical requirements

What is an attribute and how can it be applied?

Limiting attribute usage

Sealing your attribute class

Finding types with specific attributes

Personal Identifiable Information (PII)

Generic attributes

Summary

6

Dynamic Proxy Generation

Technical requirements

An introduction to IL and Reflection.Emit

Creating a dynamic assembly and module

Virtual members and overrides

Implementing an interface

NotifyObjectWeaver class

Summary

7

Reasoning about Expressions

Technical requirements

What are expressions?

Expression

Lambda expression

Traversing an expression tree

Using expressions as descriptors of members on types

Summary

8

Building and Executing Expressions

Technical requirements

Creating your own expressions

Creating expressions as delegates and executing them

Creating a query engine

A MongoDB-like database

Building a simple query engine

Summary

9

Taking Advantage of the Dynamic Language Runtime

Technical requirements

Understanding the DLR

The CLR at a glance

The DLR building blocks

Call sites and binders

Reasoning about a dynamic type

Creating DynamicObject and providing metadata

Building a JSON schema type

Summary

Part 3: Increasing Productivity, Consistency, and Quality

10

Convention over Configuration

Technical requirements

Inversion of control and its role

Refactoring the code

Automatic ServiceCollection registrations by convention

Further refactoring

Composing

Summary

11

Applying the Open-Closed Principle

Technical requirements

Encapsulating type discovery

Encapsulating the discovery of instances

Hooking up with the service collection

Practical use case

Helping the developer

Supporting properties

Using the GDPR infrastructure

Adding more providers

Summary

12

Go Beyond Inheritance

Technical requirements

Method signature conventions

Infrastructure

Using the infrastructure

Summary

13

Applying Cross-Cutting Concerns

Technical requirements

What are cross-cutting concerns?

Leveraging the ASP.NET pipeline

Building consistent result objects

CommandResult

Authorization based on metadata or structure

Summary

14

Aspect-Oriented Programming

Technical requirements

What is AOP?

Aspects

Pointcuts

Join points

Logging

Creating a logging sample

Adding the Microsoft logger

Interceptors

Trying out the interceptor

Mixins

Mixing it up

Authorization

Using pointcuts

Summary

Part 4: Compiler Magic Using Roslyn

15

Roslyn Compiler Extensions

Technical requirements

How to set up a project and its moving parts

What can they do?

Setting it up

Adding common rules

Common project settings

How to package your extension for reuse

Common package properties

Analyzer

Summary

16

Generating Code

Technical requirements

Generating additional code for the Roslyn compiler

ASTs

Application metrics

Improving the developer experience

(Ab)using the compiler to generate not just C# code

Building the generator

Improving the developer experience

Debugging

Optimization

Summary

17

Static Code Analysis

Technical requirements

What is static code analysis?

How to write an analyzer

Fleshing out an analyzer

Handling the syntax nodes

Release tracking

Trying out the analyzer

How to write a code fix for an analyzer

How to write automated tests

Analyzer tests

Code fix tests

Summary

18

Caveats and Final Words

Performance implications

Hidden magic – handle with care

When to use what

Summary

Index

Other Books You May Enjoy

Preface

“Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.”

– Martin Golding

In the world of software, there are so many things that can go wrong and often do go wrong. We’re a relatively young industry that is in an ever-changing state. Things haven’t settled and innovation happens at lightning speed. It’s not like carpentry, which has had a few thousand years of experience of what works and what doesn’t. In software, we’re still inventing the tools and reinventing them as we go. The business benefit and the possibility to increase productivity for our end users sets the expectations high and in an increasingly competitive market, time to market is of the essence.

At the level we write our software today, we have a huge potential to leverage the metadata surrounding our own code to ensure the quality and maintainability of the software we write. This is where the metaprogramming journey starts.

Metaprogramming can be really fun to work with, but it represents true opportunities for developers and businesses to set themselves apart. Things that metaprogramming can do for you include the following:

Improve the maintainability of your codeAutomate tedious tasksLet developers focus more on your business and not the plumbingHelp you stay more compliantReduce risk related to security

There are technical reasons to dive into metaprogramming, as with any other technique, but I think there is true value to be discovered in leveraging it to help you and your team become more productive and, at the end of the day, deliver more business-critical features that are easier to change and maintain over the years.

Who this book is for

The book is for any C# developer who is curious about metaprogramming and what it could do for you. More specifically, the following personas are the target audience:

Developers who are familiar with C# and .NET as a runtime looking to expand their horizons and learn in more depth about the .NET runtime and compiler capabilitiesSoftware architects familiar with C# and .NET and looking for inspiration on how to improve their architectureCTOs or development managers with either a developer background or who understand software development and want inspiration to potentially grease the wheels of the developer organization

What this book covers

Chapter 1, How Can Metaprogramming Benefit You?, dives into what metaprogramming is and how it can improve developers’ day-to-day work. It gives some concrete basic examples to explain its capabilities.

Chapter 2, Metaprogramming Concepts, provides explanations of the differences between implicit and explicit metadata through concrete examples. In addition, it gives an insight into how the .NET runtime works.

Chapter 3, Demystifying through Existing Real-World Examples, shows how Microsoft, as an example, leverages metaprogramming and how you probably already use it.

Chapter 4, Reasoning about Types Using Reflection, provides an overview of how powerful the .NET runtime reflection is and how its implicit metadata can be leveraged.

Chapter 5, Leveraging Attributes, introduces leveraging C# attributes as an explicit metaprogramming technique and how it can be used, giving real-world applicable examples.

Chapter 6, Dynamic Proxy Generation, introduces code that generates code, at runtime. A powerful concept that can really boost your developers’ productivity if used wisely.

Chapter 7, Reasoning about Expressions, provides an introduction to C# and .NET expression trees, how they represent a different aspect of metadata, and how they can be reasoned about and unpacked in your code.

Chapter 8, Building and Executing Expressions, provides an introduction to how you can build your own expressions at runtime and how these can be executed – an alternative technique to generating code.

Chapter 9, Taking Advantage of the Dynamic Language Runtime, covers what the Dynamic Language Runtime is and how it can be used to dynamically generate code – yet another alternative for your code is to create code.

Chapter 10, Convention over Configuration, unravels the superpower of conventions – code that repeats the patterns you probably already have, enabling your developers to become more productive and your code base to become more consistent.

Chapter 11, Applying the Open-Closed Principle, provides a dive into how you can create code bases that are open to extension but closed for modification – a powerful principle for maintainable software, using metaprogramming as an angle into it.

Chapter 12, Go Beyond Inheritance, provides another level on top of regular conventions, giving developers an opportunity to not just be limited by what the programming language offers, aiming for readability and maintainability.

Chapter 13, Applying Cross-Cutting Concerns, unlocks the concept of applying code consistently across an entire code base without having to revert to manual recipes.

Chapter 14, Aspect-Oriented Programming, provides details on the formalization of aspect-oriented programming and how this can help you provide cross-cutting concerns as a more formal technique.

Chapter 15, Roslyn Compiler Extensions, details the basics of what the .NET compiler SDK offers and how to get started with it, serving as the basis for the following chapters.

Chapter 16, Generating Code, provides an introduction to how you can generate code using code at the compiler level before you enter runtime – yet another great way to improve your developers’ productivity and provide consistency in your code base.

Chapter 17, Static Code Analysis, provides an introduction to how you can build your own rules that perform analysis on any code being added to your project, helping you create consistent, uniform, and more maintainable code.

Chapter 18, Caveats and Final Words, looks into what the book has covered, what benefits there are, and what caveats there are. As with anything, you have to strike the right balance and know what to use when.

To get the most out of this book

Software/hardware covered in the book

Operating system requirements

C# using .NET 7

Windows, macOS, or Linux

Postman

Windows, macOS, or Linux

MongoDB

Windows, macOS, or Linux

If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code.

Download the example code files

You can download the example code files for this book from GitHub at https://github.com/PacktPublishing/Metaprogramming-in-C-Sharp. If there’s an update to the code, it will be updated in the GitHub repository.

We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Download the color images

We also provide a PDF file that has color images of the screenshots and diagrams used in this book. You can download it here: https://packt.link/nZUlx.

Conventions used

There are a number of text conventions used throughout this book.

Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “The provider looks for ConfidentialAttribute to decide whether it can provide.”

A block of code is set as follows:

namespace Fundamentals.Compliance; public interface ICanProvideComplianceMetadataForType { bool CanProvide(Type type); ComplianceMetadata Provide(Type type); }

Any command-line input or output is written as follows:

Checking type for compliance rules: Chapter11.Patient Property: FirstName - Employment records Property: LastName - Employment records Property: SocialSecurityNumber - Uniquely identifies the employee Property JournalEntries is a collection of type Chapter11.JournalEntry with type level metadata

Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “Then select JSON in the Body tab, add an empty JSON document, and click Send.”

Tips or important notes

Appear like this.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, email us at [email protected] and mention the book title in the subject of your message.

Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form.

Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.

If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.

Share Your Thoughts

Once you’ve read Metaprogramming in C#, we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback.

Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.

Download a free PDF copy of this book

Thanks for purchasing this book!

Do you like to read on the go but are unable to carry your print books everywhere? Is your eBook purchase not compatible with the device of your choice?

Don’t worry, now with every Packt book you get a DRM-free PDF version of that book at no cost.

Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application. 

The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily

Follow these simple steps to get the benefits:

Scan the QR code or visit the link below

https://packt.link/free-ebook/9781837635429

Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directly

Part 1:Why Metaprogramming?

In this part, you will get an introduction to what metaprogramming is, its benefits, and ideas of how you can leverage it through real-world examples. You’ll also see how you are most likely already using it, directly or indirectly, and how to get some quick wins and early benefits.

This part has the following chapters:

Chapter 1, How Can Metaprogramming Benefit You?Chapter 2, Metaprogramming ConceptsChapter 3, Demystifying through Existing Real-World Examples