Wednesday 31 October 2012

How to Write a jQuery Plugin

It is actually pretty simple, you just have to follow a basic template. Here I am showing you how to build one to change elements to a round shape. Please note that because I use border radius here in the example you need IE9+ to view the result.

(function ($) {
    //This is where you define your plugin name, in this case - makeMeRound
    $.fn.makeMeRound = function (options) {

        //Extend default settings with options passed through paramete
        var settings = $.extend({
            //Below are default settings, can be overridden by parameter
            'border_color': 'red',
            'border_width': '2px'
        }, options);

        //Wrapped in a each loop in case jQuery selector returns a collection of elements
        //We return this here to maintain chainability during method calls
        return this.each(function () {
            //Below is the core of the plugin
            var max = $(this).width() > $(this).height() ? $(this).width() : $(this).height();
            $(this).css('width', max).css('height', max).css('border-color', settings.border_color).css('border-width', settings.border_width).css('border-radius', '50% 50% 50% 50%');
        });

    };

})(jQuery); //To make sure that your plugin doesn't collide with other libraries that might use the dollar sign
 
//Calling plugin
$(document).ready(function () {
    $('input').makeMeRound(); //use default setting
    $('img').makeMeRound({ 'border_width': '2px' }); //specify custom setting
});

The above script operating on the html below

<input type="button" value="Click Me" style="border-width:1px;width:100px;height:25px;"/>
<img border="1px" src="http://www.tutordoctor.com/sites/default/files/Halloween.jpg" />

will produce the following result
 
 

Thursday 25 October 2012

Using Anonymous Type as Method Parameter


Came across a petty good article with code ready for copy and paste:
http://blog.functionalfun.net/2010/08/practical-linq-6-anonymous-types-as.html

This one shows how to convert an object to Dynamic:
http://blog.jorgef.net/2011/06/converting-any-object-to-dynamic.html

How To Calculate Display Form Absolute URL



string serverUrl = item.ParentList.ParentWeb.Site.Url;

if(item.ParentList.ParentWeb.Site.ServerRelativeUrl != "/")           
    serverUrl= item.ParentList.ParentWeb.Site.Url.Substring(0, item.ParentList.ParentWeb.Site.Url.IndexOf(item.ParentList.ParentWeb.Site.ServerRelativeUrl));

string absoluteUrl = String.Format("{0}{1}?id={2}", serverUrl, item.ParentList.DefaultDisplayFormUrl, item.ID.ToString());



Friday 19 October 2012

How To Check Whether Current User Belongs To A Certain Group Using JavaScript

Using JavaScript Client Object Model:
 
function isCurrentUserInGroup(groupName, functionUserInGroup, functionUserNotInGroup, functionGroupNotFound, functionOnError) {
    var ctx = new SP.ClientContext.get_current();
    //Get info of current user
    var currentUser = ctx.get_web().get_currentUser();
    ctx.load(currentUser, 'Id', 'LoginName');
    //Retrieve all site groups
    var groups = ctx.get_web().get_siteGroups();
    ctx.load(groups);
 
    ctx.executeQueryAsync(function (sender, args) {
        //See whether the group exists
        var groupFound = false;
        var groupEnumerator = groups.getEnumerator();
        while (groupEnumerator.moveNext() && !groupFound) {
            var group = groupEnumerator.get_current();
            if (group.get_title() == groupName) {
                //Found the group, now try to load users of this group
                groupFound = true;
                var users = group.get_users();
                ctx.load(users);
                ctx.executeQueryAsync(function (sender, args) {
                    //See whether the user exists
                    var userFound = false;
                    var userEnumerator = users.getEnumerator();
                    while (userEnumerator.moveNext() && !userFound) {
                        var user = userEnumerator.get_current();
                        if (user.get_id() == currentUser.get_id()) {
                            //User exists in the group
                            userFound = true;
 
                            if (functionUserInGroup != null)
                                functionUserInGroup();
                        }
                    }
 
                    //User doesn't exist in the group
                    if (!userFound && (functionUserNotInGroup != null))
                        functionUserNotInGroup();
 
                }, function (sender, args) {
                    if (functionOnError != null)
                        functionOnError(sender, args);
 
                });
            }
        }
 
        //Group doesn't exist
        if (!groupFound && (functionGroupNotFound != null))
            functionGroupNotFound();
 
    }, function (sender, args) {
        if (functionOnError != null)
            functionOnError(sender, args);
 
    })
 
}
 
// Sample usage 
ExecuteOrDelayUntilScriptLoaded(function () {
    isCurrentUserInGroup('Approvers',
                         function () {
                            alert('User is in the group.');
                         },
                         function () {
                            alert('User is NOT in the group.');
                         },
                         function () {
                             alert('Group does NOT exist.');
                         },
                         function (sender, args) {
                             alert('Request failed.' + args.get_message() + '\n' + args.get_stackTrace());
                         });
}, "sp.js");
 

Wednesday 17 October 2012

How To Override Created/Created By/Modified/Modified By Fields

A lot of people ran into issues when trying to achieve the goal. The trick is really simple, you just need to call SPListItem.UpdateOverwriteVersion() instead of SPListItem.Update() or SPListItem.SystemUpdate().
                             
         item["Author"] = web.SiteUsers["sp2010\\user1"];
         item["Editor"] = web.SiteUsers["sp2010\\user2"];
         item["Created"] = DateTime.Now.AddYears(-50);
         item["Modified"] = DateTime.Now.AddYears(50);

         item.UpdateOverwriteVersion();