jQuery selector change not firing

I like to fire a change event when “#btnBrowse” click event fires. Here is a sample jQuery code;

$("#btnBrowse").click(function () {
   $("#btnReset").click();
   $("#xFileUpload").click();
});

$("#xFileUpload").change(function () {
   var filename = $('#xFileUpload')[0].files[0].name;
   filename = filename.replace(/\.[^/.]+$/, "");
   //alert(filename);
   $("#xFilename").val(filename);
   fileDoc.fileName = filename;
   fileDoc.fileContnet = $("#xFileUpload").get(0).files;
 });

It turns out that click event will be registered and fired on first click only. For subsequent clicks, I have to registered a change event and triggered it like this;

$("#btnBrowse").click(function () {
   $("#btnReset").click();
   $("#xFileUpload").click().trigger("change");
});

The cons of using this approach. It will work fine for the first click but all subsequent clicks will fire a change event on click event. The reason jQuery has registered two events for the element and execute them simultaneously.

The objective is to grab file from file system. The user should be able to use same file multiple time. The best alternative to achieve this objective is to clear the contents of HTML input type rather tweaking jQuery;

This is HTML file input;

<input type="file" id="xFileUpload" name="xFileUpload" class="form-control" style="display: none" />

This is jQuery code that will clear contents of this file;

$("#btnImportReset").click(function () {
   $('#xFileUpload').val('');
});

This is your final browse script section;

$("#btnBrowse").click(function () {
   $("#btnReset").click();
   $("#xFileUpload").click();
});

Since we are clearing out HTM contents and jQuery is smart enough to figure out change. The change event will be fired this time automatically with a change in HTML file input.

Resources

https://stackoverflow.com/questions/19194177/jquery-select-change-not-firing

https://stackoverflow.com/questions/4247264/how-to-trigger-jquery-change-event-in-code

Incoming Client certificate in Azure App Service?

When we enable client certificate on Azure web site, this is the window that pops up in the browser when user try to connect to app;

When user click on Certificate information, he get following window;

Where is this certificate? How did I got this? Our environment is not AD joined. The certificate seems to be issued by AD domain server “MS-Organization-Access”.

The problem started when one of my developer asked me that he is not able to connect to App. The browser doesn’t show any certificate and he keep getting this error;

Error 403: Forbidden: Client Certificate Required

Apple clients are getting the same error.

We are not using any code to manipulate or validate certificates. It’s merely a setting thing in Azure.

Eventually, switch the mode of incoming client certificates to Allow so that my team can connect to Apps in Azure.

What are the differences between “Allow” and “Require” for Client certificate modes in App Service general settings?

All paths should not require client certificate, just /secure one require client certificate

• Ignore: This setting does not accept client certificates if presented.
• Accept: Select this setting if you want to accept client certificates (if it’s presented) but will also continue with connections where the client doesn’t present one.
• Require: Select this option to require that certificates verify client identity.

For the exclusion path the document does mention -‘To allow certain paths to remain open for anonymous access. If we add /public to the path, anything under /public path for the application would not request a client certificate.

Compliance

There are 6 standards that are applicable to this policy:

  • APRA (CPS 234) Information Security
  • Multi-Level Protection Scheme (MLPS) v2.0
  • NIST 800-53 Rev 5
  • NIST 800-53 Rev4
  • CIS v1.1 (Azure)
  • CIS v1.2.0 (Azure)

jQuery click event on view load

This is how to fire jQuery event on ASP.NET Core MVC view load;

HTML

<div class="container">
    <div class="nav">
        <ul id="menu">
            <li id="link1"><a href="#">Topic One</a></li>
            <li id="link2"><a href="#">Topic Two</a></li>
            <li id="link3"><a href="#">Topic Three</a></li>
        </ul>
    </div>
    <div class="main">
        <div id="page1" class="content">
            <h1>Page 1</h1>
            <p>First section of content.</p>
        </div>
        <div id="page2" class="content">
            <h1>Page 2</h1>
            <p>Second section of content</p>
        </div>
        <div id="page3" class="content">
            <h1>Page 3</h1>
            <p>Third section of content.</p>
        </div>
    </div>
</div>

jQuery

<script type="text/javascript">
    $('#menu a').click(function (e) {
        hideContentDivs();
        var tmp_div = $(this).parent().index();
        $('.main div').eq(tmp_div).show();
    });

    function hideContentDivs() {
        $('.main div').each(function () {
            $(this).hide();
        });
    }
    hideContentDivs();

    //fire this event on view load
    $(function () {
        $('#menu li a:first').click();
    });

</script>

This function does the auto click on view load;

$(function () {
    $('#menu li a:first').click();
});

Resources;

https://forum.jquery.com/topic/menu-links-show-hide-content-in-another-div

https://stackoverflow.com/questions/7468950/execute-click-event-on-load

AutoMapper in ASP.NET Core

How to keep a separation between domain models and view models and let them exchange data in an easier and simple way? We write code that allows us to map domain model into view model. As we add more views and domain models, we end up writing more mappers. We write mappers to map domain transfer objects from database layer into domain objects.

This practice is repetitive. AutoMapper solve this problem. It’s a convention-based object-to-object mappers.

We are going to use these NuGet packages for ASP.NET Core 2.1;

AutoMapper.Extensions.Microsoft.DependencyInjection		v3.1.0
Microsoft.Extensions.DependencyInjection.Abstractions		v3.1.0

For ASP.NET Core V2.1, we will need at least V3..0.1 of AutoMapper.Extensions.Microsoft.DependencyInjection. This package will install AutoMapper package automatically.

Configure AutoMapper in Startup.cs class under ConfigureServices method;

//Auto mapper configuration
services.AddAutoMapper();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

The above single line works fine but If we want to explicit in configuration, the alternative is;

var mapperConfig = new MapperConfiguration(mc =>
{
    mc.AddProfile(new MappingProfile());
});
IMapper mapper = mapperConfig.CreateMapper();
services.AddSingleton(mapper);
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

AutoMapper in Action

Create a user model in Model folder.

public class User
{
  public User(int id, string firstName, string lastName, string emailAddress)
  {
            Id = id;
            FirstName = firstName;
            LastName = lastName;
            EmailAddress = emailAddress;
  }

        public int Id { get; }
        public string FirstName { get; }
        public string LastName { get; }
        public string EmailAddress { get; }
}

Create a view model in Model folder that will be used to display User data.

public class UserViewModel

{
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string EmailAddress { get; set; }
 }

We need to tell AutoMapper to map from User Model to User View Model. For that we will use Profile. Profiles in AutoMapper are a way of organizing mapping collections. To create Profile, We create a new class and inherit from Profile. This class will hold mapping configuration of new classes.

public class MappingProfile : Profile
{
        public MappingProfile()
        {
            CreateMap<User, UserViewModel>();
            CreateMap<UserViewModel, User>();
        }
}

The same profile can be created like this;

public class MappingProfile : Profile
{
        public MappingProfile()
        {
            CreateMap<User, UserViewModel>().ReverseMap();
        }
}

We now have a MappingProfile class that creates the mapping between our User Model and User ViewModel. But how does AutoMapper know about our UserProfile class? Well, towards the start of this example we added this line of code to our ConfigureServices method in Startup.cs:

services.AddAutoMapper();

When our application starts up and adds AutoMapper, AutoMapper will scan our assembly and look for classes that inherit from Profile, then load their mapping configurations. I also have an alternative explicit implementation in startup class if you prefer.

Let’s create a new UserController in the Controllers folder and inject the IMapper interface into the constructor:

public class UserController : Controller
{
        private readonly IMapper _mapper;
        public UserController(IMapper mapper)
        {
            _mapper = mapper;
        }

        public IActionResult Index()
        {
            return View();
        }
}

As with Profiles, by calling AddAutoMapper in our Startup.cs ConfigureServices method, it’s taken care of registering IMapper for us. In Index Action method, let’s create a User object and use IMapper interface to call the Map method:

We give the Map method the type we want to map to and the object we would like to map from:

public IActionResult Index()
{
            var user = new User(1, "Shahzad", "Khan", "shahzad@msn.com");
            UserViewModel viewModel = _mapper.Map<UserViewModel>(user);
            return View(viewModel);
}

Finally create the view;

@model UserViewModel

@{
    ViewData["Title"] = "Index";
}

<h2>Index</h2>

<div>
    <h4>UserViewModel</h4>
    <hr />
    <dl class="dl-horizontal">
        <dt>
            @Html.DisplayNameFor(model => model.Id)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.Id)
        </dd>
        <dt>
            @Html.DisplayNameFor(model => model.FirstName)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.FirstName)
        </dd>
        <dt>
            @Html.DisplayNameFor(model => model.LastName)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.LastName)
        </dd>
        <dt>
            @Html.DisplayNameFor(model => model.EmailAddress)
        </dt>
        <dd>
            @Html.DisplayFor(model => model.EmailAddress)
        </dd>
    </dl>
</div>
<div>
    @Html.ActionLink("Edit", "Edit", new { /* id = Model.PrimaryKey */ }) |
    <a asp-action="Index">Back to List</a>
</div>

Here is the page;

We just scratched the surface of what AutoMapper has to offer in terms of mapping objects from one to another.

Summary

First, you need both a source and destination type to work with. The destination type’s design can be influenced by the layer in which it lives, but AutoMapper works best as long as the names of the members match up to the source type’s members. If you have a source member called “FirstName”, this will automatically be mapped to a destination member with the name “FirstName”. AutoMapper also supports Flattening, which can get rid of all those pesky null reference exceptions you might encounter along the way.

Once you have your types, and a reference to AutoMapper, you can create a map for the two types.

CreateMap<User, UserViewModel>().ReverseMap();

The type on the left is the source type, and the type on the right is the destination type. To perform a mapping, use the Map method.

var userEntity = await _unitOfWork.GetAllUsersAsync();
List<UserViewModel> vm = Mapper.Map<List<UserViewModel>>(userEntity.Result);

References

https://docs.automapper.org/en/stable/Getting-started.html

https://automapper.org/

https://jimmybogard.com/

https://stackoverflow.com/questions/40275195/how-to-set-up-automapper-in-asp-net-core

https://stackoverflow.com/questions/50411188/trying-to-add-automapper-to-asp-net-core-2

https://stackoverflow.com/questions/13479208/automapper-auto-map-collection-property-for-a-dto-object/13499361

https://stackoverflow.com/questions/52218340/automapper-projectto-adds-tolist-into-child-properties

https://code-maze.com/automapper-net-core/