Knockout JS Intro

0

Category : ,

Introduction

Knockout is a fast, extensible and simple JavaScript library designed to work with HTML document elements using a clean underlying view model. It helps to create rich and responsive user interfaces. Any section of UI that should update dynamically (e.g., changing depending on the user’s actions or when an external data source changes) with Knockout can be handled more simply and in a maintainable fashion.

Working with Knockout consists of several steps:

  • Get data model:
    In most cases, data will be returned from the remote server in JSON format with AJAX (Asynchronous JavaScript and XML) call.

  • Create View:
    View is a HTML template with Knockout bindings, using “data-bind” attributes. It can contain grids, divs, links, forms, buttons, images and other HTML elements for displaying and editing data.

  • Create View Model:
    View model is a pure-code representation of the data operations on a UI. It can have usual properties and observable properties. An observable property means that when it’s changed in the view model, it will automatically be updated in the UI.

  • Map data from data model to view model:
    In most cases, data in the data model are independent from UI and don’t have a concept of observables. In this step a map from the data model to the view model should be created. It can be done manually or using Knockout mapping plugin.

  • Bind view model to the view:
    When view model is initialized, it can be bound to part of the HTML document, or the whole HTML document.

Data-Bind

An HTML attribute data-bind is used to bind a view model to the view. It is a custom Knockout attribute and is reserved for Knockout bindings. The data-bind attribute value consists of two parts: name and value, separated by a colon. Multiple bindings are separated by a comma.

The binding item name should match a built-in or custom binding handler. The binding item value can be a view model property or any valid JavaScript expression or any valid JavaScript variable:
File Name



Live Examples

http://knockoutjs.com/examples/
http://www.knockmeout.net/2011/08/all-of-knockoutjscom-live-samples-in.html

Tutorials

http://learn.knockoutjs.com/

Documentation

http://knockoutjs.com/documentation/introduction.html

my thanks to the below tutorials/blogs:
https://www.devbridge.com/articles/knockout-a-real-world-example
http://www.knockmeout.net/2011/08/all-of-knockoutjscom-live-samples-in.html

Different Testing Types

0

Category :

  • Unit test: Specify and test one point of the contract of single method of a class. This should have a very narrow and well defined scope. Complex dependencies and interactions to the outside world are stubbed or mocked.

  • Integration test: Test the correct inter-operation of multiple subsystems. There is whole spectrum there, from testing integration between two classes, to testing integration with the production environment.

  • Smoke test (aka Sanity check): A simple integration test where we just check that when the system under test is invoked it returns normally and does not blow up. It is an analogy with electronics, where the first test occurs when powering up a circuit: if it smokes, it's bad.

  • Regression test: A test that was written when a bug was fixed. It ensures that this specific bug will not occur again. The full name is "non-regression test". It can also be a test made prior to changing an application to make sure the application provides the same outcome.

  • Acceptance test: Test that a feature or use case is correctly implemented. It is similar to an integration test, but with a focus on the use case to provide rather than on the components involved.

  • System test: Tests a system as a black box. Dependencies on other systems are often mocked or stubbed during the test (otherwise it would be more of an integration test).

  • Pre-flight check: Tests that are repeated in a production-like environment, to alleviate the 'builds on my machine' syndrome. Often this is realized by doing an acceptance or smoke test in a production like environment

  • Black-box testing: testing only the public interface with no knowledge of how the thing works.

  • Glass-box testing: testing all parts of a thing with full knowledge of how it works.




  • my thanks to the following answers:
    https://stackoverflow.com/questions/520064/what-is-unit-test-integration-test-smoke-test-regression-test?rq=1
    https://stackoverflow.com/questions/437897/what-are-unit-testing-and-integration-testing-and-what-other-types-of-testing-s

    Asynchronous requests with Postman's PM API

    0

    Category : , , ,

    You can send requests asynchronously with the pm API method sendRequest, these can be used in the pre-request or the test script.

    Its important to note that if you send an asynch request in the pre-request tab "The main Postman request will NOT be sent until the pre-request script is determined to be finished with all callbacks, including sendRequest."

    A blog post containing more detailed info on this can be seen on the below link:
    http://blog.getpostman.com/2017/10/03/send-asynchronous-requests-with-postmans-pm-api/

    I have only done basic testing with this but I could get the method to fire using the 2nd example of the 3 available on the previous url:
    var headers = ['reseller_id:' + environment.booking_api_reseller_id];
        headers.push('request_id:'+ environment.booking_api_request_id);
        headers.push('request_authentication:'+ environment.booking_api_request_authentication);
    console.log(headers);
    
    // Example with a full fledged SDK Request
    const echoPostRequest = {
      url: environment.booking_api_host + '/v1/Availability/product/' + environment.booking_api_availability_productKey + '?fromDateTime=' + environment.booking_api_availability_start_date + 
            '&toDateTime=' + environment.booking_api_availability_end_date,
      method: 'GET',
      header: headers,
      body: {
        mode: 'raw',
        raw: JSON.stringify({ key: 'this is json' })
      }
    };
    
    pm.sendRequest(echoPostRequest, function (err, res) {
        console.log('..............here........');
        console.log(err ? err : res.json());
    });
    
    
    I was having issues passing the headers to the request but i found the below url which states the header param should be an array.
    http://www.postmanlabs.com/postman-collection/Request.html#~definition

    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