Reuseable scripts in Postman

0

Category : , , ,

You can reuse methods across requests in postman.

Tip #5 in the below list:
http://blog.getpostman.com/2017/07/28/api-testing-tips-from-a-postman-professional/

  1. Init in Pre-Request or Tests tab or in a previous request.
  2. Store in an Environment or Global variable.
  3. Then call multiple times from other requests.
1) Setup method in Pre-Request or Tests tab in Postman, you can also list params to pass to method.
postman.setEnvironmentVariable("commonTests", (responseBody, environmentSchema) => {
    
    // parse response and log
    var responseObject = JSON.parse(responseBody);
    //console.log("response: " + JSON.stringify(responseObject));

    // test to check status code
    tests["Status code is 200"] = responseCode.code === 200;
    
    // test response time
    console.log("responseTime: " + responseTime);
    tests["Response time is less than " + environment.max_server_response_time + "ms"] = responseTime < environment.max_server_response_time;
    
    // validate schema
    eval(environment.validateSchema)(responseObject, environmentSchema);
});

2) Call method from the Pre-Request or Tests tab in Postman.
You can also call methods from within another method as you can see at the end of the previous code sample.

    // validate schema
    eval(environment.commonTests)(responseObject, environment.specificSchema);

Application Insights Basics

0

Category :

What is Application Insights?

an extensible Application Performance Management (APM) service for web developers
monitor your live web application.
automatically detect performance anomalies. It includes powerful analytics tools to help you diagnose issues and to understand what users actually do with your app.
It works for apps on a wide variety of platforms including .NET, Node.js and J2EE, hosted on-premises or in the cloud.
has connection points to a variety of development tools. It can monitor and analyze telemetry from mobile apps

How does Application Insights work?

You install a small instrumentation package in your application, and set up an Application Insights resource in the Microsoft Azure portal.
The instrumentation monitors your app and sends telemetry data to the portal.
You can instrument not only the web service application, but also any background components, and the JavaScript in the web pages themselves.
You can also set up web tests that periodically send synthetic requests to your web service.

Method Used for
TrackPageView Pages, screens, blades, or forms.
TrackEvent User actions and other events. Used to track user behavior or to monitor performance.
TrackMetric Performance measurements such as queue lengths not related to specific events.
TrackException Logging exceptions for diagnosis. Trace where they occur in relation to other events and examine stack traces.
TrackRequest Logging the frequency and duration of server requests for performance analysis.
TrackTrace Diagnostic log messages. You can also capture third-party logs.
TrackDependency Logging the duration and frequency of calls to external components that your app depends on.

You can attach properties and metrics to most of these telemetry calls.+


my thanks to:
https://docs.microsoft.com/en-us/azure/application-insights/app-insights-overview
https://docs.microsoft.com/en-us/azure/application-insights/app-insights-api-custom-events-metrics

Parameter Binding in ASP.NET Web API

0

Category :

When Web API calls a method on a controller, it must set values for the parameters, a process called binding.
By default, Web API uses the following rules to bind parameters:
  1. If the parameter is a "simple" type, Web API tries to get the value from the URI. Simple types include the .NET primitive types (int, bool, double, and so forth), plus TimeSpan, DateTime, Guid, decimal, and string, plus any type with a type converter that can convert from a string. (More about type converters later.)
  2. For complex types, Web API tries to read the value from the message body, using a media-type formatter.

Internet Media Types

https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/media-formatters A media type, also called a MIME type, identifies the format of a piece of data. In HTTP, media types describe the format of the message body. A media type consists of two strings, a type and a subtype. For example:
  1. text/html
  2. image/png
  3. application/json

Using [FromUri]

To force Web API to read a complex type from the URI, add the [FromUri] attribute to the parameter.

Using [FromBody]

To force Web API to read a simple type from the request body, add the [FromBody] attribute to the parameter.

At most one parameter is allowed to read from the message body. So this will not work:
// Caution: Will not work!    
public HttpResponseMessage Post([FromBody] int id, [FromBody] string name) { ... }

Type Converters

You can make Web API treat a class as a simple type (so that Web API will try to bind it from the URI) by creating a TypeConverter and providing a string conversion.

The client can invoke the method with a URI like this:
http://localhost/api/values/?location=47.678558,-122.130989

Model Binders

A more flexible option than a type converter is to create a custom model binder. With a model binder, you have access to things like the HTTP request, the action description, and the raw values from the route data.
To create a model binder, implement the IModelBinder interface. This interface defines a single method, BindModel

A model binder gets raw input values from a value provider. This design separates two distinct functions:
  1. The value provider takes the HTTP request and populates a dictionary of key-value pairs.
  2. The model binder uses this dictionary to populate the model.

Value Providers

A model binder gets values from a value provider. To write a custom value provider, implement the IValueProvider interface.

HttpParameterBinding

Model binders are a specific instance of a more general mechanism. If you look at the [ModelBinder] attribute, you will see that it derives from the abstract ParameterBindingAttribute class. This class defines a single method, GetBinding, which returns an HttpParameterBinding object:

An HttpParameterBinding is responsible for binding a parameter to a value. In the case of [ModelBinder], the attribute returns an HttpParameterBinding implementation that uses an IModelBinder to perform the actual binding. You can also implement your own HttpParameterBinding.

IActionValueBinder

The entire parameter-binding process is controlled by a pluggable service, IActionValueBinder. The default implementation of IActionValueBinder does the following:
  1. Look for a ParameterBindingAttribute on the parameter. This includes [FromBody], [FromUri], and [ModelBinder], or custom attributes. Otherwise, look in HttpConfiguration.ParameterBindingRules for a function that returns a non-null HttpParameterBinding.
  2. Otherwise, use the default rules that I described previously. If the parameter type is "simple"or has a type converter, bind from the URI. This is equivalent to putting the [FromUri] attribute on the parameter. Otherwise, try to read the parameter from the message body. This is equivalent to putting [FromBody] on the parameter.
If you wanted, you could replace the entire IActionValueBinder service with a custom implementation.

my thanks to:
https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

Unity Lifetime Managers

0

Category : ,

Lifetime Managers in Unity Container

The unity container manages the lifetime of objects of all the dependencies that it resolves using lifetime managers.

Unity container includes different lifetime managers for different purposes. You can specify lifetime manager in RegisterType() method at the time of registering type-mapping.

Lifetime Manager Description
TransientLifetimeManager When no lifetime manager is defined, unity defaults to Transient.
Creates a new object of requested type every time you call Resolve or ResolveAll method.
ContainerControlledLifetimeManager Creates a singleton object first time you call Resolve or ResolveAll method and then returns the same object on subsequent Resolve or ResolveAll call.
HierarchicalLifetimeManager Same as ContainerControlledLifetimeManager, the only difference is that child container can create its own singleton object. Parent and child container do not share singleton object.
PerResolveLifetimeManager Similar to TransientLifetimeManager but it reuses the same object of registered type in the recursive object graph.
PerThreadLifetimeManager Creates singleton object per thread basis. It returns different objects from the container on different threads.
ExternallyControlledLifetimeManager It manintains only weak reference of objects it creates when you call Resolve or ResolveAll method. It does not maintain the lifetime of strong objects it creates and allow you or garbage collector to control the lifetime. It enables you to create your own custom lifetime manager



my thanks to:
http://www.tutorialsteacher.com/ioc/lifetime-manager-in-unity-container

Handle errors in Web API

0

Category :

Using HttpResponseException

You can use the HttpResponseException class to return specific HTTP status code and messages from your controller methods in Web API.

var response = new HttpResponseMessage(HttpStatusCode.NotFound)
{
 Content = new StringContent("Employee doesn't exist", System.Text.Encoding.UTF8, "text/plain"),
 StatusCode = HttpStatusCode.NotFound
}
throw new HttpResponseException(response); 

Using HttpError

You can use the CreateErrorResponse extension method in your Web API controller method to return meaningful error codes and error messages. The CreateErrorResponse method creates an HttpError object and then wraps it inside an HttpResponseMessage object.

string message = "Employee doesn't exist";
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, message)); 

Using Exception filters

Exception filters are filters that can be used to handle unhandled exceptions that are generated in your Web API controller methods. global error filter is a good approach to handle exceptions in your Web API if unhandled exceptions are thrown and not handled in your controller methods.

To create an exception filter you need to implement the IExceptionFilter interface. You can also create exception filters by extending the abstract class ExceptionFilterAttribute and then overriding the OnException method. Note that the ExceptionFilterAttribute abstract class in turn implements the IExceptionFilter interface.

how you can create a custom exception filter by extending the ExceptionFilterAttribute class and then overriding the OnException method.
public class CustomExceptionFilter : ExceptionFilterAttribute
    {
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            HttpStatusCode status = HttpStatusCode.InternalServerError;

            String message = String.Empty;
            var exceptionType = actionExecutedContext.Exception.GetType();

            if (exceptionType == typeof(UnauthorizedAccessException))
            {
                message = "Access to the Web API is not authorized.";
                status = HttpStatusCode.Unauthorized;
            }
            else if (exceptionType == typeof(DivideByZeroException))
            {
                message = "Internal Server Error.";
                status = HttpStatusCode.InternalServerError;
            }
            else if (exceptionType == typeof(InternalApiException))
            {
                message = "Internal Server Api Exception.";
                status = HttpStatusCode.InternalServerError;
            }
            else
            {
                message = "Not found.";
                status = HttpStatusCode.NotFound;
            }

            actionExecutedContext.Response = new HttpResponseMessage()
            {
                Content = new StringContent(message, System.Text.Encoding.UTF8, "text/plain"),
                StatusCode = status
            };

            base.OnException(actionExecutedContext);
        }
    }
You should add the custom exception filter to the filters collection of the HttpConfiguration object.
public static void Register(HttpConfiguration config)
{ 
 config.Filters.Add(new CustomExceptionFilter());
You can register your exception filters in one of the following three ways: At the action level
public class EmployeesController : ApiController
{
    [NotImplementedExceptionFilter]
    public Employee GetEmployee(int id) 
At the controller level
[DatabaseExceptionFilter]
public class EmployeesController : ApiController
{ 
Globally
GlobalConfiguration.Configuration.Filters.Add(new DBFilterAttribute());


my thanks to this great article:
https://www.infoworld.com/article/2994111/application-architecture/how-to-handle-errors-in-web-api.html

Dependency Injection in ASP.NET Web API 2

0

Category : ,

When trying to use Dependency Injection with Web API 2 I encountered a problem because the application doesn't create the controller directly. Web API creates the controller when it routes the request, and Web API doesn't know anything about your dependencies ie AppLogger

So basically your dependencies will not be initialised on creation of the controller.

This is where the Web API dependency resolver comes in.

The Web API Dependency Resolver

Web API defines the IDependencyResolver interface for resolving dependencies.
public interface IDependencyResolver : IDependencyScope, IDisposable
{
    IDependencyScope BeginScope();
}

public interface IDependencyScope : IDisposable
{
    object GetService(Type serviceType);
    IEnumerable<>object<> GetServices(Type serviceType);
}
The IDependencyResolver method inherits IDependencyScope and adds the BeginScope method.

So basically the minimum requirement is that the 3 of these methods are implemented.

When Web API creates a controller instance, it first calls IDependencyResolver.GetService, passing in the controller type. You can use this extensibility hook to create the controller, resolving any dependencies. If GetService returns null, Web API looks for a parameterless constructor on the controller class.

Dependency Resolution with the Unity Container

The interface is really designed to act as bridge between Web API and existing IoC containers.

Here is an implementation of IDependencyResolver that wraps a Unity container.
using Microsoft.Practices.Unity;
using System;
using System.Collections.Generic;
using System.Web.Http.Dependencies;

public class UnityResolver : IDependencyResolver
{
    protected IUnityContainer container;

    public UnityResolver(IUnityContainer container)
    {
        if (container == null)
        {
            throw new ArgumentNullException("container");
        }
        this.container = container;
    }

    public object GetService(Type serviceType)
    {
        try
        {
            return container.Resolve(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return null;
        }
    }

    public IEnumerable GetServices(Type serviceType)
    {
        try
        {
            return container.ResolveAll(serviceType);
        }
        catch (ResolutionFailedException)
        {
            return new List();
        }
    }

    public IDependencyScope BeginScope()
    {
        var child = container.CreateChildContainer();
        return new UnityResolver(child);
    }

    public void Dispose()
    {
        Dispose(true);
    }

    protected virtual void Dispose(bool disposing)
    {
        container.Dispose();
    }
}
// rubbish closeout IEnumerable object list above...seen as open html tags by syntax highlighter




Configuring the Dependency Resolver

Set the dependency resolver on the DependencyResolver property of the global HttpConfiguration object.

public static void Register(HttpConfiguration config)
{
    var container = new UnityContainer();
    container.RegisterType(new HierarchicalLifetimeManager());
    config.DependencyResolver = new UnityResolver(container);

    // Other Web API configuration not shown.
}


Dependency Scope and Controller Lifetime

Controllers are created per request. To manage object lifetimes, IDependencyResolver uses the concept of a scope.

The dependency resolver attached to the HttpConfiguration object has global scope. When Web API creates a controller, it calls BeginScope. This method returns an IDependencyScope that represents a child scope.

Web API then calls GetService on the child scope to create the controller. When request is complete, Web API calls Dispose on the child scope. Use the Dispose method to dispose of the controller's dependencies.

How you implement BeginScope depends on the IoC container. For Unity, scope corresponds to a child container:
public IDependencyScope BeginScope()
{
    var child = container.CreateChildContainer();
    return new UnityResolver(child);
}



my thanks to this great article:
https://docs.microsoft.com/en-us/aspnet/web-api/overview/advanced/dependency-injection

WebApi Mvc Routing

0

Category :

Routing

Is how Web API matches a URI to an action. Web API 2 introduces attribute routing, which uses attributes to define routes, giving you more control over the URIs in your web API. convention-based routing you can combine both techniques in the same project.

HTTP Methods

Web API also selects actions based on the HTTP method of the request (GET, POST, etc). By default, Web API looks for a case-insensitive match with the start of the controller method name. For example, a controller method named PutCustomers matches an HTTP PUT request.

You can override this convention by decorating the mathod with any the following attributes
[HttpDelete] [HttpGet] [HttpHead] [HttpOptions] [HttpPatch] [HttpPost] [HttpPut]

Route Prefixes

You can set a common prefix for an entire controller by using the [RoutePrefix] attribute:

[RoutePrefix("api/books")]
public class BooksController : ApiController
{
    // GET api/books
    [Route("")]
    public IEnumerable Get() { ... }

    // GET api/books/5
    [Route("{id:int}")]
    public Book Get(int id) { ... }

    // POST api/books
    [Route("")]
    public HttpResponseMessage Post(Book book) { ... }
}
Use a tilde (~) on the method attribute to override the route prefix.
[Route("~/api/authors/{authorId:int}/books")]

Route Constraints

Route constraints let you restrict how the parameters in the route template are matched. The general syntax is "{parameter:constraint}"

[Route("users/{id:int}"]
public User GetUserById(int id) { ... }

Optional URI Parameters and Default Values

You can make a URI parameter optional by adding a question mark to the route parameter. If a route parameter is optional, you must define a default value for the method parameter or in the template.

[Route("api/books/locale/{lcid:int?}")]
public IEnumerable GetBooksByLocale(int lcid = 1033) { ... }

[Route("api/books/locale/{lcid:int=1033}")]
public IEnumerable GetBooksByLocale(int lcid) { ... }

Route Names

every route has a name. Route names are useful for generating links, so that you can include a link in an HTTP response. To specify the route name, set the Name property on the attribute.

[Route("api/books/{id}", Name="GetBookById")]
public BookDto GetBook(int id) 
{
 // Implementation not shown...
}

// Generate a link to the new book and set the Location header in the response.
string uri = Url.Link("GetBookById", new { id = book.BookId });

Route Order

When the framework tries to match a URI with a route, it evaluates the routes in a particular order. To specify the order, set the RouteOrder property on the route attribute. Lower values are evaluated first. The default order value is zero.
The order can be found on the reference page.

my thanks to:
https://docs.microsoft.com/en-us/aspnet/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2