Search This Blog

2021-03-02

Dot Net Core Useful Syntax

Some Useful Syntax

Delegate

1. Calling Function
public async Task SendEmailAsync(EmailContent emailInput)
{
await CalledFnAsync(emailInput, async () => await GetEmailContentAsync(emailInput, _emailTemplatePath));
}

2. Called Function
private async Task CalledFnAsync(EmailContent emailInput, Action getEmailContent)
{
    getEmailContent();
}

Extension Method

public async Task<CentralDashboardDataResult> GetDashboardGridResultAsync(GetCentralDashboardDataRequest request)
        {
            var result = await _centralOfficeRepository.GetCentralDashboardDataAsync(request);
           
 result.Rows.ForEach(r => r.PurchaseOrderIssuer = r.PurchaseOrderIssuer.RemoveEmailAddressFromUserName());
           
 return result;
        }

public static class StringExtensions
    {
        public static string RemoveEmailAddressFromUserName(this string userName)
        {
            if (string.IsNullOrEmpty(userName))
                return userName;

            var atIndex = userName.IndexOf("@", StringComparison.Ordinal);
            return atIndex == -1 ? userName : userName.Substring(0, atIndex);
        }
    }

Middleware

a) Service\Common
public class IMSAuthenticationManager
    {       
        private string firstname = string.Empty;
        private string lastName = string.Empty;
      
        public string FirstName
        {
            get
            {
                return this.firstname;
            }
            set
            {
                this.firstname = value;
            }
        }
        public string LastName
        {
            get
            {
                return this.lastName;
            }
            set
            {
                this.lastName = value;
            }
        }
    }

b) Service\Middleware

public class IMSAuthenticationMiddleware
    {
        private readonly RequestDelegate _next;

        public IMSAuthenticationMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext httpContext, IMSAuthenticationManager authManager)
        {
           authManager.FirstName = httpContext.Request.Headers["X-MS-CLIENT-FIRSTNAME"];
            authManager.LastName = httpContext.Request.Headers["X-MS-CLIENT-LASTNAME"];
            await _next(httpContext);
        }
    }

c)Service\Middleware

public static class MiddlewareExtensions
    {
        public static IApplicationBuilder UseIMSAuthentication(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<IMSAuthenticationMiddleware>();
        }

        public static IApplicationBuilder UseIMSExceptionHandling(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<IMSExceptionMiddleware>();
        }
    }

d)Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IMSAuthenticationManager>();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
 app.UseIMSAuthentication();
 app.UseIMSExceptionHandling();
}

e)Controller.cs

private readonly IMSAuthenticationManager _authManager;
public StoreController(
            , IStoreService storeService
            , IMSAuthenticationManager authMgr
            )
        {
            this.storeService = storeService;            
            _authManager = authMgr;
        }

Filter

a)Service\Common

namespace SampleProject.Service.Common
{
    public class AuthFilterAttribute : ActionFilterAttribute
    {
        private readonly IAuthenticationManager authManager;
        private StringValues tokenValues;

        /// <summary>
        /// Initializes a new instance of the <see cref="AuthFilterAttribute"/> class.
        /// </summary>
        /// <param name="authMgr">authMgr.</param>
        public AuthFilterAttribute(IAuthenticationManager authMgr)
        {
            this.authManager = authMgr;
        }

        /// <inheritdoc/>
        public override void OnActionExecuting(ActionExecutingContext actionContext)
        {
            var authHeader = actionContext.HttpContext.Request.Headers.TryGetValue(SampleProjectServiceResource.RequestHeader.Name.AUTHORIZATION, out this.tokenValues);
            if (authHeader)
            {
                string tokenValue = HttpUtility.UrlDecode(this.tokenValues.FirstOrDefault().ToString());
                if (!this.authManager.IsValidKey(tokenValue))
                {
                    actionContext.Result = new UnauthorizedResult();
                }
            }
            else
            {
                actionContext.Result = new UnauthorizedResult();
            }
        }
    }
}

b) Startup.cs
 public void ConfigureServices(IServiceCollection services)
        {
           
            services.AddScoped<AuthFilterAttribute>();         
        }

c) Controller.cs
    [ServiceFilter(typeof(AuthFilterAttribute))]
    public class AmendSlotAdminController : ControllerBase

Null-coalescing assignment operator

Available in C# 8.0 and later, the null-coalescing assignment operator ??= assigns the value of its right-hand operand to its left-hand operand only if the left-hand operand evaluates to null. The ??= operator doesn't evaluate its right-hand operand if the left-hand operand evaluates to non-null.

List<int> numbers = null; int? a = null; (numbers ??= new List<int>()).Add(5); Console.WriteLine(string.Join(" ", numbers)); // output: 5 numbers.Add(a ??= 0); Console.WriteLine(string.Join(" ", numbers)); // output: 5 0 Console.WriteLine(a); // output: 0

Null-coalescing assignment operator

int? a = null;
int b = a ?? -1;
Console.WriteLine(b);  // output: -1

public string Name
{
    get => name;
    set => name = value ?? throw new ArgumentNullException(nameof(value), "Name cannot be null");
}

Expression body definition

public override string GetName() => $"{fname} {lname}".Trim();

It's a shorthand version of the following method definition:

public override string GetName()
{
   return $"{fname} {lname}".Trim();
}

No comments: