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

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

Examine the Principal Elements of.NET 9

Leave a Comment

Microsoft’s release of .NET 9 continues its mission to enhance the developer experience, optimize performance, and expand its feature set for modern application development. Whether you’re a seasoned .NET developer or just starting, the updates in .NET 9 bring powerful capabilities to streamline workflows, improve cross-platform support, and elevate application performance.


In this article, we’ll explore the key features of .NET 9 and dive into practical code examples to help you leverage its full potential.

Key Highlights of .NET 9

  1. Native AOT (Ahead-of-Time) Compilation Enhancements
  2. Improved JSON Serialization with Source Generators
  3. C++ Interoperability Improvements
  4. Linux and ARM64 Optimization
  5. Modern Web Development with Minimal APIs
  6. Performance and Security Enhancements

1. Native AOT (Ahead-of-Time) Compilation Enhancements

Native AOT continues to evolve in .NET 9, enabling developers to compile applications into self-contained executables optimized for performance and reduced size. This is particularly beneficial for microservices, CLI tools, and serverless applications, where startup time and memory footprint are critical.

Key Benefits

  • Smaller executables with no runtime dependencies.
  • Faster startup time compared to JIT-compiled applications.
  • Improved diagnostics support for debugging AOT-compiled apps.

Example

using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("Hello from .NET 9 with Native AOT!");
    }
}

Building for Native AOT

dotnet publish -r win-x64 -c Release /p:PublishAot=true

2. Improved JSON Serialization with Source Generators

Serialization has always been a cornerstone of .NET development. In .NET 9, the JSON source generator enhancements deliver better performance and type safety, reducing the runtime overhead of serialization and deserialization.

Key Features

  • Improved performance: Faster and more efficient serialization.
  • Compile-time checks: Detect issues earlier in the development lifecycle.
  • Support for polymorphic types.

Example

using System;
using System.Text.Json;
using System.Text.Json.Serialization;

[JsonSerializable(typeof(User))]
public partial class UserJsonContext : JsonSerializerContext
{
}

public class User
{
    public string Name { get; set; }
    public int Age { get; set; }
}

// Serialize and Deserialize
var user = new User { Name = "John", Age = 28 };
string json = JsonSerializer.Serialize(user, UserJsonContext.Default.User);

var deserializedUser = JsonSerializer.Deserialize<User>(json, UserJsonContext.Default.User);

Console.WriteLine(deserializedUser.Name);

3. C++ Interoperability Improvements

For developers working with legacy C++ libraries or requiring low-level performance optimizations, .NET 9 enhances the interop layer, making it easier to call C++ libraries from managed code.

Key Improvements

  • Enhanced support for memory pinning and marshaling.
  • Optimized interop scenarios for cross-platform compatibility.

Example

using System;
using System.Runtime.InteropServices;

[DllImport("native.dll", EntryPoint = "Add")]
public static extern int Add(int a, int b);

class Program
{
    static void Main()
    {
        int result = Add(5, 10);
        Console.WriteLine($"Result from native library: {result}");
    }
}

4. Linux and ARM64 Optimizations

As cloud-native and containerized applications become the norm, .NET 9 introduces optimizations for Linux and ARM64 platforms. These updates ensure smoother deployments and better performance in modern cloud environments.

Key Enhancements

  • Reduced startup time for Linux-based containerized applications.
  • Improved ARM64 support for energy-efficient workloads.
  • Smaller base images for containerized applications.

Dockerfile Example

ROM mcr.microsoft.com/dotnet/runtime:9.0

WORKDIR /app

COPY . .

ENTRYPOINT ["dotnet", "MyApp.dll"]

5. Modern Web Development with Minimal APIs

Minimal APIs, introduced in .NET 6, continue to evolve in .NET 9, offering even greater flexibility and simplicity for building lightweight web services.

Example. Building a Minimal API

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/", () => "Welcome to .NET 9!");
app.MapPost("/api/data", (DataModel data) => Results.Ok(data));

app.Run();
record DataModel(string Name, int Value);

Publishing for Production

dotnet publish -c Release -o ./publish

6. Performance and Security Enhancements

Performance is a hallmark of every .NET release, and .NET 9 is no exception. Developers can expect faster execution, improved garbage collection, and better threading.

Key Improvements

  • Garbage Collection (GC): Reduced pauses and improved memory management.
  • HTTP/3 Enhancements: Lower latency and faster handshakes for web apps.
  • Security Updates: Improved cryptographic support and hardened runtime defenses.

Benchmarking Example

Using System.Diagnostics to measure performance:

using System.Diagnostics;
var sw = Stopwatch.StartNew();
// Perform a task
sw.Stop();
Console.WriteLine($"Elapsed time: {sw.ElapsedMilliseconds}ms");

Detailed Use Cases

1. Building Cloud-Native APIs

The cloud-native focus in .NET 9 makes it easier to integrate with Kubernetes and observability tools like OpenTelemetry.

using OpenTelemetry.Trace;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenTelemetryTracing(traceBuilder =>

{

    traceBuilder

        .AddAspNetCoreInstrumentation()

        .AddConsoleExporter();

});

var app = builder.Build();
app.MapGet("/", () => "Cloud-Native App with OpenTelemetry in .NET 9");
app.Run();

2. Serverless Applications

Deploy AOT-compiled applications for serverless environments to minimize cold start latency.

// Native AOT optimizes cold start times

Console.WriteLine("Optimized for serverless in .NET 9!");

Why Upgrade to .NET 9?

  1. Performance Boost: Applications run faster with reduced memory consumption.
  2. Simplified Development: Minimal APIs and improved tooling streamline the coding experience.
  3. Future-Ready: Optimized for cloud-native, cross-platform, and microservices architectures.

Conclusion

.NET 9 is a robust release packed with features that cater to modern development challenges. From Native AOT to JSON source generator improvements, the platform empowers developers to create fast, secure, and scalable applications. By embracing .NET 9, you’re not only improving your application’s performance but also ensuring long-term compatibility with emerging technologies.

Start experimenting with .NET 9 today to unlock its full potential in your projects! For more information, visit the official Microsoft .NET documentation.

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

Best Umbraco 15.0.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 Umbraco 15.0.0 site well. Because of that, we will inform you the Best Umbraco 15.0.0 Hosting in Europe provider with affordable price and high quality support. After reviewed 20+ Umbraco 15.0.0 Hosting in Europe, we had come out with the best Umbraco 15.0.0 Hosting in Europe, control libraries, databases, technical support, and web hosting price.
 


Umbraco CMS is a fully-featured open source content management system with the flexibility to run anything from small campaign or brochure sites right through to complex applications for Fortune 500's and some of the largest media sites in the world. Umbraco is easy to learn and use, making it perfect for web designers, developers and content creators alike.

Umbraco is strongly supported by both an active and welcoming community of users around the world, and backed up by a rock-solid commercial organization providing professional support and tools. Umbraco can be used in its free, open-source format with the additional option of professional tools and support if required.

How to Choose the Best Umbraco 15.0.0 Hosting in Europe?

Our Best, Cheap Umbraco 15.0.0 Hosting in Europe Recommendation goes to HostForLIFE.eu, a leading web hosts who is well-known for offering high quality Windows hosting from shared hosting. HostForLIFE.eu founded in United Kingdom, and with years’ expansion, HostForLIFE.eu has grown into one of top 10 Umbraco 15.0.0 Hosting in Europe hosting providers for offers reliable and affordable web hosting services on Windows platforms. HostForLIFE.eu a worldwide provider of hosting support the latest release of Microsoft's widely-used Umbraco 15.0.0 Hosting in Europe. You can take advantage of the powerful Umbraco 15.0.0 Hosting in Europe technology in all Windows Shared Hosting, Windows Reseller Hosting and Windows Cloud Hosting Packages.



Is Price Affordable ?

HostForLIFE.eu Budget Friendly Price – The service includes 4 packages called as HostForLIFE Basic, Budget, Economy and Business with the price starting at Є3.49/mo and now, with 15% OFF you can get only Є3.49/month.
  • 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 – HostForLIFE.eu employs state-of-the-art data centers and advanced technologies guaranteeing 99.99% uptime shown by the following chart. 

HostForLIFE Umbraco 15.0.0 Hosting in Europe Performance

HostForLIFE.eu Umbraco 15.0.0 web host reliability is absolutely outstanding compared to other comprehensive web hosting companies. HostForLIFE.eu 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, HostForLIFE.eu has an experienced team on supporting ASP.NET and Umbraco 15.0.0 Hosting in Europe. All of their technical support staffs are kindly, sophisticated and knowledgeable on either Windows platform or SQL Server 2014 databases. HostForLIFE.eu 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. HostForLIFE.eu guarantees to respond each support ticket in 12 hours.

Conclusion – HostForLIFE is Best Option for Umbraco 15.0.0 Hosting in Europe

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

Read More

FG.CsvParser: A Powerful .NET Library for Working with CSV Files

Leave a Comment

For developers, working with CSV files is a routine activity. A.NET Standard 2.1 library called FG.CsvParser was created to simplify and expedite the reading, writing, and querying of CSV files. The ideal solution for managing your CSV-related duties is FG.CsvParser because of its broad customizable options and versatile API.


Key Features of FG.CsvParser

  • Read CSV Files: Convert CSV content into JSON or a list of strongly typed objects.
  • Write CSV Files: Easily write CSV content for files or append to existing ones.
  • Highly Configurable: Adjust parsing options such as delimiters, row splitters, and encoding to suit your needs.
  • Query CSV Data: Use custom filters to query CSV content efficiently.

Installation

To start using FG.CsvParser, you can add it to your project via NuGet:

dotnet add package FG.CsvParser

Getting Started with FG.CsvParser

Creating a CsvParser Instance

FG.CsvParser allows you to create a parser instance in multiple ways. Here are some examples:

Open a CSV File with Default Settings

var parser = CsvParser.OpenFile("path/to/your/file.csv");

Open a CSV File with a Header Row

var parser = CsvParser.OpenFile("path/to/your/file.csv", hasHeader: true);

Open a CSV File with Custom Configuration

var configuration = new CsvParserConfiguration
{
    HasHeader = true,
    Delimitter = ',',
    RowSplitter = "\n",
    Encoding = Encoding.UTF8
};
var parser = CsvParser.OpenFile("path/to/your/file.csv", configuration);

Reading CSV Content

Convert CSV Content to JSON

using var parser = CsvParser.OpenFile("path/to/your/csvfile.csv", new CsvParserConfiguration
{
    HasHeader = true,
    Delimitter = ',',
    RowSplitter = "\r\n",
    Encoding = Encoding.UTF8
});

string? jsonContent = await parser.ReadAsJson();
Console.WriteLine(jsonContent);

Convert CSV Content to a List of Objects

using var parser = CsvParser.OpenFile("path/to/your/csvfile.csv", new CsvParserConfiguration
{
    HasHeader = true,
    Delimitter = ',',
    RowSplitter = "\r\n",
    Encoding = Encoding.UTF8
});

List<MyDataClass> dataList = await parser.ReadAs<MyDataClass>();
foreach (var data in dataList)
{
    Console.WriteLine(data);
}

public class MyDataClass
{
    public string Name { get; set; }

    [CsvColumn("Home address")]
    public string HomeAddress { get; set; }
}

Writing CSV Content

Write CSV Content as a String

using var parser = CsvParser.OpenFile("path/to/your/file.csv", new CsvParserConfiguration
{
    HasHeader = true,
    Delimitter = ',',
    RowSplitter = "\r\n",
    Encoding = Encoding.UTF8
});

string csvContent = "Column1,Column2\nValue1,Value2\nValue3,Value4";
await parser.WriteAsync(csvContent, append: false);
Console.WriteLine("CSV content written to file.");

Write a List of Objects to CSV

var dataList = new List<MyDataClass>
{
    new MyDataClass { Column1 = "Value1", Column2 = 1 },
    new MyDataClass { Column1 = "Value2", Column2 = 2 }
};

await parser.WriteAsync(dataList, append: false);
Console.WriteLine("List of objects written to CSV file.");

Querying CSV Content

You can query CSV data using custom filters to extract only the information you need.

using var parser = CsvParser.OpenFile("path/to/your/csvfile.csv", new CsvParserConfiguration
{
    HasHeader = true,
    Delimitter = ',',
    RowSplitter = "\r\n",
    Encoding = Encoding.UTF8
});

await foreach (var item in parser.Query<MyDataClass>(data => data.Column2 > 100))
{
    Console.WriteLine(item);
}

Configuration Options

The CsvParserConfiguration class provides extensive configuration options to customize your CSV parsing experience:

var configuration = new CsvParserConfiguration
{
    HasHeader = true,
    Delimitter = ';',
    RowSplitter = "\n",
    Encoding = Encoding.UTF8
};

using var parser = CsvParser.OpenFile("path/to/your/file.csv", configuration);

Why Choose FG.CsvParser?

FG.CsvParser simplifies working with CSV files by providing a clean and intuitive API. Whether you need to process CSV files for small tasks or large-scale applications, FG.CsvParser offers the tools and flexibility required to handle your data efficiently.

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
Previous PostOlder Posts Home