Wednesday, 17 June 2020

C# - .Net Framework vs .Net Core vs .Net Standard


Demystifying .NET Core and .NET Standard

As the newest members of the .NET family, there’s much confusion about .NET Core and .NET Standard and how they differ from the .NET Framework. In this article, I’ll explain exactly what each of these are and look at when you should choose each one.
Before going into detail, it’s helpful to look at the larger picture of .NET to see where .NET Core and .NET Standard fit in. When.NET Framework first shipped 15 years ago, it had a single .NET stack that you could use for building Windows desktop and Web applications. Since then, other .NET implementations have emerged, such as Xamarin, which you can use for building mobile apps for iOS and Android, as well as macOS desktop applications




Here’s how .NET Core and .NET Standard fit into this:
  • .NET Core: This is the latest .NET implementation. It’s open source and available for multiple OSes. With .NET Core, you can build cross-platform console apps and ASP.NET Core Web applications and cloud services.
  • .NET Standard: This is the set of fundamental APIs (commonly referred to as base class library or BCL) that all .NET implementations must implement. By targeting .NET Standard, you can build libraries that you can share across all your .NET apps, no matter on which .NET implementation or OS they run.
Introduction to .NET Core
.NET Core is a new cross-platform and fully open source .NET implementation that was forked from .NET Framework and Silverlight. It’s optimized for mobile and server workloads by enabling self-contained XCOPY deployments.
To get a better feel for .NET Core, let’s take a closer look at what developing for .NET Core looks like. And let’s do this while exploring the new command line-based tooling. You can also use Visual Studio 2017 for your .NET Core development, but because you’re reading this article, chances are you’re quite familiar with Visual Studio already, so I’ll focus on the new experience.
When .NET was created, it was heavily optimized for rapid appli­cation development on Windows. In practice, this means that .NET development and Visual Studio were inseparable friends. And sure thing: Using Visual Studio for development is a blast. It’s super productive and the debugger is hands down the best I’ve ever used.
However, there are cases where using Visual Studio isn’t the most convenient option. Let’s say you want to just play with .NET to learn C#: You shouldn’t have to download and install a multi-gigabyte IDE. Or, say you’re accessing a Linux machine over SSH where using an IDE is simply not an option. Or, say you’re simply someone who prefers using a command-line interface (CLI).
That’s why a first-class CLI was created, called .NET Core CLI. The .NET Core CLI’s main driver is called “dotnet.” You can use it for virtually all aspects of your development, including creating, building, testing and packaging projects. Let’s see what this looks like.

.Net Framework and .Net Core both are two different implementations of .Net Runtime. First one is older and .Net Core is newer than .Net Framework. Difference between and .Net Framework and .Net Core and how these both are different from .Net Standard and Why We Should Use .Net Standard.

1.     .Net Framework is a framework for building and managing the Windows and Web-based application. This is old framework created by Microsoft and provides end to end solution to create Windows application generally known as Win Forms and Web Application like Asp.Net or Asp.Net MVC application.
What we can do with .Net Framework.
a)     Create a Windows Application.
b)     Create Web Forms using Asp.Net, Rest API using Web API and enterprise application using Asp.Net MVC
c)      Can use multiple languages, that’s why it is language independent.
d)     Create an app with good performance.

2.     .Net Core is a cross-platform and open source framework for building the application which can run on any platform. It is also created by Microsoft. It is not a new version on .Net Framework, whereas it is a totally new framework which is written from scratch to develop an application which can run on any platforms like Mac, Linux or Windows.  Earlier .Net Framework was Language Independent but .Net Core is language independent as well as platforms independent.
What we can do with .Net Core.
a)     Create cross platforms application.
b)     Can use Microservices
c)      Deploy an application to Dockers container.
d)     Create highly scalable and performable system.
e)     Create Asp.Net Core, Razor page, UMP, Mobile native app and Blazor application.

Before understanding the .Net Standard, let first understand the architecture of .Net Framework and .Net Core. We need to first understand what problem we face to that we need to use .Net Standard. While working with either .Net Framework or .Net Core or Xamarin application, you required Base Class Library (BCL) that is used for sharing the code between multiple projects or solution. 



We can see that each one has its own BCL (Base Class Library).



Problem
Example: Let assume we create an application using .Net Framework and use its library for shared code. After some time, we feel to create an application in .Net Core and try to re-use the same shared code library which is created in .Net Framework.
Can we do that? The answer is NO. We cannot use .Net Framework Base Class Library in .Net Core because of compatibility issues. Basically, the libraries which target to .Net Framework can only run in .Net Framework based application and the libraries which target to .Net Core can only run in .Net Core compatible applications.

Solution
The solution is .Net Standard. .Net Standard is a specification of the set of APIs which is compatible for any .Net platforms either it is .Net Framework or .Net Core. If we create the Base Class Library using .Net Standard, then it will run with any .Net Runtimes.
So, if you are willing to create an application and keep your shared code into Base Class Library then you should choose .Net Standard, because it is portable with .Net Framework, .Net Core and Xamarin as well. If in short, we say something about .Net Standard, so it will be as follows.

1.      It is an evolution of Portable Class Library and completely replaced to PCL.
2.      It is not a framework like .Net Framework or .Net Core.
3.      It is the specification that needs to be implemented by .Net Framework or .Net Core.
4.      Use for code sharing and reuse the codes between different runtimes.
5.      Compatible with any .Net application.




AS per the above image, you can see that instead of keeping a different-different class library for each framework, we can keep only one as .Net Standard which rules them to all.

How .Net Standard is backward compatible?
Each .Net Standard version contains some set of APIs like System.Data, System.Collections etc. If a new version of .Net Standard gets introduced then it contains all the previous version set of APIs as well as some of new APIs. So, it means a newer version of .Net Standard contains all the set of APIs from beginning to end which means a higher version of .Net Standard means more APIs availability.
If you see the compatibility with another framework, then you will find that .Net Standard supports a wide range of Framework. You can refer the following link for updated framework supports.






C# - LINQ - IncludeFilter


LINQ –  IncludeFilter

EF, "Include" method is often used to load related entities / child collections. However, the method doesn't let you use LINQ queryable methods like Where to filter entities to include which is a major drawback. Excluding soft deleted records or limiting the result is a frequent real-life scenario which the "Include" method doesn't support.
EF+ Query IncludeFilter lets you filter and perform LINQ queryable methods on related entities.

// using Z.EntityFramework.Plus; // Don't forget to include this.
var ctx = new EntitiesContext();

// LOAD orders and the first 10 active related entities.
var list = ctx.Orders.IncludeFilter(x => x.Items.Where(y => !y.IsSoftDeleted)
                                               .OrderBy(y => y.Date)
                                               .Take(10))
                     .ToList();

Behind the code

Step 1 - Custom Queryable

The first time IncludeFilter is called, a custom Queryable and Provider are created for your query and will be used to append all queries.

Step 2 - Iterate or Execute

When an immediate method is invoked to resolve the query, the initial query is modified to create a new query which includes related entities.
  • The iterate method is invoked when it is possible to return multiple results like ToList() and ToArray()
  • The execute method is invoked when it is possible to return only one result like First() and Last()

Original Query:

var list = ctx.Orders.IncludeFilter(x => x.OrderItems.Where(y => !y.IsSoftDeleted))
                     .Take(10)
                     .ToList();

Executed Query:

var q1 = ctx.Orders.Take(10)
var p1 = q1.Select(x => x.OrderItems.Where(y => !y.IsSoftDeleted));
 
var list = q1.Select(x => new { x, p1 }).ToList().Select(x => x.X);

Query IncludeFilter - Load one level

// using Z.EntityFramework.Plus; // Don't forget to include this.
var ctx = new EntitiesContext();
 
// LOAD blogs and related active posts.
var blogs = ctx.Blogs.IncludeFilter(x => x.Posts.Where(y => !y.IsSoftDeleted)).ToList();

Query IncludeFilter - Load multiple levels

// using Z.EntityFramework.Plus; // Don't forget to include this.
var ctx = new EntitiesContext();
 
// LOAD blogs and related active posts and comments.
var blogs = ctx.Blogs.IncludeFilter(x => x.Posts.Where(y => !y.IsSoftDeleted))
                     .IncludeFilter(x => x.Posts.Where(y => !y.IsSoftDeleted)
                                                .Select(y => y.Comments
                                                              .Where(z => !z.IsSoftDeleted)))
                     .ToList();


Tuesday, 16 June 2020

C# - Files and Folders

// Directory of Window Form Application
string appPath = Path.GetDirectoryName(Application.ExecutablePath);

// Directory of Any Loaded Assembly
string path = Path.GetDirectoryName(Assembly.GetAssembly(typeof(MyClass)).CodeBase);


File Stream – Open Files
//Open existing file for read and write
using (var fileStream = new FileStream(@"c:\file.txt", FileMode.Open))
{
   
}

//Open existing file for reading
using (var fileStream = new FileStream(@"c:\file.txt", FileMode.Open, FileAccess.Read))
{
  
}

//Open existing file for writing
using (var fileStream = new FileStream(@"c:\file.txt", FileMode.Open, FileAccess.Write))
{
  
}

//Open file for writing(with seek to end), if the file doesn't exist create it
using (var fileStream = new FileStream(@"c:\file.txt", FileMode.Append))
{
   
}

//Create new file and open it for read and write, if the file exists overwrite it
using (var fileStream = new FileStream(@"c:\file.txt", FileMode.Create))
{
  
}

//Create new file and open it for read and write, if the file exists throw exception
using (var fileStream = new FileStream(@"c:\file.txt", FileMode.CreateNew))
{
   
}

File Stream – Read Text Files
//Read Text File into String
//It's super easy to read whole text file into string using static class File and its method File.ReadAllText.
string text = File.ReadAllText(@"c:\file.txt", Encoding.UTF8);
           
//Read Text File into String(with StreamReader)
string text;
var fileStream = new FileStream(@"c:\file.txt", FileMode.Open, FileAccess.Read);
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
{
    text = streamReader.ReadToEnd();
}

File Stream Load Text from Files To String
//Read Text File into String Array
//Again, the easy way is to use static class File and it's method File.ReadAllLi­nes.
string[] lines = File.ReadAllLines(@"c:\file.txt", Encoding.UTF8);

//Read Text File into String Array(with StreamReader)
string[] lines;
var list = new List<string>();
var fileStream = new FileStream(@"c:\file.txt", FileMode.Open, FileAccess.Read);
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
{
    string line;
    while ((line = streamReader.ReadLine()) != null)
    {
        list.Add(line);
    }
}
lines = list.ToArray();
           
//Read Text File Line by Line
foreach (string line in File.ReadLines(@"c:\file.txt", Encoding.UTF8))
{
    // process the line
}

//Read Text File Line by Line(with StreamReader)
var fileStream = new FileStream(@"c:\file.txt", FileMode.Open, FileAccess.Read);
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
{
    string line;
    while ((line = streamReader.ReadLine()) != null)
    {
        // process the line
    }
}

//To load text from file to string you can use StreamReader.
string text;
using (var streamReader = new StreamReader(@"c:\file.txt", Encoding.UTF8))
{
    text = streamReader.ReadToEnd();
}


Get File from Directory 
//Get files from directory
//Method Directory.GetFiles returns string array with files names(full paths).
string[] filePaths = Directory.GetFiles(@"c:\MyDir\");

//Get files from directory (with specified extension)
string[] filePaths = Directory.GetFiles(@"c:\MyDir\", "*.bmp");

//Get files from directory(including all subdirectories)
//If you want to search also in subfolders use parameter SearchOption.A­llDirectories.
string[] filePaths = Directory.GetFiles(@"c:\MyDir\", "*.bmp", SearchOption.AllDirectories);



Delete All Files       
//Delete all files
string[] filePaths = Directory.GetFiles(@"c:\MyDir\");
foreach (string filePath in filePaths)
    File.Delete(filePath);

//Delete all files(one - row example)
//To delete all files using one code line, you can use Array.ForEach with combination of anonymous method.
Array.ForEach(Directory.GetFiles(@"c:\MyDir\"),
              delegate (string path) { File.Delete(path); });

//Directory of windows forms application(.exe)
string appPath = Path.GetDirectoryName(Application.ExecutablePath);

//Directory of any loaded assembly(.exe or .dll)
string path = Path.GetDirectoryName(
                     Assembly.GetAssembly(typeof(MyClass)).CodeBase);


File Attributes – How To Get Or Set File Attributes
//Get file attributes
string filePath = @"c:\test.txt";
FileAttributes fileAttributes = File.GetAttributes(filePath);

//Set file attributes
File.SetAttributes(filePath, FileAttributes.Normal);
File.SetAttributes(filePath, FileAttributes.Archive | FileAttributes.ReadOnly);


// check whether a file is read only
bool isReadOnly = ((File.GetAttributes(filePath) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly);

// check whether a file is hidden
bool isHidden = ((File.GetAttributes(filePath) & FileAttributes.Hidden) == FileAttributes.Hidden);

// check whether a file has archive attribute
bool isArchive = ((File.GetAttributes(filePath) & FileAttributes.Archive) == FileAttributes.Archive);

// check whether a file is system file
bool isSystem = ((File.GetAttributes(filePath) & FileAttributes.System) == FileAttributes.System);

//Add file attributes to current ones
File.SetAttributes(filePath, File.GetAttributes(filePath) | FileAttributes.Hidden);

//Set (add) both archive and read only attributes
File.SetAttributes(filePath, File.GetAttributes(filePath) | (FileAttributes.Archive | FileAttributes.ReadOnly));

//Delete/clear file attributes from current ones
File.SetAttributes(filePath, File.GetAttributes(filePath) & ~FileAttributes.Hidden);

//Delete/clear archive and read only attributes
File.SetAttributes(filePath, File.GetAttributes(filePath) & ~(FileAttributes.Archive | FileAttributes.ReadOnly));



File Stream – Read Files
//Read file using FileStream
//First create FileStream to open a file for reading.
//Then call FileStream.Read in a loop until the whole file is read.
//Finally close the stream.
public static byte[] ReadFile(string filePath)
{
    byte[] buffer;
    FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
    try
    {
        int length = (int)fileStream.Length;  // get file length
        buffer = new byte[length];            // create buffer
        int count;                            // actual number of bytes read
        int sum = 0;                          // total number of bytes read

        // read until Read method returns 0 (end of the stream has been reached)
        while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
            sum += count;  // sum is a buffer offset for next reading
    }
    finally
    {
        fileStream.Close();
    }
    return buffer;
}