Navigate Up
Sign In
Supporters of Developer
Web

Add "follow" to SharePoint 2010

Current average rating is 2 stars. Press SHIFT+ENTER to rate this item.1 star selected. Press SHIFT+ENTER to submit. Press TAB to increase rating. Press SHIFT+ESCAPE to leave rating submit mode.2 stars selected. Press SHIFT+ENTER to submit. Press TAB to increase rating. Press SHIFT+TAB to decrease rating. Press SHIFT+ESCAPE to leave rating submit mode.3 stars selected. Press SHIFT+ENTER to submit. Press TAB to increase rating. Press SHIFT+TAB to decrease rating. Press SHIFT+ESCAPE to leave rating submit mode.4 stars selected. Press SHIFT+ENTER to submit. Press TAB to increase rating. Press SHIFT+TAB to decrease rating. Press SHIFT+ESCAPE to leave rating submit mode.5 stars selected. Press SHIFT+ENTER to submit. Press SHIFT+TAB to decrease rating. Press SHIFT+ESCAPE to leave rating submit mode.

You may also be interested in: SharePoint Solutions In-A-Box from Alcero

 

Editor's note: Contributor Chris Grist is a SharePoint Architect at Beach Energy. Follow him @gristdog

For those of you who have checked out the Office 365 or SharePoint 2013 preview, you would have noticed that Microsoft has added a follow button, on sites and documents, the functionality when clicked basically bookmarks the site similar to a favourite in your web browser.

I have been working on a SharePoint 2010 project for our company, in the new web application there will be 100s of site collections and inside each 100s of sites. The sites are organised logically in a hierarchy, the challenge was that some users will always work in level 4 of the hierarchy and some will work at level 1 or somewhere in-between. As this requirement is not really prescriptive and we cannot know which user wants to navigate where, I needed to develop follow functionality similar to what Microsoft is shipping in SharePoint 2013.

This article looks at the setup and the code that has made this possible and a very popular feature with the end users thus far.

The first step is to decide upon where to store the information, for this I decided to use the user’s profile, so if you’re running SP Foundation, stop here and think about where/how you may store the information instead.

To do this I simply added a new user property called “bimsFollow”. This property was simply a string (multi value) type.

2012-09-07-AddingFollow-01.png

I also made the property hidden from the end user.

2012-09-07-AddingFollow-02.png

The next step was to build a control to be able to follow or un-follow a particular site. For this functionality I decided upon using a user control, this makes it very simply to embed the functionality in an area of my custom master page. So the first step was to open a Visual Studio project and add a new user control, for this I called it “follow”.

The only thing I needed my user control to show was a hyperlink as to whether the user was following the current site or not, so at the bottom of the .ascx file, I added the following code:


 <asp:HyperLink ID="link" NavigateUrl="" Text="" Target="_self" runat="server" /> 

The URL and Text will be dynamic based on whether the user is following the site or not, so here I have left it blank and run the control at the server so I have access to it in the code behind.

The next step was to open the code behind file (.ascx.cs). Inside the page_load function I started by adding a couple of Boolean values:


bool followMe = false;
bool isFollowing = false;

Before constructing the bulk of the functionality I wanted to test that everything was working, so I then added the code to set the hyperlink with the correct URL and text.


if (isFollowing)
{
 link.NavigateUrl = SPContext.Current.Web.Url + "?followme=false";
 link.Text = "Click to unfollow";
}else{
 link.NavigateUrl = SPContext.Current.Web.Url + "?followme=true";
 link.Text = "Click to follow";}


I then registered the user control to the master page to make sure what I had setup was working so far, even though the if statement is always going to execute the else block at this stage. Sure enough it appeared to be working, with a bit of CSS styling I ended up with a user control that matched the style of my custom master page:

2012-09-07-AddingFollow-03.png

As you can see from the code above I decided to use query strings to toggle whether the user was following the site or not, so the first thing we had to do before the if statement is called is to get the value for the query string.


if (Request.QueryString["followme"] != "" && Request.QueryString["followme"] != null)
{
 followMe = Convert.ToBoolean(Request.QueryString["followme"]);
}

If the value exists, then we set the followMe bool to be either true or false based on the input the user has provided on the hyperlink. The next block of code, simply provides the setup for the User Profile Service so that we are able to access the current users profile.


SPContext.Current.Web.AllowUnsafeUpdates = true;
System.Security.PermissionSet ps = new System.Security.PermissionSet(System.Security.Permissions.PermissionState.Unrestricted);
ps.Assert();
Microsoft.SharePoint.SPServiceContext serviceContext = Microsoft.SharePoint.SPServiceContext.Current;
UserProfileManager upm = new Microsoft.Office.Server.UserProfiles.UserProfileManager(serviceContext);
ProfileSubtypePropertyManager pspm = upm.DefaultProfileSubtypeProperties;
UserProfile profile = upm.GetUserProfile(SPContext.Current.Web.CurrentUser.LoginName);

Once we have the profile object we are then able to retrieve the collection of value’s that are currently stored in the user property we created earlier.


UserProfileValueCollection collectionofPropertys = profile["bimsFollow"];

The property is actually returned as collection, rather than a delimited set of strings, so we can quite easily iterate over the collection, and then compare whether the stored data (i.e. set of URLs) match the URL of the current site, and therefore indicate the user is following the current site.


foreach (var st in collectionofPropertys)
{
if(st.Equals(SPContext.Current.Web.Url))
 {
 isFollowing = true;
 }
}

We now have most of the functionality we need, the missing piece is simply to add or remove objects from the collectionofPropertys that we have retrieved above based on our previous bool. The first check we therefore do is to whether the followMe bool is true.


if (followMe)
{
 isFollowing = true;
 collectionofPropertys.Add((Object)SPContext.Current.Web.Url);
 profile.Commit();
}

If the value is true, then we toggle isFollowing to true, so our hyperlink is configured correctly, and then simply add the URL to our collection of strings in the user profile, finally committing any changes. The inverse is almost as simply, however to remove values you must know the index of that particular value in the collection, so we must first iterate over the collection, find the location of the matching URL and then remove it and commit as show below.


else
if (followMe == false && Request.QueryString["followme"] != null)
{
 isFollowing = false;
int count = 0;
foreach (var st in collectionofPropertys)
 {
if (st.Equals(SPContext.Current.Web.Url))
 {
 collectionofPropertys.RemoveAt(count);
 profile.Commit();
 }
 count++;
 }
}

If all has gone successful you will have a fully functional hyperlink that toggles values when you select it:

2012-09-07-AddingFollow-04.png

If you then head over to the USPA and look at the user profile via central admin, you will see the URLs populated:

2012-09-07-AddingFollow-05.png

Now that this functionality is working, you simply need to display a listing of sites a user is following, all the code required is above, in my environment I created a web part, setup the connection to the USPA, grabbed the collection of property’s similar to this article and iterated over the values, opening the URLs and display the title of the site, the end result looked something like this:

2012-09-07-AddingFollow-06.png

The entire block of code for the functionality is below:


public partial class follow : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            bool followMe = false;
            bool isFollowing = false;

            if (Request.QueryString["followme"] != "" && Request.QueryString["followme"] != null)
            {
                followMe = Convert.ToBoolean(Request.QueryString["followme"]);
            }

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPContext.Current.Web.AllowUnsafeUpdates = true;
                System.Security.PermissionSet ps = new System.Security.PermissionSet(System.Security.Permissions.PermissionState.Unrestricted);
                ps.Assert();

                Microsoft.SharePoint.SPServiceContext serviceContext = Microsoft.SharePoint.SPServiceContext.Current;
                UserProfileManager upm = new Microsoft.Office.Server.UserProfiles.UserProfileManager(serviceContext);
                ProfileSubtypePropertyManager pspm = upm.DefaultProfileSubtypeProperties;

                UserProfile profile = upm.GetUserProfile(SPContext.Current.Web.CurrentUser.LoginName);

                UserProfileValueCollection collectionofPropertys = profile["bimsFollow"];

                foreach (var st in collectionofPropertys) 
                {
                    if(st.Equals(SPContext.Current.Web.Url))
                    {
                        isFollowing = true;
                    }
                }

                if (followMe)
                {
                    isFollowing = true;

                    collectionofPropertys.Add((Object)SPContext.Current.Web.Url);
                    profile.Commit();
                }
                else if (followMe == false && Request.QueryString["followme"] != null)
                {
                    isFollowing = false;

                    int count = 0;

                    foreach (var st in collectionofPropertys) 
                    {
                        if (st.Equals(SPContext.Current.Web.Url))
                        {
                            collectionofPropertys.RemoveAt(count);
                            profile.Commit();
                        }
                        count++;
                    }
                }
            });

            if (isFollowing)
            {
                link.NavigateUrl = SPContext.Current.Web.Url + "?followme=false";
                link.Text = "Click to unfollow";
            }
            else 
            {
                link.NavigateUrl = SPContext.Current.Web.Url + "?followme=true";
                link.Text = "Click to follow";
            }
        }
    }

Categories: CSS; Visual Studio; C#; Visual Studio 2010; dev; MOSS; WSS; 2010

Comments

Alex Choroshin

Great post

Posted 17-Sep-2012 by Alex Choroshin
Chanel iPad Mini Case

Chanel iPad Mini Case

The web site seems a lttle bit unusual once i use my portable internet browser on my small blackberry mobile phones. You want to make sure that you should.[url=http://prettyiphone5case.com/]Cute iphone 5 case[/url]

Posted 03-Jul-2013 by Chanel iPad Mini Case
dental apex locator

dental apex locator

You want to make sure that you should. DEMI

Posted 26-Jul-2013 by dental apex locator
pipo m9 tablet

pipo m9 tablet

Free shipping android tablet pc and smartphone with high quality and cheap price.

Posted 26-Jul-2013 by pipo m9 tablet
fantar

not accommodating to absorb hundreds of dollars on branded bags.

There are replica artist handbags that accord you the befalling to buy from the advanced varieties of actualization and design. There are altered allowances of purchasing such handbags. Some of the replica accoutrements are so able-bodied crafted that it becomes absurd for the designers to differentiate. Artist replica handbags can save lot of money for those who are not accommodating to absorb hundreds of dollars on branded bags. Artist affluence gucci replica uk accoutrements can accord you a agnate attending for accomplished lot less. You can acquisition abounding websites affairs replica handbags of all the above artist houses. These are fabricated of top above and absolute fabrics to accumulate it as abutting as accessible to their originals authoritative them able-bodied accustomed all over the world.

Posted 09-Sep-2013 by fantar
 LiFePO4 battery

Battery Manufacturer

China leading manufacturer of high quality LiFePO4 battery,lithium battery,li-polymer battery,NIMH battery,NiCd battery, custom battery packs, battery chargers and OEM/ODM reliable power solutions. Li-ion battery

Posted 20-Sep-2013 by LiFePO4 battery
online casino

Add "follow" to SharePoint 2010

This is a great part of code for SharePoint 2010. Thank you a lot for such considerable work.

Posted 22-Sep-2013 by online casino
windows tech support

reply

The follow button serves in analogy with the Facebook ‘Like’ button which seeks the pulse of the customers relating to various issues.I just want to let you know that I often visit your site and I find it very interesting and informative. I am coming back for more.

Posted 29-Oct-2013 by windows tech support
akin

Part of the Balearic

Part of the Balearic archipelago which also has the islands of Minorca and Ibiza among its components, yacht charter Mallorca is by far the largest and the most popular, because of its fine weather, the beaches and recently, the infrastructure. t mobile customer service number

Posted 05-Jan-2014 by akin
kaino

Another great example

Another great example of innovation, I am glad to locate it. There are so several developers working on this segment but this is one of the best innovative idea ever. Thanks for sharing it here. income support phone number

Posted 08-Jan-2014 by kaino
Eduardo

Infp

I've been searching for details about how to add follow to SharePoint or the new Office for longer than I thought it should take. Finally I got here and I think that your information is by far the best I've found around the internet. Thanks for the code! breaking news

Posted 28-Jan-2014 by Eduardo
rajakala

Super! Wonderful post

Super! Wonderful post. I'll definitely be saving it for future reference. Just 1 thing you might appreciate knowing is that in Firefox, the post seems to display correctly. It seems perfect with IE and with Chrome too, just so you know. raspberry ketones plus

Posted 28-Jan-2014 by rajakala
rajakala

Thank you so much

Thank you so much for the post you do. I like your post and all you share with us is up to date and quite informative, i would like to bookmark the page so i can come here again to read you, as you have done a wonderful job garcinia cambogia capsules

Posted 28-Jan-2014 by rajakala
rajakala

This is just what I'm looking for

This is just what I'm looking for, I was actually going through the nice helpful tips from the blog and I put respect to the writer of this post, enjoying the smart way you write articles in this http://www.http://lawyerreviewsma.com//

Posted 28-Jan-2014 by rajakala
jorgray

asd

I really enjoy simply reading all of your weblogs. Simply wanted to inform you that you have people like me who appreciate your work. http://myspecialday.info/shopping-for-engagement-rings/

Posted 20-Feb-2014 by jorgray
outsource web design

This blog will be a

This blog will be a great source blog for those who wants to know about this topic. You have provided us with many essential articles that definitely put a new spin on a subject outsource web design

Posted 20-Mar-2014 by outsource web design
website ecommerce

Excellent understand

Excellent understand personally, This is just what We needed. Cheers regarding expressing this excellent write-up! website ecommerce

Posted 20-Mar-2014 by website ecommerce
Anthonysmith

Really impressed!

Really impressed! Everything is very open and very clear explanation of issues. Kelly Pritchett

Posted 20-Mar-2014 by Anthonysmith
Anthonysmith

Good job! I must admit

Good job! I must admit that your post is really interesting. I have spent a lot of my spare time reading your content. Thank you a lot! Isaac Thomas

Posted 20-Mar-2014 by Anthonysmith
Anthonysmith

crimes against humanity

crimes against humanity and would in no manner support any international structure limiting its’ ability for practicing war and peace against any other state and/or party it considered a threat to its national interest. Cindy Wilson

Posted 20-Mar-2014 by Anthonysmith
Anthonysmith

He’s 40 years of age.

He’s 40 years of age. Lives within Sydney, close to the beach. It’s a beautiful home, full associated with children as well as animals. He’s a multimillionaire. However it wasn’t just about all roses within his previously years. website development contract sample

Posted 20-Mar-2014 by Anthonysmith
sasfdsa

You made some decent points there.

You made some decent points there. I looked on the internet for the issue and found most individuals will go along with with your website. Linda Payne

Posted 20-Mar-2014 by sasfdsa
dstgfdffd

Great post

Great post i must say and thanks for the information. Education is definitely a sticky subject. However, is still among the leading topics of our time. milwaukee web development

Posted 20-Mar-2014 by dstgfdffd
sagar

In the second Episode

In the second Episode of the Adobe@Adobe Behind the Scenes Podcast we will introduce a new concept for dealing with markup and logic when developing Adobe AEM components. css web development company

Posted 20-Mar-2014 by sagar
sagar

This is just the

This is just the information I am finding everywhere.Me and my friend were arguing about an issue similar to this! Now I know that I was right.Thanks for the information you post. Gary Sandoval

Posted 20-Mar-2014 by sagar
jacobjohnson

Aspire BDC UK

Really appreciate this wonderful post that you have provided for us.Great site and a great topic as well i really get amazed to read this Aspire BDC UK

Posted 27-Mar-2014 by jacobjohnson
mobiloans

mobiloans

Mmm.. good to be here in your article or post, whatever, I think I should also work hard for my own website like I see some good and updated working in your site. mobiloans

Posted 27-Mar-2014 by mobiloans
jacobjohnson

seems to stipulate or is this

seems to stipulate or is this just a statistical artifact within an aggregated narrative about women that's even harder to swallow Political Lawyers

Posted 29-Mar-2014 by jacobjohnson
jacobjohnson

I enjoyed this post

I enjoyed this post very much, such a out standing post. Marketing is a complex thing and there is no proper formula but constant engagement and efforts are the key of success Lawfirm News

Posted 29-Mar-2014 by jacobjohnson
jacobjohnson

A reliable blog

A reliable blog always comes-up with new and exciting information and while reading I have experience that this blog is really have all those quality that qualify a blog to be a good one. Lawsuit Helpers

Posted 29-Mar-2014 by jacobjohnson
jacobjohnson

A good point Ralph

A good point Ralph, but I believe people are going to have a hard time defending prejudice when the possibility of answering certain kinds of questions with much greater precision increases. List of Lawyers

Posted 29-Mar-2014 by jacobjohnson
jacobjohnson

Great blog

Great blog. All posts have something to learn. Your work is very good and i appreciate you and hoping for some more informative posts.keep writing. Law form spot

Posted 29-Mar-2014 by jacobjohnson
web design london

web design london

Many thanks for the exciting blog posting! Simply put your blog post to my favorite blog list and will look forward for additional updates. Simply wanted to write down a word in order to say thanks to you for those wonderful tips. pnplondon

Posted 31-Mar-2014 by web design london
yitoyitoytyo

yitoyitoytyo

La función de día y fecha Replicas de relojes apareció en mediados de la década de 1950. Es una complicación bien, práctica Relojes tag heuer sobre una base diaria, que permite ofrecer además de la hora, fecha y agenda de... En Omega, la fecha se coloca en el 6 y el Omega seamaster día de la semana (en inglés) se encuentra al mediodía en una ventana en forma.

Posted 16-Apr-2014 by yitoyitoytyo

Notify me of comments to this article

E-mail:
   

Add Comment

Title:

 
Comment:
Email:

   


Name:

 
Url: