Monday, May 30, 2011

How to check if the form passes all ASP.NET validations on client side


$(document).ready(function() {

$("form").submit(function()
{
Page_ClientValidate();
if (Page_IsValid)
{
//Ajax call
}
});


});

How to get SharePoint user profile information from Account Name


using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;

private string GetPreferredName(string accountName)
{
SPSite site = SPContext.Current.Web.Site;
ServerContext context = ServerContext.GetContext(site);
UserProfileManager profileManager = new UserProfileManager(context);
try
{
UserProfile profile = profileManager.GetUserProfile(accountName);
return profile[PropertyConstants.PreferredName].ToString();
}
catch
{
return accountName;
}
}

Saturday, May 28, 2011

Jquery Progress Notification

In our last project, we had to display a progress notification for the long running processes. After doing some research, we found the pnotify jquery plugin very useful.
It is very easy to implement aswell. Here are the steps of implementation.

This plugin requires 2 files to be downloaded from http://plugins.jquery.com/project/pnotify and they are

1. jquery.pnotify.min.js
2. jquery.pnotify.default.css

And the code goes here:









References:
http://pines.hg.sourceforge.net/hgweb/pines/pnotify/raw-file/tip/index.html
http://plugins.jquery.com/project/pnotify

Confirmation before ASP.NET Asynchronous call

Scenario - Ask for user confirmation before ASP.NET Ajax asynchronous call.

Fix- The ASP.NET Ajax PageRequestManager class fires the initilaizeRequest event before trigger the asynchronous call. The second event of this event is the initializeRequestEventArgs. It has a method called get_postBackElement() that identifies the element that triggered the call.



Clientside callback after ASP.NET Ajax Update Panel refresh



Scenario - How to implement - Calling an clientside method after ASP.NET Ajax refresh. Ex: You have a Jquery plugin to show progress of the current operation. But you also need to call it's remove method after Ajax Update Panel refresh.

Fix -


Monday, May 16, 2011

LINQ Lessons

In our recent project, we came across many situations where we had to write queries on our objects in the UI tier. Few of them are give below.

I am taking here the movie class to explain different Linq queries.
public class Movie
{
     public int ID {get; set;}
     public string Title {get; set;}
  public string Director {get; set;}
     public int Genre {get; set;}
     public int RunTime {get; set;}
     public DateTime ReleaseDate {get; set;}
     public decimal Budget{get; set;}

}

public List GetMovies()
{
return new List {
new Movie{Title="Rocky", Director="Alex", Genre=1, RunTime=180, ReleaseDate ="01/01/1990"},
new Movie{Title="Return of the Devil", Director="Michael", Genre=2, RunTime=80, ReleaseDate ="01/01/1998"},
new Movie{Title="Warriors", Director="Phil", Genre=3, RunTime=120, ReleaseDate ="01/01/1991"},
new Movie{Title="Love", Director="Kevin", Genre=4, RunTime=120, ReleaseDate ="01/01/1992"},
new Movie{Title="Live Forever", Director="Leonardo", Genre=5, RunTime=120, ReleaseDate ="01/01/1997"},
new Movie{Title="War", Director="Adams", Genre=6, RunTime=130, ReleaseDate ="01/01/2001"},
new Movie{Title="Crimes of the City", Director="Ricky", Genre=6, RunTime=130, ReleaseDate ="01/01/1995"},
new Movie{Title="Street Fighters", Director="Andrew", Genre=6, RunTime=130, ReleaseDate ="01/01/1995"},
new Movie{Title="Violence", Director="David", Genre=6, RunTime=130, ReleaseDate ="01/01/1998"},
new Movie{Title="College Days", Director="Clarke", Genre=4, RunTime=140, ReleaseDate ="01/01/1997"},

};
}


Query: Get all movies from generic movies collection.
var movies = GetMovies();
var query = from m in movies select m;

Query : Return a new projection containing Title and Genre.
var movies = GetMovies();
var query = from m in movies select new {m.Title, m.Genre};
or
var query = from m in movies select new {MovieTitle = m.Title, MovieGenre = m.Genre};

Query: Return all movies order by Title
var movies = GetMovies();
var query = from m in movies order by m.Title descending select m

Query: Adding a filter to a Linq query.
var movies = GetMovies();
var query = from m in movies where m.Genre=5 select m;

Query: Data Grouping
var movies = GetMovies();
var query = from m in movies group by m.Genre into g
            select new {Genre = g.key, Count = g.Count} 
            

Query : Linq Operators
var movies = GetMovies();
movies.Max(m=>m.RunTime)
movies.Min(m=>m.RunTim)
movies.Average(m=>m.RunTime)

Query: Linq Joins
var moveis = GetMovies();
var genres = GetGenres();

var query = from m in movies Join g in genres On m.Genre Equals g.ID
            select new {Title = m.Title, Genre = g.Name}
Query: Left Join
All movies from movies object irrespecitive of having a genre or not.

var m = from m in movies join g in generes on m.Genre equals g.ID into MovGen
              from MovGenJ in MovGen.DefaultIfEmpty()
             select new {Title = m.Title, Genre = g.Name}

Query: Paging using Linq

var query = (from m in movies Join g in generes On m.Genre Equals g.ID 
             select new {Title = m.Title, Genre = g.Name}).Skip(10).Take(10);
Query: For loop in Linq

var m = movies.ForEach(m =>m.Budget = GetMoviesBudget(m.ID))

Tuesday, May 10, 2011

What's new in VS2010



Web.Config Transformation


As we all know that Web.config in Dev environment is never same in Test and Prod environment. We have to replace couple of entries like Connection string etc. for Test and Prod.

VS2010 gives an excellent feature called as Web.Config Transformation to automate these changes. Let's see here how it is done.

1. Open Configuration Manager from Build menu.
2. Create a new Config file using Configuration Manager -> New
3. Lets name it as MyTransform.
4. Right click on the Web.Config file and select Add Config Transform. VS2010 will
create web.MyTransform.config file. This is the file where we will make our Prod entries.
5. Open the Web.Config file and add following entries.





6. Add the production entries in the web.MyTransform.config file as follows





7. For testing purpose, let's create an Application under Default Web Site on our local box. Let's assume this as Prod Url.
8. Now publish your Web Application to your Prod Url by Right click on Project and choose Publish.
9. Open the Physical path of the Prod Url and check the Web.Config file. You will find the "ProdBox" for the "ServerName" key in the appSettings section.

Thursday, May 5, 2011

ASP.NET MVC 3 Tools Update



This tools update will include following tooling improvement.

  1. Final release of EF 4.1.
  2. Built-in data scaffolding support
  3. New HTML5 project templates
  4. Intranet Project Template
  5. Newer versions of jQuery core, jQuery UI and jQuery Validation

Download

Tuesday, May 3, 2011

Breaking changes of Jquery 1.6



Case-mapping of data- attributes

In Jquery 1.5.2, an attribute of data-max-value="15" would create a data object of { max-value: 15 } but as of jQuery 1.6 it sets { maxValue: 15 }. It is done to match W3C HTML5 spec.

Handling of DOM properties and DOM attributes separatly
.prop() -
.removeProp() -
.attr() -

Properties represent the dynamic state of DOM, whereas Attributes represent the state of DOM information as retrieved from the document.
Ex: $(this).prop("checked") - returns current state of the checkbox.

Ajax
Bugs Fixed:

#6481: revert $.param should treat empty arrays/objects like empty strings
#7881: Make compatible with XHR 2
#8417: When posting AJAX and the data has “??” is formats it to jQuery?
#8744: .ajax() jsonp requests are not handled correctly when hitting timeout
#8884: jqXHR breaks names of custom header fields

Performance Improvement
.attr("alue");
.attr("name", "value")
.val() - get
.data()

boolean attributes

$(#checkbox).attr("checked","true"); - check it
$(#checkbox).attr("checked","false"); - Uncheck it

Bugs fixed
Bugs Fixed:

#1591: IE "Invalid Argument" $('table').attr('non-existent')
#3116: .attr does not work with SVG IDLs
#3786: removeAttr should use jQuery.props
#4283: .attr('checked') & XHTML 1.1 Strict
#4464: IE cannot get width attribute of detached IMG element
#4978: jQuery.prop missing cellpadding?
#5413: tag "img" width/height attribute is zero (IE)
#6562: using .attr() to set the ‘target’ attribute, with a node that has ID of 'target'
#6708: Opera has inconsistent result for usemap attribute value
#6823: Make .val(value) faster for common use case
#7472: $('form').attr('id') return DOM Element
#7485: Inconsistency between has [attribute] selector and attr() method
#7709: Permission denied to access property ‘nodeType’ from a non-chrome Firefox/3.5.15
#7996: Safari $('script').attr(‘event’); Bug
#8117: .removeAttr don’t works with select element’s size attribute
#8150: removeAttr issue in webkit, firefox
#8255: support for list attribute
#8418: set name parameter using attr() method in IE 7
#8457: attrHooks
#8570: .val method returning “on” for dynamically created radio buttons in ie9
#8699: .attr() returns -1 on missing attribute instead of undefined
#8772: Using .attr() to set input type 'range' causes script error in IE9
#8997: new attribute “form” (HTML5) is not supported, .attr(‘form’) not working properly
#9037: $('blah').attr('onclick') return event in Firefox

Event - Bugs fixed
#5884: live mouseenter/mouseleave events don’t fire as expected when nested
#6514: Mouseenter and mouseleave events not able to be triggered if bound by live
#6913: namespaced event bubbleing wrong
#6993: .bind() and .one() don’t allow a function as data
#7071: Accessing the ‘type’ property on VML elements fails on IE
#7883: .delegate (and .live) should accept false as the fn arg, like .bind
#8018: Unsafe access to frameElement causes error in crossdomain (i)frames
#8272: Exceptions in plain JS object event handlers swallowed by jQuery
#8712: Custom events don’t bubble up to window
#8732: Incorrect feature detect for IE9 focusin/focusout
#8753: jQuery 1.6: jQuery.Event contstructor to support setting properties
#8755: binding to beforeunload throws an error in IE6, 7, 8 on page unload
#8777: jQuery 1.6: undelegate() accepts custom namespaced events
#8788: Reorganize jQuery.event.trigger to use loop instead of recursion
#8790: Optimize non-attached events such as data events
#8803: jQuery.holdReady() method


Manipulation - Bugs fixed

#1954: val() returns innerHTML for button elements in IE
#6180: jQuery.clean should not touch script tags that are not of type text/javascript
#7623: Exception thrown in replaceWith
#7885: jQuery .offset doesn’t property works when current offset is float (which is possible in FireFox)
#8060: Setting checked to true on a disconnected checkbox does not carry over after attaching to DOM.
#8500: radios and checkboxes revert to default (HTML) state when wrapped in IE

Misc
Bugs Fixed:


#8203: Remove un-needed “someVar = null;”s
#8851: Wraps strings with double quotes in sources and tests
#8882: Tests: Update QUnit usage, replace id=main with id=qunit-fixture


Selector
:focus Selector

In jQuery 1.6 we now ensure that the :focus selector works properly across all browsers. You can use this selector to find the currently focused element on the page (such as a form input).

$("input:focus").addClass("active");

#3685: Selector fails for forms with an element named “name”
#4321: $(“#”) returns undefined
#8105: :focus selector filter


Support
Bugs Fixed:


#9028: IE8 crashes while loading 1.6rc1 if using body background image


Traversing

find(), closest(), and is() now all take DOM elements and jQuery objects
In jQuery 1.6 we’ve ensured that find(), closest(), and is() can all take DOM elements and jQuery objects as arguments. This gives you alternatives for filtering sets of elements based upon the passed-in elements.

// Only returns .test elements if they're inside of a div
$("div").find( $(".test") )

Bugs Fixed:

#2773: $.fn.is and $.fn.not should accept DOMelements and jQuery collections
#5712: Allow jQuery.fn.is to accept a function
#6912: $().add(selectElement) adds option children instead
#7369:
$('
ff
').closest('[attr]');
raises exception in all browsers
#8609: Result of .find("") is undefined

Reference : http://blog.jquery.com/2011/05/03/jquery-16-released/