Thursday, August 11, 2011

Assigning SharePoint List Item level permission programmatically


To add item level permission in an SharePoint List or Library, you need to keep three things in mind:

You have a valid SPUser object in your hand
You have to break the role assignment inheritance for the list
You have to add Role Definition and Role Assignment to the targeted list item

Though above statements looks complicated, don't think much about them – just use following two functions wisely and you are done :)

Assumption:

1. You have SPListItem object in your hand
2. You have a valid SPUser in your hand

Working:

First call the below method and pass the SPListItem as the input parameter:

RemoveAllPermissions Function
  1. private static void RemoveAllPermissions(SPListItem CurrentlistItem)
  2.         {
  3.             //The below function Breaks the role assignment inheritance for the list and gives the current list its own copy of the role assignments
  4.             CurrentlistItem.BreakRoleInheritance(true);
  5.             //Get the list of Role Assignments to list item and remove one by one.
  6.             SPRoleAssignmentCollection SPRoleAssColn = CurrentlistItem.RoleAssignments;
  7.             for (int i = SPRoleAssColn.Count - 1; i >= 0; i--)
  8.             {
  9.                 SPRoleAssColn.Remove(i);
  10.             }
  11.         }

Next call the below method and pass the desired parameters:

GrantPermission Function
  1. private static void GrantPermission(SPListItem CurrentListItem, SPWeb oSPWeb, SPRoleType SPRoleType, SPPrincipal SPPrincipal)
  2.         {
  3.             try
  4.             {
  5.                 //Create one Role Definition i.e Full Controls, Contribute rights or Read rights etc.
  6.                 SPRoleDefinition oSPRoleDefinition = oSPWeb.RoleDefinitions.GetByType(SPRoleType);
  7.                 //Create one Role Assignment for the specified SP user or group.
  8.                 SPRoleAssignment oSPRoleAssignment = new SPRoleAssignment(SPPrincipal);
  9.                 //Bind the role definition to the role assignment object created for the user or group.
  10.                 oSPRoleAssignment.RoleDefinitionBindings.Add(oSPRoleDefinition);
  11.                 //Add it to the specified list item.
  12.                 CurrentListItem.RoleAssignments.Add(oSPRoleAssignment);
  13.                 //update the list item so that specified user assignment will have the access.
  14.                 CurrentListItem.Update();
  15.             }
  16.             catch (Exception ex)
  17.             {
  18.                 EventLog.WriteEntry("Error in UAR Initiation Workflow", "GrantPermission() : " + ex.Message);
  19.             }
  20.         }

Thats it!!! So simple and so easy.
For your easy reference I am including the code block from where I used to call these functions:
 

How I am Calling them
  1. if (validUsername)
  2.                             {
  3.                                 if (rdr["Manager Logon"] != null)
  4.                                 {
  5.                                     SPUser CurrentUser = mySite.EnsureUser(rdr["Manager Logon"].ToString());
  6.                                     RemoveAllPermissions(item);
  7.                                     GrantPermission(item, mySite, SPRoleType.Contributor, CurrentUser);
  8.                                     SPGroup oGroup = mySite.SiteGroups["UARAdministrators"];
  9.                                     GrantPermission(item, mySite, SPRoleType.Administrator, oGroup);
  10.                                 }
  11.                             }
  12.                             else
  13.                             {
  14.                                 //Admin need to resolve this issue in the list
  15.                                 RemoveAllPermissions(item);
  16.                                 SPGroup oGroup = mySite.SiteGroups["UARAdministrators"];
  17.                                 GrantPermission(item, mySite, SPRoleType.Administrator, oGroup);
  18.                             }

Cheers,
Avik

How To: Hide the Quick Launch in a MOSS Page

1. add a CEWP in the page.
2. Select Source Editor and paste the following code:



















3. Save it then Select Apply- OK in the web part properties window. If needed you can select Web Part Hidden property to TRUE.
4. Bang – You are done.

Cheers,
Avik

Thursday, July 28, 2011

SPUtility.SendEmail - Resolving Mail Body Truncating Issue

If you are using SPUtility.SendEmail() function to send mail and your mail body has quite big statements, then you may find out some part of the mail body is not coming up in the sent/ received mail. This is because of the fact that SPUtility.SendEmail() puts a cap to the length of a single line (Probably 2048 Characters). to resolve this issue, what you need to do is add some newlines after each tag in the body of your email.

Cheers,
Avik

Wednesday, June 29, 2011

Custom Page Addition Baseline Feature for MOSS 2007


After a long break, again came some requirements where I need to work on MOSS 2007. After working with SP 2010 and VS 2010 for more than a year, it is like again going back to the stone age of SP development. So, I thought it will be good to have a base VS 2008 Web Application Solution and a base Feature Template to add custom pages in SharePoint context ready for all the MOSS developers. So, I created one custom solution and feature which you can download and the modify accordingly. This feature is strictly for adding custom pages into SharePoint context and both the solution and feature template can be downloaded from the following link:

Steps:
1. Unzip the folder and build the solution.
2. Place the compiled dll into the GAC
3. Place the feature folder in 12 Hives feature folder
4. Install and activate the feature from STSADM
5. Open a browser window and write down the url in ServerName-PortNo/SiteName/UAR/Default.aspx in this fashion and see our custom page started running in SharePoint context.
6. To add your own custom page, open the solution and add new page there.
7. Once done designing, copy that .aspx page inside our own feature folder.
8. Again compile the solution and place the dll inside the GAC and open the new page in the similar approached defined in point no 5.

Cheers,
Avik

Tuesday, June 21, 2011

How to: Create and Deploy Feature Receivers in SP 2010 and Customizing Top Link Bar


To create a Feature receiver

  1. In Microsoft Visual Studio, start an Empty SharePoint Project. When you are prompted, choose to make it a sandboxed solution.

  2. In Solution Explorer, right-click the Features folder, and then select Add Feature.

  3. Right-click the Feature, and select Add Event Receiver.

  4. Open the .cs or .vb file that was created in the previous step.

    image

image

5. Uncomment and override the event handlers in the file as needed using your event handling logic. As a general rule, if you override the FeatureActivated handler, you should also override the FeatureDeactivating handler to reverse what your code did in the FeatureActivated handler. Similarly, if you override the FeatureInstalled handler, you should also override the FeatureUninstalling handler to reverse what your code did in the FeatureInstalled handler.

6. Now to customize the top link bar, first you need to add the following reference:

Code Snippet
  1. using Microsoft.SharePoint.Navigation;

Then place the following code inside appropriate event handlers:

   1: public override void FeatureActivated(SPFeatureReceiverProperties properties)
   2: {
   3:     SPWeb topNavigationWeb = (SPWeb)properties.Feature.Parent;
   4:     SPSite topNavigationSite = topNavigationWeb.Site;
   5:  
   6:     SPNavigationNodeCollection topNavigationNodes = topNavigationWeb.Navigation.TopNavigationBar;
   7:     
   8:     SPNavigationNode MenuItem1 = new SPNavigationNode("Tab 1", "http://theSPgeek.com/Pages/default.aspx", true);
   9:     topNavigationNodes.AddAsFirst(MenuItem1);
  10:     SPNavigationNode MenuItem2 = new SPNavigationNode("Tab 2", "http://theSPgeek.com/my/default.aspx", true);
  11:     topNavigationNodes.Add(MenuItem2, MenuItem1);
  12:     SPNavigationNode MenuItem3 = new SPNavigationNode("Tab 3", "https://theSPgeek.com/", true);
  13:     topNavigationNodes.AddAsLast(MenuItem3);
  14:  
  15:     topNavigationWeb.Update(); 
  16: }

As told earlier, if you override the FeatureActivated handler, you should also override the FeatureDeactivating handler to reverse what your code did in the FeatureActivated handler. So, place the following code inside FeatureDeactivating event handler:



   1: public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
   2: {
   3:     SPWeb topNavigationWeb = (SPWeb)properties.Feature.Parent;
   4:     SPSite topNavigationSite = topNavigationWeb.Site;
   5:  
   6:     SPNavigationNodeCollection topNavigationNodes = topNavigationWeb.Navigation.TopNavigationBar;
   7:     foreach (SPNavigationNode node in topNavigationNodes)
   8:     {
   9:         if (node.Title.ToString() == "Tab 1" || node.Title.ToString() == "Tab 2"
  10:             || node.Title.ToString() == "Tab 3")
  11:         {
  12:             topNavigationNodes.Delete(node);
  13:         }
  14:     }
  15:     topNavigationWeb.Update();
  16: }

Now build the solution and then deploy it. Go to the particular SharePoint site where you want to apply this custom global navigation i.e., to update the top link bar. Now go to the Site Action > Site Settings page and from there select the ‘Manage Site Features’ option. On the Site Features page you will find our Custom Feature. Just activate it and you will see custom links has been added to the to link bar or global navigation bar. Now again come to the Site Action > Site Settings page and from there select the ‘Manage Site Features’ option again. Now deactivate our custom feature and you will see, the custom links that we have added by activating the feature just a few minutes ago, has disappeared.


Feature Receiver is a very powerful product and if you use it properly it will help not only you but the business users also to achieve some custom functionality by just activating – deactivating some feature!


Cheers,
Avik


Ref:


http://msdn.microsoft.com/en-us/library/ms469501.aspx


http://msdn.microsoft.com/en-us/library/gg615458.aspx

Thursday, June 16, 2011

How to change the Master Page of a Team Site

The master page option is not displayed in the Look and feel section of a Team Site, so you have to apply your common sense as specified below:

Append this "/_Layouts/ChangeSiteMasterPage.aspx" at the end of your site url. This will directly open the master page settings page and then you are free to do anything ;)

Cheers,
Avik

Saturday, June 11, 2011

How To: Hide the Quick Launch in a SharePoint Page


To hide the quick launch area do the following steps:

1. Edit the page and add a content editor web part

securedownload

2. Select the ’Click here to add new content’ link:

securedownload

3. Now, from the top ribbon select the Edit HTML option:

securedownload

4. Put the following code and save and close the Content Editor and you are done:

<style>
#s4-leftpanel{
display:none
}
.s4-ca{
margin-left:0px
}
</style>

securedownload

Once you select Ok, you will see the left side quick launch bar is not appearing now. You can also edit the properties of the added content editor web part and can select the Hidden option for beautification purpose.

Cheers,
Avik

Monday, May 23, 2011

Starting SharePoint solution and planning your documentation


Just found a beautiful post regarding “Starting SharePoint solution and planning your documentation” by ‘Michael Nemtsev’. Copying the whole post here for my future reference and to spread the thoughtful thinking – all credit goes to Nemstev.

“When a new SharePoint project is about to start I use the following steps to design and plan solution

  1. Creating Vision/Scope
  2. Site structure and Navigation
  3. Use Case Scenarios
  4. Data Flow scenario (create the infomation "map"  - where it locates and how it's used. Usually you either consume or produce information from/to 3rd party sources - network folders, sharepoint lists, incoming emails, BDC connections  and etc. To plan you taxonomy and build good information structure you need to visualize all information on the single page, with direction where it flows. It helps you understand what happens with existing system)
  5. Content location (this is very close to the previous point, but you concentraces on actual location - where information stored, and the way to access it - file or network paths, IP and credentials to access external information)
  6. Site Collection Boundaries
  7. List of required features and site definitions
  8. Security: Roles and Permissions
  9. Page Wireframes: layouts and content types
  10. Targeting (how all content will be targeted  - metadata information, filtering. I usually use Personas to create several scenarios for content targetting)
  11. Search strategy (define search scopes,  define all external sourced,  defile "best bets" for the targetted content)
  12. Infrastructure Plan 
  13. Disaster Recovery
  14. Deployment plan

    Take into account that SharePoint SDLC differs from standard development, and not all projects require those steps.

    PS: consider building SharePoint Roadmap before starting the development phase.”

    Ref: Michael Nemtsev's blog post

    How To tag a document to show in OOB Tag Cloud Web Part in SharePoint 2010

     

    Probably this is going to be one of my shortest blog post:

    • Select a document which need to be tagged (add tick mark).
    • On the top ribbon, you can find "Tags and Notes" . Click on that. Add the necessary tag.
    • The tags gets mapped to the document.

    image

    After crawler runs, this tags will be visible inside the OOB Tag Cloud Web Part present under the same url.

    Cheers,
    Avik

    How to make use of Document Set feature available in SP 2010


    Document Set feature is a cool concept introduced in SP 2010 for content management purpose and they are much more powerful than the ‘Folder’ based content management.

    Document Set enables users to group multiple documents, that support a single project or task, together into a single entity. All documents in a Document Set share the metadata and the entire set can also be versioned.

    To use Document Set, the first thing we need to do is to Activate the ‘Document Set’ feature at the ‘Site Collection’ level:

    Once you activated it, go to the Document Library where you want to use this beautiful feature. Next follow these steps:

    • On the Ribbon, click on the Library Tools > Library
    • Select the Library Settings
    • Click on Advanced Settings

    • Select Yes for the Allow management of content types setting, then press OK
    • Go back to the main Document Library Settings page

    • Click on the Add from existing site content types link

    • Add the Document Set content type to the current document library
    • Once the content type has been added, you can begin to use Document Sets in your document library

    Once the Document Sets feature has been enabled for your document library, you can start to create new items based on this content type.

    • Select the document library, click on the arrow next to the New Document icon in the ribbon, and then select Document Set:

    image

    Next the wizard will ask for the Document Set name and Description as shown below:

    image

    Once you select OK, the document set will be created and inside that you can upload multiple documents which will be treated as a set.

    image

    Cheers, Avik

    Red: Enabling Document ID feature within a SharePoint Server 2010