Thursday, June 23, 2016

Working with React

React

These are excerpts from a Pluralsight Webinar on React.

React is just a View library but we can still build large scale apps.
Angular and ember are full frameworks.

Angular - brings JavaScript to HTML - eg using ngfor ngif inside html tags
React is the other way around - brings HTML tags inside JavaScript!!
If state is this..then make this html be there or not

jQuery is used for DOM manipulation, add classes, event listeners and remove them etc.
it has built in AJAX, while React is just let us change states and re-render the screen only the parts that have changes...very very performant.


What is Flux and what is Redux?

Flux is a very abstract design pattern - for them MVC wasn't scalable anymore in facebook. Open source project.
Flux is very abstract and just a design pattern but can have library (Redux) that implements Flux.
Redux adds more to the design pattern that Flux suggested in its implementation.

Without using Flux, you can still write with React alone.
when writing larger apps, you will naturally run into design patterns that you want to use and that is where Flux and Redux comes in.
start learning with React and writing React components first.


Better to use React's own synthetic events, but we can also use jquery for that.

React now works with all browsers.
Diffing happens before rendering but actual DOM is changed.
For AJAX with React, recommended FETCH or AXIOS apis
No need for templating engines, as REACT comes with its own built in templating baked into the library.

Understand life cycle methods for React to understand it better.

How to deal with different CSS styles in React.
Read Pluralsight training CSS Styling with React to compare different methods of styling.

We can completely create and server side render React components from the server side, it is possible and obviously better performant but more complex.
Node and Express are back end technologies that you can use for server side rendering.

How is binding property to a state different  from 2 way data binding.
Angular is listening for browser events - happens outside of development workflow. So it detects and binds.
In React it is one way - so we can tell when to update the DOM when the state changes. This is a simpler model for development.

React doesn't include a client-side routing - can install a npm package React-routing??
When things become complex, look at Redux for routing.



React-Native - is for building native apps and running mobile apps.
React will work well with .NET. Apparently even can do server-side rendering with .NET!
By and large anything that serves a RESTFul API and returns JSON, we can use React unless we are trying to do some complex server side rendering.

WebPack is popular environment for building React that gives you a bunch of different things like Module loading etc.
You could just build React and use Gulp + Browserify instead though.

For compiling multiple components, it is better to use one component per file. Say use ES2015 Module Loader to aid that.

Babel can be used to transpile into JavaScript

Wednesday, April 27, 2016

JavaScript Variable Hoisting Example


var message = "I am Global";

function sayHello(){
     //message is truthy
     if(message){
        console.log(message);
  }
}

//This function runs as expected
sayHello();



function sayHelloHoisting(){
  //The if block should not run as message has already been initialized and is not falsy
  if(!message){
  //variable declared inside if block
  var message = "I should not get displayed";
  console.log(message);
  }
}

//The message gets logged to the console!!
sayHelloHoisting();

-----------------------------------------------------------------

//what actually happens with variable hoisting
// a new message variable created inside function which is undefined(falsy)
function sayHelloHoisting(){
var message = undefined;
if(!message){
  message = "If not for variable hoisting, I should not display!!";
  console.log(message);
  }
}

Wednesday, November 11, 2015

ReactJS and jQuery tweetbox comparison

Using jQuery

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
  <title>JS Bin</title>
</head>
<body>
  <div class="well clearfix">
      <textarea class="form-control"></textarea><br/>
      <button class="btn btn-primary pull-right">Tweet</button>
  </div>
</body>
</html>

// Initially disable the button
$("button").prop("disabled", true);

// When the value of the text area changes (using input event that works on modern browsers)
$("textarea").on("input", function() {
  // If there's at least one character...
  if ($(this).val().length > 0) {
    // Enable the button.
    $("button").prop("disabled", false);
  } else {
    // Else, disable the button.
    $("button").prop("disabled", true);
  }
});

-------------------------------------------------------------------------------------------------------------------------

Using React 
There is no markup in the HTML. Instead Markup and Behavior are together in JavaScript code!

<!DOCTYPE html>
<html>
<head>
<script src="//fb.me/react-with-addons-0.13.3.js"></script>
<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
  <title>JS Bin</title>
</head>
<body>
</body>
</html>

//JSX(React)
var TweetBox = React.createClass({
  getInitialState: function() {
    return {
      text: ""
    };
  },
  handleChange: function(event) {
    this.setState({ text: event.target.value });
  },
  render: function() {
    return (
      <div className="well clearfix">
        <textarea className="form-control" onChange={this.handleChange}></textarea>
        <br/>
        <button className="btn btn-primary pull-right" disabled={this.state.text.length === 0}>Tweet</button>
      </div>
    );
  }
});

React.render(
  <TweetBox />,
  document.body
);

--------------------------------------------------------------------------------------------------------------------

  • In jQuery, you write event handlers which modify the DOM.
  • In React.js, you write event handlers which modify the state. And you write render() to reflect the current state
  • We used input event for jQuery, but in React we use onChange - you'll learn about how events differ in React's JSX from React's documentation, so don't worry too much now.
  • More importantly, we use {...} syntax to include any JavaScript code inside the HTML syntax part of JSX. In this case, we want to pass the handler handleChange, and we prefix it with this. because it's a method on this UI object.
  • If you're used to jQuery, this might seem like a bad practice, but don't worry. Again, in large applications, the code will be more manageable if those markup and behaviors are kept together for each piece of UI!!
--------------------------------------------------------------------------------------------------------
To read more, follow the link
http://reactfordesigners.com/labs/reactjs-introduction-for-people-who-know-just-enough-jquery-to-get-by/

Sunday, October 25, 2015

JavaScript - Changing Prototype dynamically

JavaScript prototype inheritance

/* We can change the prototype of a class in the prototype chain dynamically. Not that this may be a good idea at all. */
//Define a Parent class
function Parent(){
    this.someProperty = "Some Property";
}
//Extend Parent's prototype
Parent.prototype.someMethod = function(){
    console.log("Some Method");
}
//Define Child class, making sure Parent's ctor is called
function Child(){
    Parent.call(this);
}
//Extend Child's prototype
Child.prototype.someOtherProperty = "Some other property";
//Change the Child's prototype here to the Parent's prototype
Child.prototype = Object.create(Parent.prototype);
var child = new Child();
child.someMethod(); // "Some Method"
console.log(child.someProperty); // "Some Property"

console.log(child.someOtherProperty); //undefined
-----------------------------------------------------------------------------------------

Property lookups through the JavaScript prototype chain work as follows:
  • If the object has a property with the given name, that value is returned. (The hasOwnProperty method can be used to check if an object has a particular named property.)
  • If the object does not have the named property, the object’s prototype is checked
  • Since the prototype is an object as well, if it does not contain the property either, its parent’s prototype is checked.
  • This process continues up the prototype chain until the property is found.
  • If Object.prototype is reached and it does not have the property either, the property is considered undefined.
Understanding how prototypal inheritance and property lookups work is important in general for developers but is also essential because of its (sometimes significant) JavaScript performance ramifications. Most JavaScript engines use a dictionary-like data structure to store object properties. 


Each property access therefore requires a dynamic look-up in that data structure to resolve the property. This approach makes accessing properties in JavaScript typically much slower than accessing instance variables in programming languages like Java and C#.

For further reading, http://www.toptal.com/javascript/javascript-prototypes-scopes-and-performance-what-you-need-to-know

Tuesday, July 28, 2015

Ad hoc queries and Plan Cache Pollution

Just sharing a link on why we should not issue random ad hoc queries against Production - pollutes the plan cache...I have seen instances when a random ad hoc report query run by a developer brought down Production to its knees...


http://blog.sqlauthority.com/2010/08/28/sql-server-plan-cache-retrieve-and-remove-a-simple-script/

Excerpts:
Query that demonstrates cache plans which are ‘ad hoc’ or called only once in a life time.

SELECT 
    [text], cp.size_in_bytes, plan_handle
FROM sys.dm_exec_cached_plans AS cp
CROSS APPLY sys.dm_exec_sql_text(plan_handle)
WHERE cp.cacheobjtype = N'Compiled Plan'
   AND cp.objtype = N'Adhoc'
   AND cp.usecounts = 1
ORDER BY cp.size_in_bytes DESC;

You can see how much memory is already bloated by not-so-useful queries. If you want to remove any large plan cache which you do not think is useful to you, you can run the following command to remove it:

DBCC FREEPROCCACHE(plan_handle)

Note: Do not play with this settings on production server unless you know what you are doing.

Friday, June 5, 2015

How to enable OData in Web API

ASP.NET Web API supports OData queries out of the box for all your complex data querying needs using the Web Service. There are just three steps you need to do to implement it. Make sure you install the OData nuget package though first.

1) Use the attribute [EnableQuery()] to decorate the targeted Web API end point

2) Make sure you return IQueryable (not IEnumerable or any other variant) from the REST end point

3) Add AsQueryable() at the end of your LINQ query so it can return the items as IQueryable.

Example:

[EnableQuery()]
public IQueryable<Order> Get()
{
    return orderRepository.Retrieve().AsQueryable();
}


And that's it. You can skip, sort, take, filter and do all the things you need to shape your queries for returning your data to your UI in the manner you like. Of course, you need to use the OData query syntax from your UI code to hit the endpoints. All in all, a very simple API to learn and implement, rather than trying to roll out your own custom filtering, sorting et al code.

Thursday, June 4, 2015

ASP.NET Web API Authentication from Angular

When a user logs in to be authenticated by issuing a POST request from the browser using the default Authorization Service provided by ASP.NET Web API, the POST message is not in JSON format but URL encoded like so

userName=xyz%40domain.com&password=foo_Bar&grant_type=password

This necessitates that if we use the $resource RESTful service to hit the Authorization service /token endpoint, we need to convert the JSON message format that $resource spits out to match this URL encoded format.

To do this, we need to do two things

1) Specify in the POST Request Header that the Content-Type is URL encoded like so
                
             Content-Type = application/x-www-form-urlencoded

2) Transform the JSON to URL encoded format using the transformRequest property of $resource. See code snippet

(function(){
    angular.module('common.services')
                .factory('userService',
                              ['$resource', 'appConfigs', userService]);

    function userService($resource, appConfigs) {
         return {
              register: $resource(appConfigs.serverURL + '/api/Account/Register', null,
                                {
                                    'registerUser' : { method: 'POST'}
                                }),
              login: $resource(appConfigs.serverURL + '/token', null,
                           {
                              'loginUser': { 
                                  method: 'POST',
                                  headers:{'Content-Type':'application/x-www-form-urlencoded'},
                                  transformRequest: function(data, headersGetter) {
                                      var str = [];
                                      for (var s in data)
                                         str.push(encodeURIComponent(s) + '=' +
                                                       encodeURIComponent(data[s]));

                                     return str.join('&');                                              
                            })
        };
    }
})();

Once we successfully call this endpoint from the login button, we grab and store the access token returned from the Authorization Service, thereby allowing us to pass the token along for future requests.

var user = {};
....

vm.login = function() {
   vm.user.grant_type = 'password';
   vm.user.userName = vm.user.email;

   userService.login.loginUser ( vm.user,
          function(data) {
              vm.isLoggedIn = true;
              vm.message = '';
              vm.password = '';
              vm.token = data.access_token; //SAVING TOKEN HERE!!
          },
         //add response.data.error callback message to the vm.user.message property
        ....
    );
};