Programming

TSQL-Split String Using CharIndex

DECLARE @btnID nVarChar(15)=’10_2′;
DECLARE @QID INT, @AID INT;

SET @QID = CAST(LEFT(@btnID, CHARINDEX(‘_’, @btnID) – 1) AS INT);
SET @AID = CAST(RIGHT(@btnID, LEN(@btnID) – CHARINDEX(‘_’, @btnID)) AS INT);

—————————————————————————–
DECLARE @strThis nVarChar(100) = ‘a,b,c,d’;
DECLARE @splitValues TABLE (Value nVarChar(100))

IF (SELECT COUNT(*) FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[STRING_SPLIT]’)) > 0
BEGIN
INSERT INTO @splitValues
SELECT value FROM STRING_SPLIT(@strThis, ‘,’)
END
ELSE
BEGIN
DECLARE @pos INT = CHARINDEX(‘,’, @strThis)
DECLARE @val nVarChar(100)

WHILE @pos > 0
BEGIN
SET @val = LEFT(@strThis, @pos – 1)
INSERT INTO @splitValues
VALUES (@val)

SET @strThis = RIGHT(@strThis, LEN(@strThis) – @pos)
SET @pos = CHARINDEX(‘,’, @strThis)
END

INSERT INTO @splitValues
VALUES (@strThis)
END

SELECT * FROM @splitValues

Single Page ASPX File

<%@ Page Language="C#" AutoEventWireup="true" %>



Single Page ASPX without Code Behind




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);
}

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

Scroll to Top