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 :: 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 Fix “An error occurred while starting the application” in ASP.NET Core on IIS

clock July 5, 2019 07:33 by author Scott

.NET Core is the latest Microsoft product and Microsoft always keep update their technologies. We have written tutorial about how to publish ASP.NET Core on IIS server, but we know that some of you sometimes receive error when deploying your ASP.NET Core. Feel frustrated to fix the issue? Yeah, not only you have headache, but some of our clients also experience same problem like you. That’s why we write this tutorial and hope it can help to fix your issue!

Anyone see this error? Have problem to solve it? We want to help you here!

The Problem

 

It basically means something bad happened with your application. Things you need to check

  • You might not have the correct .NET Core version installed on the server.
  • You might be missing DLL’s
  • Something went wrong in your Program.cs or Startup.cs before any exception handling kicked in

If you use Windows Server, then I believe that you can’t find anything on your Event Viewer too. You’ll notice that there is no error on your Event Viewer log. Why? This is because Event Logging must be wired up explicitly and you’ll need to use the Microsoft.Extensions.Logging.EventLog package, and depending on the error, you might not have a chance to even catch it to log to the Event Viewer.

How to Fix it?

So, how to fix error above? The followings are the steps to fix the error:

1. Open your web.config

2. Change stdoutLogEnabled=true

3. Create a logs folder

  • Unfortunately, the AspNetCoreModule doesn’t create the folder for you by default
  • If you forget to create the logs folder, an error will be logged to the Event Viewer that says: Warning: Could not create stdoutLogFile \\?\YourPath\logs\stdout_timestamp.log, ErrorCode = -2147024893.
  • The “stdout” part of  the value “.\logs\stdout” actually references the filename not the folder.  Which is a bit confusing.

4. Run your request again, then open the \logs\stdout_*.log file

Note – you will want to turn this off after you’re done troubleshooting, as it is a performance hit.

So your web.config’s aspNetCore element should look something like this

 <aspNetCore processPath=”.\YourProjectName.exe” stdoutLogEnabled=”true” stdoutLogFile=”.\logs\stdout” />

Doing this will log all the requests out to this file and when the exception occurs, it will give you the full stack trace of what happened in the \logs\stdout_*.log file

  

 

 

Hope this helps!

Looking for ASP.NET Core hosting with affordable cost?

We know it is quite hard to find reliable hosting that support ASP.NET Core. We believe that some of you have signed up for 1 hosting, but they are below your expectation. Maybe they don’t support latest ASP.NET Core or they might support .NET Core but their support are not competent. We are here to help you. If you are looking for cheap, reliable with best ASP.NET Core hosting support, then you can visit our site at https://www.hostforlife.eu.



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!



ASP.NET Core 2.2.5 Hosting - HostForLIFE.eu :: How to Read a Remote WEB Page in ASP.NET C#?

clock July 2, 2019 12:16 by author Peter

In this tutorial, let me show you how to Read a Remote WEB Page in ASP.NET C#. Below is my aspx:

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> 
     
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
    <html xmlns="http://www.w3.org/1999/xhtml"> 
    <head runat="server"> 
        <title></title> 
    </head> 
    <body> 
        <form id="form1" runat="server"> 
        <div> 
            <asp:Label ID="lblResponse" runat="server"></asp:Label></div> 
        </form> 
    </body> 
    </html> 

Now my aspx.cs is:

    using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Web; 
    using System.Web.UI; 
    using System.Web.UI.WebControls; 
    using System.Net; 
    using System.IO; 
     
    public partial class _Default : System.Web.UI.Page 
    { 
        protected void Page_Load(object sender, EventArgs e) 
        { 
            string URLResponse = GetHtmlPage("http://www.google.com"); 
            lblResponse.Text = URLResponse; 
        } 
     
        static string GetHtmlPage(string strURL) 
        { 
     
            String strResult; 
            WebResponse objResponse; 
            WebRequest objRequest = HttpWebRequest.Create(strURL); 
            objResponse = objRequest.GetResponse(); 
            using (StreamReader sr = new StreamReader(objResponse.GetResponseStream())) 
            { 
                strResult = sr.ReadToEnd(); 
                sr.Close(); 
            } 
            return strResult; 
        } 
    } 


Here I am reading http://www.google.com and showing response in a label:

 


HostForLIFE.eu ASP.NET Core 1.0 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 :: Integration Test ASP.NET Core

clock June 25, 2019 09:19 by author Scott

Writing integration tests for ASP.NET Core controller actions used for file uploads is not a rare need. It is fully supported by ASP.NET Core integration tests system. This post shows how to write integration tests for single and multiple file uploads.

Getting started

Suppose we have controller action for file upload that supports multiple files. It uses complex composite command for image file analysis and saving. Command is injected to action by framework-level dependency injection using controller action injection.

[HttpPost]
[Authorize(Roles = "Admin")]
public async Task<IActionResult> Upload(IList<IFormFile> files, int? parentFolderId,
                                        [FromServices]SavePhotoCommand savePhotoCommand)
{
    foreach(var file in files)
    {
        var model = new PhotoEditModel();
        model.FileName = Path.GetFileName(file.FileName);
        model.Thumbnail = Path.GetFileName(file.FileName);
        model.ParentFolderId = parentFolderId;
        model.File = file;
 
        list.AddRange(savePhotoCommand.Validate(model));
 
        await savePhotoCommand.Execute(model);
    }
 
    ViewBag.Messages = savePhotoCommand.Messages;
 
    return View();
}

We want to write integration tests for this action but we need to upload at least one file to make sure that command doesn’t fail.

Making files available for integration tests

It’s good practice to have files for testing available no matter where tests are run. It’s specially true when writing code in team or using continuous integration server to run integration tests. If we don’t have many files and the files are not large then we can include those files in project.

Important thing is to specify in Visual Studio that these files are copied to output folder.

Same way it’s possible to use also other types of files and nobody stops us creating multiple folders or folder trees if we want to organize files better.

Uploading files in integration tests

Here is integration tests class for controller mentioned above. Right now there’s only one test and it is testing Upload action. Notice how image files are loaded from TestPhotos folder to file streams and how form data object is built using the file streams.

public class PhotosControllerTests : IClassFixture<WebApplicationFactory<Startup>>
{
    private readonly WebApplicationFactory<Startup> _factory;
 
    public PhotosControllerTests(WebApplicationFactory<Startup> factory)
    {
        _factory = factory;
    }
 
    [Fact]
    public async Task Upload_SavesPhotoAndReturnSuccess()
    {
        // Arrange
        var expectedContentType = "text/html; charset=utf-8";
        var url = "Photos/Upload";
        var options = new WebApplicationFactoryClientOptions { AllowAutoRedirect = false };
        var client = _factory.CreateClient(options);
 
        // Act
        HttpResponseMessage response;
 
        using (var file1 = File.OpenRead(@"TestPhotos\rt-n66u.jpg.webp"))
        using (var content1 = new StreamContent(file1))
        using (var file2 = File.OpenRead(@"TestPhotos\speedtest.png.webp"))
        using (var content2 = new StreamContent(file2))
        using (var formData = new MultipartFormDataContent())
        {
            // Add file (file, field name, file name)
            formData.Add(content1, "files", "rt-n66u.jpg.webp");
            formData.Add(content2, "files", "speedtest.png.webp");
 
            response = await client.PostAsync(url, formData);
        }
 
        // Assert
        response.EnsureSuccessStatusCode();
        var responseString = await response.Content.ReadAsStringAsync();
 
        Assert.NotEmpty(responseString);
        Assert.Equal(expectedContentType, response.Content.Headers.ContentType.ToString());
 
        response.Dispose();
        client.Dispose();
    }
}

For actions that accept only one file we need only one call to Add() method of formData.

Wrapping up

Integration tests mechanism in ASP.NET Core is flexible enough to support also more advanced scenarios like file uploads in tests. It’s not very straightforward and we can’t just call few methods of HTTP client to do it but it’s still easy enough once we know the tricks. If we keep test files in integration tests project then we don’t have to worry about getting files to machine where integration tests are running.



European ASP.NET Core 2.2.5 Hosting - HostForLIFE.eu ::Server.MapPath() In ASP.NET

clock June 19, 2019 12:05 by author Peter

Many times we need to know the full path of remote server where we are hosting or the exact location of file but if we don't how we can't. Actually we have MapPath method which maps the specified relative or virtual path to the corresponding physical directory on the web server. Usually any web server never allows to access in any path if we don't have proper permission. Even we can't list the directories or file as we list in DOS like,

As in above picture, we can list on web server via remotely without proper permission because of security reason. But we can see the full path where the particular page exists as in example given below.

In above example, coded (given below) file is being hosted at remote server and it is displaying (mapping) the physical location (path) of my hosting server. Here is my coding I have used.
    protected void Page_Load(object sender, EventArgs e) {   
        Response.Write(Server.MapPath("."));   
        Response.Write("<br>");   
        Response.Write(Server.MapPath(""));   
        Response.Write("<br>");   
        Response.Write(Server.MapPath("~"));   
    }  

HAVE A HAPPY CODING!

HostForLIFE.eu ASP.NET Core 2.2.5 Hosting
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 customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



European ASP.NET Core 2.2.4 Hosting - HostForLIFE.eu :: How to create TextBox AutoComplete using JQuery or JSON in ASP.NET?

clock May 28, 2019 12:28 by author Peter

In this article, I will tell you how to create TextBox AutoComplete using JQuery or JSON in ASP.NET. First, create project in ASP.NET, then write the following code:

.Aspx Page
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>ASP.NET TextBox AutoCaomplete using JQuery or JSON</title>
<link rel="stylesheet"
href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css"/>
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        var arr = [];
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "JQueryAutoCompleteJSON.aspx/GetEmployeeName",
            data: "{}",
            dataType: "json",
            success: function (data) {
                for (var i = 0; i < data.d.length; i++) {
                    arr[i] = data.d[i].empName;
                }
            },
            error: function (result) {
                alert("Error");
            }
        });
        $("#tags").autocomplete({
        source:arr
    });
});
</script>
<style type="text/css">
table,th,td
{
border:1px solid black;
border-collapse:collapse;
}
</style>
</head>
<body>
   <form id="form1" runat="server">
   <div class="ui-widget">
  <label for="tags">Tags: </label>
  <input id="tags">
</div>
    </form>
</body>
</html>


C#

using System.Web.Services;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
public partial class JQueryAutoCompleteJSON : System.Web.UI.Page
{
    [WebMethod]
    public static EmpDetails[] GetEmployeeName()
    {
        DataTable dt = new DataTable();
        List<EmpDetails> empNames = new List<EmpDetails>();
        SqlConnection con = newSqlConnection(ConfigurationManager.ConnectionStrings["con"].ConnectionString);
        SqlCommand cmd = new SqlCommand("select * from employee", con);
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);
        foreach (DataRow drow in dt.Rows)
        {
            EmpDetails emp = new EmpDetails();
            emp.empName = drow["name"].ToString();
            empNames.Add(emp);
        }
        con.Close();
        return empNames.ToArray();
    }
    public class EmpDetails
    {
        public string empName { get; set; }
    }}

VB.NET
Imports System.Web.Services
Imports System.Data.SqlClient
Imports System.Data
Imports  System.Configuration
Partial Public Class JQueryAutoCompleteJSON
    Inherits System.Web.UI.Page
    <WebMethod()> _
    Public Shared Function GetEmployeeName() As EmpDetails()
        Dim dt As New DataTable()
        Dim empNames As New List(Of EmpDetails)()
        Dim con As NewSqlConnection(
ConfigurationManager.ConnectionStrings("con").ConnectionString)
        Dim cmd As New SqlCommand("select * from employee", con)
        con.Open()
        Dim da As New SqlDataAdapter(cmd)
        da.Fill(dt)
        For Each drow As DataRow In dt.Rows
            Dim emp As New EmpDetails()
            emp.empName = drow("name").ToString()
            empNames.Add(emp)
        Next
        con.Close()
        Return empNames.ToArray()
    End Function
    Public Class EmpDetails
        Public Property empName() As String
            Get
                Return m_empName
            End Get
            Set(ByVal value As String)
                m_empName = Value
            End Set
        End Property
        Private m_empName As String
    End Class
End Class

HostForLIFE.eu ASP.NET Core 2.2.4 Hosting
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 customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.



European ASP.NET Core Hosting - HostForLIFE.eu :: Get Currency Format Using Google In ASP.NET

clock May 21, 2019 11:00 by author Peter

Many times, I have encountered a vital question: "How can I change 20000.00 to $20,000.00?" This involves a simple currency formatter. You can use either jQuery or server-side coding to show the currency in this format. Here, in this post, I will show you how to format the currency input from user in ASP.NET.
Format Currency using jQuery

First, start with jQuery. Google has provided a very simple way to format currency. You can find out about it from here. Or you can follow this.

To continue, you have to download two JavaScript files. One is jquery.formatCurrency-1.4.0.js and the second one is jquery.min.js. I have attached these JS files with the code I have attached along with this post.

So, let's start with sample coding. First, create a new project and add a new page, name it whatever you want. Then, add a new text box. Firstly, we will do it with the onBlur function of jQuery, so we don't need any more extra buttons for showing our formatted currency.

Add those downloaded JS files into your header section of the web form. And then, paste the following code into your page.

JS
    <script src="jquery.min.js"></script> 
    <script src="jquery.formatCurrency-1.4.0.js"></script> 
    <script type="text/javascript"> 
            $(document).ready(function () { 
                $('.text').focusout(function () { 
                    $('.text').formatCurrency(); 
                    $('.text').formatCurrency('.currencyLabel'); 
                }); 
            });        
    </script> 


HTML
    <div> 
         <p>Currency Formatter</p> 
         <asp:TextBox runat="server"  
     
         ID="txtPrice" CssClass="text"></asp:TextBox> 
         Show by Jquery: <span class="currencyLabel"></span> 
    </div> 


Check the CssClass of text box. It's the method by which formatCurrency() method is calling to format it to text box and also show the output value to a span.
Format Currency using C#

I hope it's clear to you how to format currency by jQuery. Now, let's see how to do this using C#. Don't worry, C# has an inbuilt function for this. For C#, we are taking an extra button to display the output into a label.

    <asp:TextBox ID="txtCurrency" runat="server"></asp:TextBox> 
    <asp:Button ID="btnChange" Text="Format" runat="server" OnClick="btnChange_Click"   /> 
    <asp:Label ID="lblShow" runat="server"></asp:Label> 
     
    protected void btnChange_Click(object sender, EventArgs e) 
    { 
        lblShow.Text = (Convert.ToDouble(txtCurrency.Text)).ToString("C2"); 
    } 


Make sure this method is only applicable to data types like decimal and double. So you have to add a check to see whether user input is bound to numbers.

 



European ASP.NET Core Hosting - HostForLIFE.eu :: Dependency Injection For Quartz.NET In .NET Core

clock May 14, 2019 12:18 by author Peter

Quartz.NET is a handy library that allows you to schedule recurring tasks via implementing IJob interface. Yet the limitation of it is that, by default, it supports only a parameterless constructor which complicates injecting external service inside of it, i.e., for implementing repository pattern. In this article, we'll take a look at how we can tackle this problem using standard .NET Core DI container.

The whole project referred to in the article is provided inside the following Github repository. In order to better follow the code in the article, you might want to take a look at it.

Project Overview
Let's take a look at the initial solution structure.

The project QuartzDI.Demo.External.DemoService represents some external dependency we have no control over. For the sake of simplicity, it does quite a humble job.

The project QuartzDI.Demo is our working project which contains simple a Quartz.NET job.
    public class DemoJob : IJob 
    { 
        private const string Url = "https://i.ua"; 
     
        public static IDemoService DemoService { get; set; } 
     
        public Task Execute(IJobExecutionContext context) 
        { 
            DemoService.DoTask(Url); 
            return Task.CompletedTask; 
        } 
    } 


It is set up in a straightforward way:
    var props = new NameValueCollection 
    { 
        { "quartz.serializer.type", "binary" } 
    }; 
    var factory = new StdSchedulerFactory(props); 
    var sched = await factory.GetScheduler(); 
    await sched.Start(); 
    var job = JobBuilder.Create<DemoJob>() 
        .WithIdentity("myJob", "group1") 
        .Build(); 
    var trigger = TriggerBuilder.Create() 
        .WithIdentity("myTrigger", "group1") 
        .StartNow() 
        .WithSimpleSchedule(x => x 
            .WithIntervalInSeconds(5) 
            .RepeatForever()) 
    .Build(); 
    await sched.ScheduleJob(job, trigger); 


We provide our external service via the job's static property.
    DemoJob.DemoService = new DemoService(); 

As the project is a console application, during the course of the article, we'll have to manually install all needed infrastructure and will be able to build a more thorough understanding of what .NET Core actually brings to the table.

At this point, our project is up and running. And what is most important is, it's dead simple, which is great. But we pay for that simplicity with a cost of application inflexibility, which is fine if we want to leave it as a small tool. But that's often not the case for production systems. So let's tweak it a bit to make it more flexible.
Creating a Configuration File

One of the inflexibilities is that we hard-code the URL we call into a DemoJob. Ideally, we would like to change it and also change it depending on our environment. .NET Core comes with an appsettings.json mechanism for that matter.

In order to start working with the .NET Core configuration mechanism, we have to install a couple of NuGet packages.

  • Microsoft.Extensions.Configuration 
  • Microsoft.Extensions.Configuration.FileExtensions 
  • Microsoft.Extensions.Configuration.Json 

Let's create a file with such a name and extract our URL there,
    { 
      "connection": { 
        "Url": "http://i.ua" 
      } 
    } 

Now, we can extract our value from the config file as below.
    var builder = new ConfigurationBuilder() 
                    .SetBasePath(Directory.GetCurrentDirectory()) 
                    .AddJsonFile("appsettings.json", true, true); 
    var configuration = builder.Build(); 
    var connectionSection = configuration.GetSection("connection"); 
    DemoJob.Url = connectionSection["Url"];
 

Note that to make it happen, we had to change the URL from constant to property.
    public static string Url { get; set; } 

Using Constructor Injection

Injecting service via a static property is fine for a simple project, but for a bigger one, it might carry several disadvantages: such as a job might be called without a service provided, thus failing or changing the dependency during the object runtime. To address these issues, we should employ constructor injection.

Although there is nothing wrong with Pure Dependency Injection and some people argue that you should strive for it, in this article, we'll use a built-in .NET Core DI container which comes with a NuGet package Microsoft.Extensions.DependencyInjection.

Now, let us specify a service we depend on inside constructor arguments.
    private readonly IDemoService _demoService; 
    public DemoJob(IDemoService demoService) 
    { 
        _demoService = demoService; 
    } 

In order to invoke a parameterful constructor of the job, Quartz.NET provides IJobFactory interface. Here's our implementation.
    public class DemoJobFactory : IJobFactory 
    { 
        private readonly IServiceProvider _serviceProvider; 
     
        public DemoJobFactory(IServiceProvider serviceProvider) 
        { 
            _serviceProvider = serviceProvider; 
        } 
     
        public IJob NewJob(TriggerFiredBundle bundle, IScheduler scheduler) 
        { 
            return _serviceProvider.GetService<DemoJob>(); 
        } 
     
        public void ReturnJob(IJob job) 
        { 
            var disposable = job as IDisposable; 
            disposable?.Dispose(); 
        } 
    } 


Let's register our dependencies.
    var serviceCollection = new ServiceCollection(); 
    serviceCollection.AddScoped<DemoJob>(); 
    serviceCollection.AddScoped<IDemoService, DemoService>(); 
    var serviceProvider = serviceCollection.BuildServiceProvider(); 


The final piece of the puzzle is to make Quartz.NET use our factory. IScheduler has property JobFactory just for that matter.
    sched.JobFactory = new DemoJobFactory(serviceProvider); 
    Using Options Pattern 


Now, we can pull the same trick with configuration options. Again, our routine starts with a Nuget package. This time Microsoft.Extensions.Options.

Let's create a strongly typed definition for configuration options.
    public class DemoJobOptions 
    { 
        public string Url { get; set; } 
    } 


Now, we populate them as below.
    serviceCollection.AddOptions(); 
    serviceCollection.Configure<DemoJobOptions>(options => 
    { 
        options.Url = connectionSection["Url"]; 
    }); 


And inject them into a constructor. Note that we inject IOptions<T>, not the options instance directly.
    public DemoJob(IDemoService demoService, IOptions<DemoJobOptions> options) 
    { 
        _demoService = demoService; 
        _options = options.Value; 
    } 


Conclusion
In this article, we've seen how we can leverage .NET Core functionality to make our use of Quartz.NET more flexible.

 

 



European ASP.NET Core Hosting :: Alert Dialog From Controller Without JavaScript In View

clock May 9, 2019 12:27 by author Peter
We can show an alert dialog in the browser from Controller without using any JavaScript in the View, which saves our time and makes the popping up of dynamic data way faster.
 
Displaying an Alert Dialog popup can be done from the controller and even from the server-side, but it is very useful when you want to display an alert using much less code.
 
In your Controller, copy the below code just before your return code.

public ActionResult SmartRegister(csUser model)  
 {               
     User us = new User();  
     rfSocietyEntities db = new rfSocietyEntities();  
     if (ModelState.IsValid)  
     {  
         int count = db.Users.Where(a => a.Email.Equals(model.Email)).Count();  
         if (count == 0)  
         {  
             us.Admin = model.Admin;  
             us.Email = model.Email;  
             us.FullName = model.FullName;  
             us.Password = model.Password;  
             us.PhoneNo = model.PhoneNo;  
             db.Users.Add(us);  
             db.SaveChanges();  
             return RedirectToAction("Dashboard""Dashboard");  
         }  
         else  
         {  
             TempData["msg"] = "<script>alert('Email id already registered.');</script>";  
             return View (model);  
         }  
     }  
     else  
     {  
         TempData["msg"] = "<script>alert('Please Check Data entered or try later.');</script>";  
         return View(model);  
     }  
}    
In your View file, add the below code.
  @Html.Raw(TempData["msg"])




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