Tuesday, November 28, 2017

Wrote a post on Wiki Life at Official Blog of TechNet Wiki

Wrote a post in Wiki Ninjas - Official Blog of TechNet Wiki. The title of the post is TNWiki Article Spotlight – Implementing Server Side validations in AngularJS.
image
TNWiki Article Spotlight – Implementing Server Side validations in AngularJS
Read the rest on,
TNWiki Article Spotlight – Implementing Server Side validations in AngularJS

Happy Coding.

Regards,
Jaliya

Sunday, November 26, 2017

Fiddler Doesn’t Capture All RavenDB REST API Calls

I was trying to figure out an issue in a Web Application that I am currently working on and it has a RavenDB backend.

The code was doing some operations on the RavenDB database (behind the scene those method calls gets translated into API calls to RavenDB REST API), and I was using Fiddler to trace the API calls to RavenDB. But apparently, only some of the API calls were listed on Fiddler and most of the calls were not present. But RavenDB logs showed that it is receiving calls, so I was bit confused why Fiddler isn’t capturing the calls.

Spent couple of hours changing Fiddler settings, RavenDB IIS Web Application settings, but output was still the same.

I had RavenDB IIS Web Application running on 8080 and I was using Url=http://localhost:8080;Database={MyDatabaseName} as the connection string. I just replaced localhost with my machine name and that was it. I am seeing all the API calls to RavenDB in fiddler.

So  if you want Fiddler to capture all RavenDB calls being made from your application, instead of having localhost or 127.0.0.1, use the machine name.

So now everything is in-place to find out the real issue, I am back to it.

Hope someone will find this helpful.

Happy Coding.

Regards,
Jaliya

Tuesday, November 21, 2017

Visual C# Technical Guru - October 2017

Another month as a judge in Microsoft TechNet Guru Awards under Visual C# category. The TechNet Guru Awards celebrate the technical articles on Microsoft TechNet.

Post in WikiNinjas Official Blog,
image
Visual C# Technical Guru - October 2017
Happy Coding.

Regards,
Jaliya

Saturday, November 4, 2017

Azure PowerShell - Cloning App Service Slots

This is some set of scripts I keep using for cloning Azure App Service Slots. Hope someone will find it useful.
# Login
Login-AzureRmAccount
 
# List all subscriptions (this step is only useful if you have multiple subscriptions)
Get-AzureRmSubscription
 
# Select azure subscription (this step is only useful if you have multiple subscriptions)
Get-AzureRmSubscription –SubscriptionName "<SubscriptionName>" | Select-AzureRmSubscription
 
# Listing all slots for a app service
Get-AzureRmWebAppSlot -ResourceGroupName "<ResourceGroupName>" -Name "<AppServiceName>"
 
# Cloning web app to a new slot
$srcWebApp = Get-AzureRmWebApp -ResourceGroupName "<ResourceGroupName>" -Name "<AppServiceName>"
New-AzureRmWebAppSlot -ResourceGroupName "<ResourceGroupName>" -Name "<AppServiceName>" -AppServicePlan "<AppServicePlan>" -Slot "<NewSlotName>" -SourceWebApp $srcWebApp
 
# Cloning web app slot to a new slot
$srcWebAppSlot = Get-AzureRmWebAppSlot -ResourceGroupName "<ResourceGroupName>" -Name "<AppServiceName>" -Slot "<SourceSlotName>"
New-AzureRmWebAppSlot -ResourceGroupName "<ResourceGroupName>" -Name "<AppServiceName>" -AppServicePlan "<AppServicePlan>" -Slot "<NewSlotName>" -SourceWebApp $srcWebAppSlot
Happy Coding.

Regards,
Jaliya

Wednesday, November 1, 2017

ASP.NET Core 2.0: Why it’s important to have Program.BuildWebHost method?

I was doing some refactoring on an ASP.NET Core 2.0 Web Application which was migrated from ASP.NET Core 1.1.

In ASP.NET Core 1.1 Web Applications, program.cs was like this.
public class Program
{
    public static void Main(string[] args)
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup&lt;Startup>()
            .UseApplicationInsights()
            .Build();
 
        host.Run();
    }
}
But with ASP.NET Core 2.0, it has to be something like this.
public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }
 
    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup&lt;Startup>()
            .Build();
}
I felt like I can eliminate BuildWebHost method, so I did like follows.
public class Program
{
    public static void Main(string[] args)
    {
        WebHost.CreateDefaultBuilder(args)
            .UseStartup&lt;Startup>()
            .Build()
            .Run();
    }
}
All seem be good, the application was running well. After sometime, I wanted to add a database migration, and when I tried to do Add-Migration, I was getting this weird error.
Unable to create an object of type 'T'. Add an implementation of 'IDesignTimeDbContextFactory&lt;T>' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.
Apparently the error turned out to be program.cs not having BuildWebHost method.

In ASP.NET Core 1.x to ASP.NET Core 2.0 Migration Guide, it specifically says, “The adoption of this new 2.0 pattern is highly recommended and is required for product features like Entity Framework (EF) Core Migrations to work.”

Once I added it back, I was able to add database migrations back again.

Lesson learnt: When doing refactoring, somethings are better left alone!

Happy Coding.

Regards,
Jaliya

Thursday, October 12, 2017

ASP.NET Core 2.0 – Applying CORS Policies

In this post let’s see how we can apply CORS policies for different scenarios (based on the route/path etc.) in an ASP.NET Core 2.0 Web Application.

As you already know, in ASP.NET Core projects, on the Startup.cs, we have 2 methods ConfigureServices and Configure, and these two will get called by the runtime. ConfigureServices is used to add services to the container, so we can use them through out the application. Configure method is used to configure the HTTP Request pipeline.

So moving to the topic, first thing we need to do is AddCors to IoC container, (again so we can consume this through out the application). (Note: these is an alternate way, and I will be describing that later in the post, keep reading forward)
public void ConfigureServices(IServiceCollection services)
{
    // Add policies, so we can consume them when configuring HTTP request pipeline
    services.AddCors(options =>
    {
        string[] origins = new string[] { "http://localhost:2000", "http://localhost:2001" };
 
        options.AddPolicy("MyCorsPolicy", policyBuilder =>
        {
            policyBuilder
                .AllowAnyHeader()
                .AllowAnyMethod()
                .WithOrigins(origins);
        });
    });
 
    services.AddMvc();
}
Once we have defined the CORS policy (you can define many policies), we can configure the HTTP Requests for CORS policies in following ways.
  1. Application Level (Applies to all the HTTP Requests)
  2. Controller Level
  3. Custom

Application Level


This is kind of the basic approach among above three.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
 
    app.UseCors("MyCorsPolicy");
            
    app.UseMvc();
}
Something to note here is, if you prefer not to go with named policies, you can just skip Adding CORS (AddCors) and do as following in Configure method.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
 
    app.UseCors(policyBuilder =>
    {
        string[] origins = new string[] { "http://localhost:2000", "http://localhost:2001" };
 
        policyBuilder
            .AllowAnyHeader()
            .AllowAnyMethod()
            .WithOrigins(origins);
    });
 
    app.UseMvc();
}

Controller Level


If you don’t want to go with Application level and you want to go with Controller level, this is how you can do it.
[EnableCors("MyCorsPolicy")]
[Route("api/[controller]")]
public class ValuesController : Controller
{
    // actions
}
But to do this, so need to have named CORS policies defined.

Note: The precedence order is: Action, controller, global. Action-level policies take precedence over controller-level policies, and controller-level policies take precedence over global policies.

Custom


Imagine, you want to apply CORS policy based on HTTP Request route/path etc. You can use the power of Middleware for that kind of a scenario.

One approach would would be, you can use app.Map and app.MapWhen to branch off the HTTP Request pipeline and use app.UseCors as shown in above, but the downside is your HTTP Request pipeline is getting short-circuited. That of course you can merge back, but personally I don’t find it a good approach.

The other approach (which I personally find best) is, you can easily create a separate Middleware class for handling CORS in following way.
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Cors.Infrastructure;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
 
namespace WebApplication178.Middleware
{
    public class CustomCorsMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ICorsService _corsService;
        private readonly ICorsPolicyProvider _corsPolicyProvider;
        private readonly CorsPolicy _policy;
        private readonly string _corsPolicyName;
 
        public CustomCorsMiddleware(
            RequestDelegate next,
            ICorsService corsService,
            ICorsPolicyProvider policyProvider)
            : this(next, corsService, policyProvider, policyName: null) { }
 
        public CustomCorsMiddleware(
            RequestDelegate next,
            ICorsService corsService,
            ICorsPolicyProvider policyProvider,
            string policyName)
        {
            _next = next ?? throw new ArgumentNullException(nameof(next));
            _corsService = corsService ?? throw new ArgumentNullException(nameof(corsService));
            _corsPolicyProvider = policyProvider ?? throw new ArgumentNullException(nameof(policyProvider));
            _corsPolicyName = policyName;
        }
 
        public CustomCorsMiddleware(
           RequestDelegate next,
           ICorsService corsService,
           CorsPolicy policy)
        {
            _next = next ?? throw new ArgumentNullException(nameof(next));
            _corsService = corsService ?? throw new ArgumentNullException(nameof(corsService));
            _policy = policy ?? throw new ArgumentNullException(nameof(policy));
        }
 
        public async Task Invoke(HttpContext context)
        {
            if (context.Request.Headers.ContainsKey(CorsConstants.Origin))
            {
                CorsPolicy corsPolicy = null;
 
                // If the following condition matches only apply CORS Policy
                if (context.Request.Path.ToString().ToLower().Contains("something"))
                {
                    corsPolicy = _policy ?? await _corsPolicyProvider?.GetPolicyAsync(context, "MyCustomPolicy");
                }
 
                if (corsPolicy != null)
                {
                    var corsResult = _corsService.EvaluatePolicy(context, corsPolicy);
                    _corsService.ApplyResult(corsResult, context.Response);
 
                    var accessControlRequestMethod = context.Request.Headers[CorsConstants.AccessControlRequestMethod];
                    if (string.Equals(
                            context.Request.Method,
                            CorsConstants.PreflightHttpMethod,
                            StringComparison.OrdinalIgnoreCase) &&
                            !StringValues.IsNullOrEmpty(accessControlRequestMethod))
                    {
                        // Since there is a policy which was identified,
                        // always respond to preflight requests.
                        context.Response.StatusCode = StatusCodes.Status204NoContent;
                        return;
                    }
                }
            }
 
            await _next(context);
        }
    }
}
The whole piece of code is taken from CorsMiddleware.cs (cheers to Microsoft for going open source), and we can just modify it to match our need. Here I have modified it to apply CORS policy based on the request route/path. Now you can simply do following.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
 
    app.UseMiddleware<CustomCorsMiddleware>();
            
    app.UseMvc();
}
The usual behavior of CorsMiddleware would be as follows. For this, you need to have Microsoft.AspNetCore.Cors package installed.
app.UseMiddleware<CorsMiddleware>();
 
// Passing in the policy name
app.UseMiddleware<CorsMiddleware>("MyCorsPolicy");
Hope this helps.

Happy Coding.

Regards,
Jaliya

Tuesday, October 10, 2017

EF Core Automatic Migrations

As you might know and as of today, for Entity Framework Core, Microsoft does not support Automatic Database Migrations as in Entity Framework Full. The reasons are described in this Issue. But it doesn't stop you from configuring automatic migrations by your own. You can just write something like below and call this inside Startup -> Configure method passing the IApplicationBuilder.
private static void InitializeMigrations(IApplicationBuilder app)
{
    using (var serviceScope = app.ApplicationServices.GetService<IServiceScopeFactory>().CreateScope())
    {
        MyDbContext dbContext = serviceScope.ServiceProvider.GetRequiredService<MyDbContext>();
        dbContext.Database.Migrate();
 
        // TODO: Use dbContext if you want to do seeding etc.
    }
}
Happy Coding.

Regards,
Jaliya

Thursday, September 28, 2017

Visual C# Technical Guru - August 2017

Another month as a judge in Microsoft TechNet Guru Awards under Visual C# category. The TechNet Guru Awards celebrate the technical articles on Microsoft TechNet.

Post in WikiNinjas Official Blog,
image
Visual C# Technical Guru - August 2017
Happy Coding.

Regards,
Jaliya

Thursday, September 14, 2017

Wrote a post on Wiki Life at Official Blog of TechNet Wiki

Wrote a post in Wiki Ninjas - Official Blog of TechNet Wiki. The title of the post is TNWiki Article Spotlight – Getting started with Cognitive Services – Vision.
image
TNWiki Article Spotlight – Getting started with Cognitive Services – Vision

Happy Coding.

Regards,
Jaliya

Wednesday, August 30, 2017

Visual C# Technical Guru - July 2017

Another month as a judge in Microsoft TechNet Guru Awards under Visual C# category. The TechNet Guru Awards celebrate the technical articles on Microsoft TechNet.

Post in WikiNinjas Official Blog,
image
Visual C# Technical Guru - July 2017
Happy Coding.

Regards,
Jaliya