Friday, September 8, 2017

jQuery Detect when browser receives file download | Detecting the File Download Dialog In the Browser

Client Side:

<script src="./../jquery-2.1.4.js"></script>

<script type="text/javascript">
$(document).ready(function () {

var downloadToken = new Date().getTime();

$("button").click(function () {
    downloadToken = new Date().getTime();
    $("[name='downloadToken']").val(downloadToken);
    $("form").trigger("submit");
    timer();
});

function timer() {
    var attempts = 100; /* As you required */
    var downloadTimer = window.setInterval(function () {
        var token = getCookie("downloadToken");
        attempts--;

        if (token == downloadToken || attempts == 0) {
            $(".log").prepend("Browser received file from server<br/>");
            window.clearInterval(downloadTimer);
        }
        else {
            $(".log").prepend("Browser not received file from server yet<br/>");
        }
    }, 1000);
}

function parse(str) {
    var obj = {};
    var pairs = str.split(/ *; */);
    var pair;
    if ('' == pairs[0]) return obj;
    for (var i = 0; i < pairs.length; ++i) {
        pair = pairs[i].split('=');
        obj[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
    }
    return obj;
}

function getCookie(name) {
    var parts = parse(document.cookie);
    return parts[name] === undefined ? null : parts[name];
}

});
</script>

<form action="download.php" method="post">
    <input type="hidden" name="downloadToken"/>
    <button type="button">Download</button>
    <div class="log"></div>
</form>

Server Side Script as of PHP:

<?php
$file_name = "download.zip";
header('Content-Description: File Transfer');
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename=download.zip');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_name));

// Sleep 5 seconds...
sleep(5);

// Cookie will be expire after 20 seconds...
setcookie("downloadToken", $_POST["downloadToken"], time() + 20, "");

ob_clean();
flush();
readfile($file_name);

Browser Screenshot:






Thursday, September 7, 2017

Finding IP Address of my computer using VBScript | Retrieve Your Computer's IP Address | IP Address and Computer Name VBscript | How to get the IP Address for your Local Area Connection on Windows

dim NIC1, Nic, StrIP, CompName

Set NIC1 = GetObject("winmgmts:").InstancesOf("Win32_NetworkAdapterConfiguration")

For Each Nic in NIC1
    if Nic.IPEnabled then
        StrIP = Nic.IPAddress(i)

        Set WshNetwork = WScript.CreateObject("WScript.Network")
        CompName = WshNetwork.Computername

        MsgBox "IP Address:  " & StrIP & vbNewLine _
            & "Computer Name:  " & CompName, 4160, "IP Address and Computer Name"

        wscript.quit
    End if
Next


Sunday, September 3, 2017

jQuery get exact position of element | get exact left top position of jQuery element

Below is code snippet

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>jQuery Position of Element</title>
    <script src="jquery-2.1.4.js"></script>
    <script type="text/javascript">
        $(document.body).ready(function() {
            var body = $(document.body), element = body.find(".element"),
                    log = body.find(".log");
            var rect = element[0].getBoundingClientRect();
            log.append("<p>LEFT==" + rect.left + "</p>");
            log.append("<p>TOP==" + rect.top + "</p>");
            log.append("<p>RIGHT==" + rect.right + "</p>");
            log.append("<p>BOTTOM==" + rect.bottom + "</p>");
            log.append("<p>WIDTH==" + rect.width + "</p>");
            log.append("<p>HEIGHT==" + rect.height + "</p>");
        });
    </script>
</head>
<body style="margin:0">
<div style="position:relative;width:100%;height:100%;margin:0">
    <div class="element" style="position:absolute;margin:0;left:170px;top:200px;border:1px solid red;width:100px;height:30px;"></div>
</div>
<div class="log" style="font-weight:bold;"></div>
</body>
</html>

And output is below:


Monday, August 28, 2017

CLEditor Auto Grow Example



Very first position of cleditor:

After grow (change of content) of cleditor:




$(document).ready(function () {
    var panel = $(document.body).find(".editor-container");

    //https://premiumsoftware.net/cleditor/gettingstarted
    panel.find(".editor").cleditor().on("change", function () {
        this.$area.trigger("rich_editor_content_changed");
    });
    var iframe = panel.find("iframe"), iframe_body = iframe.contents().find("body");
    iframe.parent().css("height", "auto");
    iframe.attr("scrolling", "no");

    iframe.contents().find("body").bind("wheel", function(e, delta) {
        iframe.css("pointer-events", "none");
        clearTimeout($.data(this, 'mousewheel'));
        $.data(this, 'mousewheel', setTimeout(function() {
            iframe.css("pointer-events", "auto");
        }, 200));
    });

    panel.find(".cleditorMain").on('mousedown', function(e, delta) {
        iframe.css("pointer-events", "auto");
    });

    setTimeout(function () {
        panel.find("textarea").on("rich_editor_content_changed", function () {
            iframe.css("height", iframe_body.height() + 30);
        }).trigger("rich_editor_content_changed");
    }, 100);
});



Perfect Scrollbar Example

Perfect Scrollbar Example




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Perfect Scrollbar Example</title>
    <script src="jquery-1.11.1.min.js"></script>
    <script src="perfect-scrollbar.jquery.min.js"></script>
    <link rel="stylesheet" href="perfect-scrollbar.css"/>
    <style type="text/css">
        .scroll {
            top: 100px;
            left: calc(50% - 250px);
            position: relative;
            padding-right: 9px;
        }

        .scroll p {
            padding: 20px;
            margin-left: 7px;
            border: 2px solid #404040;
        }
    </style>
    <script type="text/javascript">
        $(document).ready(function () {
            $(".scroll").perfectScrollbar();
            $(".scroll").perfectScrollbar("update");
        });
    </script>
</head>
<body>
    <div class="scroll" style="height:500px;width:500px;border:1px solid red;overflow:scroll">
        <p>Paragraph 1</p>
        <p>Paragraph 2</p>
        <p>Paragraph 3</p>
        <p>Paragraph 4</p>
        <p>Paragraph 5</p>
        <p>Paragraph 6</p>
        <p>Paragraph 7</p>
        <p>Paragraph 8</p>
        <p>Paragraph 9</p>
        <p>Paragraph 10</p>
        <p>Paragraph 11</p>
        <p>Paragraph 12</p>
        <p>Paragraph 13</p>
        <p>Paragraph 14</p>
        <p>Paragraph 15</p>
        <p>Paragraph 16</p>
        <p>Paragraph 17</p>
        <p>Paragraph 18</p>
        <p>Paragraph 19</p>
        <p>Paragraph 20</p>
    </div>
</body>
</html>


Tuesday, August 22, 2017

Grails render view from service | Grails Goodness: Render GSP Views And Templates Outside Controllers | Cannot use the session in non-request rendering operations in grails

Grails render view from service | Grails Goodness: Render GSP Views And Templates Outside Controllers | Cannot use the session in non-request rendering operations in grails.


import grails.util.Holders
import org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib

class PageRenderedUtils {
    static final String gPath = "org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib"

    static void example() {
        renderTemplate("/user/info", [id: 1L, name: "Pritom Kumar"])
    }

    static String renderTemplate(String template, Map model) {
        return g.render(template: template, model: model)
    }

    static ApplicationTagLib getG() {
        return (ApplicationTagLib) Holders.applicationContext.getBean(gPath)
    }
}

Saturday, August 5, 2017

Grails Groovy: Execute Code transparent before and after any method is invoked | Override Method Implementation | Override Method Body

Grails Groovy: Execute Code transparent before and after any method is invoked | Override Method Implementation | Override Method Body.
Note:-
  • Make sure the returned value from the method call is returned from the closure as well
  • Might be a expensive of a class has number of methods with heavy implementation
  • If selective execution is required, then check for the method name and then intercept the call


class Dummy {
    def method1() { 
        System.out.println "In method 1"
    }

    def method2(String str) { 
        System.out.println "In method 2"
    }
    
    static def method3(int a, int b) {
        System.out.println "In static method 3" 
    }    
}

Dummy.metaClass.invokeMethod = {String name, List args ->
   def result = null

   System.out.println("Do something before $name is called with args $args")

   try {
       result = delegate.metaClass.getMetaMethod(name, args).invoke(delegate, args)
   }
   catch(Exception e) {
        System.out.println "Handling exception for method $name"
   }

   System.out.println("Do something after $name was called with args $args")

   return result
}

Dummy.metaClass.'static'.invokeMethod = {String name, List args ->
   def result = null

   System.out.println("Do something before static method $name is called with args $args")

   try {
       result = delegate.metaClass.getMetaMethod(name, args).invoke(delegate, args)
   }
   catch(Exception e) {
        System.out.println "Handling exception for method $name"
   }

   System.out.println("Do something after static method $name was called with args $args")

   return result
}

def dummy = new Dummy()
dummy.method1()
dummy.method2('Test')
Dummy.method3(1, 2)