Friday 8 January 2010

Redirecting to another view based on CurrentUser

What a nightmare!




Today I came accross a scenario where I thought to myself "Man! I am dead here".





I needed to allow certain user to view a SP List differently than other user.




Hopefully, Sharepoint come with the concept of Views. Thus I had to create different views to achieve that. One of these view would filter the view based on the current user by using the token [ME]. To achieve one need to create a new view and then go to the section "Filter". Once there you can associate a field to be equal to [Me]. This is a great trick to show only task item or doc belonging to the current user.





Then I had to cover the second part of my scenario allow certain user to see the same list in full. They could have been trained to select the "All Task" view, but you know how user are. This will kill their user experience. So this needed to be done automatically, without the user knowing anything of it!




So for that I created a web part with the following code:


private HttpContext current;




public UserToListView()
{
current = HttpContext.Current;
}




protected override void CreateChildControls()
{
base.CreateChildControls();
string siteRedirectionUrl = string.Format("AllItems.aspx");

if (IsCurrentUserMemberOfThatGroup())
{
SPUtility.Redirect(siteRedirectionUrl, SPRedirectFlags.Default, current);
}
}





private bool IsCurrentUserMemberOfThatGroup()
{
SPWeb web = SPContext.Current.Web;
int yourGroupId = web.Groups["TheNameOfYourGroup"].ID;

if (web.IsCurrentUserMemberOfGroup(yourGroupId ))
{
return true;
}
else
{
return false;
}
}




Then I added and hidden the web part in my SP List Default view. To add the web part, just click on site setting and then edit page.





Anytime some of open this list, the code in the web part will run and if the current user is part of the group declared then the current page would be redirected from yourcurrentdomain/yourview.aspx to yourcurrentdomain/yourredirectedview.aspx





That's it enjoy!

Seve