Facebook share and like with javascript callback

1. Like button,

Here is the html of what url in the “like” box,

<div class="fb-like-box"></div>

You have to create a facebook application, and assign the “appId” in the fbAsyncInit method,

    window.fbAsyncInit = function () {
        FB.init({
            appId: '#Replace Your AppID#',
            status: true,
            cookie: true,
            xfbml: true,
            oauth: true
        });
        FB.Event.subscribe('edge.create', function (response) {
            alert('You liked the URL: ' + response);
        });
    };
    (function (d) {
        var js, id = 'facebook-jssdk';
        if (d.getElementById(id)) {
            return;
        }
        js = d.createElement('script');
        js.id = id;
        js.async = true;
        js.src = "//connect.facebook.net/en_US/all.js";
        d.getElementsByTagName('head')[0].appendChild(js);
    }(document));

With the FB.event.subscribe callback method, you can put some of your stuff, like award the guy who liked your site =)

2. Share button

This is calling FB.init(), then FB.ui() to load the dialog and with callback, the callback response, you can retrieve the post_id for your tracking.

window.fbAsyncInit = function () {
        FB.init({
            appId: '#Replace Your AppID#',
            status: true,
            cookie: true,
            xfbml: true,
            oauth: true
        });

        FB.ui(
        {
            method: 'feed',
            name: 'Facebook Dialogs',
            link: 'http://youtubeplaylist.net',
            picture: 'http://fbrell.com/f8.jpg',
            caption: 'Reference Documentation',
            description: 'Dialogs provide a simple, consistent interface for applications to interface with users.'
        },
            function (response) {
                if (response && response.post_id) {
                    alert('Post was published.');
                } else {
                    alert('Post was not published.');
                }
            }
        );

    };
    (function (d) {
        var js, id = 'facebook-jssdk';
        if (d.getElementById(id)) {
            return;
        }
        js = d.createElement('script');
        js.id = id;
        js.async = true;
        js.src = "//connect.facebook.net/en_US/all.js";
        d.getElementsByTagName('head')[0].appendChild(js);
    }(document));

Twitter, tweet button with javascript callback

Here is an example of using Twitter Web intents with js events callback.  This is the html anchor tag.

<a href="https://twitter.com/intent/tweet?text=&amp;url=http://youtubeplaylist.net&amp;via=ytubeplaylist" class="twitter-share-button">Tweet</a>

To allow the js events, you must include the widget.js to make it working. Here is the code in below,

    window.twttr = (function (d, s, id) {
        var t, js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) return; js = d.createElement(s); js.id = id;
        js.src = "//platform.twitter.com/widgets.js"; fjs.parentNode.insertBefore(js, fjs);
        return window.twttr || (t = { _e: [], ready: function (f) { t._e.push(f) } });
    }(document, "script", "twitter-wjs"));


Next, we use twttr.ready() to to bind events in this method, we can bind several events like, tweet, follow, retweet, favorite, click,

twttr.ready(function (twttr) {
        twttr.events.bind('tweet', function (event) {
            // Do something there
            alert("callback");
        });
		twttr.events.bind('follow', function(event) {
    		var followed_user_id = event.data.user_id;
    		var followed_screen_name = event.data.screen_name;
		});

		twttr.events.bind('retweet', function(event) {
		    var retweeted_tweet_id = event.data.source_tweet_id;
		});

		twttr.events.bind('favorite', function(event) {
		    var favorited_tweet_id = event.data.tweet_id;
		});
});

For more information, check out the twitter documentation, https://dev.twitter.com/docs/intents/events#waiting-for-asynchronous-resources

JQuery ajax request not working in IE9

I have some ajax get request on the web page and it works perfectly fine in Firefox and Chrome. But it is not working with IE at all. After some research, I found out I need to specify the dataType and allow cross domain.

Before I have,

            $.ajax({
                type: "GET",
                url: 'http://example.com/abc',
                error: function (xhr, statusText) {
						//log error                    
                },
                success: function (data) {                    
						//process data
                }
            });
        }

After I have specify the dataType, contentType and crossDomain, it works straight away.

            $.ajax({
                dataType: "jsonp",
                contentType: "text/json; charset=utf-8",
                crossDomain: true,
                type: "GET",
                url: 'http://example.com/abc',
                error: function (xhr, statusText) {
						//log error                    
                },
                success: function (data) {                    
						//process data
                }
            });
        }

This little tip saved my day!

More about twitter bootstrap datepicker

I have blogged about the bootstrap datepicker earlier. Here is the link

https://kevww.wordpress.com/2012/03/20/bootstrap-from-twitter-is-missing-a-date-picker/

I personally find that is pretty annoy after you select the date, the calendar popup doesn’t disappear.

So I put some extra code in the on change event, to hide it.

$('#SelectedDate').datepicker({ format: "dd/mm/yyyy" }).on('changeDate', function (ev) {
             $(this).blur();
             $(this).datepicker('hide');
         });

If you don’t set blur(), the textbox will not lose focus and if you click the textbox again, the calendar popup will show.

And then hide the datepicker.

So what I have done here, is lose the focus and hide it.

Bootstrap from Twitter is missing a date-picker

Bootstrap is awesome, light weight. I think it is a great replacement of JQuery UI. But there are still a few elements missing from Bootstrap. Such as the very important one: date picker.

I found someone has done a plugin for it. It is pretty cool.

Here it is. http://www.eyecon.ro/bootstrap-datepicker/

To create a date picker, write the markups as follow,

    <div class="input-append date" id="dp3">
    
    <span class="add-on"><i class="icon-th"></i></span>
    </div>

image

Call the javascripts,

$('.datepicker').datepicker()

There are a few events that you can register as well,

show

This event fires immediately when the date picker is displayed.

hide

This event is fired immediately when the date picker is hidden.

changeDate

This event is fired when the date is changed.

    $('#dp5').datepicker()
    .on('changeDate', function(ev){
    if (ev.date.valueOf() < startDate.valueOf()){
    ....
    }
    });

————————-

Good stuff!

Mr. Data Converter, converting csv to other formatted strings

This is a pretty cool JS plugin to convert csv formatted string to other formats.

It supports XML – Properties, XML – Nodes, JSON – Properties, JSON – Column arrays, JSON – Row arrays, Html tables, and others.

I found it very helpful for xml, JSON and html formats.

for example, a csv string as below,

ProviderName, ProviderID, OrganizationName
"Microsoft","jamcracker","Telstra"

The converted JSON – properties looks like,

[{"ProviderName":"Microsoft"," ProviderID":"jamcracker"," OrganizationName":"Telstra"}]

The converted JSON – Column array looks like,

{
  "ProviderName":["Microsoft"],
  " ProviderID":["jamcracker"],
  " OrganizationName":["Telstra"]
}

The converted JSON – Row array looks like,

[
  ["Microsoft","jamcracker","Telstra"]
]

The converted XML – Properties look like,

<?xml version="1.0" encoding="UTF-8"?>
<rows>
  <row ProviderName="Microsoft"  ProviderID="jamcracker"  OrganizationName="Telstra" ></row>
</rows>

The converted XML – Nodes look like,

<?xml version="1.0" encoding="UTF-8"?>
<rows>
  <row>
    <ProviderName>Microsoft</ProviderName>
    < ProviderID>jamcracker</ ProviderID>
    < OrganizationName>Telstra</ OrganizationName>
  </row>
</rows>

The converted Html tables look like,

<table>
  <thead>
    <tr>
      <th class="ProviderName-cell">ProviderName</th>
      <th class=" ProviderID-cell"> ProviderID</th>
      <th class=" OrganizationName-cell"> OrganizationName</th>
    </tr>
  </thead>
  <tbody>
    <tr class="lastRow">
      <td class="ProviderName-cell">Microsoft</td>
      <td class=" ProviderID-cell">jamcracker</td>
      <td class=" OrganizationName-cell">Telstra</td>
    </tr>
  </tbody>
</table>

So cool, isn’t it. Save tons of time for my development.

It is from the website, http://www.shancarter.com/data_converter/index.html

And to download from Github, https://github.com/shancarter/Mr-Data-Converter

Create a JQuery plugin for twitter-bootstrap “Confirm Modal popup”

There is a situation that we need user to confirm before they proceed their action. You don’t want to accidently delete very important information. So I come up the idea to extend the bootstrap modal popup to create a confirm modal before calling the function to delete some stuff.

(function ($) {
    $.fn.extend({
        //pass the options variable to the function
        confirmModal: function (options) {
            var html = '<div class="modal" id="confirmContainer"><div class="modal-header"><a class="close" data-dismiss="modal">×</a>' +
            '<h3>#Heading#</h3></div><div class="modal-body">' +
            '#Body#</div><div class="modal-footer">' +
            '<a href="#" class="btn btn-primary" id="confirmYesBtn">Confirm</a>' +
            '<a href="#" class="btn" data-dismiss="modal">Close</a></div></div>';

            var defaults = {
                heading: 'Please confirm',
                body:'Body contents',
                callback : null
            };

            var options = $.extend(defaults, options);
            html = html.replace('#Heading#',options.heading).replace('#Body#',options.body);
            $(this).html(html);
            $(this).modal('show');
            var context = $(this);
            $('#confirmYesBtn',this).click(function(){
                if(options.callback!=null)
                    options.callback();
                $(context).modal('hide');
            });
        }
    });

})(jQuery);

Basically,  all you need to do in the UI, is to create a link to activate the confirm modal, and a empty div for my plugin to work with. With options, you can pass in modal heading and modal content body. With callback method, is your logic to delete stuff or something you want to do originally.


<script type="text/javascript">
$(function () {
$("#openConfirmModal").click(function () {
$("#confirmDiv").confirmModal({
heading: 'Confirm to delete',
body: 'Are you sure you want to delete this record?',
callback: function () {
alert('callback test');
}
});
});
</script>
<a href="#" id="openConfirmModal">Open Confirm Modal</a>
<div id="confirmDiv"></div>

A JQuery plugin for OpenID selector & DotNetOpenAuth integration in MVC

JQuery OpenId selector can be downloaded here http://code.google.com/p/openid-selector/

DotNetOpenAuth can be downloaded here http://www.dotnetopenauth.net/ or install using Nuget  http://nuget.org/packages/DotNetOpenAuth/3.4.7.11121

PM> Install-Package DotNetOpenAuth -Version 3.4.7.11121

Here is what the JQuery openId selector looks, and there are two files you can configure: openId-en.js & openid-jquery.js

OpenID selector

To modify the UI, in openid-en.js, change the variable of “providers_large” and “providers_small” to make your own look and feel.

To modify the settings of this plugin, such as image path, cookie name, etc. Open openid-jquery.js, it is in the openid definition section.

openid = {
	version : '1.3', // version constant
	demo : false,
	demo_text : null,
	cookie_expires : 6 * 30, // 6 months.
	cookie_name : 'openid_provider',
	cookie_path : '/',

	img_path : '../openid/images/',
	locale : null, // is set in openid-.js
	sprite : null, // usually equals to locale, is set in
	// openid-.js
	signin_text : null, // text on submit button on the form
	all_small : false, // output large providers w/ small icons
	no_sprite : false, // don't use sprite image
	image_title : '{provider}', // for image title

	input_id : null,
	provider_url : null,
	provider_id : null,

In the MVC View, you need to have


    $(document).ready(function () {
        openid.init('openid_identifier');
    });

    function facebook_click() {
        alert("wwaaa");
    }


@using (Html.BeginForm("Login", "Account", new {ReturnUrl = Request.QueryString["ReturnUrl"] },FormMethod.Post, new { id = "openid_form" }))
{     <input type="hidden" name="action" value="verify" />
	<fieldset>
		<legend>Sign-in or Create New Account</legend>
		<div id="openid_choice">
			<p>Please click your account provider:</p>
			<div id="openid_btns"></div>
		</div>
		<div id="openid_input_area">
			<input id="openid_identifier" name="openid_identifier" type="text" value="http://" />
			<input id="openid_submit" type="submit" value="Sign-In"/>
		</div>
		<noscript>
			<p>OpenID is service that allows you to log-on to many different websites using a single indentity.
			Find out <a href="http://openid.net/what/">more about OpenID</a> and <a href="http://openid.net/get/">how to get an OpenID enabled account</a>.</p>
		</noscript>
	</fieldset>
}

In the controller, we need to have Login & Register action methods using DotNetOpenAuth to implement the authentication process.

[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Get), ValidateInput(false)]
        public ActionResult Login(string openid_identifier, string returnUrl)
        {
            var response = _openId.GetResponse();
            if (response == null)
            {
                if (string.IsNullOrEmpty(openid_identifier))
                    return View();
                return SendRequestToOpenIdProvider(openid_identifier);
            }
            else 
            {
                switch (response.Status)
                {
                    case AuthenticationStatus.Authenticated:
                        string identifier = response.ClaimedIdentifier;

                        var user = _userRepo.GetUser(identifier);
                        if (user != null)
                        {
                            IssueFormsAuthenticationTicket(user);
                            if (string.IsNullOrEmpty(returnUrl))
                                return RedirectToAction("Index", "Home");
                            else
                                return Redirect(returnUrl);
                        }
                        else
                        {
                            var registrationModel = new RegistrationViewModel(identifier)
                            {
                                ReturnUrl = returnUrl
                            };
                            var simpleReg = response.GetExtension();
                            if (simpleReg != null)
                            {
                                if (!string.IsNullOrEmpty(simpleReg.Email))
                                    registrationModel.Email = simpleReg.Email;

                                if (!string.IsNullOrEmpty(simpleReg.FullName))
                                    registrationModel.FullName = simpleReg.FullName;

                                if (!string.IsNullOrEmpty(simpleReg.Nickname))
                                    registrationModel.Username = simpleReg.Nickname;
                            }
                            return View("Register", registrationModel);
                        }
                    case AuthenticationStatus.Canceled:
                        ModelState.AddModelError("openid_identifier", "Authetication canceled");
                        break;
                    case AuthenticationStatus.Failed:
                        ModelState.AddModelError("openid_identifier", "Authetication failed");
                        break;
                }
            }
            return View();
        }

        public ActionResult Register()
        {
            return RedirectToAction("Login");
        }

        [HttpPost]
        public ActionResult Register(User user, string identifier, string returnUrl)
        {
            //The registration form has been submitted
            try
            {
                if (ModelState.IsValid)
                {
                    var feed = _feedRepo.Create(new Feed(){
                        Id = Guid.NewGuid(),
                        Name = "Default"
                    });
                    user.OpenId = identifier;
                    user.ApiKey = Guid.NewGuid();
                    user.FeedUsers.Add(new FeedUser(){
                        IsOwner = true,
                        FeedId = feed.Id
                    });
                    _userRepo.Create(user);

                    // Now let's login out user to out application
                    IssueFormsAuthenticationTicket(user);

                    // We're done, let's get back to where we started from.
                    if (string.IsNullOrEmpty(returnUrl))
                        return RedirectToAction("Index", "Home");
                    else
                        return Redirect(returnUrl);
                }

                var registrationModel = new RegistrationViewModel(identifier)
                {
                    Username = user.Username,
                    Email = user.Email,
                    FullName = user.FullName,
                    ReturnUrl = returnUrl
                };

                return View(registrationModel);
            }
            catch
            {
                var registrationModel = new RegistrationViewModel(identifier)
                {
                    Username = user.Username,
                    Email = user.Email,
                    FullName = user.FullName,
                    ReturnUrl = returnUrl
                };

                return View(registrationModel);
            }
        }

A complete example can be downloaded at https://github.com/gligoran/mvcopenid