Hide/Show Div with javascript

To display and hide DIV in html;

<div class="card-body">
   <div id="divMessage">                
        @Html.Raw(@TempData["message"]);
    </div>
    </div>  
    <div> 
       <!--need to hide this form-->         
       <form method="post" asp-antiforgery="true" id="formDiv">
          <div class="card mb-3">
             <h5 class="card-header text-white">
                  Welcome To Div Hide/Display
             </h5>
        </form>
    </div>
</div>

Use this javascript;

@section Scripts
{
  <script>
     $(document).ready(function () {
            //show/hide login sections based on SSO
            divFormSection();
        });

        function divFormSection() {
            var isDivFormVisible = '@TempData["IsDivFormVisible"]';
            if (isDivFormVisible == 'false') {
                //alert(isDivFormVisible);
                $("#formDiv").hide();
            }
        }
     }
    </script>
}

We need to pass parameters from controller in TempData;

TempData["message"] = "Form Hide/Display demo";
TempData["IsDivFormVisible"] = "false";

Use TempData or ViewBag to render HTML

This is a very basic example;

Declare this in a controller.

var fontAwesomeIcon = "<span class=\"fa fa-redo\" style=\"font-size:30px; color: red; margin-bottom: 20px; \">&nbsp;Try again</span>";

TempData["message"] = $"{fontAwesomeIcon} <h5>Something went wrong. Please try again. If problem persist, reach out to your point of contact for additional information</h5>";

And you can use it in your view;

<div class="card-body">
  <div id="divMessage">
     @Html.Raw(@TempData["message"]);
  </div>
</div>            

Return values from HttpContext.Current.User.Principal and WindowsIdentity.GetCurrent()

Here is a brief explanation;

According to this forum on WindowsIdentity.GetCurrent().Name vs. User.Identity.Name:

  • User.Identity.Name represents the identity passed from IIS.
  • WindowsIdentity.GetCurrent().Name is the identity under which the thread is running.

Depending on your app’s authentication settings in IIS, they will return different values:

AnonymousImpersonateUser.Identity.NameWindowsIndentiy.GetCurrent()
YesTrueEmpty StringIUSR_<machineName>
YesFalseEmpty StringNT Authority\Network Service
NoTruedomain\userdomain\user
NoFalsedomain\userNT Authority\Network Service

Legend:

  • Where domain\user will show up as:
    • domain\user for Active Directory
    • machineName\userName for local account
  • Where NT Authority\Network Service will show up as:
    • NT Authority\Network Service for Windows Server or ASP.NET
    • machineName\ASPNET_WP for Windows XP

Resource

https://stackoverflow.com/questions/5402249/httpcontext-current-user-principal-vs-windowsidentity-getcurrent

Access to XMLHttpRequest from origin has been blocked by CORS policy…

I did a Web API deployment in Azure Web API service. I was able to access the URL in browser and Postman. I started getting following error when I try to integrate in ASP.NET Web App in my local development environment;

Access to XMLHttpRequest at ‘https://xyz-dev.azurewebsites.net/api/Authentication/GetTestUser?name=testuser’ from origin ‘http://localhost:17686’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

jquery.js:9172          GET https://xyz-dev.azurewebsites.net/api/Authentication/GetTestUser?name=testuser net::ERR_FAILED

To solve the problem, I did this;

Here is server-side (Web API) code;

Add following to Web API ConfigureServices method;

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(op =>
    {
       op.AddPolicy("AllOrigin", builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
    });
}

Add following to Web API Configure method;

public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
      //-------use cords
      app.UseCors("AllOrigin");
}

Here is client-side AJAX call.

<input type="button" id="btnWebApiCall" name=" btnWebApiCall" value="Test CORS" class=" btn btn-primary btn-lg justify-content-center" />

@section Scripts
    {

    <script>

        $(document).ready(function () {

            $("#btnAuthenticateSSO").click(function (e) {
                e.preventDefault();
                $.ajax({
                    type: "GET",
                    url: "https://xyzapi-dev.azurewebsites.net/api/Authentication/GetTestUser?name=testuser",
                    contentType: "application/json; charset=utf-8",
                    //crossDomain: true,
                    dataType: "json",
                    success: function (data, status, xhr) {
                        alert(JSON.stringify(data));
                        console.log(data);
                    }, //End of AJAX Success function
                    error: function (xhr, status, error) {
                        alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText);
                    } //End of AJAX error function

                });
            });

        });

    </script>

}

The pain is gone.

If interested in learning more about this, read below;

Researched and figured out that browser sends two requests to the server. Tiny request and actual request.

The browser sends a tiny request called a preflight request before the actual request. It includes details such as the HTTP method used and whether any custom HTTP headers are present. The preflight allows the server to see how the actual request would appear before it is sent. The server will then tell the browser whether or not to submit the request, or whether to return an error to the client instead.

See below for problem header without CORS and with CORS in web API;

Headers without CORS implementation in Web API (Problem);

Headers with CORS implementation in Web API (Problem solved);

A simple Get request make these two requests;

Resources

https://medium.com/easyread/enabling-cors-in-asp-net-web-api-4be930f97a5c

https://stackoverflow.com/questions/31942037/how-to-enable-cors-in-asp-net-core

How .NET and SQL Server Handle Dates and Times

.NET and SQL Server have always come up short when it comes to handling date and time data. To be fair, most other languages and databases do as well. Although there have always been ways to cover the inadequacies, the work-arounds have always felt clumsy to me. We deal with them so often in our daily lives to the point that they seem rather simple and intuitive to us, yet dates and times are complicated concepts. Initially, both .NET and SQL Server set out to handle some of the most complicated aspects for us, each with its own DateTime data type.

Read more Here.

https://codemag.com/Article/2203041/.NET-6-Date-and-Time?utm_source=Knowbility3.9.2022&utm_medium=newsletter&utm_campaign=sm-articles