Thursday 30 April 2015


RequireJS Getting Started

RequireJS is probably the most wide spread implementation of the AMD API nowadays. If its documentation is rather thick, it still may leave you with the feeling that it lacks a simple example that would help you get started. The goal of this tutorial is to show you the fundamentals in the easiest possible way in order to be able to experiment with Require, through a minimalist example.

A simple example

 

index.html

 














<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>Basic example of requireJS integration</title>
</head>
<body>
<div id="container">
    <p>Check console and js files</p>
</div>
<script data-main="js/main" src="js/vendor/require.js"></script>
</body>
</html>

We begin with a basic structure.
The script tag that calls require.js includes a “data-main” attribute pointing to the js/main.js file, without its extenstion (we can however keep it if we want).
The location of the main.js file is important, as it will be the root from which the modules will be looked for.

js/main.js

 








// Load modules and use them
require(['module1', 'path/to/module2'], function(module1ref, module2ref){
    // do something with the loaded modules
    var module1 = new module1ref(),
          module2 = new module2ref();
    console.log(module1.getName() === module2.getModule1Name()); // true
});

The require() function takes two arguments: an array of dependencies, and a callback function to execute once all the dependencies are loaded.
This callback function takes for parameters the specified dependencies, in their order of apparition in the array.
Here, we load module1 and module2, and we pass them to the callback function under the name “module1ref” and “module2ref” respectively.
The parameters passed in the dependency array are the names of the JavaScript files containing the modules, without their extension. They can contain a path, which will be relative to the location of the main.js file.

js/module1.js

 












define([], function () {
    var returnedModule = function () {
        var _name = 'module1 name';
        this.getName = function () {
            return _name;
        }
    };
    return returnedModule;
});

To create a module, we use the define() function provided by RequireJS.
This function, as in the case of the require() function, can specify some dependencies.
It has to return something, which will be forwarded to the callback function.
Here, we return a function that exposes a getName() method allowing us to to get the” private variable “_name.

js/path/to/module2.js

 












define(['module1'], function (module1ref) {
    var module1 = new module1ref();
    var returnedModule = function () {
        this.getModule1Name = function () {
            return module1.getName();
        }
    };
  
    return returnedModule;
  
});

For this second module, we have declared a dependency on the module1, which becomes available under the name module1ref in the callback function.
This module returns a function too, which exposes the getModule1Name() method. We can thus see how we can make use of a dependecy within a module.
Of course, you have total freedom on what you do with those dependencies within a module, and I’m sure you will find some way more interesting usages than the one in this exemple! ;)

Loading dependencies that aren’t modules

You will probably soon enough need to load third party libraries that aren’t defined as Require modules, like for example jQuery or underscore.js.
For this, James Burke (the author of RequireJS) provides a “shim” system to us.

js/main.js

 
























require.config({
    paths: {
        'jQuery': 'vendor/jquery-1.9.0.min',
        'underscore': 'vendor/underscore-1.9.min'
    },
    shim: {
        'jQuery': {
            exports: '$'
        },
        'underscore': {
            exports: '_'
        }
    }
});
require(['module1', 'path/to/module2', 'jQuery'], function (module1ref, module2ref, $) {
    // do something with the loaded modules
    var module1 = new module1ref(),
          module2 = new module2ref();
    console.log(module1.getName() === module2.getModule1Name()); // true
    console.log('jQuery version:', $.fn.jquery); // 1.9.0
});

In order to use jQuery as a dependency, we must tell RequireJS two things: the path where to find the JavaScript file, and the global variable we wish to get hold of.
To do so, we have to provide a configuration object to the config() method of the “require” (or “requirejs”, both are identical) global object.
This configuration object defines under its “paths” key the names of the virtual modules, as keys for which the value represents the file we want to load.
Under the “shim” key of the configuration object, we use those keys to point to the global variable defined by the library we want to get hold of.
It’s this variable that will be returned when we call the module thus defined.
Here again, the “paths” declared are relative to the location of the main.js file and don’t include their .js extension.

Wednesday 22 April 2015

Responsive Facebook Page widget 


                 <div class="facebook_cont">
                    <div id="fb-root"></div>
                    <script>

// facebook widget js 
                       (function (d, s, id) {
                            var js, fjs = d.getElementsByTagName(s)[0];
                            if (d.getElementById(id)) return;
                            js = d.createElement(s); js.id = id;
                            js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.3";
                            fjs.parentNode.insertBefore(js, fjs);
                        }(document, 'script', 'facebook-jssdk'));

// script for making the widget responsive 
                           $(window).bind("load resize", function () {
                            var container_width = $('#container').width();
                            $('.fb-page').each(function () {
                                // Change 'data-width' attribute
                                $(this).first('span').width(container_width);
                                $(this).attr('data-width', container_width);

                                FB.XFBML.parse();
                            });
                        });
                    </script>

// Html from facebook widget
                    <div id="container" style="width: 100%">
                        <div class="fb-page" data-href="https://www.facebook.com/your_Page" data-width="500" data-height="500" data-hide-cover="false" data-show-facepile="true" data-show-posts="true">
                            <div class="fb-xfbml-parse-ignore">
                                <blockquote cite="https://www.facebook.com/
your_Page"><a href="https://www.facebook.com/your_Page">Your Page</a></blockquote>
                            </div>
                        </div>
                    </div>
                 </div>

Wednesday 8 April 2015

HTML !DOCTYPE declaration for various HTML versions

(X)HTML5:
<!DOCTYPE html>
(X)HTML5 (alternative):
<!DOCTYPE html SYSTEM "about:legacy-compat">
XHTML 1.1+Aria 1.0:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+ARIA 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-aria-1.dtd">
XHTML 1.1+RDFa 1.1:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.1//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-2.dtd">
XHTML 1.1+RDFa 1.0:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd">
XHTML 1.1:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
XHTML Basic 1.1:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.1//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic11.dtd">
XHTML 1.0 Strict:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
XHTML 1.0 Loose:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
XHTML 1.0 Frameset:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd">
XHTML-Print 1.0:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML-Print 1.0//EN" "http://www.w3.org/TR/xhtml-print/xhtml-print10.dtd">
XHTML Basic 1.0:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Basic 1.0//EN" "http://www.w3.org/TR/xhtml-basic/xhtml-basic10.dtd">
XHTML Mobile Profile 1.2:
<!DOCTYPE html PUBLIC "-//WAPFORUM//DTD XHTML Mobile 1.2//EN" "http://www.openmobilealliance.org/tech/DTD/xhtml-mobile12.dtd">
HTML 4.01+Aria 1.0:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML+ARIA 1.0//EN" "http://www.w3.org/WAI/ARIA/schemata/html4-aria-1.dtd">
HTML 4.01+RDFa 1.1:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01+RDFa 1.1//EN" "http://www.w3.org/MarkUp/DTD/html401-rdfa11-1.dtd">
HTML 4.01+RDFa Lite 1.1:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01+RDFa Lite 1.1//EN" "http://www.w3.org/MarkUp/DTD/html401-rdfalite11-1.dtd">
HTML 4.01+RDFa 1.0:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/html401-rdfa-1.dtd">
HTML 4.01 Strict:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
HTML 4.01 Loose:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
HTML 4.01 Frameset:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">
HTML 4.0 Strict:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
HTML 4.0 Loose:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
HTML 4.0 Frameset:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN" "http://www.w3.org/TR/REC-html40/frameset.dtd">
ISO/IEC 15445:
<!DOCTYPE html PUBLIC "ISO/IEC 15445:2000//DTD HTML//EN">
ISO/IEC 15445 (alternative):
<!DOCTYPE html PUBLIC "ISO/IEC 15445:2000//DTD HyperText Markup Language//EN">
HTML 3.2:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
HTML 3.2 (alternative):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
HTML 3.2 (alternative):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Draft//EN">
HTML 2.0:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">
HTML 2.0 (alternative):
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

MVC running Background service without creating any scheduler.exe (inspired from stackoverflow's idea)

In Global.asax      

    public class MvcApplication : System.Web.HttpApplication
    {
        private const string DummyCacheItemKey = "BackgroundService";
        private static string DummyPageUrl = "localhost/dummy";// any other valid url


        protected void Application_Start()
        {  // other code snippets

           ...................................
           ...................................
           RegisterCacheEntry();
        }


                   protected void Application_BeginRequest(object sender, EventArgs e)
        {  // other code snippets

           ....................................
           ....................................
           if (HttpContext.Current.Request.Url.ToString() == DummyPageUrl)
            {
                // Add the item in cache and when succesful, do the work.
                RegisterCacheEntry();
            }
        }

        private bool RegisterCacheEntry()
        {
            if (null != HttpContext.Current.Cache[DummyCacheItemKey]) return false;

            HttpContext.Current.Cache.Add(DummyCacheItemKey, "Test", null,
                DateTime.MaxValue, TimeSpan.FromMinutes(1),
                CacheItemPriority.Normal,
                new CacheItemRemovedCallback(CacheItemRemovedCallback));

            return true;
        }

        public void CacheItemRemovedCallback(string key, object value, CacheItemRemovedReason reason)
        {
            // Do the service works
            new Thread(() =>
            {
                try
                {
                    BackgroundServices.DoWork();
                }
                catch (Exception ex)
                {
                    //log the exception
                }
            }).Start();

            BackgroundServices.HitPage();
        } 

     }

Create BackgroundServices class as follows

    public class BackgroundServices
    {
        private static readonly string DummyPageUrl ;

        static BackgroundServices()
        {
            DummyPageUrl = "localhost/dummy";// any other valid url        }       

        public static void HitPage()
        {
            WebClient client = new WebClient();
            client.DownloadData(DummyPageUrl);
        }

        public static void DoWork()
        {
            try
            {
                using (SqlConnection con = new SqlConnection("connectionstring"))
                {
                    con.Open();
                    // database related work
                    con.Close();
                }
            }catch(Exception ex)
            {
                //logging the exception
            }
        }
    }


Now create a dummy action in any controller and map the route of the same in RouteConfig.cs and set the "DummyPageUrl" to that url.

Find Latitude and Longitude of Location using address in C#

        public static List<float> GetLatLongOfAddress(string Address)
        {
            WebClient webClient = new WebClient();
            webClient.QueryString.Add("address", Address);
            string result = webClient.DownloadString("https://maps.googleapis.com/maps/api/geocode/json");
            var json = JObject.Parse(result);
            var loc = json["results"].First()["geometry"]["location"];
            return new List<float>
            {
                float.Parse(Regex.Replace((string)loc["lat"], "[^0-9A-Za-z.-]+", " ").Trim()),
                float.Parse(Regex.Replace((string)loc["lng"], "[^0-9A-Za-z.-]+", " ").Trim())
            };
        }
 

Find distance between two locations using their Latitudes and Longitudes in C#

        public static float GetDistanceBetween(List<float> location1, List<float> location2)
        {
            var lat1 = location1[0];
            var lat2 = location2[0];
            var lon1 = location1[1];
            var lon2 = location2[1];
            var R = 6371; // Radius of the earth in km
            var dLat = deg2rad(lat2 - lat1);  // deg2rad below
            var dLon = deg2rad(lon2 - lon1);
            var a = Math.Sin(dLat / 2) * Math.Sin(dLat / 2) +
                    Math.Cos(deg2rad(lat1)) * Math.Cos(deg2rad(lat2)) *
                    Math.Sin(dLon / 2) * Math.Sin(dLon / 2);
            var c = 2 * Math.Atan2(Math.Sqrt(a), Math.Sqrt(1 - a));
            var d = R * c; // Distance in km
            return (float)d;
        }

        private static double deg2rad(double deg)
        {
            return deg * (Math.PI / 180);
        }