O'Reilly logo

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Improving your C# Skills

Book Description

Conquer complex and interesting programming challenges by building robust and concurrent applications with caches, cryptography, and parallel programming.

Key Features

  • Understand how to use .NET frameworks like the Task Parallel Library (TPL)and CryptoAPI
  • Develop a containerized application based on microservices architecture
  • Gain insights into memory management techniques in .NET Core

Book Description

This Learning Path shows you how to create high performing applications and solve programming challenges using a wide range of C# features. You'll begin by learning how to identify the bottlenecks in writing programs, highlight common performance pitfalls, and apply strategies to detect and resolve these issues early. You'll also study the importance of micro-services architecture for building fast applications and implementing resiliency and security in .NET Core. Then, you'll study the importance of defining and testing boundaries, abstracting away third-party code, and working with different types of test double, such as spies, mocks, and fakes. In addition to describing programming trade-offs, this Learning Path will also help you build a useful toolkit of techniques, including value caching, statistical analysis, and geometric algorithms. This Learning Path includes content from the following Packt products:

  • C# 7 and .NET Core 2.0 High Performance by Ovais Mehboob Ahmed Khan
  • Practical Test-Driven Development using C# 7 by John Callaway, Clayton Hunt
  • The Modern C# Challenge by Rod Stephens

What you will learn

  • Measure application performance using BenchmarkDotNet
  • Leverage the Task Parallel Library (TPL) and Parallel Language Integrated Query (PLINQ)library to perform asynchronous operations
  • Modify a legacy application to make it testable
  • Use LINQ and PLINQ to search directories for files matching patterns
  • Find areas of polygons using geometric operations
  • Randomize arrays and lists with extension methods
  • Use cryptographic techniques to encrypt and decrypt strings and files

Who this book is for

If you want to improve the speed of your code and optimize the performance of your applications, or are simply looking for a practical resource on test driven development, this is the ideal Learning Path for you. Some familiarity with C# and .NET will be beneficial.

Downloading the example code for this book You can download the example code files for all Packt books you have purchased 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.

Table of Contents

  1. Title Page
  2. Copyright and Credits
    1. Improving your C# Skills
  3. About Packt
    1. Why subscribe?
    2. Packt.com
  4. Contributors
    1. About the authors
    2. Packt is searching for authors like you
  5. Preface
    1. Who this book is for
    2. What this book covers
    3. To get the most out of this book
      1. Download the example code files
      2. Conventions used
    4. Get in touch
      1. Reviews
  6. What's New in .NET Core 2 and C# 7?
    1. Evolution of .NET
    2. New improvements in .NET Core 2.0
      1. Performance improvements
        1. RyuJIT compiler in .NET Core
        2. Profile guided optimization
      2. Simplified packaging
    3. Upgrading path from .NET Core 1.x to 2.0
      1. 1. Install .NET Core 2.0
      2. 2. Upgrade TargetFramework
      3. 3. Update .NET Core SDK version
      4. 4. Update .NET Core CLI
      5. Changes in ASP.NET Core Identity
    4. Exploring .NET Core CLI and New Project Templates
    5. Understanding .NET Standard
      1. Versioning of .NET Standard
      2. New improvements in .NET Standard 2.0
        1. More APIs in .NET Standard 2.0
        2. Compatibility mode
    6. Creating a .NET Standard library
    7. What comes with ASP.NET Core 2.0
      1. ASP.NET Core Razor Pages
        1. Automatic Page and View compilation on publishing
        2. Razor support for C# 7.1
      2. Simplified configuration for Application Insights
      3. Pooling connections in Entity Framework Core 2.0
    8. New features in C# 7.0
      1. Tuples
      2. Patterns
        1. Constant pattern
        2. Type pattern
        3. Var pattern
      3. Reference returns
      4. Expression bodied member extended
      5. Creating Local Functions
      6. Out variables
      7. Async Main
    9. Writing quality code
    10. Summary
  7. Understanding .NET Core Internals and Measuring Performance
    1. .NET Core internals
      1. CoreFX
      2. CoreCLR
      3. Understanding MSIL, CLI, CTS, and CLS
      4. How the CLR works
      5. From compilation to execution – Under the hood
      6. Garbage collection
        1. Generations in GC
      7. .NET Native and JIT compilation
    2. Utilizing multiple cores of the CPU for high performance
    3. How releasing builds increases performance
    4. Benchmarking .NET Core 2.0 applications
      1. Exploring BenchmarkDotNet
      2. How it works
      3. Setting parameters
      4. Memory diagnostics using BenchmarkDotnet
      5. Adding configurations
    5. Summary
  8. Multithreading and Asynchronous Programming in .NET Core
    1. Multithreading versus asynchronous programming
    2. Multithreading in .NET Core
      1. Multithreading caveats
      2. Threads in .NET Core
        1. Creating threads in .NET Core
        2. Thread lifetime
        3. The thread pool in .NET
      3. Thread synchronization
        1. Monitors
      4. Task parallel library (TPL)
        1. Creating a task using TPL
        2. Task-based asynchronous pattern (TAP)
          1. Naming convention
          2. Return type
          3. Parameters
          4. Exceptions
          5. Task status
          6. Task cancellation
          7. Task progress reporting
        3. Implementing TAP using compilers
        4. Implementing TAP with greater control over Task
      5. Design patterns for parallel programming
        1. Pipeline pattern
        2. Dataflow pattern
        3. Producer/consumer pattern
        4. Parallel.ForEach
        5. Parallel LINQ (PLINQ)
    3. Summary
  9. Securing and Implementing Resilience in .NET Core Applications
    1. Introduction to resilient applications
      1. Resilient policies
        1. Reactive policies
          1. Implementing the retry pattern
          2. Implementing circuit breaker
          3. Wrapping the circuit breaker with retry
          4. Fallback policy with circuit breaker and retry
        2. Proactive policies
          1. Implementing timeout
          2. Implementing caching
          3. Implementing health checks
    2. Storing sensitive information using Application Secrets
    3. Protecting ASP.NET Core APIs
      1. SSL (Secure Socket Layer)
        1. Enabling SSL in an ASP.NET Core application
      2. Preventing CSRF (Cross-Site Request Forgery) attacks
      3. Reinforcing security headers
      4. Adding the HTTP strict transport security header
        1. Adding the X-Content-Type-Options header
        2. Adding the X-Frame-Options header
        3. Adding the X-Xss-Protection header
        4. Adding the Content-Security-Policy header
        5. Adding the referrer-policy header
        6. Enabling CORS in the ASP.NET Core application
      5. Authentication and authorization
        1. Using ASP.NET Core Identity for authentication and authorization
      6. Authentication
      7. Authorization
      8. Implementing authentication and authorization using the ASP.NET Core Identity framework
        1. Adding more properties in the user table
    4. Summary
  10. Why TDD is Important
    1. First, a little background
      1. John's story on TDD
      2. Clayton's story on TDD
    2. So, what is TDD?
    3. An approach to TDD 
      1. An alternative approach 
      2. The process
        1. Red, green, and refactor
        2. Coder's block
      3. Why should we care?
    4. Arguments against TDD
      1. Testing takes time
      2. Testing is expensive
      3. Testing is difficult
      4. We don't know how
    5. Arguments in favor of TDD
      1. Reduces the effort of manual testing
      2. Reduces bug count
      3. Ensures some level of correctness
      4. Removes the fear of refactoring
      5. A better architecture 
      6. Faster development 
    6. Different types of test
      1. Unit tests 
      2. Acceptance tests 
      3. Integration tests 
      4. End to end tests 
        1. Quantity of each test type 
      5. Parts of a unit test
        1. Arrange
        2. Act
        3. Assert
      6. Requirements 
        1. Why are they important? 
        2. User stories 
          1. Role 
          2. Request 
          3. Reason 
        3. Gherkin 
          1. Givens 
          2. When 
          3. Then 
      7. Our first tests in C#
        1. Growing the application with tests
      8. Our first tests in JavaScript
    7. Why does it matter?
    8. Summary
  11. Setting Up the .NET Test Environment
    1. Installing the .NET Core SDK
      1. Getting set up with VS Code
        1. Downloading the IDE
        2. Installing the VS Code
        3. Adding extensions
    2. Creating a project in VS Code
      1. Setting up Visual Studio Community
        1. Downloading Visual Studio Community
        2. Installing Visual Studio Community
    3. Switching to xUnit
      1. Code katas
        1. FizzBuzz
      2. Creating the test project
        1. The Given3ThenFizz test
        2. The Given5ThenBuzz test
        3. The Given15ThenFizzBuzz test
        4. The Given1Then1 test
        5. Theories
        6. Solution to the FizzBuzz Problem
    4. What is Speaker Meet?
      1. Web API project
      2. Listing Speakers (API)
        1. Requirements
        2. A new test file
    5. Summary
  12. Setting Up a JavaScript Environment
    1. Node.js
      1. What is Node?
      2. Why do we need Node?
      3. Installing Node
        1. Linux
        2. Mac OSX
        3. Windows
      4. NPM
        1. What is NPM?
        2. Why do we need NPM?
        3. Installing NPM?
    2. A quick introduction to JavaScript IDEs
      1. Visual Studio Code
        1. Why Visual Studio Code?
        2. Installing Visual Studio Code
          1. Linux
          2. Mac
          3. Windows
        3. Installing the plugins you will need
        4. Configuring the testing environment
      2. WebStorm
        1. Why WebStorm?
        2. Installing WebStorm
          1. Linux
          2. Mac
          3. Windows
        3. Installing the plugins you will need
        4. Configuring the testing environment
      3. Create React App
        1. What is Create React App?
        2. Installing the global module
        3. Creating a React application
          1. Running the Create React App script
      4. Mocha and Chai
        1. Jest
        2. Mocha
        3. Chai
        4. Sinon
        5. Enzyme
        6. Ejecting the React app
        7. Configuring to use Mocha and Chai
      5. A quick kata to check our test setup
        1. The requirements
        2. The execution
      6. Starting the kata
    3. Summary
  13. What to Know Before Getting Started
    1. Untestable code
      1. Dependency Injection
        1. Static
        2. Singleton
        3. Global state
      2. Abstracting third-party software
      3. Test doubles
      4. Mocking frameworks
      5. The SOLID principles
        1. The Single Responsibility Principle
        2. The Open/Closed principle
        3. The Liskov Substitution principle
        4. The Interface Segregation Principle
        5. The Dependency Inversion principle
      6. Timely greeting
      7. Fragile tests
        1. False positives and false failures
        2. Abstract DateTime
      8. Test double types
        1. Dummies
        2. Dummy logger
          1. Example in C#
          2. Example in JavaScript
        3. Stubs
          1. Example in C#
          2. Example in JavaScript
        4. Spies
          1. Example in C#
          2. Example in JavaScript
        5. Mocks
          1. Example in C#
          2. Example in JavaScript
        6. Fakes
          1. Example in C#
          2. Example in JavaScript
      9. N-Tiered example
        1. Presentation layer
        2. Moq
        3. Business layer
    2. Summary
  14. Tabula Rasa – Approaching an Application with TDD in Mind
    1. Where to begin
    2. Yak shaving
      1. Big design up front
    3. A clean slate
      1. One bite at a time
      2. Minimum Viable Product
      3. Different mindset
      4. YAGNI – you aren't gonna need it
    4. Test small
    5. Devil's advocate
    6. Test negative cases first
    7. When testing is painful
      1. A spike
      2. Assert first
      3. Stay organized
    8. Breaking down Speaker Meet
      1. Speakers
      2. Communities
      3. Conferences
      4. Technical requirements
    9. Summary
  15. Testing JavaScript Applications
    1. Creating a React app
      1. Ejecting the app
      2. Configuring Mocha, Chai, Enzyme, and Sinon 
    2. The plan
      1. Considering the React component
      2. Looking at Redux testability
        1. The store
        2. Actions
        3. Reducers
      3. Unit-testing an API service
    3. Speaker listing
      1. A mock API service
      2. The Get All Speakers action
        1. Testing a standard action
        2. Testing a thunk
      3. The Get All Speakers reducer
      4. The Speaker listing component
    4. Speaker detail
      1. Adding to the mock API Service
      2. The Get Speaker action
      3. The Get Speaker reducer
      4. The Speaker Detail component
    5. Summary
  16. Exploring Integrations
    1. Implementing a real API service
      1. Replacing the mock API with the real API service
      2. Using Sinon to mock Ajax responses
        1. Fixing existing tests
        2. Mocking the server
      3. Application configuration
    2. End-to-end integration tests
      1. Benefits
      2. Detriments
      3. How much end-to-end testing should you do?
    3. Configuring the API project
      1. Integration test project
      2. Where to begin?
      3. Verifying the repository calls into the DB context
        1. InMemory database
        2. Adding speakers to the InMemory database
      4. Verify that the service calls the DB through the repository
        1. ContextFixture
      5. Verify the API calls into the service
        1. TestServer
        2. ServerFixture
    4. Summary
  17. Changes in Requirements
    1. Hello World
      1. A change in requirements
        1. Good evening 
    2. FizzBuzz
      1. A new feature
        1. Number not found
    3. TODO app  
      1. Mark complete
      2. Adding tests
      3. Production code
        1. But don't remove from the list!
      4. Adding tests
      5. Production code
    4. Changes to Speaker Meet
      1. Changes to the back-end
      2. Changes to the front-end 
        1. Sorted by rating on client side
    5. What now?
      1. Premature optimization
    6. Summary
  18. The Legacy Problem
    1. What is legacy code?
      1. Why does code go bad?
      2. When does a project become a legacy?
      3. What can be done to prevent legacy decay?
    2. Typical issues resulting from legacy code
      1. Unintended side effects
        1. Open Closed Principle and legacy code
        2. Liskov Substitution Principle and legacy code
      2. Over-optimization
      3. Overly clever code
      4. Tight coupling to third-party software
    3. Issues that prevent adding tests 
      1. Direct dependence on framework and third-party code 
      2. Law of Demeter
      3. Work in the constructor
      4. Global state
      5. Static methods
      6. Large classes and functions 
    4. Dealing with legacy problems
      1. Safe refactoring
        1. Converting values to variables
        2. Extracting a method
        3. Extracting a class
        4. Abstracting third-party libraries and framework code
      2. Early tests
        1. Gold standard tests
        2. Testing all potential outcomes 
    5. Moving forward 
      1. Fixing bugs 
      2. Free to do unsafe refactoring 
    6. Summary
  19. Unraveling a Mess
    1. Inheriting code
      1. The game
      2. A change is requested
    2. Life sometimes hands you lemons
      1. Getting started
      2. Abstracting a third-party class
      3. Unexpected Input
      4. Making sense of the madness
      5. Final beautification
      6. Ready for enhancements
    3. Summary
  20. Geometry
    1. Problems
      1. 1. Monte Carlo π
      2. 2. Newton's π
      3. 3. Bisection root-finding
      4. 4. Newton's method
      5. 5. Gaussian elimination
      6. 6. Monte Carlo integration
      7. 7. Rectangle rule integration
      8. 8. Trapezoid rule integration
      9. 9. Arrowheads
      10. 10. Line-line intersection
      11. 11. Point-line distance
      12. 12. Point-segment distance
      13. 13. Segment-segment distance
      14. 14. Circle selection
      15. 15. Line-circle intersection
      16. 16. Circle-circle intersection
      17. 17. Circle-line tangents
      18. 18. Polygon area
      19. 19. Point in a polygon
      20. 20. Convexity testing
      21. 21. Stars
    2. Solutions
      1. 1. Monte Carlo π
      2. 2. Newton's π
      3. 3. Bisection root-finding
      4. 4. Newton's method
      5. 5. Gaussian elimination
      6. 6. Monte Carlo integration
      7. 7. Rectangle rule integration
      8. 8. Trapezoid rule integration
      9. 9. Arrowheads
      10. 10. Line-line intersection
      11. 11. Point-line distance
      12. 12. Point-segment distance
      13. 13. Segment-segment distance
      14. 14. Circle selection
      15. 15. Line-circle intersection
      16. 16. Circle-circle intersection
      17. 17. Circle-line tangents
      18. 18. Polygon area
      19. 19. Point in a polygon
      20. 20. Convexity testing
      21. 21. Stars
    3. Summary
  21. Randomization
    1. Problems
      1. 22. Random doubles
      2. 23. Random items
      3. 24. Randomize items
      4. 25. Random groups
      5. 26. Choose items with probabilities
      6. 27. Random passwords
      7. 28. Random walks
    2. Solutions
      1. 22. Random doubles
      2. 23. Random items
      3. 24. Randomize items
      4. 25. Random groups
      5. 26. Choose items with probabilities
      6. 27. Random passwords
      7. 28. Random walks
    3. Summary
  22. Files and Directories
    1. Problems
      1. 29. Removing blank lines
      2. 30. Directory size
      3. 31. Finding duplicate files
      4. 32. Thumbnails
      5. 33. Thumbnail web page
      6. 34. Find files
      7. 35. Find and Replace
      8. 36. Saving images
      9. 37. Compressing images
    2. Solutions
      1. 29. Removing blank lines
      2. 30. Directory size
      3. 31. Finding duplicate files
      4. 32. Thumbnails
      5. 33. Thumbnail web page
      6. 34. Find files
      7. 35. Find and Replace
      8. 36. Saving images
      9. 37. Compressing images
    3. Summary
  23. Advanced C# and .NET Features
    1. Problems
      1. 38. Directory size, LINQ style
      2. 39. Directory size, PLINQ style
      3. 40. Find files, LINQ style
      4. 41. Parallel Monte Carlo π
      5. 42. Yielding primes
      6. 43. Yielding Fibonacci numbers
      7. 44. Complex numbers
    2. Solutions
      1. 38. Directory size, LINQ style
      2. 39. Directory size, PLINQ style
      3. 40. Find files, LINQ style
      4. 41. Parallel Monte Carlo π
      5. 42. Yielding primes
      6. 43. Yielding Fibonacci numbers
      7. 44. Complex numbers
    3. Summary
  24. Cryptography
    1. Problems
      1. 45. Caesar cipher
      2. 46. Vigenère cipher
      3. 47. Cryptographic pseudorandom numbers
      4. 48. Find primes
      5. 49. Hash files
      6. 50. Steganography
      7. 51. Encrypt and decrypt strings
      8. 52. Encrypt and decrypt files
      9. 53. CryptoPad
    2. Solutions
      1. 45. Caesar cipher
      2. 46. Vigenère cipher
      3. 47. Cryptographic random numbers
      4. 48. Find primes
      5. 49. Hash files
      6. 50. Steganography
      7. 51. Encrypt and decrypt strings
      8. 52. Encrypt and decrypt files
      9. 53. CryptoPad
    3. Summary
  25. Other Books You May Enjoy
    1. Leave a review - let other readers know what you think