Wednesday, January 25, 2017

How to execute JavaScipt code inserted as innerHTML/text in DOM

If you tried to load scripts into a page using innerHTML on HTML element like div it will not be executed.

The alert statement in below code will not be executed since it is set as inner HTML.

document.getElementById('divTemp').innerHTML = "<scr" + "ipt>alert('hi')</scr" + "ipt>";

You can use eval() but there is an easier and better way to do this. That is to load the script element into DOM.

Here is an example -

        var script1 = document.createElement("script");
        script1.innerHTML = "alert('hi');";
        document.body.appendChild(script1);

In this way you can execute javascript statements set as innerHTML or text. This will help you to execute scripts that are loaded asynchronously using APIs.

Live example in codepen- 

Friday, January 13, 2017

How to scale html elements and fonts based on the container

When we generate html we can use '%' to scale the containers based on parent element. But html elements set with pixel value will not scale correctly if parent container size is changed.

Here is an example to scale html elements correctly. Keep in mind that this is not a solution for setting layouts for different devices like desktop, mobile and tablet. The example below can be used when you want the layout to look exactly the same and scale the content size and position based on parent element's size.

We can achieve this by setting the transform property
 transform: scale(scaleWidthValue,scaleHeightValue);

To scale twice the size -
-ms-transform: scale(2,2); /* IE 9 */
transform: scale(2,2); /* Safari */
transform: scale(2,2); /* Standard syntax */

Here is the codepen link to live example -http://codepen.io/deebujacob/pen/OWXjjp

/********************* Here is the auto scaling html logic ***************/
<html>
<style>
#containerElement{
width:200px;
height:120px;
}
.outerWrapperStyle{
background-color:yellow;
width:400px;
height:225px;
padding:10px;
transform-origin:top left;
}
.innerWrapperStyle{
background-color:red;
width:200px;
height:125px;
padding:10px;
}
.contentStyle{
font-family:arial;
font-size:18px;
font-color:#333;
}
.transform{/*not used directly here*/
    transform: scale(1.5,1.5); /* Standard syntax */
}
</style>
<div id="containerElement" >
<div id="contentElement" class="outerWrapperStyle transform">
<div class="contentStyle">
Outer wrapper  content.
</div>
<div class="innerWrapperStyle">
<div class="contentStyle">
Inner Wrapper Content
</div>
</div>
</div>
</div>
<script>
var containerElement = document.getElementById("containerElement");/*get container element*/
var contentElement = document.getElementById("contentElement");/*get content element*/

var scaleWidth = containerElement.clientWidth/contentElement.clientWidth; /*find out how much to scale for width*/
var scaleHeight = containerElement.clientHeight/contentElement.clientHeight; /*find out how much to scale for height*/

contentElement.style.transform  = "scale("+scaleWidth+","+scaleHeight+")"; /*set the scale on content Element*/
</script>

</html>

Wednesday, September 14, 2016

How to POST JSON object to ASP.NET httphandler API using XmlHttpRequest and Javascript

This example show how to post a JSON object to asp.net http handler using xmlhttprequest in JavaScript.

Passing objects this way will help to maintain the same object model in UI , business object and database. Similar to MVC framework - but here you are building your own framework and have more control over the functionalities and performance.

JS
<script>

        function postData() {
            var xhr = new XMLHttpRequest();
            /*set the asp.net end point*/
            var url = "departmentAPI?action=add";
            /*set method as post*/
            xhr.open("POST", url, true);
            xhr.setRequestHeader("Content-type", "application/json");
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    var json = JSON.parse(xhr.responseText);
                    console.log(json)
                }
            }
            /*create object*/
            var department = {};
            department.department_name = "Finance";
            var data = JSON.stringify(department);
            /*post data to server*/
            xhr.send(data);

        }
        /*call the function*/
        postData();
    </script>


C#/.net

public class DepartmentAPI : IHttpHandler
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
      public void ProcessRequest(HttpContext context)
        {
            /*read data from server side*/
            string jsonString = String.Empty;
            context.Request.InputStream.Position = 0;
            using (StreamReader inputStream = new StreamReader(context.Request.InputStream))
            {
                jsonString = inputStream.ReadToEnd();
            }
            DepartmentBO department = serializer.Deserialize<DepartmentBO>(jsonString);
        }


        public bool IsReusable
        {
            get { return true; }
        }
    }

}

Wednesday, May 25, 2016

Set content in an iframe or load scripts in it asynchronously

Sometimes you may have to load the scripts or content inside and iframe. This will be helpful especially if you are loading an ad or video on a web page and do not want to slow down the whole web page. Given below is an example on how to load content inside an iframe asynchronously.


    <iframe id="myiframe" height="300" width="700"></iframe>
    <script>
        window.setTimeout(setIframeContent,1000);
        function setIframeContent() {
            //set content or script
            var html = '<body><div>my content</div><scr' + 'ipt>alert("test")</' + 'script></body>';
            //get reference to iframe and load the content to iframe
            var iframe = document.getElementById("myiframe");
            iframe.contentWindow.document.open();
            iframe.contentWindow.document.write(html);
            iframe.contentWindow.document.close();
           
        }

    </script>

Tuesday, April 19, 2016

Add HTTP access control (CORS) to response

For security reasons, browsers restrict cross-origin HTTP requests initiated from within scripts.  For example, XMLHttpRequest follows the same-origin policy. So, a web application using XMLHttpRequest could only make HTTP requests to its own domain unless CORS headers are added  in the response.

Given below is the code to add CORS header to response in asp.net

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "domain.com" );
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");

If you want to include CORS header for requests from all domains, you have to format the referrer url to get the correct domain

public static string GetDomain(string referrer)
{
    string tmpReferrer = String.IsNullOrEmpty(referrer) || referrer.Length < 5 ? "" : referrer;

    // strip out the domain portion of the referring url, if there is a starting point
    if (tmpReferrer.Length > 0 && tmpReferrer.Substring(0, 4) == "http")
    {

        //remove string after first /
        if (tmpReferrer.IndexOf("/", 8) > 0)
        {
            tmpReferrer = tmpReferrer.Substring(0, tmpReferrer.IndexOf("/", 8));
        }

        //remove string after first ?
        if (tmpReferrer.IndexOf("?") > 0)
        {
            tmpReferrer = tmpReferrer.Substring(0, tmpReferrer.IndexOf("?"));
        }
    }
    else if (tmpReferrer.Length > 0)
    {
        //remove string after first /
        if (tmpReferrer.IndexOf("/") > 0)
        {
            tmpReferrer = tmpReferrer.Substring(0, tmpReferrer.IndexOf("/", 8));
        }

    }
    return tmpReferrer;
}

And then call the function to add domain name to CORS header

string referrer = HttpContext.Current.Request.ServerVariables["HTTP_REFERER"];
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", GetDomain(referrer));
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true");



JS code to call endpoint

var httpRequest = new XMLHttpRequest();
 httpRequest.open("GET", "http://somedomain.com/endpoint", true);
 httpRequest.withCredentials = true;
 httpRequest.send();
   
 httpRequest.onreadystatechange =  function () {
     if (httpRequest.readyState == 4) {//wait for request to complete
               
         console.log(httpRequest.responseText);
               
     }
 };

How to add semi transparent background

You can set semi transparent background on a div or any html element by adding below style -

background-image: linear-gradient(to bottom, rgba(255, 255, 255, 0.5) 0%,rgba(255, 255, 255, 0.5) 100%), url(http://www.bestmanspeechestoasts.com/wp-content/themes/thesis/rotator/sample-4.jpg);


You can see the example here - http://codepen.io/deebujacob/pen/xVzRxw

Wednesday, December 2, 2015

LINQ - Group multiple columns or keys

Using .NET linq you can easily group data in a list. This is an example of grouping data based on multiple keys.

This is the class that I created for testing
public class Employee
{
public string Name { get; set; }
public string Department { get; set; }
public string SubDepartment { get; set; }
public float Salary { get; set; }
}

This is the multi- key grouping using LINQ
/*create employee list*/
List<Employee> emps = new List<Employee>();

/*Add test data */
emps.Add(new Employee() { Name = "Employee 1", Department = "HR", SubDepartment="Recruitment",  Salary = 4000 });
emps.Add(new Employee() { Name = "Employee 2", Department = "HR",SubDepartment="Recruitment", Salary = 4500 });
emps.Add(new Employee() { Name = "Employee 3", Department = "Tech",SubDepartment="Engineering", Salary = 5000 });
emps.Add(new Employee() { Name = "Employee 4", Department = "Tech",SubDepartment="Engineering", Salary = 5200 });

/*group data based on departments*/
List<Employee> newlist = (from x in emps
group x by new { x.Department, x.SubDepartment } into grp
select new Employee()
{
Department = grp.Key.Department,
SubDepartment = grp.Key.SubDepartment,
Salary = grp.Sum(x => x.Salary)
}
).ToList();