Publishing ASP.NET Core in IIS

With ASP.NET Core, we can develop applications that runs cross-platform. We have choices whether to use the full .NET framework (4.5.2 or greater) or .NET Core, where .NET Core works cross platform. Comparatively with ASP.NET 4, ASP.NET Core framework is more powerful, modular and fast and provide different options for hosting ASP.NET Core application.

ASP.NET Core comes with two servers that hooks up the port to listen for requests.

WebListener: Only for Windows

Kestrel (recommended) : For Windows, MAC and Linux

Both Kestrel and WebListener servers are a very light weight servers with a very basic feature set. With production, we usually want other capabilities like load balancing, HTTP modules, request filtering, etc. Therefore, we have to pair Kestrel with any mature or powerful server like IIS or Apache that can act as a reverse proxy, listen for incoming request and pass it to kestrel to process. image

Configure IIS to Publish ASP.NET Core Apps

We will start first by setting up IIS to run ASP.NET Core app. First of all ensure that the IIS is installed on your OS. You can install IIS from windows features under program and features option.

Once the IIS is installed, we have to install the .NET Core hosting bundle that installs the .NET Core runtime, .NET Core library and the ASP.NET Core Module (ANCM). The job of ANCM is to create a reverse proxy between IIS and Kestrel. Restart is recommended after installing these components.

Create Website and Configure App Pool in IIS

To create an application, open IIS and create a new website as shown below.

image

 

Once the website is created, go to Application Pool and select No Managed Code for HelloWorld application as shown below.

image

This is important, because for ASP.NET Core apps we don’t want IIS to process the request.

Adding Data Protection

ASP.NET Core uses Data Protection API to encrypt and store keys that are used for authentication. When hosting your application with IIS, we need to run power shell script that creates a registry hive where all the application level keys are stored.

to create our Application registry hive, we will first go to https://raw.githubusercontent.com/aspnet/DataProtection/dev/Provision-AutoGenKeys.ps1 and download it to some local repository. Then open Power shell in Administrative mode and run following command to get the remotesigned policy to run the .ps1 file downloaded above.

powershell –ExecutionPolicy RemoteSigned

Next, we point it to .ps1 file and specify our Application Name (HelloWorld) as shown below.

image

Adding IIS Integration Package in ASP.NET Core and Publish

To run ASP.NET Core application on IIS we have to add a Nuget Package known as Microsoft.AspNetCore.Server.IISIntegration.Tools and make an entry in the program.cs to use IIS integration by calling UseIISIntegration method.

Here is the screen shot of the NuGet package needed to be installed.

image

And here is the updated program.cs of our HelloWorld application

image

UseIISIntegration method actually tells your ASP.NET Core that IIS will be the reverse proxy for the incoming requests. It doesn’t replace Kestrel but allow IIS and ASP.NET Core to setup ports and read other environment variables.

Once this is done, publish your application. Publishing can be done either through Visual Studio or through a Dotnet CLI (dotnet publish). When publishing, choose a destination to the path which is configured in IIS for your application so you don’t have to copy the package files again.

Running your application

Navigate to localhost (hostname as configured above while creating a website) and you will see the default ASP.NET Core home page as shown below.

image

Hope this helps!

My book on JavaScript for .NET Developers

I am pleased to inform you that my book on “JavaScript for .NET developers has been published by Packt Publishing. It was a very good experience but of course it took lot of time from me.

image

This book is a mastering series and targeted primarily to .NET Developers but other non .NET developers can also leverage with the knowledge I shared in this book and understand the concepts and use them with any web application platform. I have tried to accommodate all the information that will be required to master JavaScript.

This book has 10 chapters, starting from the basics to advanced concepts, learning superset of JavaScript i.e. TypeScript and discusses what superset is and how to use TypeScript with Angular 2 and ASP.NET Core. One chapter on WinJS, a JavaScript library that is widely used by UWP developers to bring rich look and feel and other windows runtime features to web applications. Chapter on Node.js that shows how JavaScript can be used on server side and how to develop Node.js applications using Visual Studio 2015. Then covered all about design patterns and shown the usage of around dozen of design patterns to handle particular problem or scenario. Finally, there are the chapters of using JavaScript for large scale projects and how to test and debug JavaScript.

To order either an e-book or a printed copy, It is available on Packt Publishing website i.e. https://www.packtpub.com/application-development/javascript-net-developers and Amazon at https://www.amazon.com/JavaScript-Developers-Ovais-Mehboob-Ahmed-ebook/dp/B01E7GP8I6

Enjoy reading!!

Using WCF SOAP Services in ASP.NET Core

When working with an ASP.NET Core application in Visual Studio 2015, there is no out of the box support to add WCF service references. To add services references of WCF services, Microsoft introduced the WCF Connected services preview to generate the SOAP service references for applications that are using .NET Core.

To install WCF Connected Services tool extension we need to have Visual Studio 2015 installed. And then it can be installed from the Visual Studio Extensions and Updates dialog as shown below. This dialog can be opened from Tools > Extensions and Updates option. Search for WCF Connected Services and download. This tool requires to have Visual Studio Update 3 plus the ASP.NET and Web Tools for Visual Studio 2015 extension installed as well.

  image

After installing WCF Connected Services, It asks you to restart Visual Studio and then you can add service reference by right clicking the references node and click on Add Connected Service option

image

Add Connected Service option will open up the dialog where you can choose  WCF Service – Preview as shown below

image

And finally, you can specify the service URL and add WCF Soap Service reference in your project that creates a proxy and you can use that proxy object to invoke WCF service methods.

Hope this helps!

Transaction Per Request using AutoFac in WebAPI

When working with business applications, transactions plays an important role and providing atomic transactions is a good practice to commit or rollback transaction on either condition. In this post we will implement the Transaction per request in Web API controllers using AutoFac and action filters. Transaction per request is a recommended approach when designing your Web API as it provides the Database object per request and no matter how many transactions you are doing in particular request but provides commit and rollback feature using action filters. We will see how easy it is to handle that using AutoFac dependency injector

Following are the steps you can implement in your Web API project to implement Transaction Per request.

1. FIrst of all add the Autofac for Web API package through NuGet

image

2. Add Entity framework file and connect to some data source. In my case I have ProductEntities and below is the Web API code of Products

public class ProductsController : ApiController
{

ProductsEntities context;

public ProductsController(ProductsEntities entities)
{
context = entities;
}

// GET: api/Products
public IEnumerable<Product> Get()
{
return context.Products.AsEnumerable();
}

// GET: api/Products/5
public Product Get(int id)
{
return context.Products.Where(i => i.ProductID == id).FirstOrDefault();
}

// POST: api/Products
public void Post(Product product)
{
context.Products.Add(product);
context.SaveChanges();

}

// DELETE: api/Products/5
public void Delete(int id)
{
var product = context.Products.Where(i => i.ProductID == id).FirstOrDefault();
if (product != null)
{
context.Products.Remove(product);
context.SaveChanges();
}
}
}

 

I have defined a pamaterized constructor that takes ProductEntities as a parameter to perform CRUD operation on database

4. Now go to your Startup class and write following code snippet.

using Autofac;
using Autofac.Integration.WebApi;
using System.Reflection;

public void Configuration(IAppBuilder app)
{

        var builder = new ContainerBuilder();
var config = GlobalConfiguration.Configuration;

//Register all Controllers with AutoFac so it will inject ProductEntities by calling
//parameterized constructors
builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
builder.RegisterWebApiFilterProvider(config);

//Initialize ProductEntities per request
builder.RegisterType<ProductsEntities>().InstancePerRequest();

var container = builder.Build();
config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

ConfigureAuth(app);

}

First initialize the dependency container builder object and register API controllers that resides in your project by calling builder.RegisterApiControllers method.  After that I have register the ProductEntities type as InstancePerRequest. This InstancePerRequest will create the new context object per request to preform CRUD operation. Next, build your builder and specify the dependency resolver for your Web API.

5. That’s all set for injecting ProductEntities in Web API Controllers

6. Now in order to handle transactions, we will create a custom ActionFilter class that imlements IAutofacActionFilter interface

It provides two methods OnActionExecuted and OnActionExecuting that you can use to perform begin transactions and commit/rollback transactions.

public class TransactionActionFilter : IAutofacActionFilter
{
public void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
throw new NotImplementedException();
}

public void OnActionExecuting(HttpActionContext actionContext)
{
throw new NotImplementedException();
}
}

But before writing code to begin or commit transactions we have to inject the ProductEntities so create parameterized constructor and pass ProductEntities. So lets add a TransactionActionFilter constructer with having ProductEnttities as a parameter

ProductsEntities context;
public TransactionActionFilter(ProductsEntities entities)
{
context = entities;
}

7. Following is the code to handle transactions on action executed and executing methods

DbContextTransaction currentTransaction;

public void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext.Exception != null)
currentTransaction.Rollback();
else
currentTransaction.Commit();
}

public void OnActionExecuting(HttpActionContext actionContext)
{
currentTransaction= context.Database.BeginTransaction();
}

 

8. Finally, register the action filter for Web API controller method to which you want to have transaction applied on. Once the request comes the OnExecuting will be invoked before the actual method call and after it is executed OnExecuted method will be invoked which check if there is any exception and commit or rollback the transaction accordingly.

Register Web API Filter provider

builder.RegisterWebApiFilterProvider(config);

Then add following code to register TransactionActionFilter with your Web API Controller’s method.

builder.Register(c => new TransactionActionFilter(c.Resolve<ProductsEntities>()))
.AsWebApiActionFilterFor<ProductsController>(c => c.Post(default(Product)))
.InstancePerRequest();

 

builder.Build() should be called after all declaration of container injections.

Hope this helps!

2015 in review

The WordPress.com stats helper prepared a 2015 annual report for this blog.

Here’s an excerpt:

The concert hall at the Sydney Opera House holds 2,700 people. This blog was viewed about 34,000 times in 2015. If it were a concert at Sydney Opera House, it would take about 13 sold-out performances for that many people to see it.

Click here to see the complete report.

Enable CORS in ASP.NET Web API

In modern web applications developers mostly use any client side frameworks like AngularJS, EmberJS, Knockout etc. and in order to make server-side request they either call a Web API or a web service through XMLHttpRequest object and perform CRUD operations.

XHR or XMLHttpRequest in an API available to web browser scripting languages like javascript to send HTTP request to a webserver and load the server response data back in the script. Due to some security reasons these requests are allowed only if both server and the application making that request have same protocol, domain and port values.

So for example if the application URL is http://localhost/WebApplication and it is calling http://localhost:8089/WebService it will fail and give cross-origin request issue.

In internet explorer it ignores the port no. so if both are on localhost or same base address it will call it without any issue. But this does not solve the case. In order to develop a service or a Web Api that has to be accessed by any client we need to handle it properly.

In this post, I will show how simply with few steps we can enable Cross Origin Resource sharing in ASP.NET Web Api.

  • First of all in your Web API project add a NuGet Package “Microsoft.AspNet.WebApi.Cors” through NuGet Package Manager

image

  • Then in the WebApiConfig.cs class add an entry to enable cors.

image

  • And finally add the EnableCors attribute on Controller and specify the allowed origins, headers and methods

image

  • You can set origin, header and methods as below.

image

Hope this helps!

Detach EDI node when Source XML element is missing in BizTalk maps

In this post I will share a TIP to detach EDI N2 node segment when the source XML element is missing

Business Scenario:

A BizTalk environment containing some BizTalk maps that  transforms the source XML files into EDI documents. In the scenario we have to generate the EDI 940 document and avoid printing N2 if the source AdditionalName element is missing.

In order to achieve this scenario I have used Logical Existence Functoid that takes input from AdditionalName source element and map to the N2 segment.

1

This will detach the N2 element if AdditionalName is not present in the source document. Additional Name value is actually mapped to N201 segment but in order to avoid N2 populating on EDI document we are good with this.

Next. I have used Logical Existence and Value Mapping functoids for N201 mapping that displays the actual value of Additional Name and avoid throwing exception if the data is not present.

image

Hope this helps!