Meet The Author

I'm Ethan Jackson, An 25 years old blogger Currently living in London, United Kingdom. I'm a Skilled Blogger, Part Time web Developer And Creating new things as a web Designer.

author

What is Interlocked In .NET?

Leave a Comment

In multithreaded applications, multiple threads can access and modify shared variables concurrently. This can lead to race conditions. The System.Threading.Interlocked class provides atomic operations on variables, ensuring thread safety without using locks.


Common Use Cases

  • Counters (Increment/Decrement)
  • Flags (Boolean states)
  • Exchange operations
  • Compare-and-swap (CAS)

Why Use Interlocked?

  • Atomic operations: Guaranteed to complete without interruption
  • Lightweight: Faster than locking mechanisms
  • Lock-free: Reduces the chance of deadlocks

Thread-Safe Counter Example
using System;
using System.Threading;

class Program
{
    private static int counter = 0;

    static void Main()
    {
        Thread[] threads = new Thread[10];

        for (int i = 0; i < threads.Length; i++)
        {
            threads[i] = new Thread(() =>
            {
                for (int j = 0; j < 1000; j++)
                {
                    Interlocked.Increment(ref counter);
                }
            });
            threads[i].Start();
        }

        foreach (var t in threads) t.Join();

        Console.WriteLine($"Final counter value: {counter}");
    }
}


Methods in Interlocked

  • Interlocked.Increment(ref int location)
  • Interlocked.Decrement(ref int location)
  • Interlocked.Add(ref int location, int value)
  • Interlocked.Exchange(ref T location, T value)
  • Interlocked.CompareExchange(ref T location, T value, T comparand)

Thread-Safe Flag Example (Boolean)
Booleans aren't directly supported by Interlocked, but you can simulate them using integers:
private static int isRunning = 0;

if (Interlocked.CompareExchange(ref isRunning, 1, 0) == 0)
{
    try
    {
        // Do work
    }
    finally
    {
        Interlocked.Exchange(ref isRunning, 0);
    }
}


Summary
Interlocked is ideal for low-level concurrency control. Best for simple shared variable updates. Use it when you want lock-free synchronization. For complex data structures, prefer lock or concurrent collections.

Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 7.0.10 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Read More

What's New in C# 14 and ASP.NET Core 10?

Leave a Comment

C# 14 introduces several powerful language features focused on performance, flexibility, and developer convenience.

 

Here are the key updates:

Implicit Span Conversions

C# 14 offers first-class support for the System.Span<T> and System.ReadOnlySpan<T>. These types are designed for high-performance, memory-safe manipulation of contiguous data. C# 14 introduces implicit conversions between.

  • T[ ] → Span<T>
  • T[ ] → ReadOnlySpan<T>
  • Span<T> → ReadOnlySpan<T>

This means you can now write APIs that accept spans and call them with arrays, reducing the need for explicit casts and avoiding unnecessary allocations.

void Print(ReadOnlySpan<char> data)
{
    foreach (var ch in data)
        Console.Write(ch);
    Console.WriteLine();
}

char[] buffer = { 'H', 'e', 'l', 'l', 'o' };
// Implicitly converts char[] to ReadOnlySpan<char>
Print(buffer);

Benefits

  • Zero allocations
  • Type safety
  • Improved performance for memory-intensive operations
Unbound Generic Types in the nameof

Before C# 14, you could only use closed generic types with nameof, such as nameof(List<int>). With C# 14, you can now reference unbound generics in the nameof, enabling cleaner and more flexible metadata or logging scenarios.

Console.WriteLine(nameof(Dictionary<,>));
Console.WriteLine(nameof(List<>));

Output

  • Dictionary
  • List
Simple Lambda Parameters with Modifiers

C# 14 allows you to use modifiers like ref, out, in, scoped, and ref readonly in lambda parameters, even without specifying the type. Previously, you had to provide full-type declarations to use modifiers.

delegate bool TryParse<T>(string text, out T result);
private static void LambdaParameterModifiersExample()
{
  TryParse<int> tryParse = (text, out result) => int.TryParse(text, out result);

  if (tryParse("123", out var num))
  Console.WriteLine($"Parsed: {num}");
  else
  Console.WriteLine("Failed to parse");
}
C#

Benefits

  • Cleaner syntax
  • Better support for modern API design
  • Enhanced lambda expressiveness

.NET 10 Library Enhancements

.NET 10 introduces powerful enhancements to its base-class libraries. Here's a breakdown of the most impactful additions.

Finding Certificates by Thumbprint (SHA-2 & SHA-3)

Before .NET 10: Only SHA-1 hash thumbprints were supported, limiting security standards. Now, you can use secure hashing algorithms like SHA-256 or SHA-3 directly.

X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);

string thumbprint = "ABCD1234...";
X509Certificate2Collection certs = store.Certificates.FindByThumbprint(HashAlgorithmName.SHA256, thumbprint);

if (certs.Count == 1)
{
    Console.WriteLine("Certificate found: " + certs[0].Subject);
}

Benefits: Stronger certificate validation in secure systems.

Improved PEM File Parsing (UTF-8)

Initially, manual encoding conversion was needed to read UTF-8 PEM files. Now, Native support for UTF-8 parsing simplifies the process.

byte[] pemData = File.ReadAllBytes("key.pem");
PemFields pemFields = PemEncoding.FindUtf8(pemData);
string label = Encoding.UTF8.GetString(pemData[pemFields.Label]);
byte[] keyData = Convert.FromBase64String(Encoding.UTF8.GetString(pemData[pemFields.Base64Data]));

Benefits: Faster, cleaner handling of standard security file formats.

Numeric String Comparison

Earlier, strings sorted lexically, so "File10" came before "File2". Now, natural numeric ordering is built-in.

var versions = new[] { "File1", "File10", "File2" };
Array.Sort(versions, StringComparer.Create(CultureInfo.InvariantCulture, CompareOptions.NumericString));

Console.WriteLine(string.Join(", ", versions)); // File1, File2, File10

Benefits: Sorting UI lists, filenames, and version numbers.

TimeSpan.FromMilliseconds Overloads

Earlier, Ambiguity with LINQ and long arrays. Now, cleaner LINQ integration.

long[] delays = { 200, 400, 800 };
var spans = delays.Select(TimeSpan.FromMilliseconds);

foreach (var span in spans)
    Console.WriteLine(span);

Benefits: Simplifies time-related functional code.

OrderedDictionary Enhancements

Earlier, limited index handling APIs. Now, you can update values directly using index-aware methods.

var counts = new OrderedDictionary<string, int>();
if (!counts.TryAdd("bananas", 1, out int idx))
{
    counts.SetAt(idx, counts.GetAt(idx).Value + 1);
}
Console.WriteLine(counts.GetAt(0));

Benefits: Frequency tracking, ordered logs, quick updates.

ReferenceHandler Support in JSON Source Generators

Earlier, serializing object graphs with cycles caused stack overflows. Now, the Preserve option supports circular references.

public class Category
{
    public string Name { get; set; }
    public Category? Parent { get; set; }
}
[JsonSourceGenerationOptions(ReferenceHandler = JsonKnownReferenceHandler.Preserve)]
[JsonSerializable(typeof(Category))]
internal partial class JsonCtx : JsonSerializerContext { }
var node = new Category { Name = "Root" };
node.Parent = node;
string output = JsonSerializer.Serialize(node, JsonCtx.Default.Category);
Console.WriteLine(output);

Benefits: Enables safe serialization for complex graphs.

Wrapping Up

The combination of C# 14 and the new base library capabilities in .NET 10 presents a compelling platform for modern developers. With enhancements in API design, runtime performance, and language expressiveness, this release solidifies .NET as a top-tier development framework. I have added one demo project with the article. Please feel free to explore that as well.

Thank You, and Stay Tuned for More!

Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 7.0.10 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Read More

Integration of SonarLint with Various IDEs

Leave a Comment

For incorporating static code analysis straight into your development environment, SonarLint is a well-liked tool. Additionally, it helps detect any errors, vulnerabilities, and code smells while giving immediate feedback on the quality of the code. You can incorporate SonarLint into your development process in the following ways:

1. Supported IDEs

SonarLint supports the following IDEs:

  • Visual Studio
  • Visual Studio Code
  • IntelliJ IDEA
  • Eclipse
2. SonarLint for Visual Studio

2.1 Install the SonarLint Extension

  1. Open Visual Studio.
  2. Go to Extensions > Manage Extensions.
  3. Search for "SonarLint".
  4. Click Install and restart Visual Studio.

2.2 Configure SonarLint

  1. Open any project in Visual Studio.
  2. SonarLint automatically starts analyzing your code as you edit and saves your changes.
  3. View detected issues in the Error List window.

2.3 Optional: Bind to SonarQube or SonarCloud

  1. Go to Tools > Options > SonarLint.
  2. Bind to a SonarQube server or SonarCloud project for enhanced issue detection (e.g., issues with organization-specific rules).
3. SonarLint for Visual Studio Code

3.1 Install the SonarLint Extension

  1. Open Visual Studio Code.
  2. Go to the Extensions view (Ctrl+Shift+X).
  3. Search for "SonarLint".
  4. Install the extension.

3.2 Configure SonarLint

  • SonarLint automatically analyzes your code when you open or save files.
  • To customize settings:
    1. Open the Command Palette (Ctrl+Shift+P).
    2. Search for and select Preferences: Open Settings (JSON).
    3. Add SonarLint settings. Example:
"sonarlint.connectedMode.servers": [

    {

        "serverId": "my-server",
        "serverUrl": "http://localhost:9000",
        "token": "your-sonarqube-token"
    }

],

"sonarlint.connectedMode.project": {

    "serverId": "my-server",
    "projectKey": "my-project-key"

}
4. SonarLint for IntelliJ IDEA

4.1 Install the SonarLint Plugin

  1. Open IntelliJ IDEA.
  2. Go to File > Settings > Plugins.
  3. Search for "SonarLint".
  4. Click Install and restart IntelliJ IDEA.

4.2 Configure SonarLint

  • SonarLint analyzes your code on-the-fly.
  • To bind to SonarQube or SonarCloud:
    1. Go to File > Settings > Tools > SonarLint.
    2. Add your SonarQube server details and authenticate.
5. SonarLint for Eclipse

5.1 Install the SonarLint Plugin

  1. Open Eclipse.
  2. Go to Help > Eclipse Marketplace.
  3. Search for "SonarLint".
  4. Click Install and restart Eclipse.

5.2 Configure SonarLint

  • SonarLint automatically scans your code.
  • To bind to SonarQube:
    1. Go to Window > Preferences > SonarLint > Connected Mode.
    2. Add your SonarQube server and bind to a project.
6. Advantages of SonarLint Integration
  • On-the-Fly Feedback: Instantly see potential issues while coding.
  • Seamless Workflow: Works directly in your IDE without requiring additional steps.
  • Custom Rules: Leverages SonarQube/SonarCloud for organization-specific coding standards.
  • Local Validation: No need to commit code before seeing results.
7. Tips for Best Practices
  • Always keep the SonarLint plugin updated for the latest rules and bug fixes.
  • Use connected mode to ensure consistent rules between SonarLint and your SonarQube/SonarCloud instance.
  • Regularly address code smells and vulnerabilities highlighted by SonarLint to maintain high-quality code.

HostForLIFE is Best Option for ASP.NET Core 9.0 Hosting in Europe

Frankly speaking, HostForLIFE is best option to host your ASP.NET Core 9.0 Hosting in Europe. You just need to spend €2.97/month to host your site with them and you can install the latest ASP.NET Core 9.0 via their Plesk control panel. We would highly recommend them as your ASP.NET Core 9.0 Hosting in Europe.

http://hostforlifeasp.net/European-ASPNET-Core-2-Hosting
Read More

Choosing the Best ASP.NET Core 9.0 Hosting in Europe

Leave a Comment
Based on its useful features and easy to use, many developer need powerful web hosting to support their ASP.NET Core 9.0 site well. Because of that, we will inform you the Best ASP.NET Core 9.0 Hosting in Europe provider with affordable price and high quality support. After reviewed 20+ ASP.NET Core 9.0 Hosting in Europe, we had come out with the best ASP.NET Core 9.0 Hosting in Europe, control libraries, databases, technical support, and web hosting price. 


ASP.NET Core is a free and open-source web framework, and higher performance than ASP.NET, developed by Microsoft and the community. It is a modular framework that runs on both the full .NET Framework, on Windows, and the cross-platform .NET Core. Despite being a new framework, built on a new web stack, it does have a high degree of concept compatibility with ASP.NET MVC. ASP.NET Core applications supports side by side versioning in which different applications, running on the same machine, can target different versions of ASP.NET Core. This is not possible with previous versions of ASP.NET.

Best & Cheap ASP.NET Core 9.0 Hosting in Europe

Our Best, Cheap ASP.NET Core 9.0 Hosting in Europe Recommendation goes to HostForLIFEASP.NET, a leading web hosts who is well-known for offering high quality Windows hosting from shared hosting

http://hostforlifeasp.net/European-ASPNET-Core-2-Hosting

Founded in United Kingdom, and with years’ expansion, HostForLIFEASP.NET has grown into one of top 10 ASP.NET Core 9.0 Hosting in Europe hosting providers for offers reliable and affordable web hosting services on Windows platforms. HostForLIFEASP.NET a worldwide provider of hosting support the latest release of Microsoft's widely-used ASP.NET Core 9.0 Hosting in Europe. You can take advantage of the powerful ASP.NET Core 9.0 Hosting in Europe technology in all Windows Shared Hosting, Windows Reseller Hosting and Windows Cloud Hosting Packages. 

SALE 35% OFF NOW!

HostForLIFEASP.NET Budget Friendly Price – The service includes 4 packages called as HostForLIFE Basic, Budget, Economy and Business with the price starting at Є2.97/mo.


  • 30 Days Money Back Guarantee – This means webmasters are allowed to get a refund if they cancel the services because of dissatisfaction within the first 30 days.
  • Satisfactory Uptime – HostForLIFEASP.NET employs state-of-the-art data centers and advanced technologies guaranteeing 99.99% uptime shown by the following chart.

HostForLIFE ASP.NET Core 9.0 Hosting in Europe Performance

HostForLIFEASP.NET ASP.NET Core 9.0 web host reliability is absolutely outstanding compared to other comprehensive web hosting companies. HostForLIFEASP.NET is managed by a sophisticated team with lots of Windows server experts. With the correct IIS, website and file system permission configuration, the security of the hosting websites is well isolated. That means, when one website is hacked by improper code, it’s rare opportunity for other websites be affected.

Technical Support

As introduced above, HostForLIFEASP.NET has an experienced team on supporting ASP.NET and ASP.NET Core 9.0 Hosting in Europe. All of their technical support staffs are kindly, sophisticated and knowledgeable on either Windows platform or SQL Server 2016 databases. HostForLIFEASP.NET provides 24/7 email and ticket system support mainly. Based on our testing, the average of the first response is about 30 minutes, and it could be faster in working time. HostForLIFEASP.NET guarantees to respond each support ticket in 12 hours.

HostForLIFE is Best Option for ASP.NET Core 9.0 Hosting in Europe

Frankly speaking, HostForLIFE is best option to host your ASP.NET Core 9.0 Hosting in Europe. You just need to spend €2.97/month to host your site with them and you can install the latest ASP.NET Core 9.0 via their Plesk control panel. We would highly recommend them as your ASP.NET Core 9.0 Hosting in Europe.

http://hostforlifeasp.net/European-ASPNET-Core-2-Hosting

Read More

Avoid Accidental Data Erasure with These Two Easy Steps

Leave a Comment

Many of us have experienced the repercussions of accidentally deleting more data than we intended, and it's a typical problem in large systems. Here are two practical methods to protect your data from these kinds of incidents:

1. SQL Trigger to Prevent DELETE Without WHERE Clause

CREATE TRIGGER trg_PreventDeleteWithoutWheree
on TableName
INSTEAD OF DELETE
AS
BEGIN
   -- Check if any rows were attempted to be deleted (meaning no WHERE clause)
   IF @@ROWCOUNT >
   BEGIN
        -- Raise an error
        RAISERROR('DELETE statements must have a WHERE clause to prevent accidental full table deletion.'
, 16, 1)
        -- Optionally, rollback the transaction if you want to completely prevent the delete
        ROLLBACK TRANSACTION
   END
   ELSE
   BEGIN
   -- If no rows were attempted to be deleted.
   DELETE FROM TableName
   WHERE EXISTS (SELECT 1 FROM deleted WHERE TableName. Id = deleted. Id) ;
   END
END;

First approach is to use a SQL Trigger to ensure that no delete operation runs without a WHERE clause. A trigger can be created to fire on DELETE operations and validate the statement before it executes.

  • Prevents accidental deletes at the database level.
  • Provides an additional layer of protection, especially against unintentional bulk deletions.
  • Ensures that your data is protected even if an application bypasses safeguards.

Cons. Requires additional database configuration and can add complexity to your schema. Doesn’t offer as much flexibility for more complex delete scenarios.

 2. Interceptor to Prevent DELETE Without WHERE Clause

public override InterceptionResult<int> NonQueryExecuting(
  DbCommand command,
  CommandEventData eventData,
  InterceptionResult<int> result)
{
  ReadOnlySpan<char> sqlSpan = command.CommandText. AsSpan().TrimStart();
   if (sqlSpan.StartsWith ("DELETE", StringComparison.OrdinalIgnoreCase) &&
       (sqlSpan. Indexof ("WHERE", StringComparison.OrdinalIgnoreCase) = -1))
   {
       throw new InvalidOperationException ("DELETE statements must include a WHERE clause.");
   }
    return base.NonQueryExecuting(command, eventData, result);
}

You can create a custom command interceptor to intercept any DELETE operation and ensure that it includes a WHERE clause. This prevents broad deletion commands from executing, ensuring that no rows are accidentally deleted without proper conditions.

  • Prevents accidental deletes via the application.
  • Helps enforce better practices for safe deletion operations.
  • Increases application-level security

Cons

While the performance overhead is generally acceptable, it can be configured to limit the scope, applying the interceptor only to specific queries or operations, thereby reducing unnecessary overhead.

Note. The same approach for preventing DELETE without a WHERE clause can be easily achieved with different ORMs.

Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 7.0.10 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/
Read More

Features of WebMethod and ScriptMethod in.NET Webforms

Leave a Comment

In Web forms, .Net applications to call the client side scripts like javascript and Jquery web calls are handled by using WebMethod and ScriptMethod Attributes. The shared function keyword from server-side pages is used in this technique. The function will send a post and receive a request on that, as indicated by the Shared keyword and WebMethod property that WebService exposes. The same kind of online technique will be utilized for sharing data in JSON format. Below is an example of the code.

Server End code

Public Class WebCall
    Inherits System.Web.UI.Page
    <WebMethod()>
    <ScriptMethod()>
    Public Shared Function GetServerTime() As String
        Return DateTime.Now.ToString()
    End Function

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
        ' No server-side logic needed for this example.
    End Sub
End Class

From the client end, an OnClick event will be sent a request for getting a server date & timely response. The client-side code example is below.

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server"><main>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script type="text/javascript">
        function callWebMethod() {
            alert("callweb");
            $.ajax({
                type: "POST",
                url: "WebCall.aspx/GetServerTime",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    alert(msg.d);
                    $("#lblTime").text(msg.d);
                },
                error: function (xhr, status, error) {
                    alert("Error: " + xhr.responseText);
                }
            });
        }
    </script>
    <div>

  <button type="button" onclick="callWebMethod()">Get current server time</button><p id="btnGetTime"></p>
          <label id="lblTime" Text=""></label>
    </div>
    </main>
</asp:Content>

Output


 

Windows Hosting Recommendation

HostForLIFEASP.NET receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 7.0.10 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/

 

Read More

How to Use AES to Encrypt a SQLite Database File?

Leave a Comment

Here, we'll go over how to use the Advanced Encryption Standard (AES) symmetric encryption algorithm to encrypt the SQLite DB file in.NET C#. The encryption will be carried out from the sender using a key and IV (initialization vector). The same key will be used by the receiver to decode the data on the other end.


IV is a pseudo-random value multiple times encrypting the plain text, IV size typically 16 bytes (128 bits). AES supports different key sizes like 128 bits, 192 bits, and 256 bits. Hash key using SHA256 method example is given here.

using System.Security.Cryptography;
using System.Text;

Console.WriteLine("SQLite DB file Encrpytion");

string encryptedCsvFilePath = @"file path";
using (var aesAlg = new AesCryptoServiceProvider())
{
    byte[][] KeyIV = GetHashKeys();
    aesAlg.Key = KeyIV[0];
    aesAlg.IV = KeyIV[1];

    using (FileStream inputFileStream = new FileStream(@"file path", FileMode.Open))
    using (FileStream outputFileStream = new FileStream(encryptedCsvFilePath, FileMode.Create))
    using (ICryptoTransform encryptor = aesAlg.CreateEncryptor())
    using (CryptoStream cryptoStream = new CryptoStream(outputFileStream, encryptor, CryptoStreamMode.Write))
    {
        inputFileStream.CopyTo(cryptoStream);
        Console.WriteLine("Encrpytion in progress..... ");
    }
    Console.WriteLine(" Encrpytion completed ");
}

 public static string EncryptStringToBytes_Aes(string strPlainText, byte[] Key, byte[] IV)
          {
              byte[] encrypted;
              try
              {
                  //check the plaintext & key exists or not
                  if (strPlainText == null || strPlainText.Length <= 0)
                      throw new ArgumentNullException("strPlainText");
                  if (Key == null || Key.Length <= 0)
                      throw new ArgumentNullException("_strEncryptionKey");
                  if (IV == null || IV.Length <= 0)
                      throw new ArgumentNullException("IV");
                  using (AesManaged aesAlg = new AesManaged())
                  {
                      //encrypt the text using Hash key &  initialization vector
                      aesAlg.Key = Key;
                      aesAlg.IV = IV;
                      ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
                      using (MemoryStream msEncrypt = new MemoryStream())
                      {
                          using (CryptoStream csEncrypt =
                                  new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                          {
                              using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                              {
                                  swEncrypt.Write(strPlainText);
                              }
                              //encrpted array is generated and save in string
                              encrypted = msEncrypt.ToArray();
                          }
                      }
                  }
              }
              catch (Exception ex) { throw new Exception(ex.Message); }

              //generete a encoded string using base64
              return Convert.ToBase64String(encrypted);
          }

Using Security.Cryptography library AES encryption encryption is handled, and CryptographicException is used for Exception handling. SHA256CryptoServiceProvider is used to get the hash key.

public static byte[][] GetHashKeys()
{
    byte[][] result = new byte[2][];
    try
    {
        Encoding enc = Encoding.UTF8;
        SHA256 sha2 = new SHA256CryptoServiceProvider();
        //covert the readable key hashing value in byte array
        byte[] raw_strEncryptionKey = enc.GetBytes(_strEncryptionKey);
        byte[] rawIV = enc.GetBytes(_strEncryptionKey);
        // initialization vector and hashkey genrate
        byte[] hash_strEncryptionKey = sha2.ComputeHash(raw_strEncryptionKey);
        byte[] hashIV = sha2.ComputeHash(rawIV);
        Array.Resize(ref hashIV, 16);
        result[0] = hash_strEncryptionKey;
        result[1] = hashIV;

    }
    catch (Exception ex) {  throw new Exception(ex.Message); }
    return result;
}

Using the FileStream class, an Encrypted SQLite DB file will be created.

public static void CreateEncrytedSQLiteFile()
{
    try
    {
        using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
        {
            byte[][] KeyIV = GetHashKeys();
            aesAlg.Key = KeyIV[0];
            aesAlg.IV = KeyIV[1];

            using (FileStream inputFileStream = new FileStream(SQLITE_DB_FILE, FileMode.Open))
            using (FileStream outputFileStream = new FileStream(SQLITE_DB_ENCRYTED_FILE, FileMode.Create))
            using (ICryptoTransform encryptor = aesAlg.CreateEncryptor())
            using (CryptoStream cryptoStream = new CryptoStream(outputFileStream, encryptor, CryptoStreamMode.Write))
            {
                inputFileStream.CopyTo(cryptoStream);
            }
        }

    }
    catch (Exception ex) {  throw ex; }

}

Output


 

Windows Hosting Recommendation

HostForLIFE.eu receives Spotlight standing advantage award for providing recommended, cheap and fast ecommerce Hosting including the latest Magento. From the leading technology company, Microsoft. All the servers are equipped with the newest Windows Server 2022 R2, SQL Server 2022, ASP.NET Core 8.0 , ASP.NET MVC, Silverlight 5, WebMatrix and Visual Studio Lightswitch. Security and performance are at the core of their Magento hosting operations to confirm every website and/or application hosted on their servers is highly secured and performs at optimum level. mutually of the European ASP.NET hosting suppliers, HostForLIFE guarantees 99.9% uptime and fast loading speed. From €3.49/month , HostForLIFE provides you with unlimited disk space, unlimited domains, unlimited bandwidth,etc, for your website hosting needs.
 
https://hostforlifeasp.net/


Read More
Previous PostOlder Posts Home