Author name: EkAdmin

ASP.Net 7 : Using ADO Helper Class in Minimal API/Controller

public class MyController : Controller
{
private readonly ADONetHelper _ado;

public MyController(ADONetHelper ado)
{
_ado = ado;
}

[HttpGet(“/a”)]
public async Task GetData()
{
SqlParameter[] parameters = new SqlParameter[]
{
new SqlParameter(“MobileNo”, “1234”),
new SqlParameter(“FullNo”, “1234”),
new SqlParameter(“TZDiff”, “0”)
};
var jsonData = await _ado.GetDT_SP_Async2(“getHukamnama”, parameters);
return Ok(jsonData);
}
}

app.MapGet(“/a”, async (ADONetHelper ado) =>
{

SqlParameter[] parameters = new SqlParameter[]
{
new SqlParameter(“MobileNo”, “1234”),
new SqlParameter(“FullNo”, “1234”),
new SqlParameter(“TZDiff”, “0”)
};
var jsonData = await ado.GetDT_SP_Async2(“getHukamnama”, parameters);
return jsonData;
});

ADO.NET Helper Class

using Microsoft.Data.SqlClient;
using Newtonsoft.Json;
using System.Data;

namespace EkHukam_Gurudwara.Data
{

public class ADONetHelper
{
private readonly IConfiguration _config;

public ADONetHelper(IConfiguration config)
{
_config = config;
}

public string GetDefaultConnection()
{
return _config.GetConnectionString(“DefaultConnection”);
}
public async Task GetConnStr()
{
return await Task.FromResult(_config.GetConnectionString(“DefaultConnection”));
}

public async Task GetDT_SP_Async(string spName, SqlParameter[] parameters)
{
string connString = GetDefaultConnection();
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand(spName, conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddRange(parameters);
await conn.OpenAsync();
using (SqlDataReader reader = await cmd.ExecuteReaderAsync())
{
DataTable dt = new DataTable();
dt.Load(reader);
return dt;
}
}
}
}

public async Task GetDT_SP_Async2(string spName, SqlParameter[] parameters)
{
string connString = GetDefaultConnection();
string json = “”;
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand(spName, conn))
{
cmd.CommandType = CommandType.StoredProcedure;

if (parameters != null)
{
cmd.Parameters.AddRange(parameters);
}

await conn.OpenAsync();
using (SqlDataReader reader = await cmd.ExecuteReaderAsync())
{
DataTable dt = new DataTable();
dt.Load(reader);
json = JsonConvert.SerializeObject(dt, Formatting.Indented);
return json;
}
}
}
}

public async Task GetTest()
{
return await Task.FromResult(“EkOnkar”);
}

public DataTable getDataTable(string ConnStr, string sql)
{
using (SqlConnection connection = new SqlConnection(ConnStr))
{
connection.Open();
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.CommandType = CommandType.StoredProcedure;
SqlDataAdapter adapter = new SqlDataAdapter(command);
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
return dataTable;
}
}
}

public async Task getDataTableAsync(string ConnStr, string sql)
{
using (SqlConnection connection = new SqlConnection(ConnStr))
{
await connection.OpenAsync();
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.CommandType = CommandType.StoredProcedure;
SqlDataReader reader = await command.ExecuteReaderAsync();
DataTable dataTable = new DataTable();
dataTable.Load(reader);
return dataTable;
}
}

}

}
}

ASP.Net Core7 : Set Global Static Variable For Application Life

public class UserService
{
public int UserId { get; set; }
}

builder.Services.AddSingleton();

public IActionResult Login(string username, string password)
{
// Authenticate the user and get their ID
int userId = …

// Set the UserId in the UserService class
var userService = HttpContext.RequestServices.GetService();
userService.UserId = userId;

return RedirectToAction(“Index”, “Home”);
}

In Controller

public IActionResult Index()
{
var userService = HttpContext.RequestServices.GetService();
var userId = userService?.UserId ?? 0;
ViewData[“userId”] = userId;
return View();
}

public async Task Logout()
{
await HttpContext.SignOutAsync();
var userService = HttpContext.RequestServices.GetService();
if (userService != null)
{
userService.UserId = 0;
}
return RedirectToAction(“Index”, “Hukam”);
}

In View
@using EkHukam_Gurudwara.Data

@{
ViewData[“Title”] = “Dashboard”;

var userService = (UserService)ViewContext.HttpContext.RequestServices.GetService(typeof(UserService));

var @UID = (userService?.UserId ?? 0);
}

Visual Studio : If Dev Env is Slow

Clean the solution: Sometimes, cleaning the solution can resolve performance issues in Visual Studio. To do this, go to Build > Clean Solution.

Reset Visual Studio settings: If your Visual Studio settings have become corrupted, you can reset them to the default settings. To do this, go to Tools > Import and Export Settings > Reset all settings.

Delete the suo file: The suo file is a hidden file that stores Visual Studio settings. Deleting the suo file can help resolve performance issues in Visual Studio. To do this, close Visual Studio, locate the suo file in the solution folder, and delete it.

ASP.Net Core7 , How To Check Run Time Environment (Development/Production) In Controller and view both

In ASP.NET Core, you can check the runtime environment by using the IHostEnvironment interface, which is available in the controller and view.

To check the runtime environment in a controller, you can inject the IHostEnvironment interface into the constructor of the controller and then use the EnvironmentName property to determine the environment. Here is an example:

public class HomeController : Controller
{
private readonly IHostEnvironment _hostEnvironment;

public HomeController(IHostEnvironment hostEnvironment)
{
_hostEnvironment = hostEnvironment;
}

public IActionResult Index()
{
if (_hostEnvironment.IsDevelopment())
{
// Development environment-specific code
}
else if (_hostEnvironment.IsProduction())
{
// Production environment-specific code
}

return View();
}
}

In View (Razor Pages)

@using Microsoft.AspNetCore.Hosting
@inject IHostEnvironment HostEnvironment

Environment: @HostEnvironment.EnvironmentName

When Core-7 MVC Then

@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment hostingEnv
string EnvName = @hostingEnv.EnvironmentName;

VB.NET : XML To JSON

Imports Newtonsoft.Json
Imports System.Xml

Module XMLtoJSON
Sub Main()
‘ Sample XML
Dim xml As String = “NavaFP01004882023-01-307000.00.08050.0S C 10 %700.0C.Gst 2.5 %175.0S.Gst 2.5 %175.0Credit CardSale

‘ Load XML to XmlDocument object
Dim doc As New XmlDocument()
doc.LoadXml(xml)

‘ Convert XmlDocument to Json string
Dim json As String = JsonConvert.SerializeXmlNode(doc)

‘ Print the Json string
Console.WriteLine(json)
Console.ReadLine()
End Sub
End Module

TSQL : Insert XML To Database Table(s)

CREATE TABLE sales (
POSName varchar(255),
BillNo varchar(255),
Date date,
Time datetime,
SubTotal decimal(18,2),
DiscountAmount decimal(18,2),
GrandTotalAmount decimal(18,2),
SettelementMode varchar(255),
TransactionStatus varchar(255)
);

CREATE TABLE taxes (
BillNo varchar(255),
TaxDesciption varchar(255),
TaxAmount decimal(18,2)
);

DECLARE @xml xml = ‘NavaFP01000012022-12-170.00.00.0S C 10 %0.0C.Gst 2.5 %0.0S.Gst 2.5 %0.0NcSale‘;

INSERT INTO sales (POSName, BillNo, Date, Time, SubTotal, DiscountAmount, GrandTotalAmount, SettelementMode, TransactionStatus)
SELECT r.value(‘POSName[1]’, ‘varchar(255)’),
r.value(‘BillNo[1]’, ‘varchar(255)’),
r.value(‘Date[1]’, ‘date’),
r.value(‘Time[1]’, ‘datetime’),
r.value(‘SubTotal[1]’, ‘decimal(18,2)’),
r.value(‘DiscountAmount[1]’, ‘decimal(18,2)’),
r.value(‘GrandTotalAmount[1]’, ‘decimal(18,2)’),
r.value(‘SettelementMode[1]’, ‘varchar(255)’),
r.value(‘TransactionStatus[1]’, ‘varchar(255)’)
FROM @xml.nodes(‘/Records/Record’) AS t(r);

INSERT INTO taxes (BillNo, TaxDesciption, TaxAmount)
SELECT r.value(‘BillNo[1]’, ‘varchar(255)’),
t.value(‘TaxDesciption[1]’, ‘varchar(255)’),
t.value(‘TaxAmount[1]’, ‘decimal(18,2)’)
FROM @xml.nodes(‘/Records/Record’) AS t(r)
CROSS APPLY t.r.nodes(‘Taxes/Tax’) AS x(t);

Calling

Imports System.Data.SqlClient

Module Module1
Sub Main()
Dim con As SqlConnection = New SqlConnection(“Data Source=(local);Initial Catalog=TestDB;Integrated Security=True”)
con.Open()
Dim cmd As SqlCommand = New SqlCommand(“sp_InsertXMLData”, con)
cmd.CommandType = CommandType.StoredProcedure
Dim xmlData As String = “NavaFP01000012022-12-170.00.00.0S C 10 %0.0C.Gst 2.5 %0.0S.Gst 2.5 %0.0NcSale
cmd.Parameters.AddWithValue(“@xmlData”, xmlData)
Dim reader As SqlDataReader = cmd.ExecuteReader()
While reader.Read()
Console.WriteLine(reader(0).ToString())
End While
reader.Close()
con.Close()
End Sub
End Module

Alternate

CREATE PROCEDURE usp_InsertRecord (@xmlData XML)
AS
BEGIN
DECLARE @POSName VARCHAR(50)
DECLARE @BillNo VARCHAR(50)
DECLARE @Date DATE
DECLARE @Time TIME
DECLARE @SubTotal DECIMAL(18, 2)
DECLARE @DiscountAmount DECIMAL(18, 2)
DECLARE @GrandTotalAmount DECIMAL(18, 2)
DECLARE @SettelementMode VARCHAR(50)
DECLARE @TransactionStatus VARCHAR(50)

— extract values from the XML
SELECT @POSName = T.c.value(‘POSName[1]’, ‘VARCHAR(50)’),
@BillNo = T.c.value(‘BillNo[1]’, ‘VARCHAR(50)’),
@Date = T.c.value(‘Date[1]’, ‘DATE’),
@Time = T.c.value(‘Time[1]’, ‘TIME’),
@SubTotal = T.c.value(‘SubTotal[1]’, ‘DECIMAL(18, 2)’),
@DiscountAmount = T.c.value(‘DiscountAmount[1]’, ‘DECIMAL(18, 2)’),
@GrandTotalAmount = T.c.value(‘GrandTotalAmount[1]’, ‘DECIMAL(18, 2)’),
@SettelementMode = T.c.value(‘SettelementMode[1]’, ‘VARCHAR(50)’),
@TransactionStatus = T.c.value(‘TransactionStatus[1]’, ‘VARCHAR(50)’)
FROM @xmlData.nodes(‘/Record’) T(c)

— insert values into the Sales table
INSERT INTO Sales (POSName, BillNo, Date, Time, SubTotal, DiscountAmount, GrandTotalAmount, SettelementMode, TransactionStatus)
VALUES (@POSName, @BillNo, @Date, @Time, @SubTotal, @DiscountAmount, @GrandTotalAmount, @SettelementMode, @TransactionStatus)

DECLARE @TaxId INT
SELECT @TaxId = SCOPE_IDENTITY()

— insert values into the Taxes table
INSERT INTO Taxes (SalesId, TaxDesciption, TaxAmount)
SELECT @TaxId, T1.c1.value(‘TaxDesciption[1]’, ‘VARCHAR(50)’), T1.c1.value(‘TaxAmount[1]’, ‘DECIMAL(18, 2)’)
FROM @xmlData.nodes(‘/Record/Taxes/Tax’) T1(c1)
END

Scroll to Top