Discover millions of ebooks, audiobooks, and so much more with a free trial

Only $11.99/month after trial. Cancel anytime.

C# 7 and .NET Core Cookbook
C# 7 and .NET Core Cookbook
C# 7 and .NET Core Cookbook
Ebook796 pages5 hours

C# 7 and .NET Core Cookbook

Rating: 0 out of 5 stars

()

Read preview

About this ebook

About This Book
  • Easy-to-follow recipes to get you up-and-running with the new features of C# 7 and .NET Core 1.1
  • Practical solutions to assist you with microservices and serverless computing in C#
  • Explore the new Visual Studio environment and write more secure code in it
Who This Book Is For

The book will appeal to C# and .NET developers who have a basic familiarity with C# and the Visual Studio 2015 environment

LanguageEnglish
Release dateApr 25, 2017
ISBN9781787289208
C# 7 and .NET Core Cookbook

Read more from Dirk Strauss

Related to C# 7 and .NET Core Cookbook

Related ebooks

Programming For You

View More

Related articles

Reviews for C# 7 and .NET Core Cookbook

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    C# 7 and .NET Core Cookbook - Dirk Strauss

    Title Page

    C# 7 and .NET Core Cookbook

    Quick solutions to common programming problems with the latest features of C# 7.0, .NET Core 1.1, and Visual Studio 2017

    Dirk Strauss

    BIRMINGHAM - MUMBAI

    Copyright

    C# 7 and .NET Core Cookbook

    Copyright © 2017 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, and its dealers and distributors will be held liable for any damages caused or alleged to be 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.

    First published: April 2017

    Production reference: 1210417

    Published by Packt Publishing Ltd.

    Livery Place

    35 Livery Street

    Birmingham 

    B3 2PB, UK.

    ISBN 978-1-78728-627-6

    www.packtpub.com

    Credits

    Foreword

    When the author of this book, Dirk Strauss, asked me if I'd write a foreword, it took me about n milliseconds (where n is a small integer) to reply with a yes. I've known Dirk for a few years, starting when we worked on a project that involved C# Code Contracts. Quite some time ago I worked with the Research in Software Engineering group at Microsoft Research, who originally developed Code Contracts, so when I saw Dirk's explanation of the technology, I knew immediately that Dirk has a rare ability to understand, use, and most importantly with regards to C# 7 and .NET Core Cookbook, explain ideas in a clear and precise way.

    Most of my colleagues and I believe that a major challenge facing .NET developers, and in fact all software developers, is the astonishing explosion of new technologies and the associated tidal wave of various forms of documentation. It's becoming increasingly difficult to find those few valuable resources that get to the point quickly, and explain technologies and paradigms succinctly so you can get on with your work. This book is one such reference. I hope you'll enjoy and value C# 7 and .NET Core Cookbook as much as I do!

    Dr. James McCaffrey

    Microsoft Research

    About the Author

    Dirk Strauss is a software developer and Microsoft .NET MVP from South Africa with over 13 years of programming experience. He has extensive experience in SYSPRO Customization (an ERP system), with C# and web development being his main focus.

    He works for Evolution Software, but in all fairness, he can't really call it working at all. When you're having fun and loving what you do with incredibly inspirational individuals, you will not work a day in your life.

    He authored the C# Programming Cookbook in 2016 (also published by Packt) and has written for Syncfusion, contributing to the Succinctly series of eBooks.

    He also blogs at https://dirkstrauss.com/, whenever he gets a chance.

    I would like to thank the team at Evolution Software for being such an incredible source of inspiration to me in my professional and personal life. Working with you folks challenges me to become better at what I do and the way I live my life. Being a part of the Evolution Software team is the most fulfilling experience of my career. It is something that I will always be incredibly grateful for.

    Last but by no means least, I would like to thank my wife and kids. Thank you for reminding me what life is actually about. Without your love and support, this book would not have been possible. I love you.

    About the Reviewer

    Fabio Claudio Ferracchiati is a senior consultant and a senior analyst/developer using Microsoft technologies. He works for Agic Technology (http://www.agictech.com). He is a Microsoft Certified Solution Developer for .NET, Microsoft Certified Application Developer for .NET, and Microsoft Certified Professional. He is also a prolific author and a technical reviewer. Over the last ten years, he's written articles for Italian and international magazines, and coauthored more than 10 books on a variety of computer topics.

    www.PacktPub.com

    For support files and downloads related to your book, please visit www.PacktPub.com.

    Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@packtpub.com for more details.

    At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

    https://www.packtpub.com/mapt

    Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

    Why subscribe?

    Fully searchable across every book published by Packt

    Copy and paste, print, and bookmark content

    On demand and accessible via a web browser

    Customer Feedback

    Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1787286274.

    If you'd like to join our team of regular reviewers, you can e-mail us at customerreviews@packtpub.com. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!

    Table of Contents

    Preface

    What this book covers

    What you need for this book

    Who this book is for

    Sections

    Getting ready

    How to do it…

    How it works…

    There's more…

    See also

    Conventions

    Reader feedback

    Customer support

    Downloading the example code

    Errata

    Piracy

    Questions

    New Features in C# 7.0

    Introduction

    Working with Tuples - getting started

    Getting ready

    How to do it...

    How it works...

    Working with Tuples - going deeper

    Getting ready

    How to do it...

    How it works...

    Pattern matching

    Getting ready

    How to do it...

    How it works...

    Out variables

    Getting ready

    How to do it...

    How it works...

    Deconstruction

    Getting ready

    How to do it...

    How it works...

    Local functions

    Getting ready

    How to do it...

    How it works...

    Improvements to literals

    Getting ready

    How to do it...

    How it works...

    Ref returns and locals

    Getting ready

    How to do it...

    How it works...

    Generalized async return types

    Getting ready

    How to do it...

    How it works...

    Expression bodies for accessors, constructors, and finalizers

    Getting ready

    How to do it...

    How it works...

    throw expressions

    Getting ready

    How to do it...

    How it works...

    Classes and Generics

    Introduction

    Creating and implementing an abstract class

    Getting ready

    How to do it...

    How it works...

    Creating and implementing an interface

    Getting ready

    How to do it...

    How it works...

    Creating and using a generic class or method

    Getting ready

    How to do it...

    How it works...

    Creating and using a generic interface

    Getting ready

    How to do it...

    How it works...

    Object-Oriented Programming in C#

    Introduction

    Using inheritance in C#

    Getting ready

    How to do it...

    How it works...

    Using abstraction

    Getting ready

    How to do it...

    How it works...

    Leveraging encapsulation

    Getting ready

    How to do it...

    How it works...

    Implementing polymorphism

    Getting ready

    How to do it...

    How it works...

    Single responsibility principle

    Getting ready

    How to do it...

    How it works...

    Open/closed principle

    Getting ready

    How to do it...

    How it works...

    Exception handling

    Getting ready

    How to do it...

    How it works...

    Code Analyzers in Visual Studio

    Introduction

    Finding and installing analyzers

    Getting ready

    How to do it...

    How it works...

    Creating a code analyzer

    Getting ready

    How to do it...

    How it works...

    Creating a custom code analyzer

    Getting ready

    How to do it...

    How it works...

    Deploying your code analyzer within your organization only

    Getting ready

    How to do it...

    How it works...

    Regular Expressions

    Introduction

    Getting started with regex - Matching a valid date

    Getting ready

    How to do it...

    How it works...

    Sanitizing input

    Getting ready

    How to do it...

    How it works...

    Dynamic regex matching

    Getting ready

    How to do it...

    How it works...

    Working with Files, Streams, and Serialization

    Introduction

    Creating and extracting ZIP archives

    Getting ready

    How to do it...

    How it works...

    In-memory stream compression and decompression

    Getting ready

    How to do it...

    How it works...

    Async and await file processing

    Getting ready

    How to do it...

    How it works...

    How to make a custom type serializable?

    Getting ready

    How to do it...

    How it works...

    Using ISerializable for custom serialization to a FileStream

    Getting ready

    How to do it...

    How it works...

    Using XmlSerializer

    Getting ready

    How to do it...

    How it works...

    JSON serializers

    Getting ready

    How to do it...

    How it works...

    Making Apps Responsive with Asynchronous Programming

    Introduction

    Return types of asynchronous functions

    Getting ready

    How to do it...

    How it works...

    Handling tasks in asynchronous programming

    Getting ready

    How to do it...

    How it works...

    Exception handling in asynchronous programming

    Getting ready

    How to do it...

    How it works...

    High Performance Programming Using Parallel and Multithreading in C#

    Introduction

    Creating and aborting a low-priority background thread

    Getting ready

    How to do it...

    How it works...

    Increasing the maximum thread pool size

    Getting ready

    How to do it...

    How it works...

    Creating multiple threads

    Getting ready

    How to do it...

    How it works...

    Locking one thread until the contended resources are available

    Getting ready

    How to do it...

    How it works...

    Invoking parallel calls to methods using Parallel.Invoke

    Getting ready

    How to do it...

    How it works...

    Using a parallel foreach loop

    Getting ready

    How to do it...

    How it works...

    Cancelling a parallel foreach loop

    Getting ready

    How to do it...

    How it works...

    Catching errors in parallel foreach loops

    Getting ready

    How to do it...

    How it works...

    Debugging multiple threads

    Getting ready

    How to do it...

    How it works...

    Composing Event-Based Programs Using Reactive Extensions

    Introduction

    Installing Rx

    Getting ready

    How to do it...

    How it works...

    Events versus observables

    Getting ready

    How to do it...

    How it works...

    Using LINQ to perform queries

    Getting ready

    How to do it...

    How it works...

    Using schedulers in Rx

    Getting ready

    How to do it...

    How it works...

    Debugging lambda expressions

    Getting ready

    How to do it...

    How it works...

    Exploring .NET Core 1.1

    Introduction

    Creating a simple .NET Core application and running it on a Mac

    Getting ready

    How to do it...

    How it works...

    Creating your first ASP.NET Core application

    Getting ready

    How to do it...

    How it works

    Publishing your ASP.NET Core application

    Getting ready

    How to do it...

    How it works...

    ASP.NET Core on the MVC Framework

    Introduction

    Including middleware and why it is useful

    Getting ready

    How to do it...

    How it works...

    Creating Controllers and using routing

    Getting ready

    How to do it...

    How it works...

    Rendering Views

    Getting ready

    How to do it...

    How it works...

    Choosing and Using a Source Control Strategy

    Introduction

    Setting up Visual Studio account management and determining which source control solution is best for you

    Getting ready

    How to do it...

    How it works...

    Setting up Visual Studio GitHub integration, checking in code for the first time, and checking in changes

    Getting ready

    How to do it...

    How it works...

    Working as a team using GitHub, handling and resolving conflicts in code

    Getting ready

    How to do it...

    How it works...

    Creating a Mobile Application in Visual Studio

    Introduction

    Installing Xamarin and other required components on your Windows PC and Mac

    Getting ready

    How to do it...

    How it works...

    Creating a mobile application using Apache Cordova

    Getting ready

    How to do it...

    How it works...

    Creating an iOS application using Xamarin.Forms and Visual Studio for Mac

    Getting ready

    How to do it...

    How it works...

    Writing Secure Code and Debugging in Visual Studio

    Introduction

    Encrypting and storing passwords correctly

    Getting ready

    How to do it...

    How it works...

    Using SecureString in code

    Getting ready

    How to do it...

    How it works...

    Securing sensitive parts of the App.config/web.config

    Getting ready

    How to do it...

    How it works...

    Preventing SQL injection attacks

    Getting ready

    How to do it...

    How it works...

    Using IntelliTrace, diagnostic tools, and historical debugging

    Getting ready

    How to do it...

    How it works...

    Setting conditional breakpoints

    Getting ready

    How to do it...

    How it works...

    Using PerfTips to identify bottlenecks in code

    Getting ready

    How to do it...

    How it works...

    Creating Microservices on Azure Service Fabric

    Introduction

    Downloading and installing Service Fabric

    Getting ready

    How to do it...

    How it works...

    Creating a Service Fabric application with a stateless actor service

    Getting ready

    How to do it...

    How it works...

    Using Service Fabric Explorer

    Getting ready

    How to do it...

    How it works...

    Azure and Serverless Computing

    Introduction

    Creating an Azure function

    Getting ready

    How to do it...

    How it works...

    Providing print functionality with DocRaptor

    Getting ready

    How to do it...

    How it works...

    Using AWS and S3

    Getting ready

    How to do it...

    How it works...

    Creating C# Lambda functions with AWS

    Getting ready

    How to do it...

    How it works...

    Preface

    Visual Studio 2017 allows developers to harness the latest technology and create world-class applications across a variety of platforms. The new language features in C# 7.0 are powerful tools that will allow you to write better functioning software and deliver complex business requirements quicker.

    The book takes a look at all of the awesome new features in C# 7. It also looks at how developers can write diagnostic analyzers to produce better code and adhere to specific code standards. It explores .NET Core 1.1 and looks at creating an ASP.NET Core application using the MVC framework.

    If creating mobile apps is something you are interested in, this book will show you how to do so using Cordova. If you want to create native iOS applications, this book shows you how to do just that using Visual Studio for Mac.

    If serverless computing is something that want to understand more, then look no further. In the book, we take a look at what the term serverless computing means. We also look at how to create an Azure function and how to use AWS and S3. Lastly, hot off the press from Amazon, we take a look at using C# lambda functions with AWS.

    This book will show you the beauty of C#, which when combined with the power of Visual Studio, makes you a very formidable developer, capable of meeting a variety of programming challenges head on.

    Whatever your skill level when it comes to programming with C#, this book provides something for everyone and will make you a better developer.

    What this book covers

    Chapter 1, New Features in C# 7.0, shows how C# 7.0 brings a lot of new functionality to the C# language. The biggest of these features by far are Tuples and pattern matching. Getting to grips with what’s new in C# 7.0 is essential for developers in order to stay on top of their game.

    Chapter 2, Classes and Generics, form the building blocks of software development and are essential in building good code. The power of classes, which is to describe the world around us and translate it into a programming language that a compiler can understand, allows developers to create great software.

    Chapter 3, Object-Oriented Programming in C#, is the foundation of C# and object-oriented programming (OOP). Understanding this concept is essential to .NET developers everywhere.

    Chapter 4, Code Analyzers in Visual Studio, talks about how code analyzers help developers to write better code. Be sure that the code you or your team ships measures up to your specific set of code quality standards.

    Chapter 5, Regular Expressions, is about how regex make use of patterns that describe a string through the use of special characters that denote a specific bit of text to match. The use of regex, when applied properly, can be a very powerful approach to certain programming problems.

    Chapter 6, Working with Files, Streams, and Serialization, teaches the readers that working with files, streams, and serialization is something you as a developer will do many times. Being able to do so correctly will definitely give you an edge as a developer.

    Chapter 7, Making Apps Responsive with Asynchronous Programming, talks about how asynchronous programming is an exciting feature in C#. It allows you to continue program execution on the main thread while a long-running task finishes its execution. This enables your applications to remain responsive.

    Chapter 8, High Performance Programming Using Parallel and Multithreading in C#, improves your code's performance. Using multithreading and parallel programming can mean the difference between users experiencing an application as working or broken.

    Chapter 9, Composing Event-Based Programs Using Reactive Extensions, teaches the reader how Rx is an exciting technology. If you need to create search-as-you-type functionality in an application, have data that changes notify your application instead of having to poll the data all the time (think stock prices), or generally make your app more responsive, the chances are you need to consider using Rx.

    Chapter 10, Exploring .NET Core 1.1,  is about the buzz regarding .NET Core these days. It allows you to create cross-platform applications that run on Windows, Linux, and macOS. Knowing how to use it is essential for all .NET developers.

    Chapter 11, ASP.NET Core on the MVC Framework, talks about the MVC framework, which is named according to the MVC design pattern it follows. It allows developers to separate the logic by letting each component of the framework focus on one specific thing. It is this separation of concerns that makes MVC so powerful, especially when combined with .NET Core.

    Chapter 12, Choosing and Using a Source Control Strategy, is about how source control is an essential part of every developer's toolkit. It doesn't matter whether you are a hobbyist or professional programmer; when you get up from your desk to go home, you'd better be sure your code is safe.

    Chapter 13, Creating a Mobile Application in Visual Studio, allows developers to create mobile applications with ease. It also gives developers more choice about how to go about doing it. From creating a mobile app with Xamarin, to using Cordova, to writing native iOS applications with Visual Studio for Mac, .NET developers can expand their service offering using the IDE they know and love.

    Chapter 14, Writing Secure Code and Debugging in Visual Studio, talks about how debugging is something developers do more often than not. Being able to do so efficiently is a different story. In a similar way, being able to write secure code is essential to any developer. Creating secure code and being able to efficiently debug that code properly results in a better end product.

    Chapter 15, Creating Microservices on Azure Service Fabric, is about how, traditionally, developers wrote applications in a monolithic manner, which is one single executable broken up into components via classes and so on. Microservices is a technology that aims to address the issues surrounding traditional monolithic applications. It allows developers to create smaller bits (services) that can function on their own without being dependent on any of the other services.

    Chapter 16, Azure and Serverless Computing, is about how serverless does not mean the lack of a server, but rather you (or the application) does not know which server is used to provide some functionality to an application. Splitting some of your application logic into a serverless-type architecture allows for extreme scalability when loads increase (or decrease), increased performance, and less code to write and debug.

    What you need for this book

    You will need the latest version of Visual Studio 2017. For some of the chapters on mobile development, you will need an active Apple iTunes account. Regarding the last chapter, you will need to create a free AWS account. Lastly, some of the recipes might also require access to the Azure portal.

    Who this book is for

    The book will appeal to C# and .NET developers who have a basic familiarity with C# and the Visual Studio 2015 environment.

    Sections

    In this book, you will find several headings that appear frequently (Getting ready, How to do it, How it works, There's more, and See also).

    To give clear instructions on how to complete a recipe, we use these sections as follows:

    Getting ready

    This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.

    How to do it…

    This section contains the steps required to follow the recipe.

    How it works…

    This section usually consists of a detailed explanation of what happened in the previous section.

    There's more…

    This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.

    See also

    This section provides helpful links to other useful information for the recipe.

    Conventions

    In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

    Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: You will find the script in the _database scripts folder in the accompanying source code.

    A block of code is set as follows:

    New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: From the Tools menu, select NuGet Package Manager and then Manage NuGet Packages for Solution....

    Warnings or important notes appear in a box like this.

    Tips and tricks appear like this.

    Reader feedback

    Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

    To send us general feedback, simply e-mail feedback@packtpub.com, and mention the book's title in the subject of your message.

    If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors .

    Customer support

    Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

    Downloading the example code

    You can download the example code files for this book 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.

    You can download the code files by following these steps:

    Log in or register to our website using your e-mail address and password.

    Hover the mouse pointer on the SUPPORT tab at the top.

    Click on Code Downloads & Errata.

    Enter the name of the book in the Search box.

    Select the book for which you're looking to download the code files.

    Choose from the drop-down menu where you purchased this book from.

    Click on Code Download.

    You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

    Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

    WinRAR / 7-Zip for Windows

    Zipeg / iZip / UnRarX for Mac

    7-Zip / PeaZip for Linux

    The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/CSharp-7-and-DotNET-Core-Cookbook. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

    Errata

    Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

    To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

    Piracy

    Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

    Please

    Enjoying the preview?
    Page 1 of 1