Docsity

Consultas OData en .NET, Esquemas y mapas conceptuales de Matemáticas

Toggle sidebar
bg1
Bonus Content
We finish this book with three online chapters on building and consuming specialized services,
using .NET MAUI, and protecting your data and applications. The book closes with the
answers to the Test your knowledge sections from the end of each chapter. This PDF contains
all three online chapters and the appendix.
Chapter 18, Building and Consuming Specialized Services, introduces you to building services
using gRPC, implementing real-time communications between server and client using SignalR,
exposing an EF Core model using OData, and hosting functions in the cloud that respond to
triggers using Azure Functions.
Chapter 19, Building Mobile and Desktop Apps Using .NET MAUI, introduces you to building
cross-platform mobile and desktop apps for Android, iOS, macOS, and Windows. You will
learn the basics of XAML, which can be used to define the user interface for a graphical app.
Chapter 20, Protecting Your Data and Applications, is about protecting your data from being
viewed by malicious users using encryption and from being manipulated or corrupted using
hashing and signing. You will also learn about authentication and authorization to protect
applications from unauthorized users.
Appendix, Answers to the Test Your Knowledge Questions, has the answers to the test questions at
the end of each chapter.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Vista previa parcial del texto

¡Descarga Consultas OData en .NET y más Esquemas y mapas conceptuales en PDF de Matemáticas solo en Docsity!

Bonus Content

We finish this book with three online chapters on building and consuming specialized services, using .NET MAUI, and protecting your data and applications. The book closes with the answers to the Test your knowledge sections from the end of each chapter. This PDF contains all three online chapters and the appendix. Chapter 18 , Building and Consuming Specialized Services , introduces you to building services using gRPC, implementing real-time communications between server and client using SignalR, exposing an EF Core model using OData, and hosting functions in the cloud that respond to triggers using Azure Functions. Chapter 19 , Building Mobile and Desktop Apps Using .NET MAUI , introduces you to building cross-platform mobile and desktop apps for Android, iOS, macOS, and Windows. You will learn the basics of XAML, which can be used to define the user interface for a graphical app. Chapter 20 , Protecting Your Data and Applications , is about protecting your data from being viewed by malicious users using encryption and from being manipulated or corrupted using hashing and signing. You will also learn about authentication and authorization to protect applications from unauthorized users. Appendix , Answers to the Test Your Knowledge Questions , has the answers to the test questions at the end of each chapter.

[ ii ]

Table of Contents

Table of Contents

  • Chapter 18: Building and Consuming Specialized Services Table of Contents
    • Understanding specialized service technologies
      • Understanding Windows Communication Foundation (WCF)
    • Exposing data as a web service using OData
      • Understanding OData
      • Building a web service that supports OData
        • Defining OData models for EF Core models
        • Testing the OData models
      • Creating and testing OData controllers
      • Testing OData controllers using REST Client
      • Querying OData models
        • Understanding OData operators
        • Understanding OData functions
        • Exploring OData queries
      • Logging OData requests
      • Versioning OData controllers
      • Enabling entity inserts using POST
      • Building a client for OData
        • Adding a services page to the Northwind MVC website
    • Exposing data as a service using GraphQL
      • Understanding GraphQL
      • Building a service that supports GraphQL
      • Defining GraphQL schema for Hello World
      • Defining GraphQL schema for EF Core models
      • Exploring GraphQL queries with Northwind
      • Understanding GraphQL mutations and subscriptions
      • Building a client for GraphQL
    • Implementing services using gRPC
      • Understanding gRPC
      • Building a gRPC service
      • Building a gRPC client
      • Testing a gRPC client to the gRPC service
      • Implementing a gRPC service for an EF Core model
      • Implementing a gRPC client for an EF Core model
    • Implementing real-time communication using SignalR
      • Understanding the history of real-time communication on the web
        • Understanding XMLHttpRequest
        • Understanding AJAX [ iii ]
        • Understanding WebSocket
        • Introducing SignalR
        • Designing method signatures
      • Building a live communication service using SignalR
        • Defining some shared models
        • Enabling a server-side SignalR hub
        • Adding the SignalR client-side JavaScript library
        • Adding a chat page to the Northwind MVC website
      • Testing the chat feature
      • Building a console app chat client
    • Implementing serverless services using Azure Functions
      • Understanding Azure Functions
        • Understanding Azure Functions triggers and bindings
        • Understanding Azure Functions versions and languages
        • Understanding Azure Functions hosting models
      • Setting up a local development environment for Azure Functions
      • Building an Azure Functions project for running locally
        • Using Visual Studio
        • Using Visual Studio Code
        • Using the func CLI
      • Reviewing the project
      • Implementing the function
      • Testing the function
      • Publishing an Azure Functions project to the cloud
        • Using Visual Studio
      • Cleaning up Azure resources
    • Understanding identity services
    • Summary of choices for specialized services
    • Practicing and exploring
      • Exercise 18.1 – Test your knowledge
      • Exercise 18.2 – Explore topics
    • Summary
  • Chapter 19: Building Mobile and Desktop Apps Using .NET MAUI
    • Understanding the .NET MAUI delay
    • Understanding XAML
      • Simplifying code using XAML
      • Choosing common controls
      • Understanding markup extensions
    • Understanding .NET MAUI
      • Development tools for mobile first, cloud first
        • Using Windows to create iOS and macOS apps
      • Understanding additional functionality
        • Understanding MVVM
        • Understanding the INotificationPropertyChanged interface
        • Understanding ObservableCollection
        • Understanding dependency services
      • Understanding .NET MAUI user interface components [ iv ]
        • Understanding the ContentPage view
        • Understanding the ListView control
        • Understanding the Entry and Editor controls
      • Understanding .NET MAUI handlers
      • Writing platform-specific code
    • Building mobile and desktop apps using .NET MAUI
      • Creating a virtual Android device for local app testing
      • Creating a .NET MAUI solution
      • Creating a view model with two-way data binding
      • Creating views for the list of customers and customer details
      • Implementing the customer list view
      • Implementing the customer detail view
      • Setting the main page for the mobile app
      • Testing the mobile app
    • Consuming a web service from a mobile app
      • Configuring the web service to allow insecure requests
        • Configuring the iOS app to allow insecure connections
        • Configuring the Android app to allow insecure connections
      • Getting customers from the web service
    • Practicing and exploring
      • Exercise 19.1 – Test your knowledge
      • Exercise 19.2 – Explore topics
    • Summary
  • Chapter 20: Protecting Your Data and Applications
    • Understanding the vocabulary of protection
      • Keys and key sizes
      • IVs and block sizes
      • Salts
      • Generating keys and IVs
    • Encrypting and decrypting data
      • Encrypting symmetrically with AES
    • Hashing data
      • Hashing with the commonly used SHA256
    • Signing data
      • Signing with SHA256 and RSA
    • Generating random numbers
      • Generating random numbers for games and similar apps
      • Generating random numbers for cryptography
    • Authenticating and authorizing users
      • Authentication and authorization mechanisms
        • Identifying a user
        • User membership
      • Implementing authentication and authorization
      • Protecting application functionality
      • Real-world authentication and authorization [ v ]
    • Practicing and exploring
      • Exercise 20.1 – Test your knowledge
      • Exercise 20.2 – Practice protecting data with encryption and hashing
      • Exercise 20.3 – Practice protecting data with decryption
      • Exercise 20.4 – Explore topics
    • Summary
  • Appendix: Answers to the Test Your Knowledge Questions
    • Chapter 1 – Hello, C#! Welcome, .NET!
    • Chapter 2 – Speaking C#
      • Exercise 2.1 – Test your knowledge
      • Exercise 2.2 – Test your knowledge of number types
    • Chapter 3 – Controlling the Flow and Converting Types
      • Exercise 3.1 – Test your knowledge
      • Exercise 3.2 – Explore loops and overflow
      • Exercise 3.5 – Test your knowledge of operators
    • Chapter 4 – Writing, Debugging, and Testing Functions
    • Chapter 5 – Building Your Own Types with Object-Oriented Programming
    • Chapter 6 – Implementing Interfaces and Inheriting Classes
    • Chapter 7 – Packaging and Distributing .NET Types
    • Chapter 8 – Working with Common .NET Types
    • Chapter 9 – Working with Files, Streams, and Serialization
    • Chapter 10 – Working with Data Using Entity Framework Core
    • Chapter 11 – Querying and Manipulating Data Using LINQ
    • Chapter 12 – Improving Performance and Scalability Using Multitasking
    • Chapter 13 – Practical Applications of C# and .NET
    • Chapter 14 – Building Websites Using ASP. NET Core Razor Pages
    • Chapter 15 – Building Websites Using the Model-View-Controller Pattern
    • Chapter 16 – Building and Consuming Web Services
    • Chapter 17 – Building User Interfaces Using Blazor
    • Chapter 18 – Building and Consuming Specialized Services
    • Chapter 19 – Building Mobile and Desktop Apps Using .NET MAUI
    • Chapter 20 – Protecting Your Data and Applications

Building and Consuming

Specialized Services

In this chapter, you will be introduced to the fundamentals of several service technologies that are used in more specialized scenarios than a general-purpose web service. Once you understand the concepts and benefits of each, then you can dig deeper into the ones that interest you most. This chapter will cover the following topics:

  • Understanding specialized service technologies
  • Exposing data as a web service using OData
  • Exposing data as a service using GraphQL
  • Implementing services using gRPC
  • Implementing real-time communication using SignalR
  • Implementing serverless services using Azure Functions
  • Understanding identity services
  • Summary of choices for specialized services

Understanding specialized service technologies

ASP.NET Core Web API is often the best choice for implementing a general-purpose web service, but it is not the only technology for implementing services or communicating between components of a distributed application. Although we will not cover these technologies in detail, you should be aware of what they can do and when they should be used.

Building and Consuming Specialized Services

Understanding Windows Communication

Foundation (WCF)

In 2006, Microsoft released .NET Framework 3.0 with some major new frameworks, one of which was Windows Communication Foundation ( WCF ). It abstracted the business logic implementation of a service from the communication technology infrastructure so that you could easily switch to an alternative in the future or even have multiple mechanisms to communicate with the service. WCF heavily uses XML configuration to declaratively define endpoints, including their address, binding, and contract. This is known as the ABC of WCF endpoints. Once you understand how to do this, WCF is a powerful yet flexible technology. Microsoft decided not to officially port WCF to modern .NET, but there is a community-owned OSS project named Core WCF managed by the .NET Foundation. If you need to migrate an existing service from .NET Framework to modern .NET or build a client to a WCF service, then you could use Core WCF. Be aware that it can never be a full port since parts of WCF are Windows-specific. Technologies like WCF allow for the building of distributed applications. A client application can make remote procedure calls ( RPCs ) to a server application. Instead of using a port of WCF to do this, we could use an alternative RPC technology like gRPC that is covered later in this chapter.

Exposing data as a web service using OData

One of the most common uses of a web service is to expose a database to clients that do not understand how to work with a native database. Another common use is to provide a simplified or abstracted API that exposes only an authenticated interface to a subset of the data. In Chapter 10 , Working with Data Using Entity Framework Core , you learned how to create an EF Core model to expose a database to any .NET app or website. But what about non-.NET apps and websites? I know it's crazy to imagine, but not every developer uses .NET! Luckily, all development platforms support HTTP so that they can call web services, and ASP.NET Core has a package for making that easy and powerful using a standard named OData.

Understanding OData

OData ( Open Data Protocol ) is an ISO/IEC approved OASIS standard that defines a set of best practices for building and consuming RESTful APIs. Microsoft created it in 2007 and released versions 1.0, 2.0, and 3.0 under their Microsoft Open Specification Promise. Version 4.0 was then standardized at OASIS and released in 2014. ASP.NET Core OData implements OData version 4.0.

Building and Consuming Specialized Services

  1. In the Northwind.OData folder, delete WeatherForecast.cs.
  2. In the Controllers folder, delete WeatherForecastController.cs.
  3. In Program.cs, configure UseUrls to specify port 5004 for HTTPS, as shown highlighted in the following code: var builder = WebApplication.CreateBuilder(args); builder.WebHost.UseUrls("https://localhost:5004");
  4. Build the Northwind.OData project.
Defining OData models for EF Core models

The first task is to define what we want to expose as OData models in the web service. You have complete control, so if you have an existing EF Core model, as we do for Northwind, you do not have to expose all of it. You do not even have to use EF Core models. The data source can be anything, although in this book we will only look at using it with EF Core because that is the most common use for .NET developers. Let's define two OData models: one to expose the Northwind product catalog, i.e. the categories and products tables; and one to expose the customers, their orders, and related tables:

  1. In Program.cs, import namespaces for working with OData and our EF Core model for the Northwind database, as shown in the following code: using Microsoft.AspNetCore.OData; // AddOData extension method using Microsoft.OData.Edm; // IEdmModel using Microsoft.OData.ModelBuilder; // ODataConventionModelBuilder using Packt.Shared; // NorthwindContext and entity models
  2. At the bottom of Program.cs, add a method to define and return an OData model for the Northwind catalog that will only expose the entity sets, i.e. tables for Categories, Products, and Suppliers, as shown in the following code: IEdmModel GetEdmModelForCatalog() { ODataConventionModelBuilder builder = new(); builder.EntitySet("Categories"); builder.EntitySet("Products"); builder.EntitySet("Suppliers"); return builder.GetEdmModel(); }

Chapter 18

  1. Add a method to define an OData model for the Northwind customer orders, and note that the same entity set can appear in multiple OData models like Products does, as shown in the following code: IEdmModel GetEdmModelForOrderSystem() { ODataConventionModelBuilder builder = new(); builder.EntitySet("Customers"); builder.EntitySet("Orders"); builder.EntitySet("Employees"); builder.EntitySet("Products"); builder.EntitySet("Shippers"); return builder.GetEdmModel(); }
  2. In the services configuration section, after the call to AddControllers, chain a call to the AddOData extension method to define two OData models and enable features like projection, filtering, and sorting, as shown in the following code: builder.Services.AddControllers() .AddOData(options => options // register OData models including multiple versions .AddRouteComponents(routePrefix: "catalog", model: GetEdmModelForCatalog()) .AddRouteComponents(routePrefix: "ordersystem", model: GetEdmModelForOrderSystem()) // enable query options .Select() // enable $select for projection .Expand() // enable $expand to navigate to related entities .Filter() // enable $filter .OrderBy() // enable $orderby .SetMaxTop( 100 ) // enable $top .Count() // enable $count );
  3. Add statements before the call to AddControllers, to register the Northwind database context, as shown in the following code: builder.Services.AddNorthwindContext();
  4. In the Properties folder, open launchSettings.json.
  5. In the Northwind.OData profile, modify the applicationUrl to use port 5004 , as shown in the following markup: "applicationUrl": "https://localhost:5004",

Chapter 18 Figure 18.1: OData model metadata for the Northwind catalog

  1. Click GET /catalog/$metadata to collapse that section.
  2. Close Chrome and shut down the web server.

Creating and testing OData controllers

Next, we must create OData controllers, one for each type of entity, to retrieve data:

  1. In the Controllers folder, add an empty controller class named CategoriesController.
  2. Modify its contents to inherit from ODataController, get an instance of the Northwind database context using constructor parameter injection, and define two Get methods to retrieve all categories or one category using a unique key, as shown in the following code: using Microsoft.AspNetCore.Mvc; // IActionResult using Microsoft.AspNetCore.OData.Query; // [EnableQuery] using Microsoft.AspNetCore.OData.Routing.Controllers; // ODataController using Packt.Shared; // NorthwindContext namespace Northwind.OData.Controllers;

Building and Consuming Specialized Services public class CategoriesController : ODataController { private readonly NorthwindContext db; public CategoriesController(NorthwindContext db) { this.db = db; } [EnableQuery] public IActionResult Get() { return Ok(db.Categories); } [EnableQuery] public IActionResult Get(int key) { return Ok(db.Categories.Find(key)); } }

  1. Repeat the above step for Products and Suppliers. (I will leave it to you to do the same for the other entities to enable the order system OData model if you choose. Note that CustomerId is a string instead of an integer.)
  2. Start the Northwind.OData web service.
  3. Start Chrome.
  4. Navigate to https://localhost:5004/swagger and note the Categories , Products , and Suppliers entity sets are now usable because you created OData controllers for them.
  5. Click GET /catalog/Categories , click Try it out , click Execute , and note the response body that shows a JSON document containing all categories in the entity set, as partially shown in the following output: { "@odata.context": "https://localhost:5004/catalog/$metadata#Categories", "value": [ { "CategoryId": 1, "CategoryName": "Beverages", "Description": "Soft drinks, coffees, teas, beers, and ales", "Picture": null }, { "CategoryId": 2,

Building and Consuming Specialized Services https://localhost:5004/catalog/ products JSON document containing all products. https://localhost:5004/catalog/ products/$count 77 https://localhost:5004/catalog/ products(2) { "@odata.context": "https://localhost:5004/cat alog/$metadata#Products/$entity", "ProductId": 2 , "ProductName": "Chang", "SupplierId": 1 , "CategoryId": 1 , "QuantityPerUnit": "24 - 12 oz bottles", "UnitPrice": 19 , "UnitsInStock": 17 , "UnitsOnOrder": 40 , "ReorderLevel": 25 , "Discontinued": false } https://localhost:5004/catalog/ suppliers JSON document containing all suppliers. https://localhost:5004/catalog/ suppliers/$count 29

Querying OData models

To execute arbitrary queries against an OData model, we earlier enabled selecting, filtering, and ordering. One of the benefits of OData is that it defines standard query options, as shown in the following table: Option Description Example $select Selects properties for each entity. $select=CategoryId,CategoryName $expand Selects related entities via navigation properties. $expand=Products $filter The expression is evaluated for each resource, and only entities where the expression is true are included in the response. $filter=startswith(ProductName,'ch') or (UnitPrice gt 50) $orderby Sorts the entities by the properties listed in ascending (default) or descending order. $orderby=UnitPrice desc,ProductName $skip $top Skips the specified number of items. Takes the specified number of items. $skip=40&$take= For performance reasons, batching with $skip and $top is disabled by default.

Chapter 18

Understanding OData operators

OData has operators for use with the $filter option, as shown in the following table: Operator Description eq Equals. ne Not equals. lt Less than. gt Greater than. le Less than or equal to. ge Greater than or equal to. and And. or Or. not Not. add Arithmetic addition for numbers and date/time values. sub Arithmetic subtraction for numbers and date/time values. mul Arithmetic multiplication for numbers. div Arithmetic division for numbers. mod Arithmetic modulus division for numbers.

Understanding OData functions

OData has functions for use with the $filter option, as shown in the following table: Operator Description startswith(property, 'value') Text values that start with the specified value. endswith(property, 'value') Text values that end with the specified value. concat(property, 'value') Concatenate two text values. contains(property, 'value') Text values that contain the specified value. indexof(property, 'value') Returns the position of a text value. length(property) Returns the length of a text value. substring Extracts a substring from a text value. tolower Converts to lowercase. toupper Converts to uppercase. trim Trims whitespace before and after text value. now The current date and time. date, day, month, year Extracts date components. time, hour, minute, second Extracts time components.

Chapter 18 namespace Packt.Shared; public class ConsoleLoggerFactory : ILoggerFactory { public void AddProvider(ILoggerProvider provider) { } public ILogger CreateLogger(string categoryName) { return new ConsoleLogger(); } public void Dispose() { } } public class ConsoleLogger : ILogger { public IDisposable BeginScope(TState state) { return null; } public bool IsEnabled(LogLevel logLevel) { switch(logLevel) { case LogLevel.Trace: case LogLevel.Information: case LogLevel.None: return false; case LogLevel.Debug: case LogLevel.Warning: case LogLevel.Error: case LogLevel.Critical: default: return true; }; } public void Log(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { if (eventId.Id == 20100 ) // execute SQL statement {

Building and Consuming Specialized Services Write($"Level: {logLevel}, Event Id: {eventId.Id}"); // only output the state or exception if it exists if (state != null) { Write($", State: {state}"); } if (exception != null) { Write($", Exception: {exception.Message}"); } WriteLine(); } } }

  1. In NorthwindContextExtensions.cs, in the AddNorthwindContext method, after the call to UseSqlServer or UseSqlite, call UseLoggerFactory to register your custom console logger, as shown highlighted in the following code: services.AddDbContext(options => options.UseSqlServer(connectionString) // or UseSqlite(...) .UseLoggerFactory(new ConsoleLoggerFactory()) );
  2. Start the Northwind.OData web service.
  3. Start Chrome.
  4. Navigate to https://localhost:5004/catalog/products/?$filter=startswith(Product Name,'Ch') or (UnitPrice gt 50)&$select=ProductId,ProductName,UnitPrice.
  5. In Chrome, note the result, as shown in the following output: {"@odata.context":"https://localhost:5004/catalog/$metadata#Products(Prod uctId,ProductName,UnitPrice)","value":[{"ProductId":1,"ProductName":"Chai ","UnitPrice":18.0000},{"ProductId":2,"ProductName":"Chang","UnitPrice": 9.0000},{"ProductId":4,"ProductName":"Chef Anton's Cajun Seasoning","Uni tPrice":22.0000},{"ProductId":5,"ProductName":"Chef Anton's Gumbo Mix"," UnitPrice":21.3500},{"ProductId":9,"ProductName":"Mishi Kobe Niku","Unit Price":97.0000},{"ProductId":18,"ProductName":"Carnarvon Tigers","UnitPr ice":62.5000},{"ProductId":20,"ProductName":"Sir Rodney's Marmalade","Un itPrice":81.0000},{"ProductId":29,"ProductName":"Th\u00fcringer Rostbrat wurst","UnitPrice":123.7900},{"ProductId":38,"ProductName":"C\u00f4te de Blaye","UnitPrice":263.5000},{"ProductId":39,"ProductName":"Chartreuse ver te","UnitPrice":18.0000},{"ProductId":48,"ProductName":"Chocolade","UnitPr ice":12.7500},{"ProductId":51,"ProductName":"Manjimup Dried Apples","UnitP rice":53.0000},{"ProductId":59,"ProductName":"Raclette Courdavault","UnitP rice":55.0000}]}