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 :)


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


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.                             }


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.


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.


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:

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.


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.



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;
   6:     SPNavigationNodeCollection topNavigationNodes = topNavigationWeb.Navigation.TopNavigationBar;
   8:     SPNavigationNode MenuItem1 = new SPNavigationNode("Tab 1", "", true);
   9:     topNavigationNodes.AddAsFirst(MenuItem1);
  10:     SPNavigationNode MenuItem2 = new SPNavigationNode("Tab 2", "", true);
  11:     topNavigationNodes.Add(MenuItem2, MenuItem1);
  12:     SPNavigationNode MenuItem3 = new SPNavigationNode("Tab 3", "", true);
  13:     topNavigationNodes.AddAsLast(MenuItem3);
  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;
   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!



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 ;)


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


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


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


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



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.


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.


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


    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:


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


    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.


    Cheers, Avik

    Red: Enabling Document ID feature within a SharePoint Server 2010

    Monday, May 16, 2011

    Checklist for WSS 3.0 to SP 2010 Migration using Detach–Attach Method

    Today we completed migration of around 200 sites from WSS 3.0 platform to SP 2010 platform. There are mainly two basic ways to do the same:

    • In-place upgrade
    • Database attach upgrade

    Before starting the upgrade process, you need to determine the upgrade approach. Following TechNet documentation provides excellent comparison between the different upgrade process and helps you to plan and prepare for the upgrade process:

    Determine Upgrade Approach @ TechNet

    In our case, we selected Database Attach Upgrade method. And there is one excellent check list available from Microsoft in TechNet. We just followed that and in a bang we migrated good amount of WSS 3.0 sites to SP 2010 environment. From the following url you can access the checklist:

    Checklist for Database Attach Upgrade @ TechNet


    Wednesday, May 4, 2011

    Site Quota Usage Reports in SP 2010

    At the time of MOSS 2007, Administrators were used to go to “Site Usage Reports” link that was present inside the “Side Administration” group in the “Site Settings” page to find out the details about disc space usage by specific sites. But, to achieve the same in SP 2010 you need to do the following things as there is no “Site Usage Reports” links available in the site settings:

    Navigate to the site.

    Select Site Actions >> Site Settings

    Then Select the highlighted option


    Then on the left hand navigation option, select the highlighted one and you are done


    Alternative option for experienced users:

    After the site name delete rest of the url and add the following "/_layouts/usage.aspx" and select Enter.
    Site quota usage report will be displayed in the browser.

    Tuesday, May 3, 2011

    PAGETYPE Enumeration in SP 2010


    Many time we need to direct user’s from custom pages to SharePoint’s OOB list or library specific view, edit, display, dialog pages. In those scenarios developer needs to create the navigating url from the code using some logics like URL = Site Name + Page Type + List/ Library ID + Item ID …
    This parameters usually passed in the form of query string. For better understanding, open the Edit form of a list/ library item and study the url.
    While you can retrieve Site Name, List/ Library ID or Item ID programmatically, you need to know the Page Type value for constructing that url. Following table lists all the Page Type values available in SharePoint 2010 platform:

    Member Name Description
    PAGE_INVALID Not used. Value= -1.
    PAGE_DEFAULTVIEW Default view. Value=0.
    PAGE_NORMALVIEW Normal view. Value=1.
    PAGE_DIALOGVIEW File dialog box view. Value=2.
    PAGE_VIEW View, including both default view and normal view. Value=3.
    PAGE_DISPLAYFORM Display form for list items. Value=4.
    PAGE_DISPLAYFORMDIALOG Display form for a file dialog box. Value=5.
    PAGE_EDITFORM Edit form for list items. Value=6.
    PAGE_EDITFORMDIALOG Edit form for a file dialog box. Value=7.
    PAGE_NEWFORM New form for list items. Value=8.
    PAGE_NEWFORMDIALOG New form for a file dialog box. Value=9.
    PAGE_SOLUTIONFORM Solution form. Value=10.
    PAGE_MAXITEMS Not used. Value=11.

    Monday, March 28, 2011

    How to: Create a Joined View (Displaying the content of more than one list/ library) using SPD 2010


    SharePoint 2010 allows you to create views where the data’s can fetched from several different lists. Following are the steps you need to follow to have your own view page.

    At the very first stage, create two list, say L1 and L2



    Next place some dummy data into those lists as shown below:



    Now, open up SharePoint Designer and select Linked Data Sources and then select properties


    On the properties window, select Sources tab and then add the two newly created lists



    In our case, we need to select the first option.





    So we have created one linked source which is going to be displayed in the view page.


    Now, we need to select the attributes that we want to show in the view page.


    We can also sort the values as shown below





    Now create a blank web part page in your SharePoint site.


    Check out and open that page via SharePoint Designer.



    Select the web part zone where you want to display your linked data source and select Data View tab and then select the linked source that we have created just now.



    Check in the page and if required publish it as a major version.




    If needed you can apply Grouping also as shown below



    When everything is done, open up the page in the browser and you will see the content of more than one list is appearing in that view page.




    Sunday, January 23, 2011

    How to create feature based list definition of a SP 2010 list/ library with the help of VS 2010

    In the development environment, developer has the flexibility to create lists and libraries with out of the box SharePoint list/lib creation wizard. But, when a project moves from Dev env to QA env to Production env, development team generally don’t have the admin power on those environment. So, they are supposed to create the solution package and need to pass the same to the QA or Prod owner. This article will provide steps one need to follow to create a feature based list definition and list instance, which can be a part of the solution package.

    Step I

    First create a List named ‘MailingWFList’ in a SharePoint site and create the following column there:


    So, our objective is to create a feature file activating which in specific site will create a ‘MailingWFList’ (i.e., a List Instance) named List in that site.

    Step II

    Open VS 2010 and Select New Project. Then navigate to SharePoint 2010 installed project templates and select List Definition Project. Give it a proper name and select Ok.


    In the next page, specify the site where you would like to debug it and then select the ‘Deploy as a farm Solution’ option and select Next.


    In the next screen, we need to define List Definition Settings. Give a proper name to your List Definition and as we are going to create feature of an custom list, select the ‘Custom List’ option from the type dropdown. Make sure ‘Add a list instance for this list definition’ option is checked out. Select Finish.


    Step III

    In the solution explorer, expand the ‘ListDefinition1’ node and open the highlighted Element.xml file (i.e., Element File of the List Definition).


    Now we need to modify certain attribute of this xml file:


    See the auto generated warning message before the starting of List Template and Name tag. Though I have changed it, I will suggest you not to change the Name attribute’s value. Change the type to some unique number greater than 10000. If you want to change the DisplayName or Description change it. BaseType = ‘0’ indicates a SharePoint List. In case you want to create a Doc Lib, change it to 1. So, after changing the List Definition Element File, our xml file looks like:


    Save it and close the file.

    Step IV

    Now open the Element.xml file of the ListInstance1 Node.



    Now the Title present here, is going to be the name of the List/ Lib in your site, so change it carefully. In our case, we want the name of the list should be ‘MailingWFList’. Copy and paste the new title after ‘Lists/’ value present in the ‘Url’ attribute. Change the TemplateType to the unique greater than 10000 number that you have already assigned in the List Definition’s element.xml file. In our case it is 15000.


    Save and Close it.

    Step V

    Open the Schema.xml file


    The first thing you need to do is delete the highlighted ‘ContentType’ section.


    Next, inside the fields tag, starts putting the columns you want to be a part of MailingWFList.


    Let’s look into more details


    Certain points that developer need to keep in mind:

    1. ID should be unique GUID for each field.

    2. Display Name can be anything but, Name and Static Name should be same.

    3. Type should be changed as per requirement, means ‘Text’ for string values, ‘Number’ for integer values and so on.

    4. ColName should be on sequential, means first Text Type Column will be nvarchar1, next one should be nvarchar2 and so on. Similarly for the columns of type Integer, ColName should be int1 for the first column, int2 for the second column and so on.

    Now, if you want the columns that you just added needed to be shown in the default view of the list, expand the ‘ViewFields’ node and insert the column names there as shown below:


    So our final ViewFields tag looks like:


    Now save it and rebuild the solution. Next open up your target site and delete the MailingWFList that you have created at very first step. Next, come back to the Visual Studio solution and right click on the MailingWFList project and select Deploy.Now again go to the target site and select View All Site Content. You should find out one new list – ‘MailingWFList’ – created using feature file.