#useRouter
Explore tagged Tumblr posts
Text
Understanding next.js useRouter
Next.js is a popular framework for building React applications. It provides many features that make developing web applications easier, including client-side routing. One of the key tools in Next.js for handling routing is the useRouter hook. In this article, we will explore what useRouter is and how it can be used effectively in Next.js applications.
1. Introduction to useRouter
The useRouter hook is a built-in hook provided by Next.js. It allows us to access and manipulate the current page's routing information. With useRouter, we can extract data from the URL, handle dynamic routing, process query parameters, and perform page redirection. https://nextjs.org/docs/pages/api-reference/functions/use-router
 2. Benefits of using useRouter
Using the useRouter hook in Next.js offers several benefits: Simplified routing setup: useRouter simplifies the process of setting up routing in Next.js applications. It provides an intuitive interface for handling routing-related tasks. Dynamic routing support: With useRouter, implementing dynamic routing becomes straightforward. You can use dynamic parameters in the URL to generate pages dynamically. Query parameter handling: useRouter makes it easy to extract and process query parameters from the URL. Page redirection: useRouter enables seamless page redirection based on specific conditions or user interactions.
3. Handling dynamic routing with useRouter
Let's explore how to implement dynamic routing using the useRouter hook. First, create a file named .js in the pages directory. Here,  represents the dynamic part of the URL. Inside this file, you can use useRouter to handle dynamic routing. Origin : https://worldgoit.com/archives/posts/software-development/understanding-next-js-userouter/ Read the full article
0 notes
Text
C# Interview Questions and Answers - Part 18:
Q175. What is Routing? How does routing work in ASP .Net Core? Q176. What is the difference between Route, RouteCollection, and Route Handler? Q177. What is the difference between MapControllerRoute vs MapDefaultControllerRoute vs MapControllers in ASP .Net Core MVC? Q178. What is Route URL Pattern in ASP .Net Core MVC? Q179. What is Default Route? How can you define multiple routes in ASP .Net MVC Core? Q180. What are the different types of routing in ASP .Net Core? Q181. What is Conventional based Routing in ASP .Net Core? Q182. What is Attribute-based Routing in ASP .Net Core? Q183. What is the use of UseRouting() middleware in ASP .Net Core? How it is different from UseEndPoints()?
#CSharpInterviewQuestionsAndAnswers#CSharpInterviewQuestions2022#InterviewQuestionsAndAnswers#techpointfundamentals#techpointfunda#techpoint#interview#csharpprogramming
1 note
·
View note
Text
Middleware

Microsoft Middleware Product
Middleware Meaning
Middleware Definition
Middleware Definition
Middleware Products
-->
Microsoft Middleware Product
Middleware is a general term for software that serves to 'glue together' separate, often complex and already existing, programs. Some software components that are frequently connected with middleware include enterprise applications and Web services. Answered Mar 3 '16 at 5:03. Middleware enables the DoD PKI certificates stored on your Common Access Card (CAC) to interface with the many Public Key Enabled (PKE) applications on your system and across the Internet. Two of the most common middleware applications used across DoD are ActivClient and Spyrus. Middleware is software that provides common services and capabilities to applications outside of what’s offered by the operating system. Data management, application services, messaging, authentication, and API management are all commonly handled by middleware. Middleware helps developers build applications more efficiently. Using middleware in this fashion avoids the problems that occur when applications are responsible for these tasks and incompatible versions arise. The Internet2 project was designed to make. Middleware is a tool that processes data through multiple sources. For example, order data is processed from your eCommerce website, passed into your middleware, and then distributed to your ERP, accounting software, and email marketing tool. For website administrators managing a highly custom website strategy (particularly websites that manage.
By Rick Anderson and Steve Smith
Middleware is software that's assembled into an app pipeline to handle requests and responses. Each component:
Chooses whether to pass the request to the next component in the pipeline.
Can perform work before and after the next component in the pipeline.
Request delegates are used to build the request pipeline. The request delegates handle each HTTP request.
Request delegates are configured using Run, Map, and Use extension methods. An individual request delegate can be specified in-line as an anonymous method (called in-line middleware), or it can be defined in a reusable class. These reusable classes and in-line anonymous methods are middleware, also called middleware components. Each middleware component in the request pipeline is responsible for invoking the next component in the pipeline or short-circuiting the pipeline. When a middleware short-circuits, it's called a terminal middleware because it prevents further middleware from processing the request.
Migrate HTTP handlers and modules to ASP.NET Core middleware explains the difference between request pipelines in ASP.NET Core and ASP.NET 4.x and provides additional middleware samples.
Create a middleware pipeline with IApplicationBuilder
The ASP.NET Core request pipeline consists of a sequence of request delegates, called one after the other. The following diagram demonstrates the concept. The thread of execution follows the black arrows.
Middleware Meaning
Each delegate can perform operations before and after the next delegate. Exception-handling delegates should be called early in the pipeline, so they can catch exceptions that occur in later stages of the pipeline.
The simplest possible ASP.NET Core app sets up a single request delegate that handles all requests. This case doesn't include an actual request pipeline. Instead, a single anonymous function is called in response to every HTTP request.
Chain multiple request delegates together with Use. The next parameter represents the next delegate in the pipeline. You can short-circuit the pipeline by not calling the next parameter. You can typically perform actions both before and after the next delegate, as the following example demonstrates:
When a delegate doesn't pass a request to the next delegate, it's called short-circuiting the request pipeline. Short-circuiting is often desirable because it avoids unnecessary work. For example, Static File Middleware can act as a terminal middleware by processing a request for a static file and short-circuiting the rest of the pipeline. Middleware added to the pipeline before the middleware that terminates further processing still processes code after their next.Invoke statements. However, see the following warning about attempting to write to a response that has already been sent.
Warning
Don't call next.Invoke after the response has been sent to the client. Changes to HttpResponse after the response has started throw an exception. For example, setting headers and a status code throw an exception. Writing to the response body after calling next:
May cause a protocol violation. For example, writing more than the stated Content-Length.
May corrupt the body format. For example, writing an HTML footer to a CSS file.
HasStarted is a useful hint to indicate if headers have been sent or the body has been written to.
Run delegates don't receive a next parameter. The first Run delegate is always terminal and terminates the pipeline. Run is a convention. Some middleware components may expose Run(Middleware) methods that run at the end of the pipeline:
If you would like to see code comments translated to languages other than English, let us know in this GitHub discussion issue.
In the preceding example, the Run delegate writes 'Hello from 2nd delegate.' to the response and then terminates the pipeline. If another Use or Run delegate is added after the Run delegate, it's not called.
Middleware order
The following diagram shows the complete request processing pipeline for ASP.NET Core MVC and Razor Pages apps. You can see how, in a typical app, existing middlewares are ordered and where custom middlewares are added. You have full control over how to reorder existing middlewares or inject new custom middlewares as necessary for your scenarios.
The Endpoint middleware in the preceding diagram executes the filter pipeline for the corresponding app type—MVC or Razor Pages.
The order that middleware components are added in the Startup.Configure method defines the order in which the middleware components are invoked on requests and the reverse order for the response. The order is critical for security, performance, and functionality.
The following Startup.Configure method adds security-related middleware components in the typical recommended order:
In the preceding code:
Middleware that is not added when creating a new web app with individual users accounts is commented out.
Not every middleware needs to go in this exact order, but many do. For example:
UseCors, UseAuthentication, and UseAuthorization must go in the order shown.
UseCors currently must go before UseResponseCaching due to this bug.
In some scenarios, middleware will have different ordering. For example, caching and compression ordering is scenario specific, and there's multiple valid orderings. For example:
With the preceding code, CPU could be saved by caching the compressed response, but you might end up caching multiple representations of a resource using different compression algorithms such as gzip or brotli.
The following ordering combines static files to allow caching compressed static files:
The following Startup.Configure method adds middleware components for common app scenarios:
Exception/error handling
When the app runs in the Development environment:
Developer Exception Page Middleware (UseDeveloperExceptionPage) reports app runtime errors.
Database Error Page Middleware reports database runtime errors.
When the app runs in the Production environment:
Exception Handler Middleware (UseExceptionHandler) catches exceptions thrown in the following middlewares.
HTTP Strict Transport Security Protocol (HSTS) Middleware (UseHsts) adds the Strict-Transport-Security header.
HTTPS Redirection Middleware (UseHttpsRedirection) redirects HTTP requests to HTTPS.
Static File Middleware (UseStaticFiles) returns static files and short-circuits further request processing.
Cookie Policy Middleware (UseCookiePolicy) conforms the app to the EU General Data Protection Regulation (GDPR) regulations.
Routing Middleware (UseRouting) to route requests.
Authentication Middleware (UseAuthentication) attempts to authenticate the user before they're allowed access to secure resources.
Authorization Middleware (UseAuthorization) authorizes a user to access secure resources.
Session Middleware (UseSession) establishes and maintains session state. If the app uses session state, call Session Middleware after Cookie Policy Middleware and before MVC Middleware.
Endpoint Routing Middleware (UseEndpoints with MapRazorPages) to add Razor Pages endpoints to the request pipeline.
In the preceding example code, each middleware extension method is exposed on IApplicationBuilder through the Microsoft.AspNetCore.Builder namespace.
UseExceptionHandler is the first middleware component added to the pipeline. Therefore, the Exception Handler Middleware catches any exceptions that occur in later calls.
Static File Middleware is called early in the pipeline so that it can handle requests and short-circuit without going through the remaining components. The Static File Middleware provides no authorization checks. Any files served by Static File Middleware, including those under wwwroot, are publicly available. For an approach to secure static files, see Static files in ASP.NET Core.
If the request isn't handled by the Static File Middleware, it's passed on to the Authentication Middleware (UseAuthentication), which performs authentication. Authentication doesn't short-circuit unauthenticated requests. Although Authentication Middleware authenticates requests, authorization (and rejection) occurs only after MVC selects a specific Razor Page or MVC controller and action.
The following example demonstrates a middleware order where requests for static files are handled by Static File Middleware before Response Compression Middleware. Static files aren't compressed with this middleware order. The Razor Pages responses can be compressed.
For Single Page Applications (SPAs), the SPA middleware UseSpaStaticFiles usually comes last in the middleware pipeline. The SPA middleware comes last:
To allow all other middlewares to respond to matching requests first.
To allow SPAs with client-side routing to run for all routes that are unrecognized by the server app.
For more details on SPAs, see the guides for the React and Angular project templates.
Forwarded Headers Middleware order
Forwarded Headers Middleware should run before other middleware. This ordering ensures that the middleware relying on forwarded headers information can consume the header values for processing. To run Forwarded Headers Middleware after diagnostics and error handling middleware, see Forwarded Headers Middleware order.
Branch the middleware pipeline
Map extensions are used as a convention for branching the pipeline. Map branches the request pipeline based on matches of the given request path. If the request path starts with the given path, the branch is executed.
The following table shows the requests and responses from http://localhost:1234 using the previous code.
RequestResponselocalhost:1234Hello from non-Map delegate.localhost:1234/map1Map Test 1localhost:1234/map2Map Test 2localhost:1234/map3Hello from non-Map delegate.
When Map is used, the matched path segments are removed from HttpRequest.Path and appended to HttpRequest.PathBase for each request.
Map supports nesting, for example:
Map can also match multiple segments at once:
MapWhen branches the request pipeline based on the result of the given predicate. Any predicate of type Func<HttpContext, bool> can be used to map requests to a new branch of the pipeline. In the following example, a predicate is used to detect the presence of a query string variable branch:
The following table shows the requests and responses from http://localhost:1234 using the previous code:
RequestResponselocalhost:1234Hello from non-Map delegate.localhost:1234/?branch=mainBranch used = main

UseWhen also branches the request pipeline based on the result of the given predicate. Unlike with MapWhen, this branch is rejoined to the main pipeline if it doesn't short-circuit or contain a terminal middleware:
In the preceding example, a response of 'Hello from main pipeline.' is written for all requests. If the request includes a query string variable branch, its value is logged before the main pipeline is rejoined.
Built-in middleware
ASP.NET Core ships with the following middleware components. The Order column provides notes on middleware placement in the request processing pipeline and under what conditions the middleware may terminate request processing. When a middleware short-circuits the request processing pipeline and prevents further downstream middleware from processing a request, it's called a terminal middleware. For more information on short-circuiting, see the Create a middleware pipeline with IApplicationBuilder section.
MiddlewareDescriptionOrderAuthenticationProvides authentication support.Before HttpContext.User is needed. Terminal for OAuth callbacks.AuthorizationProvides authorization support.Immediately after the Authentication Middleware.Cookie PolicyTracks consent from users for storing personal information and enforces minimum standards for cookie fields, such as secure and SameSite.Before middleware that issues cookies. Examples: Authentication, Session, MVC (TempData).CORSConfigures Cross-Origin Resource Sharing.Before components that use CORS. UseCors currently must go before UseResponseCaching due to this bug.DiagnosticsSeveral separate middlewares that provide a developer exception page, exception handling, status code pages, and the default web page for new apps.Before components that generate errors. Terminal for exceptions or serving the default web page for new apps.Forwarded HeadersForwards proxied headers onto the current request.Before components that consume the updated fields. Examples: scheme, host, client IP, method.Health CheckChecks the health of an ASP.NET Core app and its dependencies, such as checking database availability.Terminal if a request matches a health check endpoint.Header PropagationPropagates HTTP headers from the incoming request to the outgoing HTTP Client requests.HTTP Method OverrideAllows an incoming POST request to override the method.Before components that consume the updated method.HTTPS RedirectionRedirect all HTTP requests to HTTPS.Before components that consume the URL.HTTP Strict Transport Security (HSTS)Security enhancement middleware that adds a special response header.Before responses are sent and after components that modify requests. Examples: Forwarded Headers, URL Rewriting.MVCProcesses requests with MVC/Razor Pages.Terminal if a request matches a route.OWINInterop with OWIN-based apps, servers, and middleware.Terminal if the OWIN Middleware fully processes the request.Response CachingProvides support for caching responses.Before components that require caching. UseCORS must come before UseResponseCaching.Response CompressionProvides support for compressing responses.Before components that require compression.Request LocalizationProvides localization support.Before localization sensitive components.Endpoint RoutingDefines and constrains request routes.Terminal for matching routes.SPAHandles all requests from this point in the middleware chain by returning the default page for the Single Page Application (SPA)Late in the chain, so that other middleware for serving static files, MVC actions, etc., takes precedence.SessionProvides support for managing user sessions.Before components that require Session.Static FilesProvides support for serving static files and directory browsing.Terminal if a request matches a file.URL RewriteProvides support for rewriting URLs and redirecting requests.Before components that consume the URL.WebSocketsEnables the WebSockets protocol.Before components that are required to accept WebSocket requests.
Additional resources
Lifetime and registration options contains a complete sample of middleware with scoped, transient, and singleton lifetime services.
By Rick Anderson and Steve Smith
Middleware is software that's assembled into an app pipeline to handle requests and responses. Each component:
Chooses whether to pass the request to the next component in the pipeline.
Can perform work before and after the next component in the pipeline.
Request delegates are used to build the request pipeline. The request delegates handle each HTTP request.
Request delegates are configured using Run, Map, and Use extension methods. An individual request delegate can be specified in-line as an anonymous method (called in-line middleware), or it can be defined in a reusable class. These reusable classes and in-line anonymous methods are middleware, also called middleware components. Each middleware component in the request pipeline is responsible for invoking the next component in the pipeline or short-circuiting the pipeline. When a middleware short-circuits, it's called a terminal middleware because it prevents further middleware from processing the request.
Migrate HTTP handlers and modules to ASP.NET Core middleware explains the difference between request pipelines in ASP.NET Core and ASP.NET 4.x and provides additional middleware samples.
Create a middleware pipeline with IApplicationBuilder
The ASP.NET Core request pipeline consists of a sequence of request delegates, called one after the other. The following diagram demonstrates the concept. The thread of execution follows the black arrows.
Each delegate can perform operations before and after the next delegate. Exception-handling delegates should be called early in the pipeline, so they can catch exceptions that occur in later stages of the pipeline.
The simplest possible ASP.NET Core app sets up a single request delegate that handles all requests. This case doesn't include an actual request pipeline. Instead, a single anonymous function is called in response to every HTTP request.
The first Run delegate terminates the pipeline.
Chain multiple request delegates together with Use. The next parameter represents the next delegate in the pipeline. You can short-circuit the pipeline by not calling the next parameter. You can typically perform actions both before and after the next delegate, as the following example demonstrates:
When a delegate doesn't pass a request to the next delegate, it's called short-circuiting the request pipeline. Short-circuiting is often desirable because it avoids unnecessary work. For example, Static File Middleware can act as a terminal middleware by processing a request for a static file and short-circuiting the rest of the pipeline. Middleware added to the pipeline before the middleware that terminates further processing still processes code after their next.Invoke statements. However, see the following warning about attempting to write to a response that has already been sent.
Warning
Don't call next.Invoke after the response has been sent to the client. Changes to HttpResponse after the response has started throw an exception. For example, changes such as setting headers and a status code throw an exception. Writing to the response body after calling next:
May cause a protocol violation. For example, writing more than the stated Content-Length.
May corrupt the body format. For example, writing an HTML footer to a CSS file.
HasStarted is a useful hint to indicate if headers have been sent or the body has been written to.
Middleware order
The order that middleware components are added in the Startup.Configure method defines the order in which the middleware components are invoked on requests and the reverse order for the response. The order is critical for security, performance, and functionality.
The following Startup.Configure method adds security related middleware components in the recommended order:
In the preceding code:
Middleware that is not added when creating a new web app with individual users accounts is commented out.
Not every middleware needs to go in this exact order, but many do. For example, UseCors and UseAuthentication must go in the order shown.
The following Startup.Configure method adds middleware components for common app scenarios:
Exception/error handling
When the app runs in the Development environment:
Developer Exception Page Middleware (UseDeveloperExceptionPage) reports app runtime errors.
Database Error Page Middleware (Microsoft.AspNetCore.Builder.DatabaseErrorPageExtensions.UseDatabaseErrorPage) reports database runtime errors.
When the app runs in the Production environment:
Exception Handler Middleware (UseExceptionHandler) catches exceptions thrown in the following middlewares.
HTTP Strict Transport Security Protocol (HSTS) Middleware (UseHsts) adds the Strict-Transport-Security header.
HTTPS Redirection Middleware (UseHttpsRedirection) redirects HTTP requests to HTTPS.
Static File Middleware (UseStaticFiles) returns static files and short-circuits further request processing.
Cookie Policy Middleware (UseCookiePolicy) conforms the app to the EU General Data Protection Regulation (GDPR) regulations.
Authentication Middleware (UseAuthentication) attempts to authenticate the user before they're allowed access to secure resources.
Session Middleware (UseSession) establishes and maintains session state. If the app uses session state, call Session Middleware after Cookie Policy Middleware and before MVC Middleware.
MVC (UseMvc) to add MVC to the request pipeline.
In the preceding example code, each middleware extension method is exposed on IApplicationBuilder through the Microsoft.AspNetCore.Builder namespace.
UseExceptionHandler is the first middleware component added to the pipeline. Therefore, the Exception Handler Middleware catches any exceptions that occur in later calls.
Static File Middleware is called early in the pipeline so that it can handle requests and short-circuit without going through the remaining components. The Static File Middleware provides no authorization checks. Any files served by Static File Middleware, including those under wwwroot, are publicly available. For an approach to secure static files, see Static files in ASP.NET Core.
If the request isn't handled by the Static File Middleware, it's passed on to the Authentication Middleware (UseAuthentication), which performs authentication. Authentication doesn't short-circuit unauthenticated requests. Although Authentication Middleware authenticates requests, authorization (and rejection) occurs only after MVC selects a specific Razor Page or MVC controller and action.
The following example demonstrates a middleware order where requests for static files are handled by Static File Middleware before Response Compression Middleware. Static files aren't compressed with this middleware order. The MVC responses from UseMvcWithDefaultRoute can be compressed.
Use, Run, and Map
Configure the HTTP pipeline using Use, Run, and Map. The Use method can short-circuit the pipeline (that is, if it doesn't call a next request delegate). Run is a convention, and some middleware components may expose Run(Middleware) methods that run at the end of the pipeline.
Map extensions are used as a convention for branching the pipeline. Map branches the request pipeline based on matches of the given request path. If the request path starts with the given path, the branch is executed.
The following table shows the requests and responses from http://localhost:1234 using the previous code.
RequestResponselocalhost:1234Hello from non-Map delegate.localhost:1234/map1Map Test 1localhost:1234/map2Map Test 2localhost:1234/map3Hello from non-Map delegate.
When Map is used, the matched path segments are removed from HttpRequest.Path and appended to HttpRequest.PathBase for each request.
MapWhen branches the request pipeline based on the result of the given predicate. Any predicate of type Func<HttpContext, bool> can be used to map requests to a new branch of the pipeline. In the following example, a predicate is used to detect the presence of a query string variable branch:
The following table shows the requests and responses from http://localhost:1234 using the previous code.
RequestResponselocalhost:1234Hello from non-Map delegate.localhost:1234/?branch=mainBranch used = main
Map supports nesting, for example:
Map can also match multiple segments at once:
Built-in middleware
ASP.NET Core ships with the following middleware components. The Order column provides notes on middleware placement in the request processing pipeline and under what conditions the middleware may terminate request processing. When a middleware short-circuits the request processing pipeline and prevents further downstream middleware from processing a request, it's called a terminal middleware. For more information on short-circuiting, see the Create a middleware pipeline with IApplicationBuilder section.
Middleware Definition
MiddlewareDescriptionOrderAuthenticationProvides authentication support.Before HttpContext.User is needed. Terminal for OAuth callbacks.Cookie PolicyTracks consent from users for storing personal information and enforces minimum standards for cookie fields, such as secure and SameSite.Before middleware that issues cookies. Examples: Authentication, Session, MVC (TempData).CORSConfigures Cross-Origin Resource Sharing.Before components that use CORS.DiagnosticsSeveral separate middlewares that provide a developer exception page, exception handling, status code pages, and the default web page for new apps.Before components that generate errors. Terminal for exceptions or serving the default web page for new apps.Forwarded HeadersForwards proxied headers onto the current request.Before components that consume the updated fields. Examples: scheme, host, client IP, method.Health CheckChecks the health of an ASP.NET Core app and its dependencies, such as checking database availability.Terminal if a request matches a health check endpoint.HTTP Method OverrideAllows an incoming POST request to override the method.Before components that consume the updated method.HTTPS RedirectionRedirect all HTTP requests to HTTPS.Before components that consume the URL.HTTP Strict Transport Security (HSTS)Security enhancement middleware that adds a special response header.Before responses are sent and after components that modify requests. Examples: Forwarded Headers, URL Rewriting.MVCProcesses requests with MVC/Razor Pages.Terminal if a request matches a route.OWINInterop with OWIN-based apps, servers, and middleware.Terminal if the OWIN Middleware fully processes the request.Response CachingProvides support for caching responses.Before components that require caching.Response CompressionProvides support for compressing responses.Before components that require compression.Request LocalizationProvides localization support.Before localization sensitive components.Endpoint RoutingDefines and constrains request routes.Terminal for matching routes.SessionProvides support for managing user sessions.Before components that require Session.Static FilesProvides support for serving static files and directory browsing.Terminal if a request matches a file.URL RewriteProvides support for rewriting URLs and redirecting requests.Before components that consume the URL.WebSocketsEnables the WebSockets protocol.Before components that are required to accept WebSocket requests.
Additional resources
Middleware is a type of computer software that provides services to software applications beyond those available from the operating system. It can be described as 'software glue'.(1)
Middleware makes it easier for software developers to implement communication and input/output, so they can focus on the specific purpose of their application. It gained popularity in the 1980s as a solution to the problem of how to link newer applications to older legacy systems, although the term had been in use since 1968.(2)
In distributed applications(edit)
Software architecture: Middleware
The term is most commonly used for software that enables communication and management of data in distributed applications. An IETF workshop in 2000 defined middleware as 'those services found above the transport (i.e. over TCP/IP) layer set of services but below the application environment' (i.e. below application-level APIs).(3) In this more specific sense middleware can be described as the dash ('-') in client-server, or the -to- in peer-to-peer. Middleware includes web servers, application servers, content management systems, and similar tools that support application development and delivery.(4)
Middleware Definition
ObjectWeb defines middleware as: 'The software layer that lies between the operating system and applications on each side of a distributed computing system in a network.'(5) Services that can be regarded as middleware include enterprise application integration, data integration, message oriented middleware (MOM), object request brokers (ORBs), and the enterprise service bus (ESB).(6)
Database access services are often characterised as middleware. Some of them are language specific implementations and support heterogeneous features and other related communication features.(7) Examples of database-oriented middleware include ODBC, JDBC and transaction processing monitors.(8)
Distributed computing system middleware can loosely be divided into two categories—those that provide human-time services (such as web request servicing) and those that perform in machine-time. This latter middleware is somewhat standardized through the Service Availability Forum(9) and is commonly used in complex, embedded systems within telecom, defence and aerospace industries.(10)
Other examples(edit)
The term middleware is used in other contexts as well. Middleware is sometimes used in a similar sense to a software driver, an abstraction layer that hides detail about hardware devices or other software from an application.
The Android operating system uses the Linux kernel at its core, and also provides an application framework that developers incorporate into their applications. In addition, Android provides a middleware layer including libraries that provide services such as data storage, screen display, multimedia, and web browsing. Because the middleware libraries are compiled to machine language, services execute quickly. Middleware libraries also implement device-specific functions, so applications and the application framework need not concern themselves with variations between various Android devices. Android's middleware layer also contains the ARTvirtual machine and its core Java application libraries.(11)
Middleware also refers to the software that separates two or more APIs and provides services such as rate-limiting, authentication, and logging.
Game engine software such as Gamebryo and RenderWare are sometimes described as middleware, because they provide many services to simplify game development.(12)
In simulation technology, middleware is generally used in the context of the high level architecture (HLA) that applies to many distributed simulations. It is a layer of software that lies between the application code and the run-time infrastructure. Middleware generally consists of a library of functions, and enables a number of applications—simulations or federates in HLA terminology—to page these functions from the common library rather than re-create them for each application.(13)
Wireless networking developers can use middleware to meet the challenges associated with a wireless sensor network (WSN). Implementing a middleware application allows WSN developers to integrate operating systems and hardware with the wide variety of various applications that are currently available.(14)
The QNX operating system offers middleware for providing multimedia services for use in automobiles, aircraft and other environments.(15)
Radio-frequency identification (RFID) software toolkits provide middleware to filter noisy and redundant raw data.(16)
See also(edit)
References(edit)
^'What is Middleware?'. Middleware.org. Defining Technology. 2008. Archived from the original on June 29, 2012. Retrieved 2013-08-11.CS1 maint: unfit URL (link)
^Gall, Nick (July 30, 2005). 'Origin of the term middleware'.
^'Home'. IETF.
^Etzkorn, L. H. (2017). Introduction to Middleware: Web Services, Object Components, and Cloud Computing. CRC Press. pp. 4–5. ISBN9781498754101.
^Krakowiak, Sacha. 'What's middleware?'. ObjectWeb.org. Archived from the original on 2005-05-07. Retrieved 2005-05-06.
^Luckham, D. C. (2011). Event Processing for Business: Organizing the Real-Time Enterprise. John Wiley & Sons. pp. 27–28. ISBN9781118171851.
^Simon, A. R.; Wheeler, T. (2014). Open Client/Server Computing and Middleware. Academic Press. pp. 43–49. ISBN9781483214276.
^Arregoces, M.; Portolani, M. (2003). Data Center Fundamentals. Cisco Press. pp. 92–93. ISBN9781587140747.
^'Service Availability Interface Specification'(PDF). Service Availability Forum. 30 September 2011. Retrieved 26 July 2018.
^Jokiaho, T.; Fryer, J. (2012). 'Foreword'. Service Availability: Principles and Practice. John Wiley & Sons. p. xv. ISBN9781119941675.
^Charlie Collins, Michael Galpin and Matthias Kaeppler, Android in Practice, Manning Publications, 2011
^Moore, M. E. (2006). Introduction to the Game Industry. Pearson Prentice Hall. p. 169. ISBN9780131687431.
^Becchini, R.; Chilaev, P.; Krivtsov, V.; et al. (2003). 'Chapter 4: Middleware'. In Drira, K.; Martelli, A.; Villemur, T. (eds.). Cooperative Environments for Distributed Systems Engineering: The Distributed Systems Environment Report. Springer. pp. 41–4. ISBN9783540455820.
^Hadim, S. and Mohamed, N. (2006). Middleware challenges and approaches for wireless sensor networks. IEEE Distributed Systems Online vol 7. Issue 3. Retrieved March 4, 2009 fromiEEE Distributed Systems OnlineArchived 2011-09-28 at the Wayback Machine
^'QNX Software Joins Internet ITS Consortium of Japan'. QNX News Releases. QNX. 6 May 2008. Retrieved 26 July 2018.
^Glover, B.; Bhatt, H. (2006). RFID Essentials. O'Reilly Media. pp. 38–44. ISBN9780596009441.
External links(edit)
The dictionary definition of middleware at Wiktionary
Middleware Products
Retrieved from 'https://en.wikipedia.org/w/index.php?title=Middleware&oldid=1019034461'

0 notes
Text
Updating an ASP.NET Core 2.2 Web Site to .NET Core 3.1 LTS
Now that .NET Core 3.1 is out jus this last week and it is a "LTS" or Long Term Support version, I thought it'd be a good time to update my main site and my podcast to .NET 3.1. You can read about what LTS means but quite simply it's that "LTS releases are supported for three years after the initial release."
I'm not sure about you, but for me, when I don't look at some code for a few months - in this case because it's working just fine - it takes some time for the context switch back in. For my podcast site and main site I honestly have forgotten what version of .NET they are running on.
Updating my site to .NET Core 3.1
First, it seems my main homepage is NET Core 2.2. I can tell because the csproj has a "TargetFramework" of netcoreapp2.2. So I'll start at the migration docs here to go from 2.2 to 3.0. .NET Core 2.2 reaches "end of life" (support) this month so it's a good time to update to the 3.1 version that will be supported for 3 years.
Here's my original csproj
<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>netcoreapp2.2</TargetFramework> <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel> <RootNamespace>hanselman_core</RootNamespace> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.AspNetCore.App" /> <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" /> <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.3" /> </ItemGroup> <ItemGroup> <None Update="IISUrlRewrite.xml"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> </ItemGroup> </Project>
and my 3.0 updated csproj. You'll note that most of it is deletions. Also note that I have a custom IISUrlRewrite.xml that I want to make sure gets to a specific place. You'll likely not have anything like this, but be aware.
<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>netcoreapp3.1</TargetFramework> <RootNamespace>hanselman_core</RootNamespace> </PropertyGroup> <ItemGroup> <None Update="IISUrlRewrite.xml"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> </ItemGroup> </Project>
Some folks are more little methodical about this, upgrading first to 3.0 and then to 3.1. You can feel free to jump all the way if you want. In this case the main breaking changes are from 2.x to 3.x so I'll upgrade the whole thing all in one step.
I compile and run and get an error "InvalidOperationException: Endpoint Routing does not support 'IApplicationBuilder.UseMvc(...)'. To use 'IApplicationBuilder.UseMvc' set 'MvcOptions.EnableEndpointRouting = false' inside 'ConfigureServices(...)." so I'll keep moving through the migration guide, as things change in major versions.
Per the docs, I can remove using Microsoft.AspNetCore.Mvc; and add using Microsoft.Extensions.Hosting; as IHostingEnvironment becomes IWebHostEnvironment. Since my app is a Razor Pages app I'll add a call to servicesAddRazorPages(); as well as calls to UseRouting, UseAuthorization (if needed) and most importantly, moving to endpoint routing like this in my Configure() call.
app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); });
I also decide that I wanted to see what version I was running on, on the page, so I'd be able to better remember it. I added this call in my _layout.cshtml to output the version of .NET Core I'm using at runtime.
<div class="copyright">© Copyright @DateTime.Now.Year, Powered by @System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription</div>
In order versions of .NET, you couldn't get exactly what you wanted from RuntimeInformation.FrameworkDescription, but it works fine in 3.x so it's perfect for my needs.
Finally, I notice that I was using my 15 year old IIS Rewrite Rules (because they work great) but I was configuring them like this:
using (StreamReader iisUrlRewriteStreamReader = File.OpenText(Path.Combine(env.ContentRootPath, "IISUrlRewrite.xml"))) { var options = new RewriteOptions() .AddIISUrlRewrite(iisUrlRewriteStreamReader); app.UseRewriter(options); }
And that smells weird to me. Turns out there's an overload on AddIISUrlRewrite that might be better. I don't want to be manually opening up a text file and streaming it like that, so I'll use an IFileProvider instead. This is a lot cleaner and I can remove a using System.IO;
var options = new RewriteOptions() .AddIISUrlRewrite(env.ContentRootFileProvider, "IISUrlRewrite.xml"); app.UseRewriter(options);
I also did a little "Remove and Sort Usings" refactoring and tidied up both Program.cs and Startup.cs to the minimum and here's my final complete Startup.cs.
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Rewrite; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace hanselman_core { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddHealthChecks(); services.AddRazorPages().AddRazorPagesOptions(options => { options.Conventions.AddPageRoute("/robotstxt", "/Robots.Txt"); }); services.AddMemoryCache(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHealthChecks("/healthcheck"); var options = new RewriteOptions() .AddIISUrlRewrite(env.ContentRootFileProvider, "IISUrlRewrite.xml"); app.UseRewriter(options); app.UseHttpsRedirection(); app.UseDefaultFiles(); app.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } } }
And that's it. Followed the migration, changed a few methods and interfaces, and ended up removing a half dozen lines of code and in fact ended up with a simpler system. Here's the modified files for my update:
❯ git status On branch main Your branch is up to date with 'origin/main'. Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git restore <file>..." to discard changes in working directory) modified: Pages/Index.cshtml.cs modified: Pages/Shared/_Layout.cshtml modified: Program.cs modified: Startup.cs modified: hanselman-core.csproj
Updating the Web Site in Azure App Service and Azure DevOps
That all works locally, so I'll check in in and double check my Azure App Service Plan and Azure DevOps Pipeline to make sure that the staging - and then production - sites are updated.
ASP.NET Core apps can rely on a runtime that is already installed in the Azure App Service or one can do a "self contained" install. My web site needs .NET Core 3.1 (LTS) so ideally I'd change this dropdown in General Settings to get LTS and get 3.1. However, this only works if the latest stuff is installed on Azure App Service. At some point soon in the future .NET Core 3.1 will be on Azure App Service for Linux but it might be a week or so. At the time of this writing LTS is still 2.2.7 so I'll do a self-contained install which will take up more disk space but will be more reliable for my needs and will allow me full controll over versions.
I am running this on Azure App Service for Linux so it's running in a container. It didn't startup so I checked the logs at startup via the Log Stream and it says that the app isn't listening on Port 8080 - or at least it didn't answer an HTTP GET ping.
I wonder why? Well, I scrolled up higher in the logs and noted this error:
2019-12-10T18:21:25.138713683Z The specified framework 'Microsoft.AspNetCore.App', version '3.0.0' was not found.
Oops! Did I make sure that my csproj was 3.1? Turns out I put in netcoreapp3.0 even though I was thinking 3.1! I updated and redeployed.
It's important to make sure that your SDK - the thing that builds - lines up with the the runtime version. I have an Azure DevOps pipeline that is doing the building so I added a "use .NET Core SDK" task that asked for 3.1.100 explicitly.
Again, I need to make sure that my Pipeline includes that self-contained publish with a -r linux-x64 parameter indicating this is the runtime needed for a self-contained install.
Now my CI/CD pipeline is building for 3.1 and I've set my App Service to run on 3.1 by shipping 3.1 with my publish artifact. When .NET Core 3.1 LTS is released on App Service I can remove this extra argument and rely on the Azure App Service to manage the runtime.
All in all, this took about an hour and a half. Figure a day for your larger apps. Now I'll spend another hour (likely less) to update my podcast site.
Sponsor: Like C#? We do too! That’s why we've developed a fast, smart, cross-platform .NET IDE which gives you even more coding power. Clever code analysis, rich code completion, instant search and navigation, an advanced debugger... With JetBrains Rider, everything you need is at your fingertips. Code C# at the speed of thought on Linux, Mac, or Windows. Try JetBrains Rider today!
© 2019 Scott Hanselman. All rights reserved.
     Updating an ASP.NET Core 2.2 Web Site to .NET Core 3.1 LTS published first on http://7elementswd.tumblr.com/
0 notes
Text
Updating an ASP.NET Core 2.2 Web Site to .NET Core 3.1 LTS
Now that .NET Core 3.1 is out jus this last week and it is a "LTS" or Long Term Support version, I thought it'd be a good time to update my main site and my podcast to .NET 3.1. You can read about what LTS means but quite simply it's that "LTS releases are supported for three years after the initial release."
I'm not sure about you, but for me, when I don't look at some code for a few months - in this case because it's working just fine - it takes some time for the context switch back in. For my podcast site and main site I honestly have forgotten what version of .NET they are running on.
Updating my site to .NET Core 3.1
First, it seems my main homepage is NET Core 2.2. I can tell because the csproj has a "TargetFramework" of netcoreapp2.2. So I'll start at the migration docs here to go from 2.2 to 3.0. .NET Core 2.2 reaches "end of life" (support) this month so it's a good time to update to the 3.1 version that will be supported for 3 years.
Here's my original csproj
<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>netcoreapp2.2</TargetFramework> <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel> <RootNamespace>hanselman_core</RootNamespace> </PropertyGroup> <ItemGroup> <PackageReference Include="Microsoft.AspNetCore.App" /> <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" /> <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.3" /> </ItemGroup> <ItemGroup> <None Update="IISUrlRewrite.xml"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> </ItemGroup> </Project>
and my 3.0 updated csproj. You'll note that most of it is deletions. Also note that I have a custom IISUrlRewrite.xml that I want to make sure gets to a specific place. You'll likely not have anything like this, but be aware.
<Project Sdk="Microsoft.NET.Sdk.Web"> <PropertyGroup> <TargetFramework>netcoreapp3.1</TargetFramework> <RootNamespace>hanselman_core</RootNamespace> </PropertyGroup> <ItemGroup> <None Update="IISUrlRewrite.xml"> <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory> </None> </ItemGroup> </Project>
Some folks are more little methodical about this, upgrading first to 3.0 and then to 3.1. You can feel free to jump all the way if you want. In this case the main breaking changes are from 2.x to 3.x so I'll upgrade the whole thing all in one step.
I compile and run and get an error "InvalidOperationException: Endpoint Routing does not support 'IApplicationBuilder.UseMvc(...)'. To use 'IApplicationBuilder.UseMvc' set 'MvcOptions.EnableEndpointRouting = false' inside 'ConfigureServices(...)." so I'll keep moving through the migration guide, as things change in major versions.
Per the docs, I can remove using Microsoft.AspNetCore.Mvc; and add using Microsoft.Extensions.Hosting; as IHostingEnvironment becomes IWebHostEnvironment. Since my app is a Razor Pages app I'll add a call to servicesAddRazorPages(); as well as calls to UseRouting, UseAuthorization (if needed) and most importantly, moving to endpoint routing like this in my Configure() call.
app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); });
I also decide that I wanted to see what version I was running on, on the page, so I'd be able to better remember it. I added this call in my _layout.cshtml to output the version of .NET Core I'm using at runtime.
<div class="copyright">© Copyright @DateTime.Now.Year, Powered by @System.Runtime.InteropServices.RuntimeInformation.FrameworkDescription</div>
In order versions of .NET, you couldn't get exactly what you wanted from RuntimeInformation.FrameworkDescription, but it works fine in 3.x so it's perfect for my needs.
Finally, I notice that I was using my 15 year old IIS Rewrite Rules (because they work great) but I was configuring them like this:
using (StreamReader iisUrlRewriteStreamReader = File.OpenText(Path.Combine(env.ContentRootPath, "IISUrlRewrite.xml"))) { var options = new RewriteOptions() .AddIISUrlRewrite(iisUrlRewriteStreamReader); app.UseRewriter(options); }
And that smells weird to me. Turns out there's an overload on AddIISUrlRewrite that might be better. I don't want to be manually opening up a text file and streaming it like that, so I'll use an IFileProvider instead. This is a lot cleaner and I can remove a using System.IO;
var options = new RewriteOptions() .AddIISUrlRewrite(env.ContentRootFileProvider, "IISUrlRewrite.xml"); app.UseRewriter(options);
I also did a little "Remove and Sort Usings" refactoring and tidied up both Program.cs and Startup.cs to the minimum and here's my final complete Startup.cs.
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Rewrite; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace hanselman_core { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddHealthChecks(); services.AddRazorPages().AddRazorPagesOptions(options => { options.Conventions.AddPageRoute("/robotstxt", "/Robots.Txt"); }); services.AddMemoryCache(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHealthChecks("/healthcheck"); var options = new RewriteOptions() .AddIISUrlRewrite(env.ContentRootFileProvider, "IISUrlRewrite.xml"); app.UseRewriter(options); app.UseHttpsRedirection(); app.UseDefaultFiles(); app.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } } }
And that's it. Followed the migration, changed a few methods and interfaces, and ended up removing a half dozen lines of code and in fact ended up with a simpler system. Here's the modified files for my update:
❯ git status On branch main Your branch is up to date with 'origin/main'. Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git restore <file>..." to discard changes in working directory) modified: Pages/Index.cshtml.cs modified: Pages/Shared/_Layout.cshtml modified: Program.cs modified: Startup.cs modified: hanselman-core.csproj
Updating the Web Site in Azure App Service and Azure DevOps
That all works locally, so I'll check in in and double check my Azure App Service Plan and Azure DevOps Pipeline to make sure that the staging - and then production - sites are updated.
ASP.NET Core apps can rely on a runtime that is already installed in the Azure App Service or one can do a "self contained" install. My web site needs .NET Core 3.1 (LTS) so ideally I'd change this dropdown in General Settings to get LTS and get 3.1. However, this only works if the latest stuff is installed on Azure App Service. At some point soon in the future .NET Core 3.1 will be on Azure App Service for Linux but it might be a week or so. At the time of this writing LTS is still 2.2.7 so I'll do a self-contained install which will take up more disk space but will be more reliable for my needs and will allow me full controll over versions.
I am running this on Azure App Service for Linux so it's running in a container. It didn't startup so I checked the logs at startup via the Log Stream and it says that the app isn't listening on Port 8080 - or at least it didn't answer an HTTP GET ping.
I wonder why? Well, I scrolled up higher in the logs and noted this error:
2019-12-10T18:21:25.138713683Z The specified framework 'Microsoft.AspNetCore.App', version '3.0.0' was not found.
Oops! Did I make sure that my csproj was 3.1? Turns out I put in netcoreapp3.0 even though I was thinking 3.1! I updated and redeployed.
It's important to make sure that your SDK - the thing that builds - lines up with the the runtime version. I have an Azure DevOps pipeline that is doing the building so I added a "use .NET Core SDK" task that asked for 3.1.100 explicitly.
Again, I need to make sure that my Pipeline includes that self-contained publish with a -r linux-x64 parameter indicating this is the runtime needed for a self-contained install.
Now my CI/CD pipeline is building for 3.1 and I've set my App Service to run on 3.1 by shipping 3.1 with my publish artifact. When .NET Core 3.1 LTS is released on App Service I can remove this extra argument and rely on the Azure App Service to manage the runtime.
All in all, this took about an hour and a half. Figure a day for your larger apps. Now I'll spend another hour (likely less) to update my podcast site.
Sponsor: Like C#? We do too! That’s why we've developed a fast, smart, cross-platform .NET IDE which gives you even more coding power. Clever code analysis, rich code completion, instant search and navigation, an advanced debugger... With JetBrains Rider, everything you need is at your fingertips. Code C# at the speed of thought on Linux, Mac, or Windows. Try JetBrains Rider today!
© 2019 Scott Hanselman. All rights reserved.
     Updating an ASP.NET Core 2.2 Web Site to .NET Core 3.1 LTS published first on https://deskbysnafu.tumblr.com/
0 notes