Sunday 25 August 2024

What is Parallel LINQ (PLINQ) in C#

  Hello friends,

 In this article, I will explain to you below details of PLINQ

  • What is Parallel LINQ (PLINQ) in C# 
  • What are the Benefits of PLINQ  
  • How to Write Parallel LINQ Queries 
  • What are the  methods available in PLINQ
  • Performance 
  • Example

1. What is Parallel LINQ (PLINQ) in C# 

        Parallel LINQ (PLINQ) is an extension of LINQ (Language Integrated Query) in C# that allows you to write queries that are automatically parallelized and executed on multiple threads.
 By leveraging the power of multi-core processors, PLINQ improves query performance.
 It simplifies the process of writing parallel code for data-intensive operations, such as filtering, transforming, and aggregating large datasets.

PLINQ automatically partitions the data and processes it concurrently on multiple threads. It uses the Task Parallel Library (TPL) under the hood to manage the parallelization of query operations. 
This parallel execution can significantly improve performance, especially when dealing with large datasets.

 2. What are the benefits of PLINQ

LINQ provides a convenient way to query data, but PLINQ takes it to the next level by automatically parallelizing the queries. This can lead to significant speed improvements when working with extensive datasets or results

3. What are the  methods available in PLINQ

Here's a list of common  methods available for configuring  the behavior of Parallel LINQ (PLINQ) queries

  1. Parallel execution for a LINQ query by converting it into a PLINQ query.
  2. WithDegreeOfParallelism(int degreeOfParallelism): Specifies the maximum number of concurrently executing tasks that will be used by the query.
  3. WithExecutionMode(ParallelExecutionMode mode): Sets the execution mode of the PLINQ query to either ParallelExecutionMode.ForceParallelism or ParallelExecutionMode.Default.
  4. WithCancellation(CancellationToken cancellationToken): Specifies a cancellation token to enable cancellation of the PLINQ query.
  5. WithMergeOptions(ParallelMergeOptions options): Sets the merge options for combining results from parallel partitions (e.g., ParallelMergeOptions.NotBuffered or ParallelMergeOptions.AutoBuffered).
  6. WithOrdered(): Indicates that the output of the query should maintain the original order, even when parallelized.
  7. WithDegreeOfParallelism(int degreeOfParallelism): Sets the maximum number of concurrently executing tasks used by the query.
  8. WithExecutionMode(ParallelExecutionMode mode): Specifies the execution mode of the query (ForceParallelism or Default).
  9. WithCancellation(CancellationToken cancellationToken): Specifies a cancellation token for enabling query cancellation.
  10. WithMergeOptions(ParallelMergeOptions options): Sets the merge options for combining results from parallel partitions.
  11. ForAll(Action<TSource> action): Executes the specified action on each element of the query in parallel.
  12. AsSequential(): Returns a query that ensures subsequent operations are executed sequentially.
  13. AsUnordered(): Returns an unordered query that may execute more efficiently by ignoring the order of elements.
  14. Where<TSource>(Func<TSource, bool> predicate): Filters the elements of the query based on a specified condition.
  15. Select<TSource, TResult>(Func<TSource, TResult> selector): Projects each element of the query into a new form.
  16. OrderBy<TSource, TKey>(Func<TSource, TKey> keySelector): Sorts the elements of the query in ascending order based on a specified key.
  17. OrderByDescending<TSource, TKey>(Func<TSource, TKey> keySelector): Sorts the elements of the query in descending order based on a specified key.
  18. ThenBy<TSource, TKey>(Func<TSource, TKey> keySelector): Performs a secondary ascending sort on the elements based on a specified key.
  19. ThenByDescending<TSource, TKey>(Func<TSource, TKey> keySelector): Performs a secondary descending sort on the elements based on a specified key.
  20. GroupBy<TSource, TKey>(Func<TSource, TKey> keySelector): Groups the elements of the query based on a specified key.
  21. SelectMany<TSource, TResult>(Func<TSource, IEnumerable<TResult>> selector): Projects each element of the query into a sequence and flattens the resulting sequences into one sequence.

4. Performance of PLINQ queries 

PLINQ is most effective when dealing with operations that are time-consuming, such as computations, filtering, or transformations. It may not be beneficial for relatively quick operations, as the overhead of parallelization could outweigh the performance gain.
Although PLINQ can significantly speed up data processing, it's not always the best choice. Make sure to consider factors like data size, hardware, and overhead when deciding whether to use PLINQ.


5. How to write Parallel LINQ Queries


PLINQ seamlessly integrates with the LINQ query syntax. You can use the familiar LINQ keywords (from, where, select, group, join, etc.) to construct your queries. The difference is that PLINQ will automatically parallelize the execution of these queries when appropriate.

Sunday 31 March 2024

What’s New? Explore ALL NET .8 Features

 

What’s New? Explore ALL NET .8 Features


This article discusses the biggest highlights of .NET 8, from my point of view, and includes some code examples to get you started with the new features.



1. Long-term Support (LTS) Release

.NET 8 is classified as a Long-term Support (LTS) release, meaning Microsoft will continue to provide updates and extended support for it (up to three years). LTS releases are designed for stability and continuity, making them suitable for enterprise applications requiring long-term maintenance.

The extended support ensures that businesses can maintain the stability and security of their applications over an extended duration without being forced into frequent upgrades, providing a reliable foundation for sustained software development and deployment



2. Blazor Update

Now, you can use Blazor for both client-side (Blazor WebAssembly) and server-side (Blazor Server) rendering in the same app.
It supports stateless server-side rendering, streaming rendering, progressive enhancement for navigation and form handling, and interactivity per component.

3. System.Text.Json Serialization

System.Text.Json is a JSON serialization library in .NET that offers high-performance and customizable JSON serialization and deserialization. Introduced as part of .NET Core, it’s now a fundamental component in .NET version 8.

System.Text.Json has improved significantly, especially regarding dependability and performance when utilized in Native AOT apps with ASP.NET Core. These improvements include:

4. Improved support for IAsyncDisposable


In .NET core 8, IAsyncDisposable is an interface introduced to support asynchronous resource cleanup. It is similar to IDisposable, but it allows for asynchronous operations during the disposal of an object. This is particularly useful when dealing with asynchronous resources or cleanup tasks.


5. Extended AI and ML Support

Machine learning and artificial intelligence are essential technologies in today’s software environment. Microsoft has improved AI and ML support with .NET 8, which makes it simpler for developers to easily include complex algorithms and models in their apps.


6. Improved Diagnostics and Observability


In .NET development, improved diagnostics and observability refer to enhanced tools and features for monitoring and understanding the behavior of applications. These .NET 8 features include advanced logging, profiling, and tracing capabilities.


7. New C# Language Features


.NET Core 8 gains from the most recent improvements made to C#, a constantly changing language. The coding experience with this version is more efficient and expressive thanks to new features like enhanced pattern matching, record types, and nullable reference types.



8. Performance Improvements



Microsoft team hits a new .NET version to increase performance. Similarly, making sure your apps are quick, effective, and seamless across various platforms is a top priority of the .NET 8 framework.


End Note

As the .NET ecosystem evolves continuously, developers must stay current with the newest developments and best practices.
Although .NET 7 and .NET 8 both provide excellent features and improvements. NET Core 8 is a more compelling option for developers who want to ensure their applications are future-proof. This new version offers a solid basis for the development of modern applications.

 

Tuesday 23 May 2023

How to implement global exception handling in .NET Core

  Hello friends,

 In this article, I will explain What is global exception and Pros and cons of global exception and  

  • How to implement it via middleware’s


Introduction of Global Exception

We often come up with exceptions in our application and we have two ways in general to handle that exception.

  • Handle at controller/service level everywhere in the application
  • Handle from one place and control the application

 

Pros and Cons of Global Exception

Let’s see the pros and cons of this approach

Pros  :

  • Code becomes easy to manage because we don’t need to look into n different try-catch blocks, just look from one place and deal with them.
  • More readable because a few lines of code managing the whole exceptions of the application
  • Removes repeated code (try-catch everywhere)
  • It gives us more control so we can catch exceptions and return responses of our own type, in most cases we return Internal Server Error.  

Cons :

  • A global exception handler can make it harder because sometimes it will catch the exception at a broad level and deal with it accordingly without digging down to the exact lower-level exception

If you are on short time and you need to implement exception handling then global exception handling is the best solution.


How to Implement it via Middleware

We have different ways to implement global exception handling in our .NET application e.g. using custom/built-in exception filter or creating our custom middleware using IMiddleware and implementing its methods.

So every time before and after controller request will come in this middleware and we would add a try-catch block here and the request would be caught here.

Step 1: Create Middleware




If you are worried about what is JsonConvert.SerializeObject(response) then check post on ‘Serialization’.


Step 2 : Register the Middleware as a Service and then use it in Middleware in Program.cs



That’s all you need to do. Now you can add any exception by throwing a new Exception("This is a test exception"), and test if it works or not


 Happy programming!!

Don’t forget to leave your feedback and comments below!

Regards

Sujeet Bhujbal

--------------------------------------------------------------------------------

Blog: www.sujeetbhujbal.com

Personal Website :-http://sujeetbhujbal.wordpress.com/ 

CodeProject:-http://www.codeproject.com/Members/Sujit-Bhujbal 

CsharpCorner:-http://www.c-sharpcorner.com/Authors/sujit9923/sujit-bhujbal.aspx

Linkedin :-http://in.linkedin.com/in/sujitbhujbal 

Twitter :-http://twitter.com/SujeetBhujbal 

------------------------------------------------------------------------------



 

Monday 8 August 2022

How to prevent 𝐂𝐫𝐨𝐬𝐬 𝐒𝐢𝐭𝐞 𝐒𝐜𝐫𝐢𝐩𝐭𝐢𝐧𝐠 (𝐗𝐒𝐒) 𝐚𝐭𝐭𝐚𝐜𝐤𝐬 in Asp.Net Core

Hello friends,

 In this article, I will explain What is Cross-Site Scripting (XSS) attacks and how to prevent -Site Scripting (XSS) attacks


 What is Cross-Site Scripting (XSS) attacks 

    Cross-Site Scripting (XSS) attacks are a type of injection, in which malicious scripts are injected into otherwise benign and trusted websites.

XSS attacks occur when an attacker uses a web application to send malicious code, generally in the form of a browser-side script, to a different end user.

    Flaws that allow these attacks to succeed are quite widespread and occur anywhere a web application uses input from a user within the output it generates without validating or encoding it.

    An attacker can use XSS to send a malicious script to an unsuspecting user. The end user’s browser has no way to know that the script should not be trusted, and will execute the script. Because it thinks the script came from a trusted source, the malicious script can access any cookies, session tokens, or other sensitive information retained by the browser and used with that site.

 

How to Protect Yourself

The primary defenses against XSS are described in the OWASP XSS Prevention Cheat Sheet.

Also, it’s crucial that you turn off HTTP TRACE support on all web servers. An attacker can steal cookie data via Javascript even when document.cookie is disabled or not supported by the client.

This attack is mounted when a user posts a malicious script to a forum so when another user clicks the link, an asynchronous HTTP Trace call is triggered which collects the user’s cookie information from the server, and then sends it over to another malicious server that collects the cookie information so the attacker can mount a session hijack attack.

This is easily mitigated by removing support for HTTP TRACE on all web servers.

 

 

How to Prevent XSS -  

To keep yourself safe from XSS, you must sanitize your input. Your application code should never output data received as input directly to the browser without checking it for malicious code.

One of the steps in the process is to use the 𝐗-𝐗𝐒𝐒-𝐏𝐫𝐨𝐭𝐞𝐜𝐭𝐢𝐨𝐧.
X-XSS-Protection is a header that can be set on a webpage to activate “limited” XSS protection in certain browsers.

 

1.    X-XSS-Protection: 1 : Force XSS protection (useful if XSS protection was disabled by the user)

2.    X-XSS-Protection: 0 : Disable XSS protection

3.    The token mode=block will prevent browser (IE8+ and Webkit browsers) to render pages (instead of sanitizing) if a potential XSS attack is detected.

 



Syntax
:

 

𝐗-𝐗𝐒𝐒-𝐏𝐫𝐨𝐭𝐞𝐜𝐭𝐢𝐨𝐧: 1; 𝐦𝐨𝐝𝐞=𝐛𝐥𝐨𝐜𝐤

- This enables XSS filtering. Rather than sanitizing the page, the browser will prevent rendering of the page if an attack is detected.

Please Note: Some of the popular browsers like chrome, edge have changed their policy of implementing XSS protection. This means that if you do not need to support legacy browsers, it is recommended that you use Content-Security-Policy without allowing unsafe-inline scripts instead - we will talk about that in the next post.

 

 

Example:

 



  Happy programming!!

Don’t forget to leave your feedback and comments below!

Regards

Sujeet Bhujbal

--------------------------------------------------------------------------------

 Blog: www.sujeetbhujbal.com

Personal Website :-http://sujeetbhujbal.wordpress.com/ 

CodeProject:-http://www.codeproject.com/Members/Sujit-Bhujbal 

CsharpCorner:-http://www.c-sharpcorner.com/Authors/sujit9923/sujit-bhujbal.aspx

Linkedin :-http://in.linkedin.com/in/sujitbhujbal 

Twitter :-http://twitter.com/SujeetBhujbal 

------------------------------------------------------------------------------