Tuesday, February 13, 2018

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 – Azure DevOps Project – A review of the preview.
image
TNWiki Article Spotlight – Azure DevOps Project – A review of the preview

Happy Coding.

Regards,
Jaliya

Wednesday, January 31, 2018

Visual C# Technical Guru - December 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 - December 2017
Happy Coding.

Regards,
Jaliya

Tuesday, January 23, 2018

Rename/Move Files and Directories using git-mv

If you have used git, I am sure you must have experienced this where you have renamed files/folders specially a case change, it won't reflect in the remote. For instance, if you rename a file from helloworld.txt to helloWorld.txt or HelloWorld.txt, even though it's changed in the local, it won't get changed in the remote. 

In such cases, git-mv is a really handy command. A guy named Patrick Wied has written this wonderful post back in 2012 explaining use of git-mv with different scenarios. Great post!

Hope this helps.

Happy Coding.

Regards,
Jaliya

Wednesday, January 17, 2018

Getting Started with Azure Functions

Serverless Computing has become a trending area in Azure than ever before. Basically, Serverless Computing is completely abstracting away the required resources from your concerns. It acts in an event-driven manner, resources are utilized only when you want them to, those are not up and running when you are not using them. So you are getting billed for only for what’s being used. You don’t have to worry about anything else.

When talking about Serverless Computing in Azure, as of today Azure provides following 3 set of features.
  1. Functions - Serverless Compute
  2. Logic Apps - Serverless Workflow
  3. Event Grid - Serverless Events
In this post, let’s see how we can get started with Azure Functions.

First, open up the Azure Portal. Go to New and search for “functions”. And click on Function App.
1. create
Function App
From the next panel, click on Create.
1.1 create
Create
From the next screen, fill in the details as required. For the Hosting Plan, let’s go ahead with the Consumption Plan because we can then get billed per execution of our functions.
3.  create config
New Function App Details
Once the function app is created. Find the created function app by going to More services and searching.
4. find function apps
Find Function Apps
And you should see all your function apps.
image
Function App
Now when you can click on created function app, you will something like below.
5. function app - overview
Function App: Overview
You can find the function app URL under Overview tab. If you click on the URL, an application will open, just as an App Service.
5. url-running
Function App
Function apps’ Settings is under Platform features.
5. function app - platform features
Function App: Platform Features
Right now to get us keep going, let’s create a Function. Click on Functions and then New Function as below.
6. new function
New Function
You are presented with a set of templates.
7. select template
Select Template
All the languages available are as follow (please note, for some of the languages all the templates are not available).
7. languages
Available Languages
First, let’s create an HTTP Trigger.
image
New HTTP Trigger
I have selected Language as C#. For the Name, you can give whatever the name you want. And then we need to select the Authorization level.
  • Function - A function-specific API key is required. This is the default value if none is provided.
  • Anonymous - No API key is required.
  • Admin - The master key is required.
Let’s go ahead with Anonymous for the purpose of the demo.

Once the function is created, you are presented with a page with a csx file. csx stands for C# Script file. Here you can edit the body of the Run method. Please note, you need to have the method signature as it is.

On the Test panel, let’s change the HTTP Method to GET and add in a new query parameter ‘’name”. Give it some value and click on Run, and you can see your Azure Function is running.
8. httptrigger
run.csx
You can get the function’s URL as above, let’s just copy it into a notepad.

To make the demo nicer, let’s add another function, this time a Timer trigger.
image
New Timer Trigger
I have selected C# as the Language, some Name and you can see the Schedule is expressed as a CRON expression. I have updated the CRON expression to every second.

Like the previous function, you will see the Run method, here let’s modify the method to send an HTTP GET to our previously created function.
using System;
 
public static async Task Run(TimerInfo myTimer, TraceWriter log)
{
    var client = new HttpClient();
    var response = await client.GetAsync("{FunctionUrl}?name=John");
    var result = await response.Content.ReadAsStringAsync();
 
    log.Info($"C# Timer trigger function executed at: {DateTime.Now}, Result: {result}");
}
You can replace the {FunctionUrl} with the URL we have copied over to notepad. And let’s run it. You can see our Timer trigger function is executing every second calling the HTTP trigger function.
9 - time trigger log
Timer Trigger Running Log
Isn’t it nice or what?

Happy Coding.

Regards,
Jaliya

Monday, January 15, 2018

Passing Nullable Value for a DbCommand Parameter

I had this requirement where I wanted to pass a nullable property for a Parameter in DbCommand.
public void Execute(int? someId)
{
    using (DbCommand dbCommand = _context.Database.GetDbConnection().CreateCommand())
    {
        dbCommand.CommandType = CommandType.StoredProcedure;
        dbCommand.CommandText = "sp_SomeStoredProcedure";
        dbCommand.Parameters.Add(new SqlParameter("ParameterId", someId);

        // some code
    }

    // some code
}
I was expecting when someId is null, ADO.NET will consider passing null for the parameter. But apparently, that doesn't seem to be the case. Got required parameter is not supplied error. I even tried below which I felt would work,
dbCommand.Parameters.Add(new SqlParameter("ParameterId", someId.HasValue ? someId.Value : null));
But kept getting the error. Finally, Null coalescing operator with DBNull was there to my rescue.
dbCommand.Parameters.Add(new SqlParameter("ParameterId", someId ?? (object)DBNull.Value));
Happy Coding.

Regards,
Jaliya

Monday, January 8, 2018

C# 7.2 : in Parameters

With C# 7.2, a nice set of syntax improvements that enable working with value types were introduced. My favorite among these is in Parameters.

In this post let’s see what in parameters really is.

As you have already know C# had ref and out for a quite a while now. If we recall what ref and out does (within parameter modifier context), it’s basically as follows.
static void Main(string[] args)
{
    Method1(out int i);
    Console.WriteLine(i); // 10
 
    Method2(ref i);
    Console.WriteLine(i); // 20
}
 
static void Method1(out int i)
{
    // Variable i needs to be assigned a value before leaving the method
    i = 10;
}
 
static void Method2(ref int i)
{
    // Variable i might/might not be assigned a value before leaving the method
    i = 20;
}
Both were used to pass the parameter by reference. The difference is when using out parameter, variable needs to be assigned a value before returning from the method. In ref parameter, there is no such requirement, within the method being called you can or not assign a value to ref parameter. But since there is a possibility of a value not being set there, before passing the ref parameter, it should have a value assigned.

But here from the caller, there is no option to say, within the method being called, the parameter should stay as readonly (if we make the parameter readonly, it’s affecting for outside use of the variable as well).

For this comes the in parameters.
static void Main(string[] args)
{
    Method1(out int i);
    Console.WriteLine(i); // 10
 
    Method2(ref i);
    Console.WriteLine(i); // 20
 
    Method3(i);
    Console.WriteLine(i); // 20
}
 
static void Method1(out int i)
{
    // Variable i needs to be assigned a value before leaving the method
    i = 10;
}
 
static void Method2(ref int i)
{
    // Variable i might/might not be assigned a value before leaving the method
    i = 20;
}
 
static void Method3(in int i)
{
    // Variable i is 20 and cannot assign a value
}
You can see, we have Method3 which accepts int i with in modifier. Unlike out and ref, when we are calling the methods which has in parameters, we don’t have to call like Method(in i). We can omit the in modifier, because the variable is going to be readonly within the method being called. Trying to set a value for in parameters from the method being called is illegal.

Isn’t it nice!

Happy Coding.

Regards,
Jaliya

Saturday, January 6, 2018

No CREATE OR ALTER before Microsoft SQL Server 2016 SP1

In one of the applications that I am working on, there was a stored procedure pushed in by a fellow developer as follows.
ALTER PROCEDURE [someSchema].[someProcedureName]
//--implementation
Since I didn’t have the procedure in my local Microsoft SQL Server database, I have changed the procedure with following and pushed back.
CREATE OR ALTER PROCEDURE [someSchema].[someProcedureName]
//--implementation
The change is I have made is from ALTER PROCEDURE to CREATE OR ALTER PROCEDURE. Then to my surprise got to know that, the stored procedure is breaking on my fellow developer's environment. He was having Microsoft SQL Server 2014 and I am on Microsoft SQL Server 2017.

Did some googling and got to know that CREATE OR ALTER was introduced with as part of Microsoft SQL Server 2016 SP1 enhancements.

For more  information read the following post,
Developers Choice: CREATE OR ALTER

Happy Coding.

Regards,
Jaliya

Friday, January 5, 2018

C# 7 Point Releases

C# 7.0 was publicly released on March, 2017 with the release of Visual Studio 2017. Prior to C# 7, there was less to no discussion about point releases to C# language version (citation needed). But with C# 7, the story is not the same. As of today, we already have C# 7.1 and 7.2.

C# 7.1 was released on August, 2017 with Visual Studio 15.3 while 7.2 was released on December, 2017 with Visual Studio 15.5.

Here is a list of features which got available with point releases.

C# 7.1
  • async Main method
  • default literal expressions
  • Inferred tuple element names
C# 7.2
  • Reference semantics with value types
  • Non-trailing named arguments
  • Leading underscores in numeric literals
  • private protected access modifier
Visual Studio 2017 lets you select the language version for your project. Go to Project Properties -> Build -> Advanced. You can decide whether you are going to live by the edge or not.
image
Project Language Version
Happy Coding.

Regards,
Jaliya

Sunday, December 31, 2017

Visual C# Technical Guru - November 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 - November 2017
Happy Coding.

Regards,
Jaliya

Tuesday, December 5, 2017

AutoMapper : Handling Profile Dependencies using Custom Value Resolvers

If you are using or if you have used (I am sure you have) AutoMapper, Profiles lets you organize your mapping configurations in an easy manner.

In this post, let’s see how we can handle AutoMapper Profile dependencies using Custom Value Resolvers. As it’s always good to go with an example, let’s go with an example ASP.NET Core Web Application.

For an ASP.NET Core Web Application, AutoMapper can be configured with following easy steps.
You can add a class deriving from Profile class, and in the constructor you can setup your mapping configurations.
public class SomeProfile : Profile
{
    public SomeProfile()
    {
        CreateMap<MyClass, MyClassDTO>();
        // likewise
    }
}
Next in the Startup.ConfigureServices method, you just need to add the following line. (note: you will need to installer required AutoMapper nuget package)
public void ConfigureServices(IServiceCollection services)
{
    // some code
    services.AddAutoMapper();
}
Now you can use IMapper in your required classes as follows.
public class MyController : Controller
{
    private IMapper _mapper;
 
    public MyController(IMapper mapper)
    {
        _mapper = mapper;
    }
}
Now consider we have following two classes.
public class MyClass
{
    public int Id { get; set; }
}
 
public class MyClassDTO
{
    public int Id { get; set; }

    public string SomeProperty { get; set; }
}
And here on MyClassDTO, SomeProperty can't be mapped directly, we will need to get the value by calling ISomeService.GetSomeProperty(int id). Imagine ISomeService is registered for dependency injection.
public interface ISomeService
{
    string GetSomeProperty(int id);
}
So what we would expect is we can get the MyProperty value as follows.
public class SomeProfile : Profile
{
    private ISomeService _someService;
 
    public SomeProfile(ISomeService someService)
    {
        _someService = someService;
 
        CreateMap<MyClass, MyClassDTO>()
            .ForMember(obj => obj.SomeProperty,
                exp => exp.MapFrom(prop => _someService.GetSomeProperty(prop.Id)));
    }
}
But unfortunately, if we run this, we will get an error “No parameterless constructor defined for this object” on services.AddAutoMapper().

In these kinds of scenarios, we can use AutoMapper Custom Value Resolvers. Here I can do the DI without any issues.
public class MyPropertyResolver : IValueResolver<MyClass, MyClassDTO, string>
{
    private ISomeService _someService;
 
    public MyPropertyResolver(ISomeService someService)
    {
        _someService = someService;
    }
 
    public string Resolve(MyClass source, MyClassDTO destination, string destMember, ResolutionContext context)
    {
        return _someService.GetSomeProperty(source.Id);
    }
}
And the usage would be as follows.
public class SomeProfile : Profile
{
    public SomeProfile()
    {
        CreateMap<MyClass, MyClassDTO>()
            .ForMember(obj => obj.SomeProperty,
                exp => exp.ResolveUsing<MyPropertyResolver>());
    }
}
Now SomeProperty value should get resolved without any errors.

Hope this helps.

Happy Coding.

Regards,
Jaliya

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

Friday, November 3, 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

Wednesday, October 11, 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

Wednesday, September 13, 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

Tuesday, August 29, 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

Thursday, August 17, 2017

Getting Started with ASP.NET Core 2.0 Razor Pages

With the release of ASP.NET Core 2.0, one of the new features that got introduced was Razor Pages. The easiest way to get yourself started on ASP.NET Core Razor Pages is with Visual Studio 2017 Update 15.3.

Once you have installed Visual Studio 2017 Update 15.3 and if you try to create a new ASP.NET Core Web Application,
image
New Project
You are presented with an improved dialog window. 
image
New ASP.NET Core Web Application
When you selected ASP.NET Core 2.0 from the ASP.NET Core version selection dropdown, you are presented with multiple application templates. From there, when you select your template as Web Application, you can see that it uses Razor Pages.

Let’s go ahead and create a Web Application. Once the project is created, if you have a look at Solution Explorer, you should be able to see something like below.
image
Pages Folder
When I first had a look at this, for me it was familiar MVC file names and Web Forms like file structure (HTML file and a code behind file).

Now if you run the application, you should be seeing the familiar template.
image
Running
Now to explore what ASP.NET Core Razor Pages really is, let’s open up About.cshtml and About.cshtml.cs (I am going ahead with About files as there are less static content there).

About.cshtml
image
About.cshtml
Here the highlighted @page directive is one of the most important things. It enables, razor file to link with it’s related PageModel.

About.cshtml.cs
image
About.cshtml.cs
If you prefer, to improve productivity in development, you can have the content in code behind in the razor file itself.

About.cshtml
@page
@model AboutModel
@using Microsoft.AspNetCore.Mvc.RazorPages
@{
    ViewData["Title"] = "About";
}
 
@functions{
    public class AboutModel : PageModel
    {
        public string Message { get; set; }
 
        public void OnGet()
        {
            Message = "Your application description page.";
        }
    }
}
 
<h2>@ViewData["Title"]</h2>
<h3>@Model.Message</h3>
 
<p>Use this area to provide additional information.</p>
While above will work fine, there is a advantage, above supports run-time compilation. That is pretty handy in development, you don't need to stop the debugger to do some change in PageModel class.

When the page is requested by http://localhost:xxxx/About, OnGet method will get called and when you want to post something, you can introduce OnPost method and it will get trigged upon POST requests. For async requests, you can name  the methods as OnGetAsync, OnPostAsync etc.

About.cshtml
@page
@model AboutModel
@using Microsoft.AspNetCore.Mvc.RazorPages
@{
    ViewData["Title"] = "About";
}
 
@functions{
    public class AboutModel : PageModel
    {
        public string Message { get; set; }
 
        public void OnGet()
        {
            Message = "Your application description page.";
        }
 
        public void OnPost()
        {
            Message = $"You just made a post on {DateTime.Now}.";
        }
    }
}
 
<h2>@ViewData["Title"]</h2>
<h3>@Model.Message</h3>
 
<p>Use this area to provide additional information.</p>
 
<form method="post">
    <input type="submit" value="Submit"/>
</form>
Hopefully, this will help you get started on ASP.NET Core Razor Pages.

More reads,

Happy Coding.

Regards,
Jaliya