Friday, April 14, 2023

Code practise : Good and Bad

  1. Follow naming conventions:
  2. arduino
    // Bad: int a; int x1; // Good: int age; int numberOfCustomers;
    1. Use comments:
    arduino
    // Bad: int result = 10 / 0; // Divide by zero // Good: // Divide the dividend by the divisor and return the result. // Throws DivideByZeroException if divisor is zero. int Divide(int dividend, int divisor) { if (divisor == 0) { throw new DivideByZeroException("Divisor cannot be zero."); } return dividend / divisor; }
    1. Keep your code clean and organized:
    c
    // Bad: int a=10,b=20,c=30,d=40;string name="John"; // Good: int a = 10; int b = 20; int c = 30; int d = 40; string name = "John";
    1. Use exception handling:
    arduino
    // Bad: int result = 10 / 0; // throws DivideByZeroException and crashes the program // Good: try { int result = 10 / 0; } catch (DivideByZeroException ex) { Console.WriteLine("Divide by zero error: " + ex.Message); }
    1. Use object-oriented programming principles:
    csharp
    // Bad: public int Add(int a, int b) { return a + b; } // Good: public interface IAddable { int Add(int a, int b); } public class Calculator : IAddable { public int Add(int a, int b) { return a + b; } }
    1. Write efficient code:
    scss
    // Bad: for (int i = 0; i < myList.Count; i++) { Console.WriteLine(myList[i]); } // Good: foreach (var item in myList) { Console.WriteLine(item); }
    1. Test your code thoroughly:
    csharp
    // Bad: public int Add(int a, int b) { return a + b; } // Good: [TestClass] public class CalculatorTests { [TestMethod] public void TestAdd() { Calculator calc = new Calculator(); int result = calc.Add(2, 3); Assert.AreEqual(5, result); } }

    By following these coding practices, you can write clean, maintainable, and efficient C# code that is easy to read and understand, and that works as expected.

.Net core feature

ASP.NET Core is a cross-platform, open-source web framework developed by Microsoft that allows developers to build modern, high-performance web applications using a variety of programming languages, including C#, F#, and Visual Basic.

Here are some of the key features of ASP.NET Core:

  1. Cross-platform: ASP.NET Core is designed to work on multiple operating systems, including Windows, macOS, and Linux. This allows developers to build and deploy web applications on a wide range of platforms.

  2. High performance: ASP.NET Core is optimized for performance, with features such as just-in-time compilation and a lightweight runtime that help to improve application speed and scalability.

  3. Modular design: ASP.NET Core has a modular design that allows developers to choose the components they need for their application, rather than being forced to use a monolithic framework. This makes it easier to build and maintain complex applications.

  4. Open source: ASP.NET Core is open source, with a large and active community of developers contributing to its ongoing development and improvement.

  5. Built-in dependency injection: ASP.NET Core includes a built-in dependency injection system, which makes it easier to manage dependencies and simplify application configuration.

  6. Middleware pipeline: ASP.NET Core uses a middleware pipeline to process incoming HTTP requests and outgoing responses. This allows developers to easily add and remove middleware components, and to build custom middleware to handle specific application requirements.

  7. Cloud-ready: ASP.NET Core is designed to work seamlessly with cloud platforms such as Azure, AWS, and Google Cloud. This makes it easier to deploy and scale applications in the cloud.

Overall, ASP.NET Core provides a powerful, flexible, and scalable framework for building modern web applications that can run on a wide range of platforms and devices. 

Sunday, April 2, 2023

SQL server : WITH TIES

WITH TIES allows adding one or more rows along with the rows limited by the TOP or similar statements. It works only when you use it alongside the ORDER BY expression.


Table data:


Query result:





SPARSE Column in sql server

What is a SPARSE Column?

Sparse columns provide a highly efficient way of managing empty space in a database by enabling NULL data to consume no physical space. For example, sparse columns enable object models that typically contain numerous null values to be stored in a SQL Server 2008 database without experiencing large space costs.

What is a Column Set?

Tables that contain sparse columns can define a column set to return the data in all of the sparse columns in the table. Similarly to a computed column, it is not physically stored in the table; however, unlike computed columns, the data in it is directly editable. The column set returns an untyped XML representation of the data. Column sets are useful when you have a large number of sparse columns in a table and working with them is awkward.

How to use SQL Server Sparse Columns ?

We can define sparse columns by using either the CREATE TABLE or ALTER TABLE statement, using the SPARSE keyword for the columns that you require to be sparse columns. 

Notes :

Sparse columns require more storage space for non-null values than a standard column.

Data types like geography, geometry, image, ntext, text, and timestamp cannot be used for sparse columns. 


Example:



Thursday, January 12, 2023

The Fastest Way To Loop In C#

These are different ways to loop over a collection:

  • do()
  • do/while()
  • for()
  • foreach()
  • ForEach()
  • For()
  • For(MaxDegreeOfParallelism)
  • ForEach()
  • ForEach(MaxDegreeOfParallelism)
  • ForEachAsync()
  • ForEachAsync(MaxDegreeOfParallelism)

Which one of these ways to loop over a collection do you think is the fastest? First, let’s look at a few of these ways to loop over an array. This is an example of using Parallel.For() with MaxDegreeOfParallelism:

var collection = personArray;
ParallelOptions options = new() {
    MaxDegreeOfParallelism = 6
};
_ = Parallel.For(fromInclusive: 0, toExclusive: collection.Length, parallelOptions: options, body: (index) => {
    base.Update(collection[index]);
});
C#

Benchmark Results

Here are the benchmark results that shows using Parallel.For() for a reference, value and record type.



Here is an example of using Parallel.ForEachAsync().

var collection = _personRecordArray;
await Parallel.ForEachAsync(collection, (person, token) => {
    base.Update(person);
    return new ValueTask();
});
C#

Benchmark Results

Here are the benchmark results that shows using Parallel.ForEachAsync() for a reference, value and record type.



As you can see from these benchmarks, using Parallel.ForEachAsync() is a lot slower than using Parallel.For() (around 6.86 times slower).

So, what is the fastest way to loop over an array? Well, according to my benchmark tests, it can actually vary depending on the type used in the array. If the array contains a reference or value type, then using for() is the clear winner! If the array contains the record type, then using Parallel.For() is the fastest (around 1.13 times faster) Here is an example:

var collection = personRecordArray;
_ = Parallel.For(0, collection.Length, (index) => {
    base.Update(collection[index]);
});
C#

In all of my benchmark tests, value types (structures) loops the slowest when compared to the reference and record type. I recommend to not use them in collections.

Using Spargine to Speed Up Arrays

I am currently making changes to my OSS project Spargine based on the findings in the latest edition of my code performance book. To make processing collections as fast as possible easy, I’m adding extension methods called PerformAction(). Here is how I unit test this method:

var words = RandomData.GenerateWords(count: 10, minLength: 10, maxLength: 100).ToArray();
var sb = new StringBuilder();
words.PerformAction((word) => {
    sb.Append(word);
});
var result = sb.ToString();
C#

This method also verifies there are items in the array to prevent exceptions. I will be using this method from now on when processing arrays because if the .NET team comes out with an even faster way to loop over an array, I can just change the code in PerformAction() and instantly all projects that use it get the performance boost! Code reuse is a good thing! I will revisit these methods whenever I do a major run of my benchmark tests so make sure to keep the Spargine NuGet packages up to date. You can add Spargine to your projects by going here: http://bit.ly/dotNetDaveNuGet.

Tuesday, January 3, 2023

SingleOrDefault vs FirstOrDefault

 SingleOrDefault returns a SINGLE element or null if no element is found. If 2 elements are found in your Enumerable then it throws the exception you are seeing. Just like Highlander... with Single - there can be only one.

FirstOrDefault returns the FIRST element it finds or null if no element is found. so if there are 2 elements that match your predicate the second one is ignored.

deliveryGroup.DeliveryMethods.SingleOrDefault(x => x.Id == methodId)

deliveryGroup rd = this.db.Details .FirstOrDefault(x => x.TId == Id && x.TypeId == TypeId);


its use very careful because when found any duplicate SingleOrDefault it will throw error.

Convert json date in jQuery

 The date format js is give in the below section, please go below and see the date.format.js and copy and use it.

Table of content for JSON date format

  1. JSON date
  2. Parse JSON date to date
  3. Date format types
  4. Demo link for live output
  5. JavaScript code for date format
  6. Full example code for multiple date format

 The JSON date is
        /Date(1297246301973)/

The JQuery Code is
        var jsonDate = "\/Date(1297246301973)\/";
        var date = new Date(parseInt(jsonDate.substr(6)));

Opps Part 1 : Abstraction

  Abstraction in C# is a fundamental concept of object-oriented programming (OOP) that allows developers t...