Thứ Năm, 5 tháng 9, 2024

How does Entity Framework Core open and close the SqlConnection?

Entity Framework Core manages the SqlConnection lifecycle internally, ensuring that connections are opened and closed as needed. Here's a detailed explanation of how this process works:

Opening the Connection

Entity Framework Core opens the connection in a lazy manner, meaning it opens the connection only when it is needed. This typically happens in the following scenarios:

  • Query Execution: When a query is executed against the database.
  • Save Changes: When changes are saved to the database using context.SaveChanges().
  • Explicit Opening: When you explicitly open the connection using context.Database.OpenConnection().

Closing the Connection

Entity Framework Core closes the connection automatically when it is no longer needed. This typically happens in the following scenarios:

  • After Query Execution: The connection is closed after the query results are retrieved.
  • After Save Changes: The connection is closed after the changes are saved to the database.
  • Disposing the DbContext: The connection is closed when the DbContext is disposed, which usually happens at the end of a using block or when the DbContext is explicitly disposed.
  • Explicit Closing: When you explicitly close the connection using context.Database.CloseConnection().

Example Code

Here is an example demonstrating how Entity Framework Core manages the connection lifecycle:

Best Practices

  • Using using Statement: Always use the using statement to ensure that the DbContext is disposed properly, which in turn ensures that the connection is closed.
  • Avoid Explicit Management: Let Entity Framework Core manage the connection lifecycle unless you have a specific reason to manage it manually.

Internals

Internally, Entity Framework Core uses the DbConnection object to manage the connection. Here is a simplified view of what happens:

  1. Query Execution:

    • Entity Framework Core checks if the connection is open.
    • If the connection is not open, it opens the connection.
    • Executes the query.
    • Closes the connection if it was opened by Entity Framework Core.
  2. Save Changes:

    • Entity Framework Core checks if the connection is open.
    • If the connection is not open, it opens the connection.
    • Saves the changes.
    • Closes the connection if it was opened by Entity Framework Core.

By following these practices and understanding the internals, you can ensure that the SqlConnection is properly managed and closed, preventing potential connection leaks.

Thứ Hai, 26 tháng 8, 2024

[C#] Check String Is Alphanumeric

    public bool IsAlphanumeric(string input)
    {
        foreach (char c in input)
        {
            if (!char.IsLetterOrDigit(c))
            {
                return false;
            }
        }
        return true;
    }
    public bool IsAlphanumeric(string input)
    {
        var regex = new Regex("^[a-zA-Z0-9]*$");
        return regex.IsMatch(input);
    }

Thứ Ba, 23 tháng 7, 2024

Thứ Ba, 16 tháng 1, 2024

Disable Fips Algorithm Policy ASP.NET

- Solution 1: Disable FipsAlgorithmPolicy in Windows Registry:
  Set Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\FipsAlgorithmPolicy\Enabled to 0

- Solution 2: Modify C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Aspnet.config

  <configuration>
    <runtime>
        <enforceFIPSPolicy enabled="false" />
    </runtime> 
</configuration>

Reference:

Chủ Nhật, 24 tháng 12, 2023

[SQL Server] Find Currently Running Queries

SELECT 
	DB_NAME(req.database_id) as db_name
	,sqltext.text
    ,req.session_id
    ,req.status
    ,req.command
	,req.start_time
    ,req.cpu_time
    ,req.total_elapsed_time
	,queryplan.query_plan
	,c.client_net_address
	,s.login_name
	,s.login_time
	,s.program_name
	,s.host_name
	,s.host_process_id
	,s.client_interface_name
	,s.client_version
	--,req.*
	--,c.*
	--,s.*
FROM sys.dm_exec_requests req
JOIN sys.dm_exec_connections c on req.connection_id = c.connection_id
JOIN sys.dm_exec_sessions s on req.session_id = s.session_id
CROSS APPLY sys.dm_exec_sql_text(sql_handle) AS sqltext
CROSS APPLY sys.dm_exec_query_plan(req.plan_handle) as queryplan

Thứ Tư, 19 tháng 4, 2023

[SQL Server] Convert DateTimeOffset to DateTime

declare @dateTime datetime2 = SYSDATETIME()
declare @dateTimeOffset datetimeoffset = SYSDATETIMEOFFSET()
 
select @dateTime as [CurrentDateTime],
@dateTimeOffset as [CurrentDateTimeOffset],
CAST(@dateTimeOffset as datetime2) as [DateTime1]


select CAST('2023-04-19 15:32:31.2721255 +07:00' as datetime2) -- Output: 2023-04-19 15:32:31.2721255
select CAST('2023-04-19 15:32:31.2721255 +08:00' as datetime2) -- Output: 2023-04-19 15:32:31.2721255

select SWITCHOFFSET('2023-04-19 15:32:31.2721255 +07:00', '+01:00') -- Output: 2023-04-19 09:32:31.2721255 +01:00
select SWITCHOFFSET('2023-04-19 15:32:31.2721255 +08:00', '+01:00') -- Output: 2023-04-19 08:32:31.2721255 +01:00

select CAST(SWITCHOFFSET('2023-04-19 15:32:31.2721255 +07:00', '+01:00') as datetime2) -- Output: 2023-04-19 09:32:31.2721255
select CAST(SWITCHOFFSET('2023-04-19 15:32:31.2721255 +08:00', '+01:00') as datetime2) -- Output: 2023-04-19 08:32:31.2721255

Thứ Ba, 2 tháng 8, 2022

[SQL Server] Convert DateTime to DateTimeOffset

declare @dateTime datetime2 = SYSDATETIME()
declare @dateTimeOffset datetimeoffset = SYSDATETIMEOFFSET()

select @dateTime as [CurrentDateTime],
@dateTimeOffset as [CurrentDateTimeOffset],
CAST(@dateTime as datetimeoffset) as [DateTimeOffset1],
TODATETIMEOFFSET(@dateTime, '+07:00') as [DateTimeOffset2],
TODATETIMEOFFSET(@dateTime, RIGHT(SYSDATETIMEOFFSET(), 6)) as [DateTimeOffset3]

Thứ Ba, 7 tháng 9, 2021

[C#] The request was aborted: Could not create SSL/TLS secure channel

 - Create tls-ssl-settings.reg

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SystemDefaultTlsVersions"=dword:00000001
"SchUseStrongCrypto"=dword:00000001
- Execute the reg file.
- Done.

Links:

Thứ Sáu, 6 tháng 8, 2021

[Js] Removing Service Workers Programmatically

if(window.navigator && navigator.serviceWorker) {
  navigator.serviceWorker.getRegistrations()
  .then(function(registrations) {
    for(let registration of registrations) {
      registration.unregister();
    }
  });
}
https://stackoverflow.com/questions/33704791/how-do-i-uninstall-a-service-worker

Thứ Hai, 30 tháng 9, 2019

Thứ Năm, 12 tháng 9, 2019

Configure TortoiseSVN to use Visual Studio 2015 for Diff Viewer (Updated including Visual Studio 2017, 2019)

Settings -> Diff Viewer -> External -> paste the command as below:

C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\devenv.exe -diff %base %mine

or

C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\vsDiffMerge.exe /t %base %mine %bname %yname

Visual Studio 2017 Professional:
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\devenv.exe -diff %base %mine

Visual Studio 2019 Enterprise:
C:\Program Files (x86)\Microsoft Visual Studio\2019\Enterprise\Common7\IDE\devenv.exe -diff %base %mine

Visual Studio Code:
C:\  ... Microsoft VS Code\Code.exe --wait  --diff %base %mine