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

European ASP.NET Core Hosting :: Dynamically Check And Uncheck Checkbox Based On DB Value In Gridview

clock July 23, 2019 12:23 by author Peter

This code will help the developers to check and uncheck the gridview checkbox based on the value from the database.
Create a GridView with checkbox.

<asp:GridView ID="Gridview" runat="server" Font-Size="8pt" 
        PageSize="200" Width="880px" AutoGenerateColumns="False"> 
        <Columns> 
            <asp:TemplateField> 
                <HeaderTemplate> 
                    <asp:CheckBox ID="chkHeader" Text="Select All" runat="server" /> 
                </HeaderTemplate> 
                <ItemTemplate> 
                    <asp:CheckBox ID="chkChild" runat="server"  Checked='<%# Eval("PROCESSED").ToString().Equals("1") %>' Enabled='<%# !Eval("PROCESSED").ToString().Equals("1") %>'/> 
                </ItemTemplate> 
            </asp:TemplateField>            
        </Columns> 
    </asp:GridView> 


Get the data from the database, the field from the database to check the checkbox should be 1 or 0.

DB Table data

PROCESSED (HEADER)
1
1
0

DataField "PROCESSED" should be 1 or 0 (boolean),

Checked='<%# Eval("PROCESSED").ToString().Equals("1") %>' 

The above GridView code will check the checkbox if the value from the PROCESSED field in DB is 1 else if the PROCESSED value is other than 1 the checkbox will be unchecked,

Enabled='<%# !Eval("PROCESSED").ToString().Equals("1") %>' 

This code will help us to enable or disable the text box. In the above mentioned code, if the PROCESSED is 1, checkbox will be disabled else the checkboc will be enable.

HostForLIFE.eu ASP.NET 4.8 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 :: A Quick And Simple Look Into .NET Core And Comparison To .NET Standard

clock July 16, 2019 11:54 by author Peter
First, as Microsoft simply described, .NET Core is an open-source, general-purpose development platform maintained by Microsoft and the .NET community on GitHub. .NET is cross-platform which supports Windows, macOS, and Linux and can be used to implement devices, cloud, and IoT applications. Historically, the .NET Framework had only worked on Windows devices. The Xamarin and Mono projects worked to bring .NET to mobile devices, macOS, and Linux. .NET Core provides a standard base library that can now be used across Windows, Linux, macOS, and mobile devices, still via Xamarin.

.NET Core has multiple characteristics such as cross-platform programming for Windows, Linux, MacOS, as well as consistency across architectures. It runs your code with the same behavior on multiple architectures, including x64, x86, and ARM. .NET Core provides flexible deployment, can be included in your app or installed side-by-side such as user-wide or system-wide installations, and can be used with Docker containers.

.NET Core makes it simpler for developers to build microservice architecture systems promptly. As such, systems include several independent and dynamic microservices, the developers can focus on specific microservices. .NET Core enables programmers to develop custom microservices by using varying programming languages, technologies, and frameworks. Likewise, the developers can build a robust system by combining multiple microservices flawlessly.

PROGRAMMING LANGUAGE SUPPORT
From a programming point of view C#, Visual Basic, and F# languages can be used to write applications and libraries for .NET Core. Additionally, with .NET Core 3.0 C# 8.0 will be supported. Currently, VB.NET compiles and runs on .NET Core, but the separate Visual Basic Runtime is not implemented. Microsoft announced that .NET Core 3 would include the Visual Basic Runtime.

GENERAL SUPPORTED FEATURES
.NET Core supports four cross-platform scenarios: ASP.NET Core web apps, command-line apps, libraries, and Universal Windows Platform apps. However, it does not presently apply Windows Forms or WPF which render the standard GUI for desktop software on Windows. Also, .NET Core 3 supports desktop technologies WinForms, WPF and UWP. Besides these, .NET Core supports the use of NuGet packages. Differently than before like .NET Framework, which is serviced using Windows Update, .NET Core depends on its package manager to get updates.

.NET Core consists of CoreCLR, a whole runtime implementation of the Common Language Runtime, which created at Microsoft as the virtual machine for handling execution of .NET programs and includes a just-in-time compiler called RyuJIT. Moreover, .NET Core also contains CoreRT, the .NET Native runtime enhanced to be integrated into AOT compiled native binaries.

.NET Core also includes CoreFX, which is a partial branch of .NET Framework standard libraries. While .NET Core shares a subset of .NET Framework APIs and comes with its own API that is not a subset of .NET Framework. Also, a variant of the .NET Core library is used for UWP.

.NET Core's command-line interface provides an execution entry point for operating systems and gives developer services similar compilation and package management.

Use .NET Core when

  • You want to build cross-platform applications
  • If the new application (web or service) needs to run on multiple platforms- Windows, Linux, macOS, choose .NET Core over .NET Framework. Visual Studio Code and third-party editors such as Sublime, Emacs, VI support .NET Core for cross-platform development.
  • The need is to build high-performance and scalable systems
  • When a performance-oriented and scalable system is on the list, it is better to prefer .NET Core over the .NET Framework. Reason being, .NET Core offers high-performance server runtime for Linux and Windows Server.
  • When you are using microservices or Docker containers
  • For applications or services that use microservices or Docker containers, opting .NET Core makes more sense. Reasons include,
    • .NET Core facilitates mixing microservices or services developed with Ruby, Java, .NET Framework, or other monolithic technologies.
    • Containers usually work in conjugation with microservices architecture. With .NET Framework, there is a limitation to work with Windows containers only. Moreover, while creating and deploying a container, the image size is smaller with .NET Core vs .NET Framework.
  • You need side-by-side .NET versions per application
  • For applications that may have a dependency on different versions of .NET for installation, opt for .NET Core. .NET Core offers side by side installation of multiple versions for .NET Core runtime on the same machine.

Use the .NET Framework when:

  • The app is using .NET technologies that are not available for .NET Core.
  • Several .NET technologies are not available for .NET Core. For example, ASP.NET web pages applications or workflow related services (WCF Data Services, Windows Workflow Foundation) are not included in. NET Core.
  • The existing app uses a platform that .NET Core does not support.
  • Some of the Microsoft or third-party services/platforms do not offer support to .NET Core. For example, Azure’s Service Fabric Stateful Reliable Services programming model does not support .NET Core and is available for.NET Framework.

Finally, the .NET Framework supports Windows and web applications. .NET Core is the new open-source and cross-platform framework to build applications for all operating systems including Windows, Mac, and Linux. .NET Core supports UWP and ASP.NET Core only.

HostForLIFE.eu ASP.NET 4.8 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 :: Register And Use Multiple Implementations Of A Dependency In ASP.NET Core Dependency Injection

clock July 12, 2019 12:13 by author Peter

There can be situations where you need to register multiple implementations of the same dependency for your applications. For example, if you want to add features to your application without changing the existing code, a good way to do it is to add a new implementation for that. Your application needs to be written in a certain way to do this correctly. We have a really simple example that demonstrates this in this article. But when you eventually need to do this, ASP.Net Core built-in Dependency Injection providers capabilities to achieve this. In this article, we will look at how to do this with an example.
Registering Multiple Implementations of a Dependency

As an example, let’s take an online e-commerce website. This site gives Discounts to the customers on certain occasions and when certain conditions are met. I have an interface called IDiscount where it defines a discount and the logic to calculate it. For each type of discount, you want to provide in your e-commerce application, you can have an implementation of the IDiscount interface. Then I have an interface called IDiscountProcessor where the implementation of this interface handles calling all the implementations of IDiscount to calculate the final discount for a given Order.

You have a couple of ways to register multiple implementations of a dependency in ASP.Net Core. One way is to just use the provided extension methods on IServiceCollection to register your implementations with the desired lifetime.
    services.AddScoped<IDiscountProcessor, OrderDiscountProcessor>(); 
    services.AddScoped<IDiscount, SeasonalDiscount>(); 
    services.AddScoped<IDiscount, LargeOrderDiscount>(); 
    services.AddScoped<IDiscount, ThreeOrModeDiscount>();  


Here, I have registered the OrderDiscountProcessor implementation of IDiscountProcessor and 3 implementations of IDiscount interface.

This will work fine when we eventually resolve all the implementations of IDiscount interface we can calculate the total discount. But the problem comes when you have multiple registrations of the same implementation. For example, let’s say one of the developers accidentally registered SeasonalDiscount implementation twice. What will happen is that the Seasonal discount will be applied twice for all the orders, costing the organization money.

A better way of registering multiple implementations is to use TryAddEnumerable extension method given in the Microsoft.Extensions.DependencyInjection.Extensions namespace. This will not register any duplicate implementations making multiple implementation registration safe. The registration is a bit different where you need to use ServiceDescriptors to register the dependency. The modified implementation looks like this.
    services.AddScoped<IDiscountProcessor, OrderDiscountProcessor>(); 
    services.TryAddEnumerable(new[] 
    { 
        ServiceDescriptor.Scoped<IDiscount, SeasonalDiscount>(), 
        ServiceDescriptor.Scoped<IDiscount, LargeOrderDiscount>(), 
        ServiceDescriptor.Scoped<IDiscount, ThreeOrModeDiscount>() 
    }); 


Injecting and Using Multiple Implementations of a Dependency

Once your implementations are registered with the Dependency Injection container, they are ready to be used. To inject all the registered implementations, you need to use IEnumerable<> of the implementation type in your constructor. So, your constructor would look something like this. This is our OrderDiscountProcessor implementation.
    public class OrderDiscountProcessor : IDiscountProcessor 
    { 
        private readonly IEnumerable<IDiscount> _discounts; 
     
        public OrderDiscountProcessor(IEnumerable<IDiscount> discounts) 
        { 
            _discounts = discounts; 
        } 
        // ... 
    } 


Here I am injecting IEnumerable<IDiscount> where it injects all the registered implementations to my class. Then in my ProcessDiscount() method I can use the implementations like this.
    public (double, List<string>) ProcessDiscount(OrderViewModel order) 
    { 
        var discountDiscroptoons = new List<string>(); 
        var totalDiscount = 0.0; 
     
        foreach (var discount in _discounts) 
        { 
            var addedDiscount = discount.CalculateDiscount(order); 
            if (addedDiscount > 0) 
            { 
                 discountDiscroptoons.Add(discount.Description); 
            } 
            totalDiscount += addedDiscount; 
        } 
     
        return (totalDiscount, discountDiscroptoons); 
     } 


I can now iterate through all the implementations of IDiscount interface and call its CalculateDiscount() method to calculate the discount for the given Order.

Note that you can only use IEnumerable<> for your injections of multiple implementations. Any other type like IList<>, ICollection<> will not work in this case.
Summary

In this article, we looked into the process of how to register multiple implementations of the same dependency in ASP.NET Core and how to use these dependencies in our classes by injecting them. The simple sample application used to demonstrate this usage is available for download with this article or you can find the source code on GitHub under the following repository

HostForLIFE.eu ASP.NET 4.8 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 Host ASP.NET Core Application as a Windows Service

clock July 4, 2019 08:38 by author Scott

I recently came across the need to host a .NET Core web app as a Windows Service. In this case, it was because each machine needed to locally be running an API. But it’s actually pretty common to have a web interface to manage an application on a PC without needing to set up IIS. For example if you install a build/release management tool such as Jenkins or TeamCity, it has a web interface to manage the builds and this is able to be done without the need for installing and configuring an additional web server on the machine.

Luckily .NET Core actually has some really good tools for accomplishing all of this (And even some really awesome stuff for being able to run a .NET Core web server by double clicking an EXE if that’s your thing).

A Standalone .NET Core Website/Web Server

The first step actually has nothing to do with Windows Services. If you think about it, all a Windows Service is, is a managed application that’s hidden in the background, will restart on a machine reboot, and if required, will also restart on erroring. That’s it! So realistically what we first want to do is build a .NET Core webserver that can be run like an application, and then later on we can work out the services part.

For the purpose of this tutorial, I’m just going to be using the default template for an ASP.net Core website. The one that looks like this:

We first need to head to the csproj file of our project and add in a specific runtime (Or multiple), and an output type. So overall my csproj file ends up looking like:

<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
    <RuntimeIdentifiers>win10-x64;</RuntimeIdentifiers>
    <OutputType>Exe</OutputType>
  </PropertyGroup> 

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.App" />
  </ItemGroup>
</Project>

Our RuntimeIdentifiers (And importantly notice the “s” on the end there) specifies the runtimes our application can be built for. In my case I’m building only for Windows 10, but you could specify other runtime monkiers if required.

Ontop of this, we specify that we want an outputtype of exe, this is so we can have a nice complete exe to run rather than using the “dotnet run” command to start our application. I’m not 100% sure, but the exe output that comes out of this I think is simply a wrapper to boot up the actual application dll. I noticed this because when you change code and recompile, the exe doesn’t change at all, but the dll does.

Now we need to be able to publish the app as a standalone application. Why standalone? Because then it means any target machine doesn’t have to have the .NET Core runtime installed to get everything running. Ontop of that, there is no “what version do you have installed?” type talk. It’s just double click and run.

To publish a .NET Core app as standalone, you need to run the following command from the project directory in a command prompt/powershell:

dotnet publish --configuration Release --self-contained -r win10-x64

It should be rather self explanatory. We are doing a publish, using the release configuration, we pass through the self contained flag, and we pass through that the runtime we are building for is Windows 10 – 64 Bit.

From your project directory, you can head to:  \bin\Release\netcoreapp2.1\win10-x64\publish

This contains your application exe as well as all framework DLL’s to run without the need for a runtime to be installed on the machine. It’s important to note that you should be inside the Publish folder. One level up is also an exe but this is not standalone and relies on the runtime being installed.

From your publish folder, try double clicking yourapplication.exe.

Hosting environment: Production
Content root path: \bin\Release\netcoreapp2.1\win10-x64\publish
Now listening on:
http://localhost:5000
Now listening on: https://localhost:5001
Application started. Press Ctrl+C to shut down.

In your browser head to http://localhost:5000 and you now have your website running from an executable. You can copy and paste this publish folder onto any Windows 10 machine, even a fresh install, and have it spin up a webserver hosting your website. Pretty impressive!

Installing As A Window Service

So the next part of this tutorial is actually kinda straight forward. Now that you have an executable that hosts your website, installing it as a service is exactly the same as setting up any regular application as a service. But we will try and have some niceties to go along with it.

First we need to do a couple of code changes for our app to run both as a service, and still be OK running as an executable (Both for debugging purposes, and in case we want to run in a console window and not as a service).

We need to install the following from your package manager console:

Install-Package Microsoft.AspNetCore.Hosting.WindowsServices

Next we need to go into our program.exe and make your main method look like the following:

public static void Main(string[] args)
{
 var isService = !(Debugger.IsAttached || args.Contains("--console"));
 var builder = CreateWebHostBuilder(args.Where(arg => arg != "--console").ToArray()); 

 if (isService)
 {

 var pathToExe = Process.GetCurrentProcess().MainModule.FileName;
 var pathToContentRoot = Path.GetDirectoryName(pathToExe);
 builder.UseContentRoot(pathToContentRoot);
 

 var host = builder.Build(); 

 if (isService)
 {
 host.RunAsService();
 }
 else
 {
 host.Run();
 }
}

This does a couple of things :

  • It checks whether we are using the debugger, or if we have a console argument of “–console” passed in.
  • If neither of the above are true, it sets the content root manually back to where the exe is running. This is specifically for the service runtime.
  • Next if we are a service, we use a special “RunAsService()” method that .NET Core gives us
  • Otherwise we just do a “Run()” as normal.

Obviously the main point of this is that if the debugger is attached (e.g. we are running from visual studio), or we run from a command prompt with the flag “–console”, it’s going to run exactly the same as before. Back in the day we used to have to run the service with a 10 second sleep at the start of the app, and quickly try and attach the debugger to the process before it kicked off to be able to set breakpoints etc. Now it’s just so much easier.

Now let’s actually get this thing installed!

In your project in Visual Studio (Or your favourite editor) add a file called install.bat to your project. The contents of this file should be:

sc create MyService binPath= %~dp0MyService.exe
sc failure MyService actions= restart/60000/restart/60000/""/60000 reset= 86400
sc start MyService
sc config MyService start=auto

Obviously replace MyService with the name of your service, and be sure to rename the exe to the actual name of your applications exe. Leave the %~dp0 part as this refers to the current batch path (Allowing you to just double click the batch file when you want to install).

The install file creates the service, sets up failure restarts (Although these won’t really be needed), starts the service, and sets the service to auto start in the future if the machine reboots for any reason.

Go ahead and create an uninstall.bat file in your project. This should look like:

sc stop MyService
timeout /t 5 /nobreak > NUL
sc delete MyService

Why the timeout? I sometimes found that it took a while to stop the service, and so giving it a little bit of a break inbetween stopping and deleting helped it along it’s way.

Important! For both of these files, be sure to set them up so they copy to the output directory in Visual Studio. Without this, your bat files won’t output to your publish directory.

Go ahead and publish your application again using our command from earlier:

dotnet publish --configuration Release --self-contained -r win10-x64

Now in your publish directory, you will find your install and uninstall bat files. You will need to run both of these as Administrator for them to work as installing Windows Services requires elevated access. A good idea is that the first time you run these, you run them from a command prompt so you can catch any errors that happen.

Once installed, you should be able to browse to http://localhost:5000 and see your website running silently in the background. And again, the best part is when you restart your machine, it starts automatically. Perfect!



European ASP.NET Hosting - HostForLIFE.eu :: jQuery PJAX Implementation In ASP.NET Core

clock February 26, 2019 11:15 by author Peter

PJAX is a jQuery plugin that uses AJAX and pushState to deliver a fast browsing experience with real permalinks, page titles, and a working back button. It is available to download from GitHub.

In all websites, the header and footer remain the same for all pages. Only the page contents (the content in the middle area between the header and footer) are changed for each page. PJAX uses this concept to fetch only the page contents while the header and footer remains the same for each page. In short, you can also say PJAX is the brother of the Update Panel of Web Forms that works for ASP.NET Core.

With PJAX, you get the following advantages.

    The website becomes fast since the header and footer are not loaded for different pages.
    You website behaves like a SPA (Single Page Application), and you don’t need to employ Angular framework in your ASP.NET Core Application.
    If you have worked with Update Panel of ASP.NET Web Forms then it is quite similar to it.

This is how PJAX will work.
See the below video which illustrates the working of PJAX.

PJAX Implementation in ASP.NET Core

Integration of PJAX in ASP.NET Core involves the following things.

Layout.cshtml View
In your application _Layout.cshml View, add jQuery and PJAX script links. You do this inside the head section:
    <script src="https://code.jquery.com/jquery-2.2.4.js"></script> 
    <script src="~/js/jquery.pjax.js"></script> 
    Also call PJAX on all anchors inside the #main element.  
    <script type="text/javascript"> 
        $(function () { 
            // call pjax 
            $(document).pjax('#menu li a', '#main', { timeout: 10000 }); 
     
        }); 
    </script> 


Loading Image
If you want to show the loading image when a new page contents are being fetched then add the following code inside the script section of Layout:
    $(document).ajaxStart(function () { 
        $("#loadingDiv").show(); 
    }); 
     
    $(document).ajaxComplete(function (event, jqxhr, settings) { 
        $("#loadingDiv").hide(); 
    }); 


Also, place the loading image somewhere in your layout.
    <div id="loadingDiv" style="display:none;"> 
        <img src="~/loading.gif" /> 
    </div> 


Do not worry as the source code contains all the loading image codes. Do check it.

Add some links to your _Layout.cshtml View. On these links, PJAX will work so when these links are clicked then their page’s contents are loaded by PJAX (but the header and footer area are not loaded).
    <ul> 
        <li><a href="/Home/Index">Index</a></li> 
        <li><a href="/Home/About">About</a></li> 
        <li><a href="/Home/Contact">Contact</a></li> 
    </ul> 


Don’t forget to add the #main element on the Layout so that PJAX only fetches the contents inside this #main element with AJAX.
    <div id="main"> 
        @RenderBody()  
    </div> 

Controller
Add a controller called Home with the following 3 action methods:

    public IActionResult Index() 
    { 
        if (string.IsNullOrEmpty(Request.Headers["X-PJAX"])) 
            return View(); 
        else 
            return PartialView("/Views/Home/Index.cshtml"); 
    } 
     
    public IActionResult About() 
    { 
        if (string.IsNullOrEmpty(Request.Headers["X-PJAX"])) 
            return View(); 
        else 
            return PartialView("/Views/Home/About.cshtml"); 
    } 
     
    public IActionResult Contact() 
    { 
        if (string.IsNullOrEmpty(Request.Headers["X-PJAX"])) 
            return View(); 
        else 
            return PartialView("/Views/Home/Contact.cshtml"); 
    }  


Make sure that the Action methods that are called by PJAX (i.e. clicking on menu links in my case) return PartialViews. Since PJAX sends ‘X-PJAX’ request in the HTTP Header therefore I can easily make a selection of View or Partial View by checking the HTTP header.

The condition applied in each action method that does this work is:
    if (string.IsNullOrEmpty(Request.Headers["X-PJAX"])) 
        return View(); 
    else 
        return PartialView("/Views/Home/Index.cshtml");  


Views

Add the 3 Views called ‘Index.cshtml’, ‘About.cshtml’ and ‘Contact.cshtml’ inside the ‘Views/Home’ folder:

Index.cshtml
    <div class="templatemo_content_area"> 
        <h1>WELCOME TO Index Page</h1> 
    </div> 


About.cshtml
    <div class="templatemo_content_area"> 
        <h1>WELCOME TO About Page</h1> 
    </div> 


Contact.cshtml
    <div class="templatemo_content_area"> 
        <h1>WELCOME TO Contact Page</h1> 
    </div> 


Also add _ViewStart.cshtml View inside the ‘Views’ folder:
    @{ 
        Layout = "_Layout"; 
    }



European ASP.NET Hosting :: Overriding ASP.NET Core Framework

clock February 20, 2019 10:57 by author Scott

OVERVIEW

In .NET it’s really easy to create your own interfaces and implementations. Likewise, it’s seemingly effortless to register them for dependency injection. But it is not always obvious how to override existing implementations. Let’s discuss various aspects of “dependency injection” and how you can override the “framework-provided services”.

As an example, let’s take a recent story on our product backlog for building a security audit of login attempts. The story involved the capture of attempted usernames along with their corresponding IP addresses. This would allow system administrators to monitor for potential attackers. This would require our ASP.NET Core application to have custom logging implemented.

LOGGING

Luckily ASP.NET Core Logging is simple to use and is a first-class citizen within ASP.NET Core.

In the Logging repository there is an extension method namely AddLogging, here is what it looks like:

public static IServiceCollection AddLogging(this IServiceCollection services)
{
    if (services == null)
    {
        throw new ArgumentNullException(nameof(services));
    }

    services.TryAdd(ServiceDescriptor.Singleton<ILoggerFactory, LoggerFactory>());
    services.TryAdd(ServiceDescriptor.Singleton(typeof(ILogger<>), typeof(Logger<>)));

    return services;
}

As you can see, it is rather simple. It adds two ServiceDescriptor instances to the IServiceCollection, effectively registering the given service type to the corresponding implementation type.

FOLLOWING THE RABBIT DOWN THE HOLE

When you create a new ASP.NET Core project from Visual Studio, all the templates follow the same pattern. They have the Program.cs file with a Main method that looks very similar to this:

public static void Main(string[] args)
{
    var host = new WebHostBuilder()
        .UseKestrel()
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .UseApplicationInsights()
        .Build();

    host.Run();
}

TEMPLATES 

One thing that is concerning about a template like this is that the IWebHost is an IDisposable, so why then is this statement not wrapped in a using you ask? The answer is that the Run extension method internally wraps itself in a using. If you were wondering where the AddLogging occurs, it is a result of invoking the Build function.

[ Microsoft.AspNetCore.Hosting.WebHostBuilder ]
    public IWebHost Build() ...
        private IServiceCollection BuildCommonServices() ...
            creates services then invokes services.AddLogging()

A FEW WORDS ON THE SERVICE DESCRIPTOR

The ServiceDescriptor class is an object that describes a service, and this is used by dependency injection. In other words, instances of the ServiceDescriptor are descriptions of services. The ServiceDescriptor class exposes several static methods that allow its instantiation.

The ILoggerFactory interface is registered as a ServiceLifetime.Singleton and its implementation is mapped to the LoggerFactory. Likewise, the generic type typeof(ILogger<>) is mapped to typeof(Logger<>). This is just one of the several key “Framework-Provided Services” that are registered.

PUTTING IT TOGETHER

Now we know that the framework is providing all implementations of ILogger<T>, and resolving them as their Logger<T>. We also know that we could write our own implementation of the ILogger<T>interface. Being that this is open-source we can look to their implementation for inspiration.

public class RequestDetailLogger<T> : ILogger<T>
{
    private readonly ILogger _logger;

    public RequestDetailLogger(ILoggerFactory factory,
                               IRequestCategoryProvider requestCategoryProvider)
    {
        if (factory == null)
        {
            throw new ArgumentNullException(nameof(factory));
        }
        if (requestCategoryProvider == null)
        {
            throw new ArgumentNullException(nameof(requestCategoryProvider));
        }

        var category = requestDetailCategoryProvider.CreateCategory<T>();
        _logger = factory.CreateLogger(category);
    }

    IDisposable ILogger.BeginScope<TState>(TState state)
        => _logger.BeginScope(state);

    bool ILogger.IsEnabled(LogLevel logLevel)
        => _logger.IsEnabled(logLevel);

    void ILogger.Log<TState>(LogLevel logLevel,
                             EventId eventId,
                             TState state,
                             Exception exception,
                             Func<TState, Exception, string> formatter)
        => _logger.Log(logLevel, eventId, state, exception, formatter);
}

The IRequestCategoryProvider is defined and implemented as follows:

using static Microsoft.Extensions.Logging.Abstractions.Internal.TypeNameHelper;

public interface IRequestCategoryProvider
{
    string CreateCategory<T>();
}

public class RequestCategoryProvider : IRequestCategoryProvider
{
    private readonly IPrincipal _principal;
    private readonly IPAddress _ipAddress;

    public RequestCategoryProvider(IPrincipal principal,
                                   IPAddress ipAddress)
    {
        _principal = principal;
        _ipAddress = ipAddress;
    }

    public string CreateCategory<T>()
    {
        var typeDisplayName = GetTypeDisplayName(typeof(T));

        if (_principal == null || _ipAddress == null)
        {
            return typeDisplayName;
        }

        var username = _principal?.Identity?.Name;
        return $"User: {username}, IP: {_ipAddress} {typeDisplayName}";
    }
}

If you’re curious how to get the IPrincipal and IPAddress into this implementation (with DI). It is pretty straight-forward. In the Startup.ConfigureServices method do the following:

public void ConfigureServices(IServiceCollection services)
{
    // ... omitted for brevity

    services.AddTransient<IRequestCategoryProvider, RequestCategoryProvider>();
    services.AddTransient<IHttpContextAccessor, HttpContextAccessor>();
    services.AddTransient<IPrincipal>(
        provider => provider.GetService<IHttpContextAccessor>()
                           ?.HttpContext
                           ?.User);
    services.AddTransient<IPAddress>(
        provider => provider.GetService<IHttpContextAccessor>()
                           ?.HttpContext
                           ?.Connection
                           ?.RemoteIpAddress);
}

Finally, we can Replace the implementations for the ILogger<T> by using the following:

public void ConfigureServices(IServiceCollection services)
{
    // ... omitted for brevity
    services.Replace(ServiceDescriptor.Transient(typeof(ILogger<>),
                                                 typeof(RequestDetailLogger<>)));
}

Notice that we replace the framework-provided service as a ServiceLifetime.Transient. Opposed to the default ServiceLifetime.Singleton. This is more or less an extra precaution. We know that with each request we get the HttpContext from the IHttpContextAccessor, and from this we have the User. This is what is passed to each ILogger<T>.

CONCLUSION

This approach is valid for overriding any of the various framework-provided service implementations. It is simply a matter of knowing the correct ServiceLifetime for your specific needs. Likewise, it is a good idea to leverage the open-source libraries of the framework for inspiration. With this you can take finite control of your web-stack.



European ASP.NET Hosting :: How to Add Custom 404 and Error Pages in ASP.NET

clock January 23, 2019 10:26 by author Scott

I post this to remind myself how we got this working for both ASP.NET and static files, both for remote and local requests on IIS 7 and IIS 7.5.

<httpErrors> over <customErrors>

<customErrors> in web.config is a construct for specifying custom error pages for requests handled by ASP.NET. In other words, static files such as HTML files or directory (“friendly”) URLs are not handled.

<httpErrors> configures error pages in IIS itself, outside the web application. This handles all requests, whether they’re in fact handled by ASP.NET or IIS natively.

We ignore customErrors altogether and only use httpErrors.

Displaying a static HTML file

This is useful for error codes such as 500 where the ASP.NET web application in itself may suffer problems:

<httpErrors errorMode="Custom" defaultResponseMode="File">
    <clear />
    <error statusCode="500" path="Static\html\error.html"/>
</httpErrors>

Displaying an ASP.NET page

This displays an ASP.NET page when a 404 error occurs, without rewriting the URL (the visitor will still see the requested URL in the address bar):

<httpErrors errorMode="Custom" existingResponse="Replace">
  <remove statusCode="404" subStatusCode="-1" />
  <error statusCode="404" path="/Errors/404.aspx" responseMode="ExecuteURL"/>
</httpErrors>

Note that we skip the <clear /> element and simply remove the standard 404 handling (in order to avoid an exception caused by duplicate elements for the 404 status code).

Redirecting to another URL

ExecuteURL can only be used to execute an ASP.NET file within the same application. If we want to redirect to another application, or possibly an entirely different external URL, we use the Rewrite response mode with an absolute URL:

<httpErrors errorMode="Custom" existingResponse="Replace">
  <clear />
  <error statusCode="404" path="http://www.bing.com" responseMode="Redirect"/>
</httpErrors>

Make sure HTTP errors is enabled in IIS

For this to work you have to make sure the HTTP Errors feature is installed for IIS, otherwise you’ll just get an empty 404 response:



ASP.NET 4.5 Hosting - HostForLIFE.eu :: Secure Your Website No Copy Paste

clock June 2, 2016 20:43 by author Anthony

Have you ever worked really hard on graphics for your site only to find later that someone has stolen them as their own. You can help encrypt and protect your site with the following codes. No right click block is 100% effective, but they will help against novices.

In the real world, sometimes a developer needs to restrict a basic facility such as cut, copy and paste on an entire web page but not on a specific control. At that time you will need some easy way to stop these kinds of facilities on the page but not create code in every control to disable these facilities.
Suppose you have 20 "TextBox" controls in your page and you want to restrict the cut, copy and paste in all the textboxes, then you do not need to write the disable code in each TextBox. In this scenario, you need to just write the disable code only in the "body" tag.
To explain such implementation, I will use the following procedure.

Step 1

Create an ASP.Net Empty Website named "My Project".

Step 2

Add a new web form named "Default.aspx" into it.

Step 3

Add 2 "TextBox" controls to the page named "Default.aspx" .


Step 4

On Cut: By this, you can disable the "Cut " facility in both of the "TextBox" Controls.
Syntax: oncut= “return false”;

On Copy: By this, you can disable the "Copy " facility in both of the "TextBox" controls.
Syntax: oncopy= “return false”;

On Paste: By this, you can disable the "Cut" facility in both of the "TextBox" controls.
Syntax: onpaste= “return false”;

To disable the All (Cut, Copy and Paste) in the entire page:



HostForLIFE.eu ASP.NET 4.5 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 4.5.1 Germany Hosting - HostForLIFE.eu :: ASP.NET Session and Concurrent Access

clock March 5, 2014 05:35 by author Peter

In one of my projects I found some a strange at first sight issue related to concurrent Session usages. During one long request the other parallel requests were waiting until the previous one is finished.This issue occurs when user tries to download file from ashx-handler. Handler requires Session to get some user-related configuration which is stored there. I've tried to dig deeper and that what I've found. By default no concurrent access to the asp.net session state is allowed. Requests with same SessionID will be locked exclusively to prevent potential corruption of its state. This topic contains only brief information about ASP.NET, if you want to be more familiar with ASP.NET, you should try HostForLife.eu

When you have request1 `in progress` and trying to do request2 - Session object will be locked by request1 and our code in request2 will be waiting for request1 completed. ASP.NET Session is thread safe and synchronization mechanism is based on System.Threading.ReaderWriterLock. This means that we can do many reads but only one writing at the same time. ASP.NET Session object is configured for full (read\write) access, by default. That's why we need to configure Session object as 'read-only' on long-term pages to have non-blocking access to Session object from other pages. Be aware that even you don't use Session object explicitly you have this issue too.

How to reproduce

To reproduce this issue let's create 2 asp.net pages.

Default page:

<%@ Page Language="C#" %>

<script runat="server">
  protected void Page_Load(object sender, EventArgs e)
  {
      Response.Write("Hello, SessionId " + Session.SessionID);
  }
</script>

Slow page (contains some long-term execution):

<%@ Page Language="C#" %>

<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        System.Threading.Thread.Sleep(10000);
        Response.Write("Hello, SessionId " + Session.SessionID);
    }
</script>

web.config

<configuration>
  <system.web>
    <sessionState mode="InProc"/>
  </system.web>
</configuration>

To resolve this issue we can re-configure ASP.NET Session object access. Session state is configured by using the sessionState element of the system.web configuration section. If you need non-blocking access to read from Session:

<%@ Page Language="C#" EnableSessionState="ReadOnly"%>

If you don't need Session:

<%@ Page Language="C#" EnableSessionState="False"%>



ASP.NET European Hosting - HostForLIFE.eu :: ASP.NET Identity

clock February 21, 2014 08:51 by author Peter

ASP.NET Identity provides an implementation of user and and rolemanagement. ASP.NET Identity does not do authentication. Cookie based authentication and redirects to external login providers such as Google and Facebook is handeled by the OWIN libraries. ASP.NET Identity is only concerned with creation of users and roles, and persisting information about users such as passwords, links to external login providers and claims. This functionality is provided by classes in the two assemblies

1. Microsoft.AspNet.Identity.Core - Core user and role management logic

2. Microsoft.AspNet.Identity.EntityFramework - EnitityFramework based persistence of Users, Roles, Claims etc.

Identity Core - user management logic

Identity.Core has two main classes which will be our main means to interact with ASP.NET Identity. They are named UserManager and RoleManager. UserManager is probably the most important one, and is the only one that are used in the AccountController that is created by the default templates for e.g. an MVC when you choose "Individual User Accounts".

The UserManager is used to add/create, find/get and remove:

1. Users
2. Passwords
3. Claims
4. Link to roles
5. Link to logins

A UserStore that is responsible for the persistence is injected into the UserManager. The usermanager will use the UserStore to perform all it's needs for persistence. The UserManager is a generic class that has a TUser type parameter. TUser must be a class that implements the IUser interface, which means that a User class needs to have a Id getter of string type and a UserName string property.

Developers often asks why Microsoft chose to type the Id as string instead of int. It is true that if we implement our own UserStore then we are free to use a different type for our primary key, but it is a bit inconvenient that this key can not be named "Id". IUser which we must implement already defines a string Id get'er.

Identity EntityFramework - Entity framework code first persistence

The classes of the Identity Core assembly require a persistence mechanism. Microsoft has provided a Entity Framework code first based implementation to us in the assembly Microsoft.AspNet.Identity. The Identity EntityFramework assembly provides a UserStore implementation that can be plugged right into the UserManager from the Core assembly. This is by far our easiest option to get started with ASP.NET Identity. In fact if you create a new MVC project and choose Individual User Accounts the template will create a working implementation for you right away.

The model consist of a IdentityUser and the following related objects:

1. IdentityUserClaim. A list of claims for the user

2. IdentityUserLogin. This is only used for external logins. Links the local user to an external account

3. IdentityRole. If you use roles this is where the roles and mapping from user to roles will be stored.

Simplicity comes at a price

This simplicity comes at a price though. The UserStore require us to not only have our user class implement the IUser interface, it also demands that we need to inherit from the ASP.NET Identity EntityFramework class called IdentityUser which adds two new properties to the IUser interface. The hashed password and a SecurityStamp is stored on the user. Many developers and myself included are not too happy about being forced to have a reference to EntityFramework and ASP.NET EntityFramework from our domain model assembly and that we are required to inherit from this IdentityUser class, but if we want to have the simplicity of just using the Microsoft Identity persistence then we just have to swallow that one.

The UserStore will by default create a DbContext that in turn will create five tables for us, one for each of the entities in the model.

1. AspNetUsers - for storing IdentityUser

2. AspNetUserClaims - for storing IdentiyUserClaim

3. AspNetUserLogin - for storing IdentityUserLogin

4. AspNetRoles - for storing IdentityRole

5. AspNetUserRoles - for storing the many-to-many relation between IdentityUser and IdentityRole

The table names and the Entity Framework configuration of relations between the entities are configured in the OnModelCreating method of the IdentityDbContext that the UserStore will create if we don't provide our own DbContext. If we want to use different table names or map things differently in our database we need to provide our own DbContext. We can either create a completely new DbContext class with the 5 required DbSets (one for each of the model classes) or we can simply subclass the IdentityDbContext and override the OnModelCreating method where we can configure the EF mappings as we wish.

What next?

As I wrote in my previous post I was hoping that Microsoft would remove the requirement of having to inherit the IdentityUser. As we have seen, it didn't happen.

If we want to use the stock implementation in the form of ASP.NET Identity EntityFramework we have to inherit from the IdentityUser class. Still, what they did do was refactor the implementation into two clearly separate concerns. The core assembly containing the core logic and the EntityFramework assembly containing EF persistence. It's the latter that forces me to do things I don't like, and because the designers has made this clean separation it is possible for me to opt out of the EF persistence implementation while still use the user management logic in the Core assembly. In my next post I will show how to write my own UserStore class. To show that the ASP.NET Identity model is flexible and in no way tied to Entity Framework or SQL server I will be persisting my user data to a MongoDatabase instead of using Entity Framework.



About HostForLIFE.eu

HostForLIFE.eu 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 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in