Saturday, August 22, 2020

Host Hangfire Dashboard with Windows Services without OWIN

 1. Add Startup class to the Windows Service project as below:


using Hangfire;

using Hangfire.Dashboard;

using Microsoft.AspNetCore.Builder;

using Microsoft.AspNetCore.Hosting;

using Microsoft.Extensions.Configuration;

using Microsoft.Extensions.DependencyInjection;


public class Startup  {

        public IConfiguration Configuration { get; }

        public Startup(IConfiguration configuration) {

            Configuration = configuration;

        }

         public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {

            app.UseHangfireDashboard();

        }

         public void ConfigureServices(IServiceCollection services) {

            services.AddHangfire(configuration => configuration

              .UseSqlServerStorage(

                    Configuration.GetConnectionString("DatabaseConnectionString")

            ));

         }

    }


2. Add/ Modify program class as below:


using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Reflection;

using Hangfire;

using Microsoft.AspNetCore.Hosting;

using Microsoft.AspNetCore.Server.HttpSys;

using Microsoft.Extensions.Configuration;

using Microsoft.Extensions.DependencyInjection;

using Microsoft.Extensions.Hosting;


public class Program {

        public static void Main(string[] args) {

            CreateHostBuilder(args).Build().Run();

        }

         public static IHostBuilder CreateHostBuilder(string[] args) =>

            Host.CreateDefaultBuilder(args)

                .ConfigureServices((hostContext, services) =>    {

                    GlobalConfiguration.Configuration

                                       .UseSqlServerStorage(hostContext.Configuration

                                       .GetConnectionString("DbConnectionString"))

                                       .UseConsole();

                })

                .UseWindowsService()

                .ConfigureWebHostDefaults(webBuilder =>    {

                    webBuilder.UseHttpSys(options =>   {

                             options.Authentication.AllowAnonymous = false;

                             options.Authentication.Schemes = AuthenticationSchemes.NTLM;

                         })

                            .UseStartup<Startup>();

                });

}


3. Run the Windows service project and access the Hangfire dashboard page from the browser through the below default URL:

http://localhost:5000/hangfire

Sunday, August 19, 2018

Configure Internet Explorer to read static files (Html, CSS, Images, Javascript) from Cache

Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://XploreSqlServer.blogspot.com/
   
Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com

Explore the Top Microsoft Blazor Technical/ Interview Questions here: https://XploreBlazor.blogspot.com/



          The static files like Html, CSS, Images and Java scripts are usually configured to read from Browser cache at the Website. This means that, when the user visits the website for the first time, these files are downloaded from web site and stored in the Temporary Internet folder of windows.
When the user visits the same website subsequently, the static files are loaded from the Temporary Internet folder instead of downloading again from the web site. This would help the user to see the pages getting loaded quickly in the browser.
         When Browser caching is enabled at the website level, browsers like Chrome takes time to load when the users visits the site for the first time and loads quickly for the subsequent times.
          But Internet Explorer always downloads the static files from the website even when browser caching is enabled. This behavior is observed whenever the site is visited through the first instance of Internet explorer. If you visit the same site through an another tab or through an another instance of Internet explorer without closing the first instance, then the static files are loaded from the cache and thus the pages are loaded fast. When the user closes all the instances of Internet explorer and visit the site again using a fresh instance of Internet Explorer, the pages are downloaded again from the website instead of loading from the browser cache.
          This behavior is due the below setting in Internet Explorer:

Internet Options > Advanced tab > Settings > Security > Empty Temporary Internet Files folder when browser is closed.

         Un-check/ deselect the above setting to make the Internet Explorer always load the static files from the browser cache instead of downloading from the website.


Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://XploreSqlServer.blogspot.com/
   
Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com

Friday, November 16, 2012

Add AutoComplete feature to Textbox in ASP.NET MVC using JQuery UI

Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://XploreSqlServer.blogspot.com/
   
Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com

Explore the Top Microsoft Blazor Technical/ Interview Questions here: https://XploreBlazor.blogspot.com/


1. Add a reference to JQuery javascript file and jQuery UI javascript file in the Razor view or in the _Layout.cshtml :


<
script src="jquery-1.8.2.js" type="text/javascript"></script>



<script src="ui/1.9.0/jquery-ui.js" type="text/javascript"></script>


Download the recent version of jQuery and jQuery UI javascript file from here:

jQuery:
http://jquery.com/download/
jQuery UI: http://jqueryui.com/download/

2. Add the following script block in the Razor View:



<
script type="text/javascript">

        $(function () {
          $("#txtCountry").autocomplete({
                source: '@Url.Action("SearchByCaption", "Country")'
         });
                 
        });

</
script>

The above script adds autocomplete feature to a textbox called txtCountry.
As the user types the characters in the textbox,  SearchByCaption method of CountryController is called through jQuery UI scripts. The typed string is passed as the parameter to the method.

3. Implement SearchByCaption action method in CountryController as follows:
public ActionResult SearchByCaption(string term)
{
       CountryBiz countryBiz;
       List<string> list;

       countryBiz = new CountryBiz(); 
       list = countryBiz.SearchByCaption(term);

       return Json(list, JsonRequestBehavior.AllowGet);
}
Important: the parameter of the action method should be named 'term'.

The SearchByCaption method of CountryBiz should perform the pattern search in the Country database table based on the parameter, 'term'.



Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://XploreSqlServer.blogspot.com/

Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com

Wednesday, October 31, 2012

Remove rows from Entity Framework dbSet based on a condition


Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://XploreSqlServer.blogspot.com/
   
Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com

Explore the Top Microsoft Blazor Technical/ Interview Questions here: https://XploreBlazor.blogspot.com/

The following extension method used to remove multiple rows (that satisfies a condition) from a dbSet:

using System;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;

public static class DbSetExtension
{
    public static void Remove<TEntity>(this DbSet<TEntity> dbSet,
             Expression<Func<TEntity, bool>> predicate) where TEntity: class
    {

       foreach (TEntity entity in dbSet.Where(predicate).ToList())
       {
           dbSet.Remove(entity);
       }
    }
}

For example, the extension method can be called as follows:


AppDbContext.ProductFeatures.Remove(prodFeature => prodFeature.ProductId == 1432);

The above method call removes all the rows with ProductId = 1432 from ProductFeatures DbSet.



Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://XploreSqlServer.blogspot.com/
   
Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com




Monday, October 29, 2012

Bind Enum constants to Dropdown control in ASP.NET


Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://XploreSqlServer.blogspot.com/
   
Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com

Explore the Top Microsoft Blazor Technical/ Interview Questions here: https://XploreBlazor.blogspot.com/



The following extension method is used to bind enumerated constants to any ListControls (DropdownList, ListBox etc) in ASP.NET:


using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web.UI.WebControls;

public static class ListControlExtension{
    public static void BindEnum(this ListControl listControl,
                                Type enumType) 
        {
       string caption;
       string value;
       object[] objArray;

       foreach (var enumValue in Enum.GetValues(enumType))    
               {
           // Get the numeric value of enum member
                value ((int)enumValue).ToString(); 

           // Get the DisplayAttribute object of enum member
           objArray = enumType.GetField(enumValue.ToString())
                            .GetCustomAttributes(
typeof(DisplayAttribute),
                            false);            

         // If Display attribute is not specified
          if (objArray.Count() == 0) 
          {
             // just take the enum member text         
             caption = enumValue.ToString(); 

          }
          else         
          {
             // take the DisplayAttribute name of enum member
             caption = ((
DisplayAttribute)objArray.Single()).GetName();            
      }

          listControl.Items.Add(new ListItem(caption, value));
                      objArray =  null;
            }
       }
}

For example, the following Enum constant,

public enum EmploymentStatus{
    Active,
    Resigned,
    Retired,
    [
Display(Name = "Unpaid Long Leave")]
    LongLeave,
         [Display(Name = "Paid Long Leave")] 
    Sabbatical
}


can be bound to a Dropdown control as
     
        ddlDefectStatus.BindEnum(typeof(EmploymentStatus));


Note that the extension method binds the Display attribute's Name property value (if it is provided) to the list control.

The Display attribute is helpful when you want to show a  text other than the enum text. For example, 'Unpaid Long Leave' and 'Paid Long Leave' are shown in the list control instead of LongLeave and Sabbatical respectively.



Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://XploreSqlServer.blogspot.com/
   
Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com

Wednesday, October 24, 2012

Initialize Struct members with default values in C#

Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://XploreSqlServer.blogspot.com/
   
Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com

Explore the Top Microsoft Blazor Technical/ Interview Questions here: https://XploreBlazor.blogspot.com/

C# structs cannot have a default constructor. Writing a default parameter-less constructor would not compile, since there is one already predefined by the compiler.

For example, the following code would result in the compilation error, 'Structs cannot contain explicit parameterless constructors' :

public struct Employee
{
      public int EmpNo;
      public string LastName;
      public string FirstName;
      public DateTime HiredDate;
      public bool IsActive;

      public Employee()      {
                  EmpNo = 0;
        LastName= null;  
        FirstName=null;  
        HiredDate = new DateTime(1,1,1);        
        IsActive = false;      }
}

  The predefined constructor initializes all the members of the struct with its default values according to their types. For example, it initializes numeric types (int, long, float etc) to 0, bool types to false, reference types to null and datetime types to 1/1/0001 12:00:00 AM.

The struct variables are usually declared and used without the new operator since struct is a value type. For example:

public struct Employee
{
      public int EmpNo;
      public string LastName;
      public string FirstName;
      public DateTime HiredDate;
      public bool IsActive;}

Employee emp;
emp.EmpNo = 0;


But to initialize the members with the default values, call the predefined default constructor using the new operator as follows:

emp = new Employee();


The above code initailizes EmpNo to 0, LastName and FirstName to null, HiredDate to 1/1/0001 12:00:00 AM and IsActive to false

An another way to initializes the struct members to their default values, is to use default keyword as follows:

emp = default(Employee);



Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://XploreSqlServer.blogspot.com/
   
Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com

Tuesday, October 23, 2012

Create Custom Display Template for Boolean Datatype in ASP.NET MVC


Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://Xplore2WinSqlServer.blogspot.com/
   
Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com

Explore the Top Microsoft Blazor Technical/ Interview Questions here: https://XploreBlazor.blogspot.com/

The ASP.NET MVC's @Html.DisplayFor method by default displays a disabled checkbox for boolean values.
Inorder to display the text, 'Yes' or 'No' instead of a checkbox, create the custom display template for boolean types as follows:

1. Create a folder called DisplayTemplates under the folder,  ~/Views/Shared.
2. Create a file called Boolean.cshtml to have the following code:

@model System.Boolean?

@if (Model.HasValue)
{

      if (Model.Value)
      {
         <text> Yes </text>
      }

      else
      {
         <text> No </text>
      }
}

else
{
      <text> &nbsp; </text>

}


Explore the Top Microsoft SQLServer Technical/ Interview Questions here: http://Xplore2WinSqlServer.blogspot.com/

Explore the Top Microsoft C# Technical/ Interview Questions here: http://XploreCSharpDotNet.blogspot.com