Thursday, January 30, 2020

Extension Methods

Extension methods allow you to inject additional methods without modifying, deriving or recompiling the original class, struct or interface.

An extension method is actually a special kind of static method defined in a static class. To define an extension method, define a static class.

The first parameter of the extension method specifies the type on which the extension method is applicable. So the first parameter must be preceded with the this modifier.

Extension methods can be recognized in Visual Studio Intellisense as shown below



Example :  In the below example I am performing multiplication on a integer by calling the Multiply() extension method. then I do a division. Here before dividing the two numbers I check if the divisor is positive by using the isPositive() extension method, then do the division by using the Division() extension method

1) static class containing Extension Methods

    public static class Extensions
    {
        public static int Multiply(this int number, int multiplier)
        {
            return number * multiplier;
        }

        public static bool isPositive(this int number)
        {
            return number > 0;
        }

        public static double Division(this int dividend, int divisor)
        {
            return dividend / divisor;
        }
    }

2) class to test the extension methods

    class ExtensionMethodsTest
    {
        /// <summary>
        ///  Usage one - Multiplication
        /// </summary>
        public void GetMultiplier()
        {
            int i = 5;
            int result = i.Multiply(10);
            Console.WriteLine(result);         
        }

    /// <summary>
    /// usage two - Division
    /// </summary>
    public void GetDivisor()
        {
            int dividend = 256;
            int divisor = -1;
            double? quotient = null;

            if (divisor.isPositive())
            {
                quotient = dividend.Division(divisor);
            }
            else
            {
                Console.WriteLine("Divisor should be a positive number");
            }
            Console.ReadLine();
        }
    }

3) calling the ExtensionMethodsTest class

            ExtensionMethodsTest test = new ExtensionMethodsTest();
            test.GetMultiplier();
            test.GetDivisor();

Result:

Wednesday, January 29, 2020

Renaming the wwwroot folder - .NET Core

In .NET Core, only the files with in the web root are served unlike in .NET. All the other files are blocked. So, you have to have all JavaScript, CSS and image files within the web root which by default is the wwwroot folder. Lets say you renamed the "wwwroot" folder to "Content", then you have to set the new name as the web root. Set it inside the main method of the Program.cs file.

public class Program
{
    public static void Main(string[] args)
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseWebRoot("Content")
            .UseIISIntegration()
            .UseStartup<MyStartup>()
            .Build();

        host.Run();
    }
}

Saturday, January 25, 2020

Run query inside a Transaction - Entity Framework

In Entity Framework you have to run the code with in a DbContextTransaction scope. In this example we run within the DbContextTransaction scope, Get a lock & finally commit at the end.

public bool MySampleMethod(Model instance)
{
using (DbContextTransaction scope = _context.Database.BeginTransaction())
{
bool sent;
_context.Database.ExecuteSqlCommand("SELECT TOP 1 Id FROM MySampleTable WITH (TABLOCKX, HOLDLOCK)");

sent = _context.MySampleTable.Any(n => n.Guid == instance.Guid &&
n.PublishedDate ==
instance.PublishedDate &&
n.UserId == instance.UserId &&
n.RegistrationId ==
instance.RegistrationId);

if (!sent)
{
DoFurtherProcessing(instance);
}
scope.Commit();
}
return sent;
}

Tuesday, January 7, 2020

AddSingleton vs AddScoped vs AddTransient methods - Dependency injection into controllers in .NET Core

The Model class

public class InventoryItems
{
public int Id { get; set; }
public string Name { get; set; }
public double Price { get; set; }
}

The interface for the service class

public interface IInventoryServices
{
InventoryItems AddInventoryItems(InventoryItems items);
Dictionary<string, InventoryItems> GetInventoryItems();
}

The service class

public class InventoryServices : IInventoryServices
{
private readonly Dictionary<string, InventoryItems> _inventoryItems;

public InventoryServices()
{
_inventoryItems = new Dictionary<string, InventoryItems>();
}
public InventoryItems AddInventoryItems(InventoryItems items)
{
_inventoryItems.Add(items.Name, items);
return items;
}

Dictionary<string, InventoryItems> IInventoryServices.GetInventoryItems()
{
return _inventoryItems;
}
}

The controller which the service is injected in the constructor

    [Route("api/[controller]")]
    [ApiController]
    public class InventoryController : ControllerBase
    {
private readonly IInventoryServices _service;

public InventoryController(IInventoryServices services)
{
_service = services;
}

[HttpPost]
[Route("AddInventoryItems")]
public ActionResult<InventoryItems> AddInventoryItem(InventoryItems items)
{
var inventoryItems = _service.AddInventoryItems(items);
return inventoryItems;
}

[HttpGet]
[Route("GetInventoryItems")]
public ActionResult<Dictionary<string, InventoryItems>> GetInventoryItems()
{
var inventoryItems = _service.GetInventoryItems();
return inventoryItems;
}
    }

Now in the Startup.cs we have to specify the dependency injection under the "ConfigureServices" method.

public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSingleton<IInventoryServices, InventoryServices>();
}

There are three ways in which you could set the Dependency Injection. They are AddSingleton(), AddScoped() and AddTransient()

Singleton - An instance of the service class (InventoryServices) is created, when the interface of the service (IInventoryServices) is first requested and that single instance of the service class (InventoryServices) is used by all http requests throughout the application

Scoped - Here we get the same instance within the scope of a given http request but a new instance of the service is created during a different http request

Transient - a new instance of the service class is created every time an instance is requested whether it is the scope of the same http request or across different http requests 

Auxiliary
Postman Post Request:









  

                                                                                                                                               
  
             Postman Get Request:



Monday, January 6, 2020

This Project is configured to use SSL. Disable https in visual studio web project - Asp.Net Core

In the .NET Core WEb applications SSL are enabled by default.

You get a message as "This Project is configured to use SSL. To avoid SSL warnings in the browser you can choose to trust the self-signed certificate that IIS Express has generated. Would you like to trust the IIS SSL certificate?"

Even though it is recommended to have SSL, during debugging you may need to disable this option.

For that, Go to project properties. In the "Debug" tab, find the "Web Server Settings" section. Un-tick the "Enable SSL" option.