Thursday, 3 March 2011

JQuery and Update Panels or Script Manager Asp.net

So many times we stuck up into problem of making Jquery work with update Panels/Script manager in asp.net (Ajax enabled sites). Now its not consistent on how we make jquery work in case ScriptManager based site in asp.net when compared to a site which does not use Script Manager so i thought of Creating a plugin to make things more consistent. Feel free to modify the code.

 
(function($) {
    /*
    * Author: Anirudh Gupta
    * This plugin checks if the update panels exists on the page 
    * if yes adds the specified code/function in Sys.Application.add_load
    * if not then adds it in $(document).ready function
    */
    $.fn.CallCode = function(codeToRun) {
        /*
        * start of method : Run Code
        * This method checks if the codeToRun is a function or a string to evaluate 
        * incase of function - the specified function is called
        * incase of string - evaluates the string specified  
        */
        function RunCode(codeToRun) {
            if ($.isFunction(codeToRun) == true) {
                codeToRun.call();
            }
            else if (typeof codeToRun == "string") {
                eval(codeToRun);
            }
        }
        $(document).ready(function() {
            /*
            * check if the page has update panel use sys.application.add_load 
            */
            if (typeof (Sys) == 'undefined') {
             
             
                RunCode(codeToRun);

            }
            else {

                Sys.Application.add_load(function() {
                    RunCode(codeToRun);
                });
            }
        });
    }
})(jQuery);
----------------End of plugin --------------- 
 
how to use ?

<script src="CallCode.js" type="text/javascript"></script>

<!------- Works for both with Script Manager and without Script Manager ---->

   <script type="text/javascript">
       var i =1;
       $().CallCode(function() {
           $(".button").append("<input type='button' value='ClickMe'/>");
           $("input[type='button']").click(function() {
               $(".helloWorld").html(" i am in " + i + "times");
               i++;
           });
       });
    </script>

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true">
    </asp:ScriptManager>
    <div class="button" />
    <div class='helloWorld'>
    
    </div>


<!--------- another way to use  for simple operations ------->
 <script type="text/javascript">      
       $().CallCode('$("#helloWorld").html("i am in")');
 

Thursday, 20 January 2011

Limit text or Show More script

Some times we need to limit the text in a Div and append "...show more" link at end and once the user clicks show more link, user will see full text without limit

Feel free to use the plugin the way you want. Leave a comment in case you like it or if you have any input

   /*  
   * plugin to limit the text and add ShowMore link incase the text exceeds the limit  
   * on click of the link full text   
   */  
   $.fn.limitText = function(options) {  
     /*set up the defaults*/  
     var defaults = {  
       showMoreText: '...Show more',  
       chartLimit: 30,  
       fullText: ''  
     };  
     /*extend the defaults*/  
     var options = $.extend(defaults, options);  
     return this.each(function() {  
       var $elem = $(this);  
       var text = '';  
       /*  
       * validation if the plugin is already attached, dont attach again  
       */  
       if ($elem.attr('limitTextAttached')) {  
         return;  
       }  
       /*set the attribute to the element to avoid multiple attachement of the plugin*/  
       $elem.attr('limitTextAttached', 'attached');  
       /*  
       * incase text of the element need to be used to trim   
       * if the options.fullText is specified then it will be used to trim   
       * and to append in the element  
       */  
       if ($.trim(options.fullText).length == 0) {  
         options.fullText = $elem.text();  
       }  
       text = options.fullText;  
       /*check if the text length is greater than charlimit specified*/  
       if (text.length > options.chartLimit) {  
         text = text.substring(0, (parseInt(options.chartLimit) - 1));  
         $elem.html("");  
         $elem.append(text);  
         var showMoreLink = $("<a href='#'>" + options.showMoreText + "</a>").appendTo($elem);  
         showMoreLink.click(function() {  
           $elem.html(options.fullText);  
         });  
       }  
       else {  
         $elem.html(options.fullText);  
       }  
     });  
   }  

use it like
$("#someDiv").limitText({fullText: 'hello world!!!!!'});
or if someDiv element already has any text in it then use it like simply
$("#someDiv").limitText() 

Tuesday, 4 January 2011

Array Sort - Number expected in Internet Explorer

While working on sorting array for date with following code
/*sort the array with date*/
data.sort(function(a, b) {
var objA = a.date;
var objB = b.date;
var dateA = new Date(objA);
var dateB = new Date(objB);
return dateA - dateA;
});
i faced "Number expected" error in IE while it was working fine in other browsers.

Fix - Parse the return as Int like this
/*sort the array with date*/
data.sort(function(a, b) {
var objA = a.date;
var objB = b.date;
var dateA = new Date(objA);
var dateB = new Date(objB);
return parseInt(dateA - dateA);
});

Thursday, 30 December 2010

Best Practices - JQuery

This space is for Best practices and various do & don'ts while writing JQuery code. (please drop comments if you (like)/(don't agree with) them or if you would like to contribute to the list)

Even before we start,first question we should answer is

In what cases we should be creating a plugin and in what cases we can simply write code in the page to do all the cool stuff?
In my view one should write a plugin if-

1. There are multiple functions required to be called to achieve one's requirement.Eg we need to convert a table to a grid, now this might require ajax functionality to get the data ,we might require functions to sort, filter etc and hence we should be writing a plugin for this. Now in other case in which we simply need to hide or show an element on click of a button , in that case we don't need to write a plugin for this.

2. In case we might want to extend the functionality in future. Again taking earlier example we might want to add filter/sorting etc to the table to grid functionality , in that case a plugin gives us better way to manage the code.

3. In case we may have various dynamic options which may change how a particular functionality works.In that case its always good to write a plugin and make use of default settings and then override those defaults by providing options while calling the plugin

4. Reusable Code : In case you would want to use the same bit of code across multiple pages/sites, its always good to code the functionality in a plugin and use it anywhere you want, rather than copy pasting the same bit of code again and again on multiple pages.


References :
http://docs.jquery.com/Plugins/Authoring
http://docs.jquery.com/
http://api.jquery.com/


note : i will be updating this post continuously as the scope for the subject is too big to be written in one go.

Sunday, 5 December 2010

Search elements with custom attributes

Lately someone on asp.net forums wanted help for searching elements with custom attributes
just incase you have similar requirement -
<script type="text/javascript">
       $(document).ready(function () {
           var searchText = "a";  //change this as per required
           String.prototype.startsWith = function (str) {
               return (this.match("^" + str) == str)
           }
           var divs = $("div").filter(function () {
               var elem = $(this);
               var validElem = false;
               $(elem.get(0).attributes).each(function () {
                   var node = this.nodeName;
                   if (node.startsWith(searchText) == true) {
                       validElem = true;
                       return false;
                   }
               });
               return validElem;
           });   
 //now  following will return you number of divs having custom attributes starting with "a"       
 var length = divs.length;        
 });
   </script>

Saturday, 20 November 2010

.net and JQGRID

Lately one of the asp.net forum user had issues with .net and jqgrid
Thread link : http://forums.asp.net/t/1624546.aspx

anyone else who needs a reference for similar requirement , have a look at the link

Saturday, 13 November 2010

BlinkMe - Blink elements

Sometimes we have required to have the elements blinked on some events and then detach it on some event

Following script will help achieve that

// Done by Anirudh Gupta
//http://mykbdump.blogspot.com/
(function ($) {

$.fn.blinkme = function (options) {

var defaults = {
bordereffect: false,
bordercolor: 'red',
backgroundeffect: true,
backgroundcolor: 'yellow',
blinkinterval: 400,
eventstoattach: 'focus',
eventstodetach: 'blur'
};
options = $.extend(defaults, options);
return this.each(function () {
var elem = $(this);
var intervalobj = null;
var bordercolor = elem.css("border-color");
var bgcolor = elem.css("backgroundColor");
elem.bind(options.eventstoattach, function () {
var blinked = false;
intervalobj = setInterval(function () {
if (blinked == true) {
elem.css({
'backgroundColor': bgcolor,
'border-color': bordercolor
});
blinked = false;
}
else {
if (options.bordereffect == true) {
elem.css({
'border-color': options.bordercolor
});
}
if (options.backgroundeffect == true) {
elem.css({
'backgroundColor': options.backgroundcolor
});
}
blinked = true;
}
}, options.blinkinterval);
});
elem.bind(options.eventstodetach, function () {
if (intervalobj) {
clearInterval(intervalobj);
elem.css({
'backgroundColor': bgcolor,
'border-color': bordercolor
});
}
});
});
}

})(jQuery);

Friday, 27 August 2010

Create Activity Feed Event by Non Admin Users

To Start with i was really excited about Activity Feed Stuff Sharepoint 2010 is providing but then when i tried using object model i realised SPServiceContext doesnt support impersonation directly. It requires HttpContext to be impersonated so that a non User Profile Admin User can also create Events .After lots of googling and modifying/updating the logic a bit , just want to share how i did this

SPServiceContext poweredCtx = null;
SPUser currentUser = SPContext.Current.Web.CurrentUser;
HttpContext currentHttpContext = HttpContext.Current;
try
{
Guid siteId = SPContext.Current.Site.ID;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite aSite = new SPSite(sampleSite))
{
using (SPWeb web = aSite.OpenWeb())
{
SPServiceContext currentCtx = SPServiceContext.Current;
SPUser user = web.CurrentUser;
web.AllowUnsafeUpdates = true;
/*
* Impersonate here ....
*/
HttpRequest request = new HttpRequest("", web.Url, "");
HttpContext.Current = new HttpContext(request, new HttpResponse(new StringWriter(CultureInfo.CurrentCulture)));
HttpContext.Current.Items["HttpHandlerSPWeb"] = web;
WindowsIdentity wi = WindowsIdentity.GetCurrent();
typeof(WindowsIdentity).GetField("m_name", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(wi, user.LoginName);
HttpContext.Current.User = new GenericPrincipal(wi, new string[0]);
WindowsIdentity wi2 = WindowsIdentity.GetCurrent();
poweredCtx = SPServiceContext.GetContext(HttpContext.Current);

m_UPM = new UserProfileManager(poweredCtx);
/*
* Create Events here and publish them
*/
}
}
});
}
finally
{
//undo the impersonated httpcontext very much required
HttpContext.Current = currentHttpContext;
WindowsIdentity wi = WindowsIdentity.GetCurrent();
typeof(WindowsIdentity).GetField("m_name", BindingFlags.NonPublic | BindingFlags.Instance).SetValue(wi, currentUser.LoginName);
HttpContext.Current.User = new GenericPrincipal(wi, new string[0]);
}


Big Thanks to STEVE CURRAN
Reference :http://sharepointfieldnotes.blogspot.com/2010/02/creating-sp2010-social-comments.html

Friday, 27 March 2009

Common Errors with Solutions in Sharepoint

While working with share point many a times we face various errors and then we have no clue about what to do ...

so i thought of putting down few of day to day errors with probable solutions to them ..


1. Error : "File Not Found"

Usually this error comes if the page is trying to get reference of some assembly or dependency and not able to get that . You can also receive this error if some thing went wrong in web.config

Solutions : Open the file and check for any invalid entries of references. You can then try with web.config If you find something like this

xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"

delete it ..

Also you can check for invalid "?" entries in web.config and trying removing them .

2. All famous .. "Unknown Error " . It can mean many things ... Few readings

http://support.microsoft.com/kb/556031

Though you can get many options to select from but i would suggest the best way to deal with this is (incase its on Dev Env only) go to web.config

change to CustomErrors = Off and CallStack= true

This in most of the cases will give you good enough information about the error

3. "401 Unauthorized" on Sign In on form authentication. Some reading

http://www.codeplex.com/MOSSFormsFeature/Thread/View.aspx?ThreadId=9702

usually people call it as a bug but in my case it came few times because of my few tweaks tests in global.asax or httphandlers .

4. "An unexpected error has occurred" : again this is very common error .again best way to find solution to this is follow changes in web.config given in point 2

5. "This page has encountered a critical error. Contact your system administrator if this problem persists. " ...90% cases atleast with me for this error has been invalid entry of "?" in web.config

6. Another of error we face is with regards to webpart ...to remove unwanted webparts from the page incase page is throwing error . eg on Default.aspx
add Default.aspx?contents=1 ..this will open webpart maintenance page where you can delete the unwanted webpart and bring back the page

7. “The server could not complete your request. Contact your internet service provider or Web server administrator to make sure that the server has the Frontpage Server Extensions or SharePoint Services installed.” ...This you might face while opening some file in sharepoint designer ... there can many ways to solve this .. some of them which i try ... 1 close the site and open again from sharepoint designer 2. do iisreset or recycle the pool 3. check for versions of assemblies referenced ...

Will try to post 2nd round of error list with probable solutions. Hope this helps !!!

Monday, 16 March 2009

Update Panel in Publishing Site Template

Lately i was trying my hands on Ajax based webpart on Publishing Site and faced problem withUpdatePanel . Page does a partial Postback but controls are not rendered properly .Example Scenario :
UpdatePanel
____________button
______________Label

button have event to update label .. .. now in this case button event happens but label text doesnt get updated . This only happens in Publishing Site Template and works fine in other site templates .How to Solve :

Open Masterpage and replace following

"
<body class="body" onload="javascript:_spBodyOnLoadWrapper();">
<WebPartPages:SPWebPartManager runat="server"/>
<form runat="server" onsubmit="return _spFormOnSubmitWrapper();">
"

with

"
<BODY scroll="yes" class="rly-body" onload="javascript:if (typeof(_spBodyOnLoadWrapper) != 'undefined') _spBodyOnLoadWrapper();">
<form runat="server" onsubmit="return _spFormOnSubmitWrapper();">

<WebPartPages:SPWebPartManager ID="SPWebPartManager1" runat="server"/>
"

Hopefully this will make it work
Enjoy !!