Executing Raw SQL Queries using EF Core

Here are some methods;

DbSet.FromSqlRaw

The DbSet.FromSqlRaw method (DbSet.FromSql prior to Entity Framework Core 3.0) enables you to pass in a SQL command to be executed against the database to return instances of the type represented by the DbSet:

public class Book
{
    public int BookId { get; set; }
    public string Title { get; set; }
    public Author Author { get; set; }
    public int AuthorId{ get; set; }
    public string Isbn { get; set; }
}
...
public class SampleContext : DbContext
{
    public DbSet<Book> Books { get; set; }
}
using (var context = new SampleContext())
{
    var books = context.Books.FromSqlRaw("SELECT BookId, Title, AuthorId, Isbn FROM Books").ToList();
}

The DbSet must be included in the model (i.e. it can not be configured as Ignored). All columns in the target table that map to properties on the entity must be included in the SQL statement. The column names must match those that the properties are mapped to. Property names are not taken into account when the results are hydrated into instances of the entity.

If any columns are missing, or are returned with names not mapped to properties, an InvalidOperationException will be raised .

Parameterized Queries

It’s always advised to parameterize user input to prevent the possibility of a SQL injection attack being successful. Entity Framework Core will parameterize SQL if you use format strings with FromSqlRaw or string interpolation with the FromSqlInterpolated method:

// Format string
var author = db.Authors.FromSqlRaw("SELECT * From Authors Where AuthorId = {0}", id).FirstOrDefault();
// String interpolation
var author = db.Authors.FromSqlInterpolated($"SELECT * From Authors Where AuthorId = {id}").FirstOrDefault();

Both of these approaches result in the following SQL being generated;

SELECT "a"."AuthorId", "a"."FirstName", "a"."LastName"
FROM (
    SELECT * From Authors Where AuthorId = @p0
) AS "a"
LIMIT 1

Entity Framework Core will only parameterize format strings if they are supplied inline to the FromSqlRaw method call. Format strings declared outside of the FromSqlRaw method call will not be parsed for parameter placeholders. In effect, you will be passing a concatenated string directly to the database, which is a SQL injection risk.

The following example is dangerous and should not be used:

var sql = string.Format("SELECT * From Authors Where AuthorId = {0}", id);
var author = db.Authors.FromSqlRaw(sql).FirstOrDefault(); 

The generated SQL is unparameterized:

SELECT "a"."AuthorId", "a"."FirstName", "a"."LastName"
FROM (
  SELECT * From Authors Where AuthorId = 2
) AS "a"
LIMIT 1

Stored Procedures

The SQL command can be any valid SQL statement that returns all the required fields of data. It is possible to call stored procedures via the FromSqlRaw method:

using (var context = new SampleContext())
{
    var books = context.Books
        .FromSqlRaw("EXEC GetAllBooks")
        .ToList();
}

It is also possible to pass in values to named parameters:

using (var context = new SampleContext())
{
    var authorId = new SqlParameter("@AuthorId", 1);
    var books = context.Books
        .FromSqlRaw("EXEC GetBooksByAuthor @AuthorId" , authorId)
        .ToList();
}

Non-Entity Types and Projections

In versions of EF Core prior to 2.1, it is not possible to use the FromSqlRaw method to return a subset of properties (a projection) directly from the database. Using the Books DbSet above as an example, the following will not work:

using(var context = new SampleContext())
{
    var books = context.Books.FromSqlRaw("SELECT BookId, Title FROM Books").ToList();
}

You must project the result of the FromSqlRaw method call to return a subset of properties:

using(var context = new SampleContext())
{
    var books = context.Books
        .FromSql("SELECT * FROM Books")
        .Select(b => new {
            BookId = b.BookId,
            Title = b.Title 
            }).ToList();
}

However, this may prove inefficient as all columns from the mapped table will be returned by the FromSql method call.

Support for returning ad hoc (not DbSet) types from direct SQL calls is possible from EF Core 2.1.

Database.ExecuteSqlCommand

The DbContext exposes a Database property which includes a method called ExecuteSqlCommand. This method returns an integer specifying the number of rows affected by the SQL statement passed to it. Valid operations are INSERTUPDATE and DELETE. The method is not used for returning entities.

using(var context = new SampleContext())
{
    var commandText = "INSERT Categories (CategoryName) VALUES (@CategoryName)";
    var name = new SqlParameter("@CategoryName", "Test");
    context.Database.ExecuteSqlCommand(commandText, name);
}

Note: You will need to add using Microsoft.Data.SqlClient; to make the SqlParameter type available to your code.

The ExecuteSqlCommand method can also be used to execute stored procedures:

using(var context = new SampleContext())
{
    var name = new SqlParameter("@CategoryName", "Test");
    context.Database.ExecuteSqlCommand("EXEC AddCategory @CategoryName", name);
}

Leveraging ADO.NET via the Context.Database property

In addition to the ExecuteSqlCommand method, the DbContext.Database property provides an API that allows you to perform ADO.NET operations directly. The GetDbConnection method returns a DbConnection object representing the context’s underlying connection. From that point, you can revert to the familiar ADO.NET APIs:

using (var context = new SampleContext())
using (var command = context.Database.GetDbConnection().CreateCommand())
{
    command.CommandText = "SELECT * From Table1";
    context.Database.OpenConnection();
    using (var result = command.ExecuteReader())
    {
        // do something with result
    }
}

EF CORE..

Get file path in .net core from wwwroot folder

This is how;

public class HomeController : Controller {
    private IWebHostEnvironment _hostEnvironment;

    public HomeController(IWebHostEnvironment environment) {
        _hostEnvironment = environment;
    }

    [HttpGet]
    public IActionResult Get() {
        string path = Path.Combine(_hostEnvironment.WebRootPath, "Sample.PNG");
        return View();
    }
}

References

https://weblog.west-wind.com/posts/2020/Feb/26/Working-with-IWebHostEnvironment-and-IHostingEnvironment-in-dual-targeted-NET-Core-Projects#out-with-old-in-with-the-new-iwebhostenvironment

Decode JWT Token

Decoding JWT token and return value;

protected string GetCalimValue(string token)
{
   var handler = new JwtSecurityTokenHandler();
   var jsonToken = handler.ReadToken(token);
   var tokenJWT = jsonToken as JwtSecurityToken;
   //var jwtSecurityToken = handler.ReadJwtToken(token);

   var jti = tokenJWT.Claims.First(claim => claim.Type == "jti").Value;
   return jti;
}

Validating and Decoding JWT Token and return value;

protected string ValidateTokenAndGetClaimValue(string token)
{
    string secret = "this is a string used for encrypt and decrypt token";
    var key = Encoding.ASCII.GetBytes(secret);
    var handler = new JwtSecurityTokenHandler();
    var validations = new TokenValidationParameters
    {
        ValidateIssuerSigningKey = true,
        IssuerSigningKey = new SymmetricSecurityKey(key),
        ValidateIssuer = false,
        ValidateAudience = false
    };
    var claims = handler.ValidateToken(token, validations, out var tokenSecure);

    var tokenJWT = tokenSecure as JwtSecurityToken;
    var emailAddress = tokenJWT.Claims.First(claim => claim.Type == "email").Value;
    return emailAddress;
}

We want to keep token inside cookies on a successful token acquisition;

Response.Cookies.Append("X-Access-Token", login.JwToken, new CookieOptions() { HttpOnly = true, SameSite = SameSiteMode.Strict });
Response.Cookies.Append("X-Email", login.Email, new CookieOptions() { HttpOnly = true, SameSite = SameSiteMode.Strict });

References

https://stackoverflow.com/questions/38340078/how-to-decode-jwt-token

https://www.codemag.com/Article/2105051/Implementing-JWT-Authentication-in-ASP.NET-Core-5

Search string array in collection using LINQ

LINQ behavior is that LINQ wouldn’t return null when results are empty rather it will return an empty enumerable. We can check this with .Any() method;

if (!YourResult.Any())

This is a LinqPad example;

var lst = new List<int>() { 1, 2, 3 };
var ans = lst.Where( i => i > 3 );

(ans == null).Dump();  // False
(ans.Count() == 0 ).Dump();  // True

Let’s go through another example where I have this string array to search;
{“dog”,”cat”};

in this string;
“This is a string and may or may not contain a word we are looking for like cat”

string input = "This is a string and may or may not contain a word we are looking for like cat";
List<string> search = new List<string>() { "dog", "cat"};
bool found = input.Split(' ').Any(x => search.Contains(x));

It works like this: the string gets split into an array of words. Then Any checks whether there is an x in this array where search.Contains(x).

Enumerable.Any(TSource) Method (IEnumerable(TSource)) (System.Linq)

Reference

What does linq return when the results are empty

Find all items in list which exist in another list using linq

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";