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!

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!