Wednesday, February 28, 2018

Javascript Generator Function

Generators are functions which can be exited and later re-entered. The function* declaration defines a generator function, which returns a Generator object.

Calling a generator function does not execute its body immediately; an iterator object for the function is returned instead. When the iterator's next() method is called, the generator function's body is executed until the first yield expression, which specifies the value to be returned from the iterator or, with yield*, delegates to another generator function. The next() method returns an object with a value property containing the yielded value and a done property which indicates whether the generator has yielded its last value as a boolean. Calling the next() method with an argument will resume the generator function execution, replacing the yield expression where execution was paused with the argument from next().

Here is an example of calling generator function.
    function* generator1() {
        yield 1;
        yield 2;
        yield 3;
    }
    var gen1 = generator1();

    let resp = gen1.next();
    console.log('Value-' + resp.value + ": Done-" + resp.done);
    //Response - Value-1: Done-false
    resp = gen1.next();
    console.log('Value-' + resp.value + ": Done-" + resp.done);
    //Response - Value-2: Done-false
    resp = gen1.next();
    console.log('Value-' + resp.value + ": Done-" + resp.done);
    //Response - Value-3 Done-false
    resp = gen1.next();
    console.log('Value-' + resp.value + ": Done-" + resp.done);

    //Response - Value-undefined: Done-true


Here is an example of calling generator function inside generator function.


    function* someFunc(param1) {
        yield "inside someFunc - param1-" + param1;
    }
    function* generator2() {
        yield* someFunc(1);
        yield* someFunc(2);
    }

    var gen2 = generator2();
    console.log(gen2.next().value);
    console.log(gen2.next().value);

Here is a simple example on how to use async, await for fetch javascript fetch


Given below is a simple example on how to use async, await when using javascript fetch.

----------------------------------------
//create fetch
let reqPromise = fetch('https://jsonplaceholder.typicode.com/posts/1');

async function getData(){
  //await for 'fetch' response and then await to convert response to 'json'
  let response = await(await reqPromise).json();
  console.log(response);
}

//call async function
getData();

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

You can see it working here - https://codepen.io/deebujacob/pen/BYveQm


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


The syntax is similar to the JS async await - http://deebujacob.blogspot.com/2018/02/here-is-simple-example-on-how-to-use.html

Tuesday, February 13, 2018

.NET MVC - Read Json Object From POST data


If you want to get JSON data posted to MVC 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-