Monday, February 19, 2018

Get string content posted to a web api

If you have to post string content to a web api you can use the below example. [FromBody] attribute will work only for formatted content like json or xml.


  [Route("GetData")]
        [HttpPost]
        public virtual async System.Threading.Tasks.Task<HttpResponseMessage> GetData()
        {
            string someData = await Request.Content.ReadAsStringAsync();
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
            return response;
        }

Tuesday, February 13, 2018

.NET Web Api - Read Json Object From POST data


If you want to get JSON data posted to web api endpoint without creating corresponding C# object, you can use the following method.

Web API endpoint

 [HttpPost]
        [Route("GetData")]
        public String GetData()
        {
            //Get the request input stream
            Stream req = Request.InputStream;
            req.Seek(0, System.IO.SeekOrigin.Begin);
            string jsonString = new StreamReader(req).ReadToEnd();

            //Convert JSON String to JObject
            JObject jsonObject = JObject.Parse(jsonString);

            //Get posted data
            string name= jsonObject["name"].ToString();
            return name;

        }



JavaScript call

            let jsonData = '{"name":"myname",age:10}';
            let reqPromise = fetch('/GetData',
                {
                    method: "POST",
                    body: jsonData,
                    headers: {
                        'Accept': 'application/json, text/plain, */*',
                        'Content-Type': 'application/json'
                    }
                });

            reqPromise.then(
                (response) => {
                    return response.text();
                }
            ).then((jsonRespnse) => {
                console.log(jsonRespnse);
                }

            );


The other option is to create corresponding C# object and accept it as a parameter in the endpoint.

1) Create object

    public class MyData
    {
        public String Name { get; set; }
        public int Age { get; set; }

    }

2) Accept the object as a parameter using [FromBody] attribute as given below

        [HttpPost]
        [Route("GetData")]
        public String GetData([System.Web.Http.FromBody] MyData myData)
        {
          return myData.Name;
        }



Friday, February 2, 2018

Youtube video thumbnail images

You can get the thumbnail images of youtube video by using the below format.

https://img.youtube.com/vi/<video-id>/0.jpg
https://img.youtube.com/vi/<video-id>/1.jpg
https://img.youtube.com/vi/<video-id>/2.jpg
https://img.youtube.com/vi/<video-id>/hqdefault.jpg

You can see a live example here - https://codepen.io/deebujacob/full/BYjxpm

Data URLs - Include Data In-line In Web Pages

Data URLs, URLs prefixed with the data: scheme, allow content creators to embed small files inline in documents.

You can pass html directly to the url as given below.

<iframe src="data:text/html,<html><body><div>test</div></body></html>" height="100%" width="100%"></iframe>
<iframe src="data:text/html,data:text/html,<script>alert('hi');</script>" height="100%" width="100%"></iframe>

Or you can set base64 data in URL


<iframe src="data:application/pdf;base64,BASE64_DATA" height="100%" width="100%"></iframe>

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; }
        }
    }

}