Programming

C# : Calculate Document Hash

using System;
using System.IO;
using System.Security.Cryptography;

namespace ReadDocumentHashExample
{
class Program
{
static void Main(string[] args)
{
string documentPath = “document.txt”;
string documentHash = CalculateDocumentHash(documentPath);
Console.WriteLine(“The hash of the document is: ” + documentHash);
}

static string CalculateDocumentHash(string documentPath)
{
using (SHA256 sha256 = SHA256.Create())
{
using (FileStream stream = File.OpenRead(documentPath))
{
byte[] hash = sha256.ComputeHash(stream);
return BitConverter.ToString(hash).Replace(“-“, “”).ToLowerInvariant();
}
}
}
}
}

Generic Handler: Response Immediately And Run DB Operation in Background

To respond to a request immediately and run code in the background without a callback, you can use asynchronous programming in ASP.NET. The basic idea is to return a response to the client as soon as possible, while allowing the code inside the API endpoint to run asynchronously on a background thread.

Here’s an example of how you can modify your code to achieve this:

Public Class updMsg : Inherits HttpTaskAsyncHandler

Private PhysicalPathOfThisFolder$
Private Const LogTitle$ = “updMsg”
Private ThisContext As HttpContext
Private IsDevEnv As Boolean = True
Dim EkConnStr$ = “”

Public Overrides Async Function ProcessRequestAsync(ByVal context As HttpContext) As Task
ThisContext = context
context.SkipAuthorization = True
context.Response.ContentType = “text/plain”
PhysicalPathOfThisFolder = context.Server.MapPath(“.”)
EkConnStr = ConfigurationManager.ConnectionStrings(“EkConnStrWA”).ConnectionString
Dim jsn$ = “”, Rtn$ = “done”
Dim err$ = “”
Dim Rdr As New StreamReader(ThisContext.Request.InputStream)
jsn = Rdr.ReadToEnd ‘jsn = File.ReadAllText(“d:\ekmailjson.txt”)
Await AddToLogAsync(jsn)

context.Response.ContentType = “text/json”
context.Response.Write(Rtn)

Try
Await Task.Run(Async Function()
Using con As New SqlConnection(EkConnStr)
Dim Qry$ = “insMsg”
Using cmd As New SqlCommand(Qry, con)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.AddWithValue(“@JSON”, jsn)
Using sda As New SqlDataAdapter(cmd)
Using dt As New DataTable()
Await Task.Run(Function() sda.Fill(dt))
If dt.Rows.Count > 0 Then
Dim sts = dt.Rows(0).Item(“sts”)
err = dt.Rows(0).Item(“errMsg”)
If sts = “done” Then
Dim MsgTo$ = dt.Rows(0).Item(“MsgTo”)
‘Rtn = GetMsgReturn(MsgTo)
Rtn = dt.Rows(0).Item(“jsn”)
Await AddToLogAsync(Rtn)
End If
Else
err = “No Rec Found”
End If
End Using
End Using
End Using
End Using
End Function)
Catch ex As Exception
Err = ex.Message.ToString + vbCrLf + ex.StackTrace.ToString
Finally

End Try

If err <> “” Then
Await AddToLogAsync(err)
End If
End Function
End Class

In this example, the response is immediately returned to the client using context.Response.Write(Rtn). The code inside the Try block is then executed asynchronously on a background thread

Generic Handler (ASHX) : Add To Log Function Async

Private Async Function AddToLogAsync(ByVal LogData$) As Task
Dim retryCount As Integer = 0
While retryCount < 5 Try Using writer As StreamWriter = File.AppendText(PhysicalPathOfThisFolder & "/updMsg.log") Await writer.WriteLineAsync(LogData) End Using ' If no exception was thrown, break the loop Exit While Catch ex As Exception If TypeOf ex Is IOException AndAlso ex.Message.Contains("being used by another process") Then ' File is locked, wait and retry Await Task.Delay(100) retryCount += 1 Else ' Log the exception Await AddToLogAsync("Error: " & ex.Message & vbCrLf & ex.StackTrace) ' If this is not a file locking exception, break the loop Exit While End If End Try End While End Function

TSQL : Set Line Breake on String

In TSQL, you can add line breaks to a string by using the CHAR(13) or CHAR(10) character.

For example, the following code will create a string with line breaks:

DECLARE @text AS VARCHAR(MAX) = ‘Line 1’ + CHAR(13) + ‘Line 2’ + CHAR(10) + ‘Line 3′
SELECT @text

The CHAR(13) character represents a Carriage Return (CR) and the CHAR(10) character represents a Line Feed (LF). When used together, they create a line break.

Alternatively, you can use the NCHAR function to add Unicode characters, for example:

DECLARE @text AS NVARCHAR(MAX) = N’Line 1′ + NCHAR(13) + N’Line 2′ + NCHAR(10) + N’Line 3’
SELECT @text

TSQL : Chk If Valid JSON

You can use the ISJSON function in T-SQL to check if a string is a valid JSON string. The ISJSON function returns 1 if the input string is a valid JSON string and 0 if it is not. Here is an example of how you can use the ISJSON function:

DECLARE @Json NVARCHAR(MAX) = ‘{
“id”: “2”,
“body”: “Media Msg”
}’

IF ISJSON(@Json) = 1
BEGIN
PRINT ‘Valid JSON’
END
ELSE
BEGIN
PRINT ‘Invalid JSON’
END

In this example, the ISJSON function is used to check if the string stored in the @Json variable is a valid JSON string. If the string is valid, the PRINT statement outputs “Valid JSON”. If the string is not valid, the PRINT statement outputs “Invalid JSON”.

VB6 : Read Date Time Format Of Login User

Option Explicit

Private Declare Function GetLocaleInfo Lib “kernel32” Alias “GetLocaleInfoA” (ByVal Locale As Long, ByVal LCType As Long, ByVal lpLCData As String, ByVal cchData As Long) As Long
Private Const LOCALE_USER_DEFAULT As Long = &H400
Private Const LOCALE_SSHORTDATE As Long = &H1F

Private Sub Form_Load()
Dim sDateFormat As String
Dim lRet As Long

sDateFormat = Space$(255)
lRet = GetLocaleInfo(LOCALE_USER_DEFAULT, LOCALE_SSHORTDATE, sDateFormat, Len(sDateFormat))
If lRet > 0 Then
sDateFormat = Left$(sDateFormat, lRet – 1)
MsgBox “The short date format is: ” & sDateFormat
Else
MsgBox “Failed to retrieve the short date format.”
End If
End Sub

Scroll to Top