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!

Debugging code using LINQ and Lambda Expressions in VS 2015

 In this post I will share how easy we can debug LINQ and Lambda expressions in Visual Studio 2015. Sometimes, it is difficult to see larger list in debugging mode. With this feature of VS 2015 we can filter list using LINQ or Lambda expression using Immediate or Watch windows.

Let’s take a quick example of a console application that calls up a method named GetPersons that returns the list of persons.

Below is the class that call GetPersons method which returns a list of 4 persons

1

Now let’s put a break point at the end of Main method

2

You can see that GetPersons() returned the list which you can even see it in the Immediate or Watch windows in earlier versions of Visual Studio as well. But if you want to filter records using some LINQ or Lambda expression, it is not possible in previous versions.

3

Below is the snap shot taken from VS 2013 that shows this error “Expression cannot contain lambda expressions”

4

If you run the same expression in Visual Studio 2015. You will see the result like this

5

You can also use Immediate Window to filter records as below

6

Hope this helps!

Diagnosing using IntelliTrace in Visual Studio 2015

One of the exciting and time saving features for diagnosing issues in Visual Studio 2015 is IntelliTrace. This allows to perform historical debugging by recording the events generated by your application. In this post we will see how easy we can enable IntelliTrace in Visual Studio 2015 and perform debugging using Diagnostic tools window.

In order to enable IntelliTrace in Visual Studio 2015, go to Tools -> Options and then select IntelliTrace

1

Check the Enable IntelliTrace option and select IntelliTrace events and call information. We should enable with the call information if we need to capture more detailed information like the name of the function, method and the parameters passed and the value returned back. This will however degrade the application performance.

Now click on the IntelliTrace Events to select the events you want to capture.

2

Now once you run the application in Debug mode it will start recording the events and you can see the Diagnostic tool window capturing the information as you use the application. This is very helpful when you don’t need to step into the code and putting break points on different statements rather, you can just enable the IntelliTrace and execute scenarios, and if some error happens, you will have the complete trace through which you can go to any event and through historical debugging exactly check what data has been passed and what happened in the background.

Let’s take a default login page example in which I will try to enter the username and password for two users and then we will step into the historical debugging based on the login events we had raised and see the values passed at each time.

First I entered the following username

3

Then I entered my another email address and got the same invalid login attempt

4

Now, In order to check what happened we don’t need to apply the break points and reproduce the login attempts. However, I will just go to the Diagnostic tool window and check what values were passed and what happened.

IntelliTrace will record continuously until we hit break All from Visual Studio. So first hit break all, then open the Diagnostic Tools Window from Show Diagnostic Tool Window option on Visual Studio or through default shortcut i.e. Ctrl+Alt+F2

5

Filter only ASP.NET events from the category

6

Select POST “/Account/Login” and click on Activate Historical Debugging

We can step over and go to the Login method and in order to check what data has been passed we can go to the Locals (Historical Debugging) tab

7

8

9

Hope this helps!

Creating ASP.NET 5 Web Application using Yeoman Generator

In this post we will explore Yeoman generator that helps to scaffold ASP.NET 5 web application using command line statements. What is Yeoman? Yeoman is a set of tools that facilitates building web applications. It comprises of three tools

  • yo (scaffolding template tool)
  • task runner/build tool (Grunt, Gulp)
  • package manager (Bower, npm)

In this post I will focus on yo tool that can be used to generate scaffolding template for aspnet web applications. This tool can be used in environments where you don’t have a Visual Studio 2015 installed or you wanted to scaffold web application using yo command. Yeoman generator for ASP.NET 5 emphasizes to continued effort to enable cross-platform development of ASP.NET It is available for Windows, Linux and OSX operating systems. First of all, configure the ASP.NET 5 environment on your machine.

  1. The easiest way to get started on windows is to install Visual Studio 2015. Visual studio 2015 installs the DNVM (Dot NET Version Manager) command line tool to manage DNX (Dot Net Execution environment) versions and much more.
  2. If you don’t want to install Visual Studio 2015 you can even run this Power shell command to install DNVM{$Branch=’dev’;iex ((new-object net.webclient).DownloadString(‘https://raw.githubusercontent.com/aspnet/Home/dev/dnvminstall.ps1&#8217;))}
  3. This command will install the DNVM and the latest DNX version available at NuGet.org.
  4. Now run following command to list the version of DNX installed on your system

C:\dnvm list

1

Once ASP.NET 5 environment is setup, develop a simple ASP.NET 5 web application using Yeoman generator.

  1. First of all install the yeoman generator using this command npm install –g yo generator-aspnet

2

2.  Now run yo aspnet to create ASP.NET 5 web application 3

3. You can select any template using top/down arrow keys

4. Let’s select 3rd template type i.e. Web Application and press Enter

5. It will ask you to specify the name 4

6.Specify any name and press enter 5

7. You can see the project is created, now go to the folder as I created on root C drive and my web application project   name was TestBlogPost so I found the folder created as TestBlogPost inside c drive root.

8. Now browse your folder and open project.json file, you will see bunch of packages specified there

9. Run kpm restore to restore the packages and then kpm build to build the web application 6

10. Run dnx . web finally to run the web server 7

11. Now browse to http://localhost:5000 address, you will see the ASP.NET 5 home page as below. (You can see the URL from project.json configured for web command)

0 Hope this helps!