C# and NET Core 2.0 High Performance Build highly performant, multi-threaded, and concurrent applications using C# and NET Core 2.0 Ovais Mehboob Ahmed Khan BIRMINGHAM - MUMBAI C# and NET Core 2.0 High Performance Copyright © 2018 Packt Publishing All rights reserved No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews Every effort has been made in the preparation of this book to ensure the accuracy of the information presented However, the information contained in this book is sold without warranty, either express or implied Neither the authors, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals However, Packt Publishing cannot guarantee the accuracy of this information Commissioning Editor: Merint Mathew Acquisition Editor: Chaitanya Nair Content Development Editor: Anugraha Arunagiri Technical Editor: Jijo Maliyekal Copy Editor: Safis Editing Project Coordinator: Ulhas Kambali Proofreader: Safis Editing Indexer: Tejal Daruwale Soni Graphics: Tania Dutta Production Coordinator: Deepika Naik First published: April 2018 Production reference: 1240418 Published by Packt Publishing Ltd Livery Place 35 Livery Street Birmingham B3 2PB, UK ISBN 978-1-78847-004-9 www.packtpub.com mapt.io Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career For more information, please visit our website Why subscribe? Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals Improve your learning with Skill Plans built especially for you Get a free eBook or video every month Mapt is fully searchable Copy and paste, print, and bookmark content PacktPub.com Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy Get in touch with us at service@packtpub.com for more details At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks Contributors About the author Ovais Mehboob Ahmed Khan is a seasoned programmer and solution architect with over 14 years of software development experience He has worked in organizations across Pakistan, the USA, and the Middle East Currently, he is working for a government entity based in Dubai A Microsoft MVP, he specializes mainly in Microsoft NET, the cloud and web development He has published technical articles on MSDN, TechNet, personal blog, and he has authored two other books published by Packt: JavaScript for NET Developers and Enterprise Application Architecture with NET Core I would like to thank my family for supporting me, especially my mother, wife, and brother, who have always encouraged me in every goal of my life My father, may he rest in peace, would have been proud of my achievements Setting up the Windows subsystem for Linux In this section, we will set up InfluxDB on the Windows subsystem for the Linux operating system First of all, we need to enable the Windows subsystem for Linux by executing the following command from the PowerShell as an Administrator: Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux After running the preceding command, restart your computer Next, we will install Linux distro from the Microsoft store In our case, we will install Ubuntu from the Microsoft Store Go to the Microsoft Store, search for Ubuntu, and install it Once the installation is done, click on Launch: This will open up the console window, which will ask you to create a user account for Linux OS (Operating System) Specify the username and password that will be used Run the following command to update Ubuntu to the latest stable version from the bash shell To run bash, open the command prompt, write bash, and hit Enter: Finally, it will ask you to create an Ubuntu username and password Specify the username and password and hit enter Installing InfluxDB Here, we will go through some steps to install the InfluxDB database in Ubuntu: To set up InfluxDB, open a command prompt in Administrator mode and run the bash shell Execute the following commands to the InfluxDB data store on your local PC: $ $ $ $ curl -sL https://repos.influxdata.com/influxdb.key | sudo apt-key add source /etc/lsb-release echo "deb https://repos.influxdata.com/${DISTRIB_ID,,} {DISTRIB_CODENAME} stable" | sudo tee /etc/apt/sources.list.d/influxdb.list Install InfluxDB by executing the following command: $ sudo apt-get update && sudo apt-get install influxdb Execute the following command to run InfluxDB: $ sudo influxd Start the InfluxDB shell by running the following command: $ sudo influx It will open up the shell where database-specific commands can be executed Create a database by executing the following command Specify a meaningful name for the database In our case, it is appmetricsdb: > create database appmetricsdb Installing Grafana Grafana is an open source tool used to display dashboards in a web interface There are various dashboards available that can be imported from the Grafana website to display real-time analytics Grafana can simply be downloaded as a zip file from http://docs.grafana.org/installation/windows/ Once it is downloaded, we can start the Grafana server by clicking on the grafana-server.exe executable from the bin directory Grafana provides a website that listens on port 3000 If the Grafana server is running, we can access the site by navigating to http://localhost:3000 Adding the InfluxDB dashboard There is an out-of-the-box InfluxDB dashboard available in Grafana which can be imported from the following link: https://grafana.com/dashboards/2125 Copy the dashboard ID and use this to import it into the Grafana website We can import the InfluxDB dashboard by going to the Manage option on the Grafana website, as follows: From the Manage option, click on the + Dashboard button and hit the New Dashboard option Clicking on Import Dashboard will lead to Grafana asking you for the dashboard ID: Paste the dashboard ID (for example, 2125) copied earlier into the box and hit Tab The system will show the dashboard's details, and clicking on the Import button will import it into the system: Configuring InfluxDB We will now configure the InfluxDB dashboard and add a data source that connects to the database that we just created To proceed, we will go to the Data Sources section on the Grafana website and click on the Add New Datasource option Here is the configuration that adds the data source for the InfluxDB database: Modifying the Configure and ConfigureServices methods in Startup Up to now, we have set up Ubuntu and the InfluxDB database on our machine We also set up the InfluxDB data source and added a dashboard through the Grafana website Next, we will configure our ASP.NET Core web application to push real-time information to the InfluxDB database Here is the modified ConfigureServices method that initializes the MetricsBuilder to define the attribute related to the application name, environment, and connection details: public void ConfigureServices(IServiceCollection services) { var metrics = new MetricsBuilder() Configuration.Configure( options => { options.WithGlobalTags((globalTags, info) => { globalTags.Add("app", info.EntryAssemblyName); globalTags.Add("env", "stage"); }); }) Report.ToInfluxDb( options => { options.InfluxDb.BaseUri = new Uri("http://127.0.0.1:8086"); options.InfluxDb.Database = "appmetricsdb"; options.HttpPolicy.Timeout = TimeSpan.FromSeconds(10); }) Build(); services.AddMetrics(metrics); services.AddMetricsReportScheduler(); services.AddMetricsTrackingMiddleware(); services.AddMvc(options => options.AddMetricsResourceFilter()); } In the preceding code, we have set the application name app as the assembly name, and the environment env as the stage http://127.0.0.1:8086 is the URL of the InfluxDB server that listens for the telemetry being pushed by the application appmetricsdb is the database that we created in the preceding section Then, we added the AddMetrics middleware and specified the metrics containing the configuration AddMetricsTrackingMiddleware is used to track the web telemetry information which is displayed on the dashboard, and AddMetricsReportScheduled is used to push the telemetry information to the database Here is the Configure method that contains UseMetricsAllMiddleware to use App Metrics UseMetricsAllMiddleware adds all the middleware available in App Metrics: public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); } app.UseStaticFiles(); app.UseMetricsAllMiddleware(); app.UseMvc(); } Rather than calling UseAllMetricsMiddleware, we can also add individual middleware explicitly based on the requirements Here is the list of middleware that can be added: app.UseMetricsApdexTrackingMiddleware(); app.UseMetricsRequestTrackingMiddleware(); app.UseMetricsErrorTrackingMiddleware(); app.UseMetricsActiveRequestMiddleware(); app.UseMetricsPostAndPutSizeTrackingMiddleware(); app.UseMetricsOAuth2TrackingMiddleware(); Testing the ASP.NET Core App and reporting on the Grafana dashboard To test the ASP.NET Core application and to see visual reporting on the Grafana dashboard, we will go through following steps: Start the Grafana server by going to {installation_directory}\bin\grafana-server.exe Start bash from the command prompt and run the sudo influx command Start another bash from the command prompt and run the sudo influx command Run the ASP.NET Core application Access http://localhost:3000 and click on the App Metrics dashboard This will start gathering telemetry information and will display the performance metrics, as shown in the following screenshots: The following graph shows the total throughput in Request Per Minute (RPM), error percentage, and active requests: Here is the Apdex score colorizing the user satisfaction into three different colors, where red is frustrating, orange is tolerating, and green is satisfactory The following graph shows the blue line being drawn on the green bar, which means that the application performance is satisfactory: The following snapshot shows the throughput graph for all the requests being made, and each request has been colorized with the different colors: red, orange, and green In this case, there are two HTTP GET requests for the about and contact us pages: Here is the response time graph showing the response time of both requests: Summary In this chapter, we have learned some key metrics which are essential for monitoring application performance We explored and set up App Metrics, which is a free tool that runs cross-platform and provides a lot of extensions that can be added to achieve more reporting We went through the stepby-step guide on how to configure and set up App Metrics and related components like InfluxDb and Grafana to store and view telemetry in the Grafana web-based tool and integrate it with ASP.NET Core application Other Books You May Enjoy If you enjoyed this book, you may be interested in these other books by Packt: Dependency Injection in NET Core 2.0 Marino Posadas, Tadit Dash ISBN: 978-1-78712-130-0 Understand the concept of DI and its implications in modern software construction Learn how DI is already implemented in today's frameworks Analyze how DI can be used with current software to improve maintainability and scalability Learn the use of DI in NET Core Get used to the possibilities that DI offers the ASP.NET Core developer in different scenarios Learn about good practices and refactoring legacy code Mastering ASP.NET Core 2.0 Ricardo Peres ISBN: 978-1-78728-368-8 Get to know the new features of ASP.NET Core 2.0 Find out how to configure ASP.NET Core Configure routes to access ASP.NET Core resources Create controllers and action methods and see how to maintain the state Create views to display contents Implement and validate forms and retrieve information from them Write reusable modules for ASP.NET Core Deploy ASP.NET Core to other environments Leave a review - let other readers know what you think Please share your thoughts on this book with others by leaving a review on the site that you bought it from If you purchased the book from Amazon, please leave us an honest review on this book's Amazon page This is vital so that other potential readers can see and use your unbiased opinion to make purchasing decisions, we can understand what our customers think about our products, and our authors can see your feedback on the title that they have worked with Packt to create It will only take a few minutes of your time, but is valuable to other potential customers, our authors, and Packt Thank you! .. .C# and NET Core 2. 0 High Performance Build highly performant, multi- threaded, and concurrent applications using C# and NET Core 2. 0 Ovais Mehboob Ahmed Khan BIRMINGHAM - MUMBAI C# and NET Core. .. Performance, discusses the core concepts of NET Core, including the compilation process, garbage collection, building highlyperformant NET Core applications utilizing multiple cores of the CPU, and publishing... improvements in NET Standard 2. 0 More APIs in NET Standard 2. 0 Compatibility mode Creating a NET Standard library What comes with ASP .NET Core 2. 0 ASP .NET Core Razor Pages Automatic Page and View compilation