Pages

Showing posts with label SharePoint Lists. Show all posts
Showing posts with label SharePoint Lists. Show all posts

Wednesday, July 11, 2012

SharePoint 2010 - Retrieving Items and Folders Recursively

At times you may have to retrieve both folders and items from a document library or list. To search in a specific folder, you can set the “Folder” property of SPQuery object to your desired folder. You will also need to specify “Scope=’RecursiveAll’” in ViewAttributes property of SPQuery object in order to make this lookup recursive. If you want to differentiate between folders and items, you can do that by retrieving “ContentType” property of SPListeItem object. Please see the following code snippet for more information.

string sourceFolder = "<Specify Source Folder URL>";
SPFolder folder = SPContext.Current.Web.GetFolder(sourceFolder);
SPQuery query = new SPQuery();
query.Folder = folder;
query.Query = "";
query.ViewAttributes = "Scope='RecursiveAll'";
SPListItemCollection sourceCol = list.GetItems(query);
foreach (SPListItem item in sourceCol)
{
     //Only check for list items in the folder
     if (item["ContentType"].ToString() == "Folder")
     {
         System.Diagnostics.Debug.WriteLine(("Folder URL: " + item.Web.Url + "/" + item.Url));
 
     }
      else
     {
                                   //System.Diagnostics.Debug.WriteLine(("Item URL: " + item.Web.Url + "/" + item.Url));
     }

Tuesday, June 12, 2012

SharePoint 2010: Updating Field Properties and Event Receivers in Custom Content Types

If you are working with custom content types in SharePoint 2010, you may face a situation where you need to update properties of existing fields after the content type has been deployed. In my experience, once the custom content type has been deployed and referenced in a list or document library and is currently in use, you CANNOT update field information through feature upgrade. Field information, however, will be updated in new document libraries or list when you add content type to it.

Updating Field Properties
You have two options if you want to update properties of existing fields in custom content types:

  1. Delete the content type from the document library or list and add it again. This might not be an ideal solution if you have items in your SharePoint list.
  2. Use PowerShell.
  3. Use a 64-bit console program referencing Microsoft.SharePoint.dll and System.Configuration.dll in order to update field information. The code snippet is provided below. Notice that I am using a for loop instead of foreach loop when accessing document libraries and content types in the document library. The foreach loop will throw a collection has been modified exception.

    using System;
    using System.Collections.Generic;
    using Microsoft.SharePoint;
    using System.Configuration;
    namespace UpdateSPFieldInfo
    {
        class Program
        {
            static void Main(string[] args)
            {
                using (SPSite currentSite = new SPSite(ConfigurationManager.AppSettings["SP_SITE_URL"]))
                {
                    //I am interested in document libraries only where I am using my custom content type
                    SPListCollection docLibraryColl = currentSite.OpenWeb().GetListsOfType(SPBaseType.DocumentLibrary);
                    //You have to use a for loop. The foreach loop will cause an exception saying collection has been modified
                    for (int docLibCount = 0; docLibCount < docLibraryColl.Count; docLibCount++)
                    {
                        for (int ctCount = 0; ctCount < docLibraryColl[docLibCount].ContentTypes.Count; ctCount++)
                        {
                            if (docLibraryColl[docLibCount].ContentTypes[ctCount].Name == "HDSDocumentContentType")
                            {
                                Console.WriteLine("Document Library:" + docLibraryColl[docLibCount].Title);
                                string fieldsToUpdate = "CustomField1,_x0033_CustomField2";
                                foreach (string fieldInternalName in fieldsToUpdate.Split(','))
                                {
                                    SPField spField = docLibraryColl[docLibCount].Fields.GetFieldByInternalName(fieldInternalName);
     
                                    if (spField == null)
                                    {
                                        Console.WriteLine("The field \"" + fieldInternalName + "\" could not be found");
                                    }
                                    else
                                    {
                                        spField.ShowInDisplayForm = false;
                                        spField.ShowInEditForm = false;
                                        spField.ShowInNewForm = false;
                                        spField.Update();
                                        Console.WriteLine("The field \"" + fieldInternalName + "\" has been updated");
                                    }
                                }
                                break;
                            }
                        }
                    }            
                    
                }
     
                Console.ReadLine();
            }
     
            
        }
    }

Updating Event Receiver Association
If you have added a new event receiver to your content type, it will not be added to the existing list or document library where you have already added the event receiver. In order to update the event receiver association, you have to do the following:



  1. Get the assembly full name. This can be done by starting Windows PowerShell and typing the following command:
    [System.Reflection.AssemblyName]::GetAssemblyName("Path_To_Event_Receiver.dll").FullName

    image
  2. Get the event receiver class name in the form of Namespace_Name.class_name from your project.
  3. Add the following code to the program that is updating content type information:



    string AssemblyFullName = "MyCustomContentType, Version=1.0.0.0, Culture=neutral, PublicKeyToken=1188765594dd1cac";
    string assemblyClassName = "MyCustomContentTypeNameSpace.ClassName";
    string delERName = "ItemDeleting";
    SPEventReceiverDefinitionCollection eventReceivers = docLibraryColl[docLibCount].EventReceivers;
    //If you want to retreive existing event receiver information
    foreach (SPEventReceiverDefinition sped in eventReceivers)
    {
          Console.WriteLine("Event Receiver Class:" + sped.Class.ToString());
          Console.WriteLine("Event Receiver Name:" + sped.Name);
    }
    //Example of an ItemDeleting event receiver
    SPEventReceiverDefinition delER = eventReceivers.Add();
    delER.Name = delERName;
    delER.Type = SPEventReceiverType.ItemDeleting;
    delER.SequenceNumber = 2;
    delER.Assembly = AssemblyFullName;
    delER.Class = assemblyClassName;
    delER.Update();
     
    Console.WriteLine("Event Receiver Added");



Friday, June 8, 2012

SharePoint Console Application: File Not Found Exception

You are developing a console application referencing Microsoft.SharePoint.dll and trying to connect to a SharePoint resource for e.g., site collection, web, list, or list item. The code compiles without any problem but when you try to run your application, you get the following exception:

image

Out of many reasons why you would get this message, one main reason is you forgot to change the platform target to 64-bit in your project properties. Change the platform target to 64-bit and then try to run your application and it should run fine this time. Remember, SharePoint 2010 is a 64-bit platform so none of the x86 based settings or application would work with SharePoint 2010 Smile

image

Monday, April 2, 2012

How to Display Edit Link in a Datasheet View?

The DataSheet view in SharePoint doesn’t display edit columns that allows user to go to the edit form of an item right from datasheet view. Why Microsoft didn’t want to add that column? Well, technically you are in edit mode once you are in datasheet view so there is no point (smart huh!!). This limitation, however, can cause some trouble when you are not displaying all of the fields from a list or document library in the datasheet view and this is what I had to face today and made me think what would be a solution. After having some fun with calculated column and formula, I got a good news and a bad news.

First the good news: in order to have that extra column added to datasheet view, I can just add a calculated column with link to the edit form in the formula value. In order to do that,

  1. Go to the standard view of your list, edit an item and note the item URL in the address bar.
  2. Create a calculated field in the list or document library e.g., CustomEditLink. The formula that you need to place in the calculated field looks like this:

    ="http://sharepoint/sites/demosite/Lists/DemoList/EditForm.aspx?ID="& [ID] &"&http%3A%2F%2Fsharepoint%2Fsites%2Fdemosite%2FLists%2FDemoList"
    image

  3. Uncheck the checkbox so that this column is not added to the default content type and default view if you don’t want to display this column to everyone.

    image

  4. Select “OK”.

That’s it, if you go to your view or page where you added the list web part and configured it to show the edit link column, you will see the link.


Now the bad news: this solution doesn’t work for new items. The reason is when you add a new item to the list, the ID field is empty and it gets populated after the item is saved. You will need to edit the field by going to list settings and resave it and it will populate the ID field correctly since the item already exist
– or –  you can write a workflow that populates field value of this column after an item is created (in my case, this is out of scope of the project :[ so I had to stop)

Thursday, March 8, 2012

How to Copy a SharePoint List or Document Library to Another Site?

You may need to copy a SharePoint list across site collections or sub-sites for various purposes. This can be done using STSADM following these steps:

STEP 1: Backup Your Target and Source Site

Make sure to backup your target and source sites. You can use STSADM backup operation for this purpose.

image

An example of the command would be:

stsadm -o backup -url http://yoursite -filename c:\yoursitebackup.bak

STEP 2: EXPORT LIST OR DOCUMENT LIBRARY


Export the list using STSADM Export operation. The syntax is provided below:

image


An example of the command would be:



stsadm -o Export -url http://yoursite/doclibrary -filename C:\doclibrary.bak -includesecurity


Note: On SharePoint 2010, you can export a list from central administration if needed. The Central Administration interface, however, does not provide an option to import the library.


STEP 3: IMPORT LIST OR DOCUMENT LIBRARY TO THE TARGET SITE


Import the list using STSADM Import operation. The syntax is provided below:


image



stsadm -o import -url http://yoursite2/doclibrary -includeusersecurity -activatesolution

Hope it helps!

Wednesday, February 1, 2012

SharePoint 2010: How to Copy a List within a Site Collection?

At times you may have to copy a list in a site collection for archiving purposes. The out-of-the-box options to achieve this are following:

  1. Save List as Template with Content: This option allows you to save list as template including content. After the template is created you can create a new list using the list template.

    Note:
    This option is not guaranteed to work all the time specially when there are too many items in the list.
  2. Take Granular Backup Using SharePoint Central Administration: This option is new in SharePoint 2010. However, it only allows you to backup the list. In order to restore the list, you will have to use Import-SPWeb cmdlet. However, you cannot use this option to copy a list within site collection.
  3. PowerShell: This is the best option when it comes to copying list in your SharePoint site. Here is what you need to do.
    • Get an instance of the SharePoint Site Collection using SharePoint SPSite object.
    • Open the root web.
    • Save the list that you want to copy as a template using SaveAsTemplate method of SPList.
    • Get a reference to the list template that is created.
    • Add a list using SPListCollection.Add Method (String, String, SPListTemplate). When successful, this method will display the list GUID.
    • Update the root web using SPWeb.Update

The PowerShell script is provided below.

#//Replace the URL with your real site collection URL
$siteURL = "http://sitecollectionURL"
#//Replace the list title with your list title in site collection
$sourceListTitle = "My List Title"
$targetListTitle = "My Target List Title"
 
$site = New-Object Microsoft.SharePoint.SPSite($siteURL)
$web = $site.OpenWeb()
$sourceList = $web.Lists[$sourceListTitle]
$sourceList.SaveAsTemplate($sourceListTitle,$sourceListTitle,$true)
$listTemplate = $site.GetCustomListTemplates($web)[$sourceListTitle]
$web.Lists.Add($targetListTitle, $targetListTitle, $listTemplate)
 
#//if successfull you will see a GUID output
$web.Update()
$web.Dispose()
$site.Dispose()

Wednesday, December 14, 2011

IIS 7 Authentication Prompt and 403 Forbidden Error

I saw this issue today when an internal web application on IIS 7 continued to display authentication prompt in Internet Explorer 8.0 and refused to accept any credentials. With valid credentials, the same web application worked in FireFox without any problem. When I analyzed the authentication header using Fiddler, I found that the server was authenticating users using FireFox by NTLM whereas IE users were being authenticated by Kerberos protocol.

 image image
Having no idea on why it started happening all of a sudden, I decided to look at the provider setting in IIS 7 and found that the default provider for this web application was Kerberos. Changing it back to NTLM resolved the issue. To do that select your web application in IIS Manager and select “Authentication”. Select “Windows Authentication” and in the “Actions” pane, select “Providers”. In the pop-up window, select NTLM and make sure that it is the first entry.

image image image

Note: If you are using Kerberos for your web application, you may get the authentication prompt if your Service Principle Name (SPN) is not setup correctly. Consult Microsoft documentation on how to set it up.

Saturday, October 1, 2011

SharePoint 2010 Single Server Farm Setup Using VMWare Server – Part 2

Virtual Machine Setup
This article discusses how to setup a virtual machine using VMWare Server for Windows 2008 Server R2 64-bit Standard Edition.

DISCLAIMER: THIS ARTICLE IS PUBLISHED FOR INFORMATIONAL PURPOSES ONLY. FOLLOW THE INSTRUCTIONS AT YOUR OWN RISK. THE AUTHOR IS NOT RESPONSIBLE FOR YOUR ACTIONS

- Part 1 - VMWare Server Setup

- Part 2 – Virtual Machine Setup [Currently Reading]

- Part 3 – Windows 2008 Server R2 64-bit Standard Edition Setup

- Part 4 – SQL Server 2008 R2 Setup

- Part 5 - SharePoint 2010 Enterprise Edition Setup

REQUIREMENTS

  1. A machine with 64-bit Intel Processor, at least 4GB of RAM, and 50 GB hard disk space. 64-bit support should be enabled in BIOS of your machine.
  2. Windows 7 64-bit. However, if you have a 32-bit Windows XP, Vista, or 7 it will still work.
  3. VMWare Server. You can download it by going to http://www.vmware.com/products/server/overview.html
  4. Windows 2008 R2 Standard Edition 64-bit Trial. You can download it by going to http://technet.microsoft.com/en-us/evalcenter/dd459137
  5. SQL Server 2008 R2 Standard Edition 64-bit trial. You can download it by going to http://msdn.microsoft.com/en-us/evalcenter/ff459612
  6. Microsoft Office SharePoint Server 2010 Enterprise Edition. You can download it by going to http://sharepoint.microsoft.com/en-us/Pages/Try-It.aspx

Virtual Machine Setup

Follow these instructions to setup a virtual machine using VMWare Server.

  1. Go to VMWare homepage by going to Start –> All Programs –> VMWare –> VMWare Server –> VMWare Server Homepage. Make sure Internet Explorer 8.0 or later is your default browser.

    image
  2. You will receive a certificate warning in IE. When VMWare server is installed, it is configured automatically to use a locally signed SSL certificate in Apache Tomcat. Select “Continue to this web site (not recommended).” The server is installed locally and is accessed through HTTPS (https://yourmachinename:port) channel so no need to worry Smile

    image
  3. In the next screen, type user name and password that you use to logon to your windows account for e.g., administrator and password. Select “Log In”.

    Note: You must specify a user name and password. At times, if you don’t specify a password, the login will be failed.

    image
  4. The homepage of VMWare Server will be displayed listing the VM’s if you already have installed. Select “Virtual Machines –> Create Virtual Machine” from the top menu.

    image
  5. In the next screen type a name of the virtual machine and select “Next”.

    image
  6. In the next screen, specify the following:
    Operating System: Windows Operating System
    Version: Microsoft Windows Server 2008 64-bit
    Product Compatibility: Leave as-is.

    Select “Next”.

    image
  7. In the next screen, specify the following and select “Next”.
    Memory: 2048 MB
    Processor Count: 1
    image
  8. In the next screen, select “Create a new Virtual Disk”
    image
  9. In the next screen, specify the following.. Select all the default option as-is and select “Next”.
    Capacity: 24 GB
    image
  10. In the next screen, select “Add a Network Adapter”.
    image
  11. In the next screen, specify the following. Leave the default option as-is and select “Next”.
    Network Connection: Bridged

    image
  12. In the next screen, select “Use a physical device” if you have Windows 2008 R2 Standard Edition image on the CD-Rom. If you downloaded the ISO like myself, select “Use an ISO Image”.

    image
  13. If you have an ISO image, select it by clicking “Browse”. Note that you will need to copy the ISO image of Windows 2008 R2 64-bit standard edition to the default location of virtual machines you selected during VMWare setup. In my case, I copied the ISO image at D:\Virtual Machines. However, I can also add a data store in VMWare where I usually download my ISO images on the laptop. Select “Next” when ready.

    image image
    image
  14. In the next screen, you will see an option to use a floppy drive. Since it is kind of old fashioned, we don’t need it Smile. Select “Don’t add a floppy drive” and select “Next”.

    image
  15. The next screen will ask you to configure a USB controller. As, at times, we may need to use a USB flash drive or hard disk, select “Add a USB Controller”.

    image
  16. We are at the last step and ready to create our VM. Select “Power on your new virtual machine now”. Select “Finish”.

    image
  17. At this point, the virtual machine is online but wait where is it? Well, it has been started but is not yet visible. VMWare may improve that in next version but for now, you will need to select your virtual machine from “Inventory” pane and click on the “Console” tab. To look at the VM, click on black console window anywhere.

    image
  18. The virtual machine will be displayed in a popup.

    image
  19. We are now ready to configure Windows 2008 R2 Standard Edition that will be covered in the next part of this series.