Reader small image

You're reading from  C# 12 and .NET 8 – Modern Cross-Platform Development Fundamentals - Eighth Edition

Product typeBook
Published inNov 2023
PublisherPackt
ISBN-139781837635870
Edition8th Edition
Right arrow
Author (1)
Mark J. Price
Mark J. Price
author image
Mark J. Price

Mark J. Price is a Microsoft Specialist: Programming in C# and Architecting Microsoft Azure Solutions, with over 20 years' experience. Since 1993, he has passed more than 80 Microsoft programming exams and specializes in preparing others to pass them. Between 2001 and 2003, Mark was employed to write official courseware for Microsoft in Redmond, USA. His team wrote the first training courses for C# while it was still an early alpha version. While with Microsoft, he taught "train-the-trainer" classes to get other MCTs up-to-speed on C# and .NET. Mark holds a Computer Science BSc. Hons. Degree.
Read more about Mark J. Price

Right arrow

Working with Data Using Entity Framework Core

This chapter is about reading from and writing to relational data stores, such as SQLite and SQL Server, by using the object-to-data store mapping technology named Entity Framework Core (EF Core).

This chapter will cover the following topics:

  • Understanding modern databases
  • Setting up EF Core in a .NET project
  • Defining EF Core models
  • Querying EF Core models
  • Loading and tracking patterns with EF Core
  • Modifying data with EF Core

Join our book community on Discord

https://packt.link/EarlyAccess

Qr code Description automatically generated

This chapter is about reading and writing to files and streams, text encoding, and serialization. Applications that do not interact with the filesystem are extraordinarily rare. As a .NET developer, almost every application that you build will need to manage the filesystem and create, open, read, and write to and from files. Most of those files will contain text, so it is important to understand how text is encoded. And finally, after working with objects in memory, you will need to store them somewhere permanently for later reuse. You do that using a technique called serialization.In this chapter, we will cover the following topics:

  • Managing the filesystem
  • Reading and writing with streams
  • Encoding and decoding text
  • Serializing object graphs
  • Working with environment variables

Managing the filesystem

Your applications will often need to perform input and output operations with files and directories in different environments. The System and System.IO namespaces contain classes for this purpose.

Handling cross-platform environments and filesystems

Let's explore how to handle cross-platform environments and the differences between Windows, Linux, and macOS. Paths are different for Windows, macOS, and Linux, so we will start by exploring how .NET handles this:

  1. Use your preferred code editor to create a new project, as defined in the following list:
    • Project template: Console App / console
    • Project file and folder: WorkingWithFileSystems
    • Solution file and folder: Chapter09
  2. In the project file, add a package reference for Spectre.Console, and then add elements to import the following classes statically and globally: System.Console, System.IO.Directory, System.IO.Path, and System.Environment, as shown in the following markup:
<ItemGroup>
  <PackageReference...

Reading and writing with streams

In Chapter 10, Working with Data Using Entity Framework Core, you will use a file named Northwind.db, but you will not work with the file directly. Instead, you will interact with the SQLite database engine, which in turn will read and write to the file. In scenarios where there is no other system that "owns" the file and does the reading and writing for you, you will use a file stream to work directly with the file.A stream is a sequence of bytes that can be read from and written to. Although files can be processed rather like arrays, with random access provided by knowing the position of a byte within the file, it is more efficient to process a file as a stream in which the bytes can be accessed in sequential order. When a human does the processing, they tend to need random access so that they can jump around the data making changes and return to the data they worked on earlier. When an automated system does the processing, they tend to be...

Encoding and decoding text

Text characters can be represented in different ways. For example, the alphabet can be encoded using Morse code into a series of dots and dashes for transmission over a telegraph line.In a similar way, text inside a computer is stored as bits (ones and zeros) representing a code point within a code space. Most code points represent a single character, but they can also have other meanings like formatting.For example, ASCII has a code space with 128 code points. .NET uses a standard called Unicode to encode text internally. Unicode has more than 1 million code points.Sometimes, you will need to move text outside .NET for use by systems that do not use Unicode or a variation of it, so it is important to learn how to convert between encodings.Some common text encodings used by computers are shown in Table 9.6:

Encoding Description
ASCII This encodes a limited range of characters using the lower seven bits of a byte.
UTF-8 This represents each Unicode code...

Serializing object graphs

An object graph is a structure of multiple objects that are related to each other, either through a direct reference or indirectly through a chain of references.Serialization is the process of converting a live object graph into a sequence of bytes using a specified format. Deserialization is the reverse process. You would use serialization to save the current state of a live object so that you can recreate it in the future, for example, saving the current state of a game so that you can continue at the same place tomorrow. The stream produced from a serialized object is usually stored in a file or database.There are dozens of formats you can choose for serialization, but the two most common text-based human-readable formats are eXtensible Markup Language (XML) and JavaScript Object Notation (JSON). There are also more efficient binary formats like Protobuf used by gRPC.

Good Practice: JSON is more compact and is best for web and mobile applications. XML is...

Working with environment variables

Environment variables are system and user-definable values that can affect the way running processes behave. They are commonly used to set options like toggling between development and production configurations in ASP.NET Core web projects, or to pass values needed by a process like service keys and passwords for database connection strings.Environment variables on Windows can be set at three scope levels: machine (aka system), user, and process. The methods for setting and getting environment variables assume process scope level by default and have overloads to specify the EnvironmentVariableTarget of Process, User, and Machine, as shown in Table 9.7:

Method Description
GetEnvironmentVariables Returns an IDictionary of all environment variables at a specified scope level or for the current process by default.
GetEnvironmentVariable Returns the value for a named environment variable.
SetEnvironmentVariable Sets the value for a named environment...

Practicing and exploring

Test your knowledge and understanding by answering some questions, getting some hands-on practice, and exploring this chapter's topics with more in-depth research.

Exercise 9.1 – Test your knowledge

Answer the following questions:

  1. What is the difference between using the File class and the FileInfo class?
  2. What is the difference between the ReadByte method and the Read method of a stream?
  3. When would you use the StringReader, TextReader, and StreamReader classes?
  4. What does the DeflateStream type do?
  5. How many bytes per character does UTF-8 encoding use?
  6. What is an object graph?
  7. What is the best serialization format to choose to minimize space requirements?
  8. What is the best serialization format to choose for cross-platform compatibility?
  9. Why is it bad to use a string value like "\Code\Chapter01" to represent a path, and what should you do instead?
  10. Where can you find information about NuGet packages and their dependencies?

Exercise 9.2 &...

Summary

In this chapter, you learned how to:

  • Read from and write to text files.
  • Read from and write to XML files.
  • Compress and decompress files.
  • Encode and decode text.
  • Serialize an object graph into JSON and XML.
  • Deserialize an object graph from JSON and XML.
  • Work with environment variables.

In the next chapter, you will learn how to work with databases using Entity Framework Core.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
C# 12 and .NET 8 – Modern Cross-Platform Development Fundamentals - Eighth Edition
Published in: Nov 2023Publisher: PacktISBN-13: 9781837635870
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Mark J. Price

Mark J. Price is a Microsoft Specialist: Programming in C# and Architecting Microsoft Azure Solutions, with over 20 years' experience. Since 1993, he has passed more than 80 Microsoft programming exams and specializes in preparing others to pass them. Between 2001 and 2003, Mark was employed to write official courseware for Microsoft in Redmond, USA. His team wrote the first training courses for C# while it was still an early alpha version. While with Microsoft, he taught "train-the-trainer" classes to get other MCTs up-to-speed on C# and .NET. Mark holds a Computer Science BSc. Hons. Degree.
Read more about Mark J. Price