European ASP.NET 4.5 Hosting BLOG

BLOG about ASP.NET 4, ASP.NET 4.5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET Core 2.2.1 Hosting - HostForLIFE.eu :: The Common Language Runtime Of Microsoft’s .Net Framework

clock December 5, 2018 10:02 by author Peter

The CLR is a runtime environment of .NET to execute applications. The major function of the CLR is converting the Managed Code to native code and executing the program. Furthermore, it acts as a layer between operating systems and apps that are written in .NET languages. The common language runtime handles execution of code as well as provides useful services for implementing the program. Aside from code execution, the CLR also provides services like memory management, security management, thread management, compilation, code verification, and other system services.

CLR is due for a makeover
The common language runtime of Microsoft is due for a makeover with Microsoft announcing plans to make it more scalable and efficient. The key to the modernization would be enhancements on the intermediate language underlying the CRL, called IL, that has not been upgraded in a decade. Microsoft wants to boost the IL as well as make the CLR a richer target for programming languages. The aim of the common language runtime is to run .NET programs in an efficient manner.

One imminent enhancement includes Span<T>, pronounced ‘span of tee’. It’s a new kind that would offer framework and language features to achieve more performing, safer, low-level code. The T in Span<T> means type parameter. It would be used by C# as well as other languages to build more efficient code, which does not require copying big amounts of data or pause for garbage collection. New CRL versions would have ‘inside knowledge’ regarding Span<T> to boost speed. It will be rolled out in the next few releases of .NET.

Serving as the counterpart of Microsoft to the JVM of the world of Java, the common language runtime provides management of code of .NET languages, which include Visual Basic, C# and F#. The source code is compiled by the language compilers to the IL code. The CLR tunes the program through the execution of the IL and translating output into a machine code while the program runs. Other services are provided by the common language runtime include automatic management of memory and type safety, saving .NET programmers from providing the services.

THE ROLE OF THE COMMON LANGUAGE RUNTIME IN THE DOT NET FRAMEWORK
  1. Base Class libraries
    Provides class libraries support to an app when required.
  2. Thread support
    Threads are managed under the CLR. Threading means the parallel execution of code. Basically, threads are lightweight processes that are responsible for multi-tasking in a single app.
  3. MSIL code to native code
    The CLR is an engine that compiles the source code to an intermediate language. The intermediate language’s called the Microsoft Intermediate Language. During program execution, the MSIL’s converted to the native code of the machine code. The conversion is possible via the Just-In-Time compiler. At compilation, the end result is the PE or the Portable Executable file.
  4. Code Manager
    The common language runtime manages code. When compiling a .NET app, one does not generate code that could actually execute on the machine. The MSIL or the Microsoft Intermediate Language or IL could actually be generated. All code of .NET is IL code. The IL code is also called the Managed Code since the CLR of.NET manages it.
  5. COM Marshaler
    It enables communication between the app and COM objects.
  6. CLS or Common Language Specification
    It is used to communicate objects that are written in various .NET languages. It defines the standards and rules to which languages should adhere to in order to be compatible with the other languages of .NET. This lets C# developers to inherit from classes, which are defined in VB.NET or other compatible languages of .NET.
  7. Debug Engine
    The CLR enables performing debugging an app during runtime.
  8. Type Checker
    It verifies the types used in the app with CLS or CTS standards that are supported by the common language runtime and provides type safety.
  9. CTS or the Common Type System
    It specifies types of data that are created in a couple of different languages compiled into the base common data type system.
  10. Security Engine
    This enforces security permission at code level security, machine level security and folder level security with the use of .NET framework setting and tools provided by .NET.
  11. Exception Manager
    It handles exceptions thrown by an app while executing Try-catch block that is provided by an exception. In ‘Try’ block used where a code part expects an error. In ‘Catch’ block throws exception caught from the ‘try’ block. If there’s no catch block, it would terminate an app.
  12. Garbage Collector
    The Garbage Collectors handles automatic memory management. Furthermore, it releases memory of unused objects in an app that provides automatic memory management.
Hire ASP.NET developers from India for maximum results and solutions. With the improvements set to boost the .NET’s CLR, applications, and solutions are more effective and streamlined.

HostForLIFE.eu ASP.NET Core 2.2.1 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET Core 2.2.1 Hosting - HostForLIFE.eu :: Assembly Attributes

clock November 27, 2018 10:01 by author Peter

I have listed down some of the assembly attributes.

    [assembly: AssemblyKeyFile(@"key.snk")] 
    [assembly: InternalsVisibleTo("System.Numerics, PublicKey=00000000000000000400000000000000", AllInternalsVisible=false)] 
    [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] 
    [assembly: AssemblyDelaySign(true)] 
    [assembly: InternalsVisibleTo("System, PublicKey=00000000000000000400000000000000", AllInternalsVisible=false)] 
    [assembly: InternalsVisibleTo("System.Core, PublicKey=00000000000000000400000000000000", AllInternalsVisible=false)] 
    [assembly: AllowPartiallyTrustedCallers] 
    [assembly: NeutralResourcesLanguage("en-US")] 
    [assembly: RuntimeCompatibility(WrapNonExceptionThrows=true)] 
    [assembly: Guid("BED7F4EA-1A96-11d2-8F08-00A0C9A6186D")] 
    [assembly: ComCompatibleVersion(1, 0, 0xce4, 0)] 
    [assembly: TypeLibVersion(2, 4)] 
    [assembly: DefaultDependency(LoadHint.Always)] 
    [assembly: StringFreezing] 
    [assembly: ComVisible(false)] 
    [assembly: CLSCompliant(true)] 
    [assembly: CompilationRelaxations(8)] 
    [assembly: SecurityRules(SecurityRuleSet.Level2, SkipVerificationInFullTrust=true)] 
    [assembly: AssemblyTitle("sample.dll")] 
    [assembly: AssemblyDescription("sample.dll")] 
    [assembly: AssemblyDefaultAlias("sample.dll")] 
    [assembly: AssemblyCompany("Microsoft Corporation")] 
    [assembly: AssemblyProduct("Microsoft\x00ae .NET Framework")] 
    [assembly: AssemblyCopyright("\x00a9 Microsoft Corporation.  All rights reserved.")] 
    [assembly: AssemblyFileVersion("4.0.30319.225")] 
    [assembly: AssemblyInformationalVersion("4.0.30319.225")] 
    [assembly: SatelliteContractVersion("4.0.0.0")] 
    [assembly: AssemblyTargetedPatchBand("1.0.21-102")] 
    [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification=true)] 

HostForLIFE.eu ASP.NET Core 2.2.1 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.



ASP.NET Core 2.2.1 Hosting - HostForLIFE.eu :: Firebase Cloud Messaging From .Net

clock November 22, 2018 10:05 by author Peter

In developing mobile web backends you might need users to broadcast messages such as push notifications to single or all  mobile subscribers from the cloud using services like Firebase Cloud Messaging (FCM).
 
In this article we will focus on sending push notifications from a .Net application using Firebase.Notification library. This library makes it very easy to send push notifications from Firebase using C#
 
To begin, download the library from Nuget:
    Install-Package Firebase.Notification -Version 1.0.0 

Using the library:
    using (var firebase = new Firebase()) 
    { 
        firebase.ServerKey = "{Your Server Key}"; 
        var id = "{Your Device Id}"; 
        firebase.PushNotifyAsync(id,"Hello","World").Wait(); 
        Console.ReadLine(); 
    }        


Error Handling and Debugging
Trace errors in your output window, all errors from this library will be captured under the category Firebase.Notification for easy debugging,

HostForLIFE.eu ASP.NET Core 2.2.1 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 



ASP.NET Core 2.2.1 Hosting - HostForLIFE.eu :: How .NET Is A Multilingual Framework?

clock November 13, 2018 08:18 by author Peter

An application is said to be multilingual if it can be deployed in many different languages. With .NET, all of the languages including Visual Basic, .NET, C#, and J# compile to a common Intermediate language (IL). This makes all languages interoperable. Microsoft has created Java bytecode, which is a low-level language with a simple syntax, which can be very quickly translated into native machine code.

CLR
.NET Framework is a multilingual application because of CLR.CLR is the key of .NET Framework. The code running under the control of the CLR is often termed as managed code.The main task of CLR is to convert compiled code into the native code. .NET Framework has one or more compilers; for e.g., VB .NET, C#, C++, JScript or any third party compiler such as COBOL.

Anyone of these compilers will convert your source code into Microsoft Intermediate Language (MSIL). The main reason for .NET to be multilingual is that you can compile your code from IL and this compiled code will be interoperable with the code that has been compiled to IL from another language.

It simply means that you can create pages in different languages (like C#, VB .NET, J# etc.) and once all of these pages are compiled they all can be used in a single application. Let us understand this point clearly with an example.

Let us consider a situation where a customer needs an application to be ready in 20 days. For completing the application in 20 days we want 30 developers who all know the specific language but we have 15 developers who know C# and 15 developers who know VB .NET. In this situation, if we don’t use .NET then we need to hire 15 more developers of C# or VB .NET which is a difficult and costly solution. Now, if we use .NET then we can use C# and VB .NET language in the same application. This is possible because once C# code is compiled from IL it becomes interoperable with VB .NET code which is compiled from IL.


Then JIT (Just In Time) of CLR converts this MSIL code into native code using metadata which is then executed by OS.

CLR stands for common language runtime. Common language runtime provides other services like memory management, thread management, remoting, and other security such as CTS and CLS. CLR is a layer between an operating system and .NET language, which uses CTS and CLS to create code.

CTS
CTS stands for the common type system. CTS defines rules that common language runtime follows when we are declaring, using and managing type. CTS deals with the data type. .NET supports many languages and every language has its own data type. One language cannot understand data types of another language. For example: When we are creating an application in C#, we have int and when we are creating an application in VB .NET, we have an integer. Here CTS comes into play --  after the compilation, CTS converts int and integer into the int32 structure.

CLS
CLS stands for common language specification. CLS is a subset of CTS and it declares all the rules and restrictions that all languages under .NET Framework must follow. The language which follows these rules is known as CLS compliant. For example, we can use multiple inheritances in c++ but when we use the same code in C# it creates a problem because C# does not support multiple inheritances. Therefore, CLS restricts multiple inheritances for all language. One other rule is that you cannot have a member with the same name and a different case.

In C# add() and Add() are different because it is case sensitive but a problem arises when we use this code in VB .NET because it is not case-sensitive and it considers add() and Add() as the same.

HostForLIFE.eu ASP.NET Core 2.2.1 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 



European ASP.NET Core Hosting :: How to Use Dapper Asynchronously in ASP.NET Core 2.1

clock November 12, 2018 08:13 by author Scott

In this post, we're going to create a very simple ASP.NET Core 2.1 application which uses Dapper to access data. There's already a sample project worked up over on GitHub, and you might want to use that to follow along here.

Step 1: Get the NuGet Package

First things first, we need to grab the NuGet package for Dapper. In Visual Studio, you can do this by right-clicking on your project file and selecting Manage NuGet Packages and then search for the Dapper package, like so:

With that installed, let's try creating a repository.

Step 2: Creating an Employee Class and Repository

For this demo, I am not going to go over how to create a database or show a demo database with sample data; I don't have one available and it's a pain to make one. So let's assume we have a table Employee with columns for FirstName, LastName, ID, and DateOfBirth. We can make a corresponding C# class for this table, like so:

public class Employee
{
   
public int ID { get; set; }
   
public string FirstName { get; set; }
   
public string LastName { get; set; }
   
public DateTime DateOfBirth { get; set; }
}

Now we need a sample repository. Let's call it EmployeeRepository and give it an interface so we can use ASP.NET Core's Dependency Injection setup.

Here's the interface:

public interface IEmployeeRepository
{
   
Task<Employee> GetByID(int id);
   
Task<List<Employee>> GetByDateOfBirth(DateTime dateOfBirth);
}

Now we can work up a skeleton implementation of this repository. Here's what we're starting with:

public class EmployeeRepository : IEmployeeRepository
{
   
public async Task<Employee> GetByID(int id)
   
{

   
}

   
public async Task<List<Employee>> GetByDateOfBirth(DateTime dateOfBirth)
    {

We also need to update our project's Startup file to include our new repository in the services layer:

public class Startup
{
   
public Startup(IConfiguration configuration)
   
{
       
Configuration = configuration;
   
}

   
public IConfiguration Configuration { get; }

   
public void ConfigureServices(IServiceCollection services)
   
{
       
services.AddTransient<IEmployeeRepository, EmployeeRepository>();

       
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
   
}

   
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
   
{
       
//...
   
}
}

Next, we need to enable this repository to use Dapper. Before we can do that, however, we need it to be aware of what connection string we are using.

Step 3: Injecting IConfiguration

Very often in ASP.NET Core projects, Connection Strings are defined in the appSettings.json file:

{
 
"Logging": {
   
"LogLevel": {
     
"Default": "Debug",
     
"System": "Information",
     
"Microsoft": "Information"
   
}
 
},
 
"ConnectionStrings": {
   
"MyConnectionString": "MyConnectionString"
 
}
}

The problem is: how do we pass that connection string to the repository so it can create a SqlConnection object for Dapper to use.

ASP.NET Core introduces a new IConfiguration object which can be injected into other classes. That injected instance will contain a method called GetConnectionString which we can use to obtain our connection string from the appSettings.json files. So, let's inject IConfiguration like so:

public class EmployeeRepository : IEmployeeRepository
{
   
private readonly IConfiguration _config;

   
public EmployeeRepository(IConfiguration config)
   
{
       
_config = config;
    }
   

   
//Remainder of file is unchanged
}

Step 4: Creating a SqlConnection

With the injected IConfiguration now available to our repository, we can create a Dapper-enabled SqlConnection object that all of our repository's methods can utilize.

public class EmployeeRepository : IEmployeeRepository
{
   
private readonly IConfiguration _config;

   
public EmployeeRepository(IConfiguration config)
   
{
       
_config = config;
   
}

   
public IDbConnection Connection
   
{
       
get
       
{
           
return new SqlConnection(_config.GetConnectionString("MyConnectionString"));
       
}
    }
   

   
//Remainder of file is unchanged
}

Step 5: Employee by ID

Let's first create a method to return employees by their ID.

To start, let's remember that the way Dapper works is by processing raw SQL and then mapping it to an object. Because our table columns and object properties share the same names, we don't need to do any special mapping here.

Here's the implementation of our GetByID method:

public class EmployeeRepository : IEmployeeRepository
{
   
//...

   
public async Task<Employee> GetByID(int id)
   
{
       
using (IDbConnection conn = Connection)
        {

            string sQuery = "SELECT ID, FirstName, LastName, DateOfBirth FROM Employee WHERE ID = @ID";
           
conn.Open();
           
var result = await conn.QueryAsync<Employee>(sQuery, new { ID = id });
           
return result.FirstOrDefault();
       
}
   
}
}

Step 6: Employees by Date of Birth

We also need to get all employees born on a particular date. Since we are now returning a collection of employees rather than a single one, the implementation changes very slightly.

public class EmployeeRepository : IEmployeeRepository
{
    //...
   

     
public async Task<List<Employee>> GetByDateOfBirth(DateTime dateOfBirth)
   
{
       
using (IDbConnection conn = Connection)
       
{
           
string sQuery = "SELECT ID, FirstName, LastName, DateOfBirth FROM Employee WHERE DateOfBirth = @DateOfBirth";
           
conn.Open();
           
var result = await conn.QueryAsync<Employee>(sQuery, new { DateOfBirth = dateOfBirth });
           
return result.ToList();
       
}
   
}
}

Step 7: Implement the Controller

The final step is creating a controller to which our EmployeeRepository can be injected. Here it is:

[Route("api/[controller]")]
[ApiController]
public class EmployeeController : ControllerBase
{
   
private readonly IEmployeeRepository _employeeRepo;

   
public EmployeeController(IEmployeeRepository employeeRepo)
   
{
       
_employeeRepo = employeeRepo;
   
}

   
[HttpGet]
   
[Route("{id}")]
   
public async Task<ActionResult<Employee>> GetByID(int id)
   
{
       
return await _employeeRepo.GetByID(id);
   
}

   
[HttpGet]
   
[Route("dob/{dateOfBirth}")]
   
public async Task<ActionResult<List<Employee>>> GetByID(DateTime dateOfBirth)
   
{
       
return await _employeeRepo.GetByDateOfBirth(dateOfBirth);
   
}
}

Summary

That's it! We've implemented Dapper into our ASP.NET Core 2.1 application!



European ASP.NET Core Hosting :: How to Measure and Report the Response Time of ASP.NET Core

clock November 8, 2018 09:57 by author Scott

Performance is a buzzword for APIs. One of the most important and measurable parameters of the API performance is the response time. In this article, we will understand how to add code to measure the response time of an API and then return the response time data to the end client.

What is the need for this?

So, let's take a moment to think why we would ever need such a feature to measure the Response time of an API. Following are some of the points that have been the inspiration for writing code to Capture response time.

  • You need to define the SLA (Service Level Agreements) for your API with your clients. The clients need to understand how much time  the API takes to respond back. The response time data over time can help us decide on an SLA for our API.
  • Management is interested in reports as to how fast or slow the application is. You need to have data to corroborate your claims. It is worth it to have reports on the performance of the application and to share it with Stakeholders.
  • The client needs to have the information of the Response time of the API so that they can track how much time is spent on the client and the Server.

You might also have encountered similar requests in your project and it is worthwhile looking at an approach to capture the response time for the API.

Where to add the code?

Let's explore a couple of approaches to capture the response time of our API focusing mostly on capturing the time spent in our API. Our objective is to calculate the time elapsed in milliseconds from the time the request is received by the Asp.net core runtime to the time the response is processed and sent back from the Server.

What factors are we ignoring?

It's important to understand that this discussion doesn't include the time spent in N/W, Time spent in IIS and Application Pool Startup. If the Application Pool wasn't up and running, then the first request can affect the overall response time of the API. There is an Application Initialization Module which we can make use of but that is out of scope for this article.

First Attempt

One very naive approach to capturing the response time of an API would be to add code to every API method at the start and end and then measure the delta to calculate the response time as shown 

// GET api/values/5   
[HttpGet]  
public IActionResult Get() {  
    // Start the watch   
    var watch = new Stopwatch();  
    watch.Start();  
    // Your actual Business logic   
    // End the watch  
    watch.Stop();  
    var responseTimeForCompleteRequest = watch.ElapsedMilliseconds;  
} 

This code should be able to calculate the time spent in an operation. But this doesn't seem to be the right approach for the following reasons.

If an API has a lot of operations, then we need to add this code to multiple places which are not good for maintainability.

This code measures the time spent in the method only, it doesn't measure the time spent on other activities like middleware, filters, Controller selection, action method selection, Model binding etc.

Second Attempt

Let's try to improve the above code by centralizing the code in one place so that it is easier to maintain. We need to execute the response time calculation code before and after a method is getting executed. If you have worked with earlier versions of Asp.net Web API, you would be familiar with concepts of Filter. Filters allow you to run code before or after specific stages in the request processing pipeline.

We will implement a filter for calculating the Response time as shown below. We will create a Filter and use the OnActionExecuting to start the timer and then stop the timer in method OnActionExecuted, thus calculating the response time of the API.

public class ResponseTimeActionFilter: IActionFilter { 
    private const string ResponseTimeKey = "ResponseTimeKey"; 
    public void OnActionExecuting(ActionExecutingContext context) { 
        // Start the timer  
        context.HttpContext.Items[ResponseTimeKey] = Stopwatch.StartNew(); 
    } 
    public void OnActionExecuted(ActionExecutedContext context) { 
        Stopwatch stopwatch = (Stopwatch) context.HttpContext.Items[ResponseTimeKey]; 
        // Calculate the time elapsed  
        var timeElapsed = stopwatch.Elapsed; 
    } 
}  

This code is not a reliable technique for calculating the response time as it doesn't address the issue of calculating the time spent in execution of middleware, controller selection, action method selection, model binding etc. The filter pipeline runs after the MVC selects the action to execute. So, it effectively doesn't instrument the time spent in the Other Asp.net pipeline. 

Third Attempt

We will use the Asp.net Core Middleware to Calculate the Response time of the API.

So, what is Middleware?

Basically, Middleware are software components which handle the Request/Response. Middleware is assembled into an application pipeline and serves in the incoming request. Each component does the following operations.

  • 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 is invoked.

If you have worked with HTTPModules or HTTPHandlers in ASP.NET, then you can think of Middleware as a replacement in ASP.NET Core. Some of the examples of middleware are -

  • MVC Middleware
  • Authentication
  • Static File Serving
  • Caching
  • CORS

 

 

We want to add code to start the timer once the request enters the ASP.NET Core pipeline and stop the timer once the response is processed by the Pipeline. Custom Middleware at the start of the request pipeline seems to be the best approach for getting the access to the request as early as possible and access until the last step is executed in the pipeline.

We will build a Response Time Middleware which we will add as the first Middleware to the request Pipeline so that we can start the timer as soon the request enters the Asp.net core pipeline.

What to do with the Response time data?

Once we capture the response time data we can process data in the following ways.

  1. Add the Response time data to a Reporting database or an analytics solution.
  2. Write the Response time data to a log file.
  3. Pass the response time data to a message queue which can further be processed by another application for reporting and analytics.
  4. Send the Response time information to the client applications consuming our Rest API using the Response headers.
  5. There may be other useful ways of using the response time data. Please leave a comment and tell me how you process the response time data in your application.

Let's write the code

We will write the code considering the following points.

  • Calculating the response time data for the API
  • Reporting the data back to client applications by passing the data in the Response headers.

Full code snippet for the ResponseTimeMiddleware is shown below.

public class ResponseTimeMiddleware { 
    // Name of the Response Header, Custom Headers starts with "X-"
 
    private const string RESPONSE_HEADER_RESPONSE_TIME = "X-Response-Time-ms";
 
    // Handle to the next Middleware in the pipeline
 
    private readonly RequestDelegate _next;
 
    public ResponseTimeMiddleware(RequestDelegate next) {
 
        _next = next;
 
    }
 
    public Task InvokeAsync(HttpContext context) {
 
        // Start the Timer using Stopwatch
 
        var watch = new Stopwatch();
 
        watch.Start();
 
        context.Response.OnStarting(() => {
 
            // Stop the timer information and calculate the time
  
            watch.Stop();
 
            var responseTimeForCompleteRequest = watch.ElapsedMilliseconds;
 
            // Add the Response time information in the Response headers.
  
            context.Response.Headers[RESPONSE_HEADER_RESPONSE_TIME] = responseTimeForCompleteRequest.ToString();
 
            return Task.CompletedTask;
 
        });
 
        // Call the next delegate/middleware in the pipeline
  
        return this._next(context);
 
    }
 
}

Explanation of the code

The interesting part happens in the InvokeAsync method, We use Stopwatch class to start the stopwatch once the requests enter into the first middleware of the request and then stop the stopwatch once the request has been processed and the response is ready to be sent back to the client. OnStarting method provides an opportunity to write a custom code to add a delegate to be invoked just before response headers will be sent to the client.

Lastly, we add the Response time information in a Custom Header. We use the X-Response-Time-msheader as a Response Header. As a convention, the Custom Header starts with an X.

Conclusion

In this article, we understood how to leverage ASP.NET middleware to manage cross-cutting concerns like measuring the response time of the APIs. There are various other useful use cases of using middleware which can help to reuse code and improve the maintainability of the application.

/p>



ASP.NET Core 2.2.1 Hosting - HostForLIFE.eu :: QRCode with Footer Text

clock November 6, 2018 11:09 by author Peter

Recently, I was working with a library which helps to generate barcode within images, the open source library is called ZXing (http://zxingnet.codeplex.com/). Its a free library with lots of great features and even supports QRCode generation. The only missing feature I came across was of writing a Barcode Text below the generated image. I reached out ZXing support team, here they replied to my thread.
http://zxingnet.codeplex.com/discussions/452290

Implementing such functionality in an html page was not that a big task.

Anyway here I came up with a solution. Hope this helps you..
<div style="border: 1px double black;width:50%;text-align:center;" id="PrintBarcode"> 
<div><asp:Image ID="imgBarcode" runat="server" /></div> 
<div style="margin-top:-10px;"><asp:Label ID="lblTexttoDisplay" runat="server"></asp:Label></div> 
</div><br /> 
<a ID="PrintMe" runat="server" Text="Print" onclick=""></a> 
<script type="text/javascript"> 
function PrintMe() 
{    
var popupWin = window.open('', '_blank', 'width=0,height=0,directories=0,fullscreen=0,location=0,menubar=0, 
 
                     resizable=0,scrollbars=0,status=0,titlebar=0,toolbar=0'); 
popupWin.document.open(); 
var divToPrint = document.getElementById('PrintBarcode'); 
popupWin.document.write('<html><body onload="window.print();this.close();"> 
 
          <div style="border: 0px double black;width:50%;text-align:center;">' + divToPrint.innerHTML + '</div></html>'); 

</script> 

HostForLIFE.eu ASP.NET Core 2.2.1 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 



ASP.NET Core 2.2.1 Hosting - HostForLIFE.eu :: ASP.NET Core Sample Website - Calculator

clock November 1, 2018 08:36 by author Peter

In this article, I will be explaining how to create a simple Web Calculator using .NET Core.

What is ASP.NET Core and why do we use it?

  • Easy to develop Web Pages as well as Web APIs.
  • Integration of modern frameworks and development workflows.
  • Easy to integrate with Azure.
  • Natural dependency injection support.
  • Large hosting variety, like on IIS, Apache, Docker, or self-host in your own process.
  • A wide range of tools that simplifies web development.
  • Multi-platform, so you may build and run on Windows, macOS, and Linux.
  • Open-source and with a powerful community.

We are using a single controller with two Action Results - one for the first HttpGet and another to calculate the operation on the server side. Here is the code.
public class HomeController : Controller 

    [HttpGet] 
    public IActionResult Index() 
    { 
        return View(); 
    } 
 
    [HttpPost] 
    public IActionResult Index( Operation model ) 
    { 
        if ( model.OperationType == OperationType.Addition ) 
            model.Result = model.NumberA + model.NumberB; 
        return View( model ); 
    } 


This is the View,
@model Operation 
<form asp-controller="Home" asp-action="Index" method="post" > 
    <div class="form-group"> 
        <div class="row"> 
            <label asp-for="NumberA" class="col-lg-2"></label> 
            <input type="number" asp-for="NumberA" class="col-lg-2" /> 
        </div> 
        <div class="row"> 
            <label asp-for="NumberB" class="col-lg-2"></label> 
            <input type="number" asp-for="NumberB" class="col-lg-2" /> 
        </div> 
        <div class="row"> 
            <label asp-for="OperationType" class="col-lg-2"></label> 
            <select asp-for="OperationType" class="col-lg-2" asp-items="Html.GetEnumSelectList<OperationType>()"> 
                <option selected="selected" value="">Select</option> 
            </select> 
        </div> 
        <div class="row"> 
            <label asp-for="Result" class="col-lg-2"></label> 
            <input type="number" disabled="disabled" class="col-lg-2" asp-for="Result" /> 
        </div> 
        <div class="row"> 
            <input type="submit" value="Submit" asp-action="Index" /> 
        </div> 
    </div> 
</form> 


View Result in the browser.


This is the model used in here.

public class Operation 

    [Display( Name = "First Number" )] 
    public double NumberA { get; set; } 
 
    [Display( Name = "Second Number" )] 
    public double NumberB { get; set; } 
 
    [Display( Name = "Result" )] 
    public double Result { get; set; } 
 
    [Display( Name = "Operation" )] 
    public OperationType OperationType { get; set; } 


public enum OperationType 

    Addition, 
    Multiplication, 
    Division, 
    Subtraction 


Right now, only addition is implemented.

You can implement multiplication, division, and subtraction as well. I will publish these methods in my next article.

Congratulations, you have successfully created your Web Calculator using .NET Core.

HostForLIFE.eu ASP.NET Core 2.2.1 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 



ASP.NET Core 2.2.1 Hosting - HostForLIFE.eu :: Google Custom Searching In ASP.NET

clock October 23, 2018 11:28 by author Peter
In many huge contented websites it is very difficult to find some information like any link, page, text etc. So, they use a textbox where visitor types his keyword to search. There are couple of ways to create it like, to search the content from database, crawler. But if you don't have such things then we use Google Custom Search. In Google Custom Search, we create account in Google and provide the domain information to Google and then Google generates some codes which are used inside our web application. If we use the Google Custom Search codes in our application, then Google searches the content from your website. It is available in cost-free and paid also. In cost-free there will be some advertisement of Google.

Let's take a look how to create it.
 
Creating Account in Google Custom Search
 
To create Google Custom Search account use the following link
http://www.google.com/cse/

Click above link to create Google Custom Search.

At the end of this process you will receive some codes generated by Google and you have to keep it for use inside web application. Here is code given Google for my own domain hostforlife.eu.
<scriptsrc="http://www.gmodules.com/ig/ifr?url=http://www.google.com/cse/api/014464787619631746113/cse/67a_iw-duna/gadget&synd=open&w=250&h=100&title=hostforlife.eu+Search&border=%23ffffff%7C0px%2C1px+solid+%23998899%7C0px%2C1px+solid+%23aa99aa%7C0px%2C2px+solid+%23bbaabb%7C0px%2C2px+solid+%23ccbbcc&output=js"></script>  

And I have used it inside the <div> tag in web page, as shown below
<div>    
     <scriptsrcscriptsrc="http://www.gmodules.com/ig/ifr?url=http://www.google.com/cse/api/014464787619631746113/cse/67a_iw-duna/gadget&synd=open&w=250&h=100&title=hostforlife.eu+Search&border=%23ffffff%7C0px%2C1px+solid+%23998899%7C0px%2C1px+solid+%23aa99aa%7C0px%2C2px+solid+%23bbaabb%7C0px%2C2px+solid+%23ccbbcc&output=js"></script>    
  </div>   

HostForLIFE.eu ASP.NET Core 2.2.1 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 



ASP.NET Core 2.2.1 Hosting - HostForLIFE.eu :: How To Use An Area In ASP.NET Core?

clock October 16, 2018 11:40 by author Peter

In order to include an Area in an ASP.NET Core app, first we need to include a conventional route in the Startup.cs file (It's best to place it before any non-area route).

In Startup.cs, configure the method.
    app.UseMvc(routes =>  
    {  
        routes.MapRoute("areaRoute", "{area:exists}/{controller=Admin}/{action=Index}/{id?}");  
        routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");  
    });   


Then, make a folder named Areas in the app root and make another directory named Admin inside the former. Inside the admin folder, create the following folders (ViewComponent is optional).

Now, we will create a Controller inside the Controllers folder named AdminController.
Now, in order for that to work, you'll need to create Views for all actions that return one. The hierarchy for Views is just like what you have in a non-area Views folder.

Now, you should be good to go!

Question - What if I want to have another Controller inside my Area?

Answer -
Just add another Controller beside AdminController and make sure the routes are like the following,
    [Area("Admin")]  
    [Route("admin/[controller]")]  
    public class ProductsController: Controller {  
        publicProductsController() {  
                //  
            }  
            [Route("{page:int?}")]  
        publicIActionResult Index() {  
            returnView();  
        }  
    }   


The important part is [Route("admin/[controller]")]. With that, you can keep the style of routing to admin /controller/ action/.

HostForLIFE.eu ASP.NET Core 2.2.1 Hosting
European best, cheap and reliable ASP.NET hosting with instant activation. HostForLIFE.eu is #1 Recommended Windows and ASP.NET hosting in European Continent. With 99.99% Uptime Guaranteed of Relibility, Stability and Performace. HostForLIFE.eu security team is constantly monitoring the entire network for unusual behaviour. We deliver hosting solution including Shared hosting, Cloud hosting, Reseller hosting, Dedicated Servers, and IT as Service for companies of all size.

 



About HostForLIFE

HostForLIFE is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2019 Hosting, ASP.NET 5 Hosting, ASP.NET MVC 6 Hosting and SQL 2019 Hosting.


Month List

Tag cloud

Sign in