C# expression trees

We want to treat lambda expressions as expression trees and look inside them instead of executing them. For example, LINQ to SQL gets the expression and converts it to the equivalent SQL statement and submits it to server (rather than executing the lambda).

With Lambda expressions we can write less code, and the code will be more readable.

A lambda expression uses the lambda operator => which means goes to.

arguments => expession

The expression reads: arguments goes to expression.

Let’s start with a common example;

using System;

namespace Lambdas
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine(Square(5));
            Console.ReadLine();
        }

        static int Square(int num)
        {
            return num * num;
        }
    }
}

we declare a method called Square of type int with one input parameter of type int. It multiplies the number and returns the result.

In the Main() method we call our Square method with an int as a parameter.

We can convert this function into a Lambda expression. This is what it would look like:

num => num * num;

This expression would read: num goes to calculation (num * num).

This expression is short and easily readable once we get used to it. The catch though, is that a Lambda expression must be assigned to a delegate.

Resources

https://stackoverflow.com/questions/793571/why-would-you-use-expressionfunct-rather-than-funct

https://tyrrrz.me/blog/expression-trees

https://thesharperdev.com/an-introduction-to-c-expression-trees/

SQL Server Transaction block

This is suggested code block for creating stored procedures in SQL Server;

BEGIN TRY
	BEGIN TRANSACTION
	--All your insert/update/delete/merge goes in here
	COMMIT TRANSACTION
END TRY

BEGIN CATCH
	SELECT ERROR_NUMBER() AS ErrorNumber
	,ERROR_MESSAGE() AS ErrorMessage
	 ROLLBACK TRANSACTION
END CATCH

While manipulating multiple tables, the transaction would be roll back if there is any error.

Using Shared Projects in ASP.NET

Shared projects are used to facilitate cross platform development. This allows you to reference an entire project as opposed to just a single assembly.

Shared project is a shred bucket of code. At compile time, any project that reference the shared project will have all of the files (including folder structure) and then they will be compiled. You wouldn’t see any separate DLL as you might have seen in PCL (Portable class libraries).

A shared project is not going to be compiled on its own. The code in the shared project is incorporated into assembly that reference it and compiled within that assembly.

Let’s create a shared project;

Create a class Math with a static method Add.

namespace SharedProject1
{
    public class Math
    {
        public static int Add(int x, int y)
        {
#if NETCOREAPP1_1
            return (x + y) + 3;
#else
            return (x + y) + 13;
#endif
        }
    }
}

Add SharedProject reference to your project. If your project is targeting .NET Core 1.1, the relevant piece of code in #if/#endif will run.

//.NET Core 1.1
SharedProject1.Math.Add(3, 4);      //return 10

//.NET Core 1.0
SharedProject1.Math.Add(3, 4);      //return 20

Here is some recommendation of using Shared Projects and Portable Class Libraries;

How the code is reused

  1. Shared Projects: Source Code (All source code is available to your reference project)
  2. PCL: Reference is available at Assembly level (for example MyLibrary.dll)

Compile time behavior

  1. Shared Projects: All source code is copied into each referenced project and compiled there
  2. PCL: Nothing new. Its compiled as usuall.

Visual Studio support

  1. Shared Projects: Full Support
  2. PCL: Each plateform is compiled separately. This can be accomplished thru IOC.

#IFDEF Support

  1. Shared Projects: Full Support
  2. PCL: Unsupported

.NET Framework Support

  1. Shared Projects: Full Support
  2. PCL: Limited

The core problem with shared project is difficulty of code testing because of conditional compilation directives. This in turn introduce errors that you wouldn’t know until you have actually compiled your application.

Resources

https://dev.to/rionmonster/sharing-is-caring-using-shared-projects-in-aspnet-e17

https://stackoverflow.com/questions/30634753/what-is-the-difference-between-a-shared-project-and-a-class-library-in-visual-st

Send email in .NET Core using Mailkit and office 365

Using SmtpClient to send email .NET core is obsolete. The current recommendation is to use the MailKit library . Here is how to use it with the office 365 SMTP servers.

var message = new MimeMessage();
message.From.Add(new MailboxAddress("{from name}", "{from email address}"));
message.To.Add(new MailboxAddress("{to name}", "{to email address}"));
message.Subject = "{subject}";

message.Body = new TextPart("plain")
{
    Text = "{body}"
};

using (var client = new SmtpClient())
{
    await client.ConnectAsync("smtp.office365.com", 587, SecureSocketOptions.StartTls);
    await client.AuthenticateAsync("{from email address}", "{from password}");
    await client.SendAsync(message);
    await client.DisconnectAsync(true);
}

Difference between mit, gpl and apache software license

The MIT, BSD, and ISC licenses are “permissive licenses”. They are extremely short and essentially say “do whatever you want with this, just don’t sue me.”

The Apache license says “do whatever you want with this, just don’t sue me” but does so with many more words, which lawyers like because it adds specificity. It also contains a patent license and retaliation clause which is designed to prevent patents (including patent trolls) from encumbering the software project.

The GPL licenses (GPLv3, GPLv2, LGPL, Affero GPL) all contain some kind of share-alike license. They essentially say “if you make a derivative work of this, and distribute it to others under certain circumstances, then you have to provide the source code under this license.” The important thing to know here is that “derivative work” and “certain circumstances” both require some legal analysis to understand the meaning and impact for your project.

You can read more about it here;