Ninject with custom attribute and filter

I am implementing a custom credit check filter for a controller action. I use Ninject as my Ioc container. First, create a action filter and implement IActionFilter interface, implement the OnActionExecuted() and OnActionExecuting() methods. Within the credit checking functions, it needs a CreditService to check against the repository and database. So I have created the parameterized constructor using Ninject to inject the CreditService object.

 public class CreditCheckFilter : IActionFilter
    {
        private ICreditService _creditService { get; set; }

        public CreditCheckFilter(ICreditService myService)
        {
            _creditService = myService;
        }

        public void OnActionExecuted(ActionExecutedContext filterContext)
        {

        }

        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var userName = filterContext.HttpContext.User.Identity.Name;
            var bal = _creditService.GetTokenBalance(WebSecurity.GetUserId(userName));
            if (bal <= 0)
            {
                RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
                redirectTargetDictionary.Add("action", "GetTokens");
                redirectTargetDictionary.Add("controller", "Account");
                filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary);
               
            }
        }
    }

Now Let’s create a CreditCheckAttribute that implements FilterAttribute, this is the attribute we put against the controller action,

    public class CreditCheckAttribute : FilterAttribute { }

Now, we need to use Ninject BindFilter() method to bind our CreditCheckFilter, when a controller action has the attribute CreditCheckAttribute. In the ninject kernel, do this,

            kernel.BindFilter(FilterScope.Action, 0).WhenActionMethodHas();

The last step is to put CreditCheckAttribute() against the controller action,

        [CreditCheckAttribute]
        public ActionResult Playlist(TestViewModel model)
        {
            return View(model);
        }
Advertisements

Google +1, share, javascript callback

Google plus button, you can set a callback attribute to a js function,

<g:plusone href="http://youtubeplaylist.net" 
   callback="plusClick"></g:plusone>

In the callback js function, you can check the state, if they have clicked +1 or removed +1.

    function plusClick(data) {
        if (data.state == "on") {
            alert("+1");
            // +1
        } else if (data.state == "off") {
            // -1 (user took their +1 Away)
            alert("-1");
        }
    }
    (function () {
        var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
        po.src = 'https://apis.google.com/js/plusone.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
    })();

There are some other js callback as well, such as onstartinteraction (when the +1 dialog popups up), onendinteraction (when +1 dialog close).

For more information, check out this google page, https://developers.google.com/+/plugins/share/#sharetag-parameters

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!