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 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.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