Why you need Proxy objects in JavaScript

JavaScript is not truly Object Oriented language, hence implementing requirements as stated below could be challenging. For example,

  • Throw an error if the setting value of a property does not satisfy a particular condition
  • If the property does not exist on set some default value instead of undefined
  • If the property does not exist on reading operation throw TypeError
  • Create a private property on the object
  • Enforce property value validation
  • Enforcing value correct on the property

There are many ways some of the above stated problems can be solved, such that by using setter or getter to set default value or throwing an error or using an object’s methods such that isExtensible(), preventExtension(, etc to avoid adding dynamic properties etc. However, the more convenient way to handle the above problems is by using the Proxy object.

You can watch video on the proxy object here:

The Proxy object is a virtualizing interface to control the behavior of the object.  To understand the proxy in a better way, let us consider Product object as shown in below code listing:


let Product = {
    id:1,
    price : 78
  }

 

The Product object has two properties id and price. Now let us say that you want to run a business logic that price should not be less than 50, or reading value of the property, which does not exist, should throw error, etc.

You can solve most of the above problems by running custom logic while performing property lookup, set, get, and enumeration operations on the object. JavaScript proxy object exactly helps here. It allows you to add custom behavior to the fundamental operations on a JavaScript object.

po

 

The syntax to create a Proxy object is as shown in the below image:

po1

You create a proxy object using the Proxy constructor and passing two parameters in it.

  1. Target
  2. Handler

Target is the object, which proxy virtualizes and adds custom behavior to it. In our example, the Product object is the target as we are adding custom behavior to it.

The handler is the object, in which you write the custom behavior. In more technical words, the handler object contains the trap.

The traps are the methods, which gives the target object’s property access inside the handler object. Traps are optional, and if not provided target object’s default methods are used.   There are traps such as to get, set, has, setPrototypeOf, isExtensible, defineProperty, etc. You can use all of these traps in the handler do define custom behavior for the target object.

Let us apply a custom behavior on the Product object that, a read operation on the property that does not exist should throw an error.  You can create a proxy for that as shown in the below code listing :


var ProductHandler = {
      get:function(obj,prop){
          return prop in obj ?
          obj[prop] : new TypeError(prop + ' - property does not exist');
      }
  };

var productProxy = new Proxy(Product,ProductHandler);

 

Let us walk through the code; we created a proxy called productProxy using the Proxy constructor and in the Proxy constructor passing,

  1. The Product object as the target
  2. The ProductHanlder object as the handler.

The ProductHandler is using the get trap, in which it is checking if property exists in the object or not. If it does not exist, return a TypeError with the message.  Now read properties value as shown in code listed below:


console.log(productProxy.price);
console.log(productProxy.color); 

 

Since price property exists, you get 78 value printed, however when you try to read property color, which does not exist, JavaScript throws you an error as shown in the image below:

po3.png

The better use case of proxy is in validation. Using the proxy, a validation can be enforced on the property value.  Let us consider the code listed below,


let Product = {
    id:1,
    price : 78
  }

Product.price = -10; 
console.log(Product.price); // -10

We can set prices to a negative value. Using the proxy, we can avoid it by enforcing value validations, as shown in the code listed below:


var ProductHandler = {
    set : function(obj, prop,value){
        if(prop == 'price'){
            if( !Number.isInteger(value)){
                throw new TypeError('passed value is not a number');
            }
            if(value < 50){
                obj[prop]= 50;
                return true; 
            }
        }
        obj[prop]= value;
        return true; 
    }
};

var productProxy = new Proxy(Product,ProductHandler);

 

To enforce value validation handler object is using the set trap, in which it is

  1. Checking for the property price
  2. Verifying whether the passed value is an integer or not
  3. If the passed value is for property price is less than 50, setting the value to 50

Now when you set price to a negative value due to defined custom behavior in the proxy object JavaScript will not allow that, and you will get 50 printed for second read operation as shown in code listed below,


console.log(productProxy.price); // 78
productProxy.price = -10; 
console.log(productProxy.price); // 50

 

You can enforce id as the private property of the Product object as shown in the code listed below:


var ProductHandler = {
    get:function(obj,prop){

        if(prop == 'id'){
            throw new Error('Cannot access private property : id!');
        }
        else {
            return prop in obj ?
            obj[prop] : new TypeError (prop + ' - property does not exist');
        }
    }
};

var productProxy = new Proxy(Product,ProductHandler);

 

Here, in the get trap of the handler, we check if the property being accessed is the id property, and if so, handler throws an error. Otherwise, it returns the value as usual.

JavaScript Proxy objects are useful and allow us to add custom behavior to a normal object.  You can use it for various purposes such as validation, creating access modifier, setting default values, etc.  I hope you find this post useful. Thanks for reading.

For any Training or Consulting reach me at debugmode[at]outlook.com 

Step by Step implementing Two-Way Data Binding in Vanilla JavaScript

Data Binding is one of the most important features of all the frameworks. It ensures that the data model and the views are in sync with each other. It is very fundamental feature of any MV* frameworks such that Model-View-Controller, Mode-View-ViewModel, and Model-View-Presenter, etc.

Popular JavaScript based frameworks such that React, Angular have their way to implement it. However, it is a good idea to know how a basic two-way data binding can be implemented using vanilla JavaScript.  That would give you an overview of how much heavy lifting is done by the framework when you use features like data binding.

To get most of this post, you should have a basic understanding of following JavaScript features

  • Creating an object as literal
  • Adding a property with Object.defineProperty
  • Using setter and getter
  • forEach statement

 

You can refresh about JavaScript object creation in this video on geek97. Let us get started,

On the HTML, we have put one input text box and two span elements.  Whenever the user enters a value in the text box, data in <span> element should get updated.

We are going to write JavaScript for data binding in the databinding.js file, so we also added a reference to that in the HTML.

To start with databinding.js file contains an Immediately Invoked Function Expression (IIFE). We write all the codes inside this function,

At this point, on launching the application, you should get below output. Right now, if you enter anything in the Name field nothing would be affected.

cd1

Note: If you are using Visual Studio Code, install the extension Live Server, and run the HTML in the browser, right click on the file and from the context menu select “Open with Live Server” to launch the application.

Our first task is to select all the elements which have [data-geek97-bind] attribute set, and also check for their type. Right now, as we are creating binding only for input type text, so we can make a selection of elements and type checking as shown below,

We have created an empty object called dbrepo, which would maintain the state between the data bound elements. The dbrepo object would make sure that all DOM elements with [data-geek97-bind] attribute set to value ‘name’ is in sync and have the same value.

To achieve that, what all we need to do is to add a property dynamically to the dbrepo object for each unique value of [data-geek97-bind] attribute in the DOM elements. For that, let us create a function called addToScope. In the function, we check whether a particular property exists or not, if not then using the Object.defineProperty() method adds a property to the dbrepo object.

Using the hasOwnProperty() method, determining whether property already exists or not, if not then add it using the Object.defineProperty() method. You can learn more about property descriptor and Object.defineProperty() here

We need to do some work in the setter function.

  • First, find all the elements with data-geek97-bind attribute set to the same value.
  • If the element type is text, set its value, otherwise set innerHtml of the element

Above two tasks can be performed in the setter function as below,

Putting everything together, code to perform two-way data binding is as below:

If you want to change the value in the code by just rewriting the value of the property in the dbrepo object,

At this point, on launching the application you should get below output. Right now, if you enter anything in the Name field, the other two spans would be affected.

cd2

Still, there is scope for much improvement in this code,

  1. Instead of rewriting the innerHtml, append the next text
  2. Extend it for other types than text.

I hope you find this post useful. Thanks for reading.

 

All about types of Action Results in the Web API

While building an API, the client should receive a proper and descriptive HTTP response message for each request. The Web API provides a very simple approach to achieve this.  A Web API controller action can return the following types:

  1. void
  2. HttpResponseMessage
  3. IHttpActionResult
  4. Other types, such as IEnumerable, object, collections, etc.

action result type

To test these different types and HTTP response message associated with them, I will use REST client tool Postman.

The void type

If the return type is set to void, Web API returns an empty HTTP response message with status code 204 means no content.  Let us create an action, which returns void,

In the Postman, on performing HTTP Post operation, you will get response as shown next:

typeinactionresult2

The HttpResponseMessage type

HttpResponseMessage type represents a HTTP response message which encapsulates data and the status code. Besides status code, you can also set other properties such that,

  • Content
  • Headers
  • IsSucessStatusCode
  • ReasonPhrase
  • RequestMessage
  • Version

You can return HttpResponseMessage with certain properties set as shown below:

 

So, /api/data returns HtppResponseMessage, which has content, status code, Reason Phrase to be sent with the code, and cache control set. In the postman, you will get a response header as shown below. Also, you will notice that the status code contains Reason Phrase, “Data is processed.”

typeinactionresult3

Also, the response would be cached for 20 milliseconds. You can also use the HttpResponseMessage type to send data into the response body. It uses media formatter to serialize the data in the format passed as the accept header of the HTTP request.  For example, training data can be sent in the body of HttpResponseMessage as shown below,

Now, in the postman client, if you set Accept Header of Request to application/XML as shown in below image,

typeinactionresult4

In the response body, you will get training data from the API serialized as XML,

typeinactionresult5

Whereas if you set Accept Header of Request to application/JSON as shown in below image,

typeinactionresult6

In the response body, you will get training data from the API serialized as JSON,

typeinactionresult7

The IHttpActionResult type

The third type is IHttpActionResult, which was introduced in Web API 2.0. It provides, a factory to construct an HttpResponse message. It allows you to construct HTTP responses in a separate class, such that controllers can be better unit tested.

You can use IHttpActionResult in two ways:

  1. Implement it in a separate class to construct the HTTP response.
  2. Directly Use IHttpActionResult defined in System.Web.Http.Results namespace.

Often, you can use IHttpActionResult to return a particular data in this case training as shown below,

IHttpSActionResult from System.Web.Http.Results provides two methods to return result from the action.

  1. NotFound
  2. Ok

As you see, GetTraining action returns data wrapped in Ok method, or NotFound, if training with given id does not exist.

In the postman client, if you pass id value to 1 as shown in the below image, you will get an HTTP response with status 404 Not Found, as there is no training with id 1 exist.

typeinactionresult8

You can also create an HTTP response message in a separate class.  By doing that, you hide low-level details of HTTP response message construction from the controller class and can also reuse the code to construct an HTTP response message. To do this,

  • Implement IHttpActionResult interface in the class
  • Define ExecuteAsync method

We can implement IHttpActionResult to return a list of trainings in the HTTP response message, as shown below:

We are, setting various properties of the HttpResponseMessage in the ExecuteAsync method. To return list of trainings as content of the HTTP response message, we are creating object of ObjectContent and using JSONMediaTypeForammter to convert list of training in a JSON format.

Now you can use newly created TrainingDataResponse in the controller class as shown below:

Now you can test it in the postman client as shown in the image below,

typeinactionresult9

Other Types

Besides the above three types, you can use any other types such as IEnuenrable<T>, List<T>, etc. To return them as HTTP response Web API uses the media formatter to serialize the returned data. Web API will write the serialized data in the body of the Http response, and set the status to 200.

Below action returns trainings, which is serialized by Web API,

In the postman, you can test it as shown below:

typeinactionresult11

Conclusion

These are the types supported by Web API. You should use them as per your requirement.  For example, to construct low level details of HTTP response message, use the type HttpResponseMessage, and to send serialize data with status code 200, use the other types such as IEnumerable<T>.

Goodbyes are hard…..

Yes, Goodbyes are hard. After almost 5 years at Infragistics, I am moving on and seeking other opportunities. I must say these years were the best years of my life.


clip_image002

At Infragistics, I was a Developer Evangelist. My job was to engage developers, create more awareness with them around Infragistics’ Ignite UI product, and to help them to be successful.   Here are some of the things I accomplished : 

  • I created a developer community for Infragistics in India
  • I helped customers to learn and implement their solutions using Ignite UI
  • I delivered many workshops and talks across India for customers on JavaScript,  Angular, Ignite UI, ASP.NET MVC and more.
  • I created samples and customer POCs
  • I wrote articles for Infragistics blog. You can read them here

As a remote employee, I worked with various teams, managers, and regions. Based on that experience, I can say that Infragistics is one of the best employers and lead by true thought-leaders. They truly believe in making their customers successful and take care of their employees. I am grateful for my time at Infragistics, and want to send a special thanks to Senior Vice President Jason Beres for his trust in me, and giving me the opportunity. 

image

Other people I would like to thank is Director of Product Developer Konstantin Dinev , Managing Director of APAC Ken Azuma , Director of India Rohit Gaur , and my first manager Anand Raja for their constant support.

What’s Next?

I have been a Developer Evangelist for the last 7 years, helping Progress Telerik and Infragistics create their developer base in India. My forte is evangelism and I want to continue helping in reaching and educating developers and in creating community.

If you are looking for someone to help you engage with, enable, and excite your developers, feel to reach me at debugmode[at]outlook.com or tweet me at @debug_mode

 

C# Basics: Delegates

Delegates are one of the most used features of C#. It allows you to pass a function as of function pointer. It is kind of same as function pointer of C++.

Put simply, delegates are the same as a function pointer of C ++. It refers to another function.

As noted in Microsoft official documentation:

“A delegate is a type that represents references to methods with a particular parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (or call) the method through the delegate instance.”

Before get deeper into technical jargon about delegates, let us create first a delegate.

Let us talk through the above code.

  1. Just before main function in comment #1, we are declaring a delegate named AddDelegate. The signature of a delegate is very important, because a delegate can only refer functions matching the same signature.
  2. We created delegate with return type set to integer and it takes two input integer parameters.
  3. In comment # 2, we are instantiating delegate and passing add function as reference.
  4. In comment # 3 invoking the delegate.

On running above, you should get output as shown in the below image:

One important thing you need to keep in mind is that the signature of delegates must match with the signature of the function pointed by the delegate. Not only signature, but also return type should match.

Read full article on the Infragistics blog

Simplest way to share data between two unrelated Components in Angular

In Angular, it is essential to know how components communicate with each other. If you use a component inside another component, they create a parent child relationship.  In such a scenario, parent and child components communicate to each other in following ways:

  • @Input()
  • @Output()
  • Temp Ref Variable
  • ViewChild and ContentChild

You can learn in detail about @Input here   and @Output here. In this blog post, you will learn how data can be shared between components that are not related to each other using Angular Service.

To understand this using an example, create a service.  In the service, create a variable called count.  Service will share value of count variable across the components. Before we create count variable, let us talk about requirement again. We want all components to access last updated value of the data shared using the service.

For this, we have to wrap the count variable in RxJS subjects. To be precise let us use BehaviorSubject.

We are using BehaviorSubject for the following reasons:

  1. Data from the service should be multicasted. Each consumer component should access the same copy of the data. For this purpose, BehaviorSubject is used.
  2. We are not using observables, as they are unicast in nature. Subscribers will have their own copy of data.
  3. BehaviorSubject stores current value. Therefore, component will always read current value of data stored in BehaviorSubject.

Read full article on the Infragistics blog

Type of Undeclared Variable in JavaScript: What is it?

 

Have you ever thought, what is type of undeclared variable in JavaScript? I know, the first thing that might come to mind is: how can an undeclared variable have a type? Yes, in JavaScript it is possible.

To understand it, let us start with understanding types in JavaScript. There are seven built in types in JavaScript. They are as follows:

  1. null
  2. undefined
  3. boolean
  4. number
  5. string
  6. object
  7. symbol (added on ES6)

Each variable with assigned value has a type. Let us consider the code listed below:

As you can see in the above snippet, if there is no value assigned then type of variable is undefined.

So far so good, we saw that variable with no assigned value is undefined.  Let us consider the next code snippet:

We have created a variable koo and have not assigned any value to it.  Now both value and type of koo are set to undefined.

Read full article on the Infragistics blog