Tuesday, March 26, 2013

SharePoint Programming


Create List Programmatically in SharePoint

Often there is a requirement of creating Lists within a SharePoint website programmatically using API calls. Described below are 2 different methods of achieving the same using C#.Net as the programming language.
In the first approach, a SharePoint List gets created using an existing custom List Template present within the List Template Gallery. This approach helps replicate a list exactly in the same structure as of the list from which the custom list template was generated.
In the second approach, a blank SharePoint List gets generated depending on the List Template Type specified during the creation process. This approach can be used to create blank lists of type Announcements, Contacts, Discussion Board, Document Library, Events, Links, Meetings, Picture Library, Survey, Tasks, etc.

using (SPSite oSPsite = new SPSite("http://Web URL"))
{
    oSPsite.AllowUnsafeUpdates = true;

    using (SPWeb oSPWeb = oSPsite.OpenWeb())
    {
        oSPWeb.AllowUnsafeUpdates = true;

        /* 1.create list from custom ListTemplate present within ListTemplateGalery */
        SPListTemplateCollection lstTemp = oSPsite.GetCustomListTemplates(oSPWeb);
        SPListTemplate template = lstTemp["custom template name"];
        oSPWeb.Lists.Add("List Name""Description", template);
  
        /* 2. create list from sharepoint list content type (e.g. Links) */
        oSPWeb.Lists.Add("List Name""Description"SPListTemplateType.Links);

        oSPWeb.AllowUnsafeUpdates = false;
    }

    oSPsite.AllowUnsafeUpdates = false;
}

Programmatically adding a document to document library in SharePoint

In some cases we need to add documents to the document library programmatically, the code snippet below demonstrates how to add a document to the document library.
 using (SPSite objSite = new SPSite("urlAddress"))
 {
        objSite.AllowUnsafeUpdates = true;

         using (SPWeb oSPWeb = objSite.OpenWeb())
         {
            oSPWeb. AllowUnsafeUpdates = true;

            
//Test1 is the document library

            SPList docLibrary = oSPWeb.Lists["Test1"];

            using (FileStream fs = File.OpenRead(FullPath))
             {
             
//Name is the name of the file
              SPFile file = oSPWeb.Files.Add(oSPWeb.Url.ToString() + "/" + docLibrary.Title.ToString()+ "/" + Name, fs);

              file.Update();

             } 
                  docLibrary.Update();
                  oSPWeb.AllowUnsafeUpdates = false;
          } 
          objSite.AllowUnsafeUpdates = false;
                
 }

SPFieldChoice to the dropdown list programatically:

  1. List Name: MyList
  2. Choice Field Name: MyChoiceField and the values are
    1. MyChoice1
    2. MyChoice2
    3.  MyChoice3
First example to set the SPChoice field default value as dropdown list default value.
  1. <asp:dropdownlist id="ddlChoiceField" runat="server">  
  2. </asp:dropdownlist>  
  1. try  
  2.   {  
  3.       using (SPSite site = new SPSite(SPContext.Current.Site.ID))  
  4.       {  
  5.           SPWeb web = site.OpenWeb(SPContext.Current.Web.ID);  
  6.           SPList liMyLists = web.Lists["MyList"];  
  7.           SPFieldChoice fcTypes = (SPFieldChoice)         
  8.                                       liMyLists.Fields["MyChoiceField"];  
  9.           ddlChoiceField.DataSource = fcTypes.Choices;  
  10.          //To set choice field default value as dropdown list default value.  
  11.           ddlChoiceField.SelectedValue = fcTypes.DefaultValue;   
  12.           ddlChoiceField.DataBind();  
  13.   }  
  14.   catch (Exception ex)  
  15.   {  
  16.      //code  
  17.    }  
OutPut:

Second example to set the “Select “value as dropdown list default value with required validation
  1. try  
  2.       {  
  3.           using (SPSite site = new SPSite(SPContext.Current.Site.ID))  
  4.           {  
  5.               SPWeb web = site.OpenWeb(SPContext.Current.Web.ID);  
  6.               SPList liMyLists = web.Lists["MyList"];  
  7.               SPFieldChoice fcTypes = (SPFieldChoice)         
  8.                                           liMyLists.Fields["MyChoiceField"];  
  9.               ddlChoiceField.DataSource = fcTypes.Choices;  
  10.              //Commented below code to display “Select” as dropdown list first value.  
  11.               //ddlChoiceField.SelectedValue = fcTypes.DefaultValue;   
  12.               ddlChoiceField.DataBind();  
  13.   
  14.             //To display “Select” as default value and to do required validation.  
  15.               ListItem lstItem = new ListItem();  
  16.               lstItem.Text = "----Select------";  
  17.               lstItem.Value = string.Empty;  
  18.               ddlChoiceField.Items.Insert(0, lstItem);  
  19.     }  
  20.       catch (Exception ex)  
  21.       {  
  22.          //code  
  23.        }  
OutPut: 
SPField’s to the dropdown List programmatically:
By default, we can get the number of built-in fields or internal fields if you try to retrieve the fields in a list. My below post will help to add only the custom fields to the dropdown list by avoiding all the internal, built-in and hidden fields.

using (SPSite site = new SPSite(SPContext.Current.Site.ID))
{
    SPWeb web = site.OpenWeb(SPContext.Current.Web.ID);
    web.AllowUnsafeUpdates = true;
    SPList list = web.Lists[new Guid(listId)];
    var fields = from SPField f in list.Fields
                        where !f.Hidden && f.AuthoringInfo == "" &&
                                      f.Type != SPFieldType.Attachments &&
                                      f.Type != SPFieldType.WorkflowStatus
                        orderby f.Title
                        select new { ListItem = new ListItem(f.Title, f.Id.ToString()),
                                               Readonly = f.ReadOnlyField, FieldType = f.Type };

ddlDestfield.DataSource = from g in fields where !g.Readonly &&
(g.FieldType == SPFieldType.Note || g.FieldType == SPFieldType.Text)                                               select g.ListItem;
ddlDestfield.DataBind();
ddlDestfield.Items.Insert(0, new ListItem("[Select]""none"));
}


Note: Set f.AuthoringInfo == null [In SP2007] and Set f.AuthoringInfo == "" [In SP2010]

Output:
















List of fields in a list SharePoint programtically:
Below post will help you to get the list of columns that is displayed when you view the items in the list programtically:

var fields = from SPField f in list.Fields
                    where !f.Hidden && f.AuthoringInfo == "" &&
                                  f.Type! = SPFieldType.Attachments &&
                                  f.Title! = "SharingID" &&
                                  f.Type! = SPFieldType.WorkflowStatus
                    orderby f.Title
                    select new { ListItem = new ListItem(f.Title, f.Id.ToString()),
                                Readonly = f.ReadOnlyField, FieldType = f.Type };



 Note: we will get the null result to the “f.AuthoringInfo” in SharePoint 2007 but we can get string empty result to the “f.AuthoringInfo” in SharePoint 2010.
 So, use: f.AuthoringInfo == null [In SP2007] & f.AuthoringInfo == ""[In SP2010]

Output: We can get the list of viewable lists by default once create a sample list in SharePoint.

























Add Columns / Fields Programmatically to a SharePoint List 

You can think of a SharePoint List somewhat similar to a table present within a Database. As tables consist of different columns, a SharePoint List also comprises of different columns / fields and these fields can indeed have different attributes associated to it (like "Required field check", "Max Length", "Display Formats", etc).
We can use SharePoint API to create these fields and associate the corresponding attributes programmatically within an existing List. Provided below is a code snippet in C#.Net describing the same.
using (SPSite oSPsite = new SPSite("http://Web-URL"))
{
oSPsite.AllowUnsafeUpdates = true;
using (SPWeb oSPWeb = oSPsite.OpenWeb())
{
oSPWeb.AllowUnsafeUpdates = true;
/* get the SPList object by list name*/
SPList lst = oSPWeb.Lists["EmpList"];
/* create a Numeric field for EmpID */
SPFieldNumber fldEmpID = (SPFieldNumber)lst.Fields.CreateNewField(
SPFieldType.Number.ToString(), "EmpID");
fldEmpID.Required = true;
fldEmpID.DisplayFormat = SPNumberFormatTypes.NoDecimal;
/* create a Text field for Name */
SPFieldText fldName = (SPFieldText)lst.Fields.CreateNewField(
SPFieldType.Text.ToString(), "Name");
fldName.Required = true;
fldName.MaxLength = 50;
/* create a Date field for Dob*/
SPFieldDateTime fldDob = (SPFieldDateTime)lst.Fields.CreateNewField(
SPFieldType.DateTime.ToString(), "Dob");
fldDob.DisplayFormat = SPDateTimeFieldFormatType.DateOnly;
/* create a Currency field for Salary */
SPFieldCurrency fldSal = (SPFieldCurrency)lst.Fields.CreateNewField(
SPFieldType.Currency.ToString(), "Salary");
fldSal.Currency = SPCurrencyFieldFormats.UnitedStates;
fldSal.DisplayFormat = SPNumberFormatTypes.TwoDecimals;
/* add the new fields to the list */
lst.Fields.Add(fldEmpID);
lst.Fields.Add(fldName);
lst.Fields.Add(fldDob);
lst.Fields.Add(fldSal);
/* finally update list */
lst.Update();
oSPWeb.AllowUnsafeUpdates = false;
}
oSPsite.AllowUnsafeUpdates = false;
}


Add Choice Field Programmatically to a SharePoint List

Choice fields are often used within SharePoint lists to display choice options like Gender, Status, etc and these choice options can be displayed using Radio Button and Dropdown formats.
Provided below is a code sample in C#.Net which describes the creation of a choice field programmatically using SharePoint API.
/* get the newly added choice field instance */
SPFieldChoice chFldGender = (SPFieldChoice)lst.Fields["Gender"];
/* set field format type i.e. radio / dropdown */
chFldGender.EditFormat = SPChoiceFormatType.Dropdown;
/* set the choice strings and update the field */
chFldGender.Choices.Add("Male");
chFldGender.Choices.Add("Female");
chFldGender.Update();
/* finally update list */
lst.Update();

Add, Update and Delete List Items Programmatically in Sharepoint

Using Microsoft Sharepoint APIs we can easily Add, Update and Delete list items programmatically. Provided below is a code snippet in C# .Net demonstrating all the three operations..
using (SPSite oSPsite = new SPSite("http://website url/"))
{
using (SPWeb oSPWeb = oSPsite.OpenWeb())
{
oSPWeb.AllowUnsafeUpdates = true;
// Fetch the List
SPList list = oSPWeb.Lists["MyList"];
//Add a new item in the List
SPListItem itemToAdd = list.Items.Add();
itemToAdd["Title"] = "Test Title";
itemToAdd["Description"] = "Test Description";
itemToAdd.Update();
// Get the Item ID
listItemId = itemToAdd.ID;
// Update the List item by ID
SPListItem itemToUpdate = list.GetItemById(listItemId);
itemToUpdate["Description"] = "Changed Description";
itemToUpdate.Update();
// Delete List item
SPListItem itemToDelete = list.GetItemById(listItemId);
itemToDelete.Delete();
oSPWeb.AllowUnsafeUpdates = false;
}
}

Attachments in SharePoint (Part I)

A list item in SharePoint can have multiple attachments. Below is a code snippet in c#.Net to add an attachment to a list item programmatically.
This example demonstrates how a file, uploaded through a file upload control is added as an attachment to a list item.
using (SPSite oSPsite = new SPSite(http: //website Url/))
{
using (SPWeb oSPWeb = oSPsite.OpenWeb())
{
oSPWeb.AllowUnsafeUpdates = true;
// Fetch the List
SPList list = oSPWeb.Lists["MyList"];
// Get the List item
SPListItem listItem = list.GetItemById(1);
// Get the Attachment collection
SPAttachmentCollection attachmentCollection = listItem.Attachments;
Stream attachmentStream;
Byte[] attachmentContent;
// Get the file from the file upload control
if (this.fileDocAttach.HasFile)
{
attachmentStream = this.fileDocAttach.PostedFile.InputStream;
attachmentContent = new Byte[attachmentStream.Length];
attachmentStream.Read(attachmentContent, 0, (int)attachmentStream.Length);
attachmentStream.Close();
attachmentStream.Dispose();
// Add the file to the attachment collection
attachmentCollection.Add(this.fileDocAttach.FileName, attachmentContent);
}
// Update th list item
listItem.Update();
oSPWeb.AllowUnsafeUpdates = false;
}
}

Adding an Attachment to a List Item Programmatically in SharePoint

As we can have multiple attachments against a list item, it has always been a requirement to fetch these attachments and get it displayed within a custom webpage.
Below is code snippet in c#.net for fetching all the attachements for a specific list item.
try
{
// Set the Site Url
SPSite objSite = new SPSite("http://Testsite/");
using (SPWeb objWeb = objSite.OpenWeb())
{
objWeb.AllowUnsafeUpdates = true;
// Get the List
SPList objList = objWeb.Lists["MyList"];
// Get the item by ID
SPListItem objItem = objList.GetItemById(1);
// Get the attachments of the item
SPAttachmentCollection objAttchments = objItem.Attachments;
// Iterate the attachments
foreach (string fileName in objItem.Attachments)
{
// Perform action on the extracted attachment
}
objWeb.AllowUnsafeUpdates = false;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

Programmatically creating Folders within SharePoint List

Folders help group related items within a list. The code snippet provided below (in C#.Net) explains the approach of creating a folder within a specific list.

using (SPSite oSPsite = new SPSite("http://website_url")){oSPsite.AllowUnsafeUpdates = true;using (SPWeb oSPWeb = oSPsite.OpenWeb()){oSPWeb.AllowUnsafeUpdates = true;/* Path within the list where the new folder gets createdLeave it empty if it needs to be created under root */String nodeDepthPath = @"/MyRootFolder";/* get the list instance by name */SPList list = oSPWeb.Lists["List_Name"];/* create a folder under the path specified */SPListItem folderItem = list.Items.Add(list.RootFolder.ServerRelativeUrl + nodeDepthPath,SPFileSystemObjectType.Folder);/* set the folder name and update */folderItem["Title"] = "New_Folder_Name";folderItem.Update();oSPWeb.AllowUnsafeUpdates = false;}oSPsite.AllowUnsafeUpdates = false;}SharePoint 2010: Accessing a Creating\Accessing a specific folder in Document Library

Here is the piece of code that I wrote to access a folder inside another folder. Although it could be  generalized to n folder by making it recursively call itself but for this specific project it was required to have only 2 folder i.e. we have only two levels of hierarchy. So I wrote a very simple code.
Anyways the description can be found in the comments of the code.

public static SPFolder CreateFolder(SPWeb web, string listName, string folderName)
        {
            web.AllowUnsafeUpdates = true;
            SPList targetList = web.Lists[listName];

            if (string.IsNullOrEmpty(folderName))
                return targetList.RootFolder;


            SPFolder  folder = targetList.ParentWeb.GetFolder(web.Url + "/" + targetList.RootFolder.Url + "/" + folderName);

/
/Checking whether the first level folder exist.
            if (!folder.Exists)
            {
                if (!targetList.EnableFolderCreation)
                {
                    targetList.EnableFolderCreation = true;
                    targetList.Update();
                } 
// Since we could not find the folder so create it

                SPListItem userFolder = null;


                userFolder = targetList.Items.Add(targetList.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder, folderName);

                userFolder["Title"] = folderName;
                userFolder.Update();

                SPListItem hoursFolder = targetList.Items.Add(web.Url + "/" + targetList.RootFolder.Url + "/" + folderName, SPFileSystemObjectType.Folder, DateTime.Now.Year.ToString());

                hoursFolder["Title"] = DateTime.Now.Year.ToString();
                hoursFolder.Update();
                folder = hoursFolder.Folder;
                return folder;
            }
            else
            {
//In case the first level folder exists then check for the folder inside it
                folder = targetList.ParentWeb.GetFolder(web.Url + "/" + targetList.RootFolder.Url + "/" + folderName + "/" + DateTime.Now.Year.ToString());


                if (!folder.Exists)

                {
                    SPListItem hoursFolder = targetList.Items.Add(web.Url + "/" + targetList.RootFolder.Url + "/" + folderName, SPFileSystemObjectType.Folder, DateTime.Now.Year.ToString());
                    hoursFolder["Title"] = DateTime.Now.Year.ToString();
                    hoursFolder.Update();
                    folder = hoursFolder.Folder;
                    return folder;
                }
            }
            if (folder == null)
                throw new SPException(string.Format("The folder '{0}' could not be found.", folderName));
            return folder;
        }

If somebody needs to reach to a multiple hierarchies, then this can code can be modified to a recursive functions.

Programatically adding a document to document library in SharePoint

In some cases we need to add documents to the doument library programatically, the code snippet below demonstrates how to add a document to the document library .
using (SPSite objSite = new SPSite("urlAddress"))
{
objSite.AllowUnsafeUpdates = true;
using (SPWeb oSPWeb = objSite.OpenWeb())
{
oSPWeb.AllowUnsafeUpdates = true;

//Test1 is the document library
SPList docLibrary = oSPWeb.Lists["Test1"];
using (FileStream fs = File.OpenRead(FullPath))
{
//Name is the name of the file
SPFile file = oSPWeb.Files.Add(oSPWeb.Url.ToString() + "/" + docLibrary.Title.ToString()
+ "/" + Name, fs);
file.Update();
}
docLibrary.Update();
oSPWeb.AllowUnsafeUpdates = false;
}
objSite.AllowUnsafeUpdates = false;

}

Sharepoint 2010: Deleting all items in SPListItemCollection


SPListItemCollection objlstCollection = list.GetItems(qry);
for (int i = 0; i < objlstCollection.Count; i++)
{
listCollection.Delete(i);
}
Above is the code that I initially wrote to delete the items in the list item collection and that was actually a very silly code. Since once I delete first item in the list the count of the list collection decreased. 
So to resolve this problem I wrote the following code.  

SPListItemCollection listCollection = list.GetItems(spQuery);

int countItem = listCollection.Count;
for (int i = 0; i < countItem; i++)
{
listCollection.Delete(0);
}

Get all documents from a Document  Set Programmatically

Here is a quick post on how to get all documents from a document set programmatically:
//First getting reference to the list:
SPList myList= web.Lists.TryGetList(“ListName”);
if(myList!=null){
string strquery = “<Where><Eq><FieldRef Name=’Title’/><Value Type=’Text’>”  +           “DocumentSetName” + “</Value></Eq></Where>”;
SPQuery strcamlquery = new SPQuery();
strcamlquery.Query = strquery;
//getting reference to the document set item inside the list
SPListItem docsetitem = myList.GetItems(camlquery)[0];
//Now to loop through items in the document set
SPQuery itemDocSetQuery = new SPQuery();
itemDocSetQuery.Folder = docsetitem.Folder;
SPListItemCollection items = myList.GetItems(itemDocSetQuery);
}
That was a quick post, but I am sure this will be helpful to someone out there.

How to add a menu button to a specific sharepoint list toolbar

When we want to add a custom button to a list toolbar we can add it by using a feature.But when we are activating the feature it will be apply to the scope secified, so all the lists present inside the scope will have a button added to it's toolbar. But if we want to add the button to a particular list then we need to specify the content type ID of the list.
To get the content type id of a list we need to follow these steps:
1. go to the list =>Settings=>List Settings=>Advance Settings=>click yes to the allow management content type
=>ok=>Now in the list setting page you will see a content type click the content type =>In the url you will see a value like

"ctype=0x010046759B602A72384BB7F4C50DEA9EE828"
This is the content type id for the list.
2. Now if you want to get it programatically then you can use this one:
oSPWeb.Lists["listname"].ContentTypes[0].Id.ToString();
Now we need to create the feature.xml file :
<?xml version="1.0" encoding="utf-8" ?>
<Feature Id="{0af0c758-9ed9-43c8-aa2f-90a6fe879c9d}"
Title="Custom Menu"
Description="This example shows how you can implement custom menu."
Version="1.0.0.0"
Scope="Web"
Hidden="FALSE"
xmlns="
http://schemas.microsoft.com/sharepoint/">
<ElementManifests>
<ElementManifest Location="Element.xml" />
</ElementManifests>
</Feature>
Here id is the feature id which is a GUID.

Scope is web, which means the feature will be available to all the subsites also

Hidden is false, which means the feature will be visible in the feature list for a site (Where you can activate the feature)
Next: Create the Element.xml file:
Here we need to add a custom action .
<?xml version="1.0" encoding="utf-8" ?>
<Elements xmlns="
http://schemas.microsoft.com/sharepoint/">
<CustomAction RegistrationType="ContentType" RegistrationId="0x0100F310C1F224701541BF37AFD23D67FEAC"
Sequence="1000" Location="ViewToolbar" Title="Test">
<UrlAction Url="/path to navigate"/>
</CustomAction>
</Elements>
Here the RegistrationId is the content type id of the list and Url is the path to navigate when the user clicks the button.

How to get size of your SharePoint site

In MOSS2007 we can get to the STSADM by opening windows command prompt and changing directory to:

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\BIN

In SharePoint 2010 we can find this at location:
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\BIN
Now to get the size of your site type the following command on the prompt:

STSADM.exe -o enumsites -url http:// <sitename>

It will display the size of your site under the tag "StorageUsedMB".

View all users in a site collection in SharePoint 2010

Some times in sharepoint 2010 we need to have to view/delete the users from site collection, moreover in sp2010 we don't have any link as "All People" as it is present in MOSS2007. So it is a tedious process to view/delete the users from site collection.
For this purpose what we can do in sp2010 is:
Go to Site Actions --> Site Permissions.
Click on any of the groups and you will see the url of your page containing the string
http://......./_layouts/people.aspx?MembershipGroupId=8........
What you need to do is just replace the "_layouts/people.aspx?MembershipGroupId=8" to
"_layouts/people.aspx?MembershipGroupId=0" and omit the succeeding part of the url (if present) and reload the page.
You can now view all the users in that site collection and also have an option in the breadcrumb to remove the user from site collection.

SharePoint2010: Inserting/Updating a Lookup Field in a SP List

Problem 

For values in a particular column in a SharePoint list, suppose list "A" , we can also refer to column in another list, suppose list B, simply by defining a column in list A as a lookup column of list B.
As I assume you know how to do that. the further is step is to update or insert values into this lookup column programatically using SP's server object model.  

Prerequisite

The value in a look up field is made of the ID of the lookup filed concatenation with ;# and Name of the lookup field (that actually shows up in the). For example if we are refering to a list named Annoucement, in another list Projects then we to add a task programmatically, we concatinate, ID of the item in the Annoucement list + ;# + Title of the Annoucement (The column selected while creating the lookup column as shown in the figure). So we can have: 1;#Project Analysis being carried out
http://weblogs.asp.net/blogs/bsimser/CreateColumnLookup2007.png

Solution

To do that we simply need to know the ID of the item in the list and the other field that you want to display
using (SPSite site = SPContext.Current.Site)
{
          SPFieldLookupValue value = new SPFieldLookupValue();
          site.AllowUnsafeUpdates = true;
          using (SPWeb web = site.OpenWeb())
          {
                   web.AllowUnsafeUpdates = true;
                   SPList list = web.Lists["Enter Your ListName"];
                   item = list.Items.Add();
                   string fieldValue = "Enter the ID" + ";#" + "Enter the Name";
                   value = new SPFieldLookupValue(fieldValue);
                   item["Column Name"] = value;
                   item.Update();
          }       
}


The above code is sort of pseudo but I believe it is quite understandable.

Managing (Save & Delete) List Templates programmatically in SharePoint

List Templates
List templates are predefined layouts available in SharePoint which can be used to create new content quickly and easily .The List templates are maintained within the site collection List template gallery. Sharepoint provides OOTB functionality to create and delete list templates. Below mentioned are ways to Save a list as List Template and deleting a list template from the List Template Gallery programmatically.

Saving a List Template
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite oSPsite = new SPSite("http://myserver/site"))
{
using (SPWeb oSPWeb = oSPsite.OpenWeb())
{
SPList lstSource = oSPWeb.Lists["SourceList"];
lstSource.SaveAsTemplate("FileName.stp", "Name", "Description", false);
lstSource.Update();
}
}
}); //end elivated privileges
Deleting a List Template
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite oSPsite = new SPSite("http://myserver/site"))
{
using (SPWeb oSPWeb = oSPsite.OpenWeb())
{
SPList objLstTempGallery = oSPWeb.Lists["List Template Gallery"];
foreach (SPListItem objLstItem in objLstTempGallery.Items)
{
if (objLstItem.Title == "DEL_LIST_TEMPLATE_NAME")
{
objLstItem.Delete();
objLstTempGallery.Update();
break;
}
}
}
}
}); //end elivated privileges

Create and Update Views Programmatically in SharePoint

In SharePoint, View is a virtual representation of a set of data from a specific list. We can programmatically create and update views for a list.
Provided below is an example in C#.Net which explains the approach of creating and updating views. The code is divided in to 2 parts i.e. Part I - describes how to create a view by assigning specific fields from a list, and Part II - describes how to update an existing view by adding few more fields to it.
using (SPSite oSPsite = new SPSite("http://website_url/"))
{
oSPsite.AllowUnsafeUpdates = true;
using (SPWeb oSPWeb = oSPsite.OpenWeb())
{
oSPWeb.AllowUnsafeUpdates = true;
/* get the list instance by list name */
SPList list = oSPWeb.Lists["List_Name"];
/* ======== Part I (create a view) ======== */
// add the field names to the string collection
StringCollection strViewFields = new StringCollection();
strViewFields.Add("FullName");
strViewFields.Add("Address");
strViewFields.Add("City");
strViewFields.Add("State");
// create a standard view with the set of fields defined in the collection
list.Views.Add("View_Name", strViewFields, String.Empty,
100, true, false, SPViewCollection.SPViewType.Html, false);
/* ==== End Part I ==== */
/* ==== Part II (add fields to an existing view) ==== */
// get the view instance by view display name
SPView view = list.Views["Existing_View_Name"];
// add fields to the view
view.ViewFields.Add("Zip");
view.ViewFields.Add("Country");
// update view for new fields
view.Update();
/* ==== End Part II ==== */
/* update the list */
list.Update();
oSPWeb.AllowUnsafeUpdates = false;
}
oSPsite.AllowUnsafeUpdates = false;
}


Copy a List Item in SharePoint List programmatically

This piece of code can be used to copy all the fields of a ListItem in a SharePoint List to a ListItem in another SharePoint List, without any hard coding….
public void CopyItem(SPListItem srcItem, SPListItem destItem)
{
    foreach (SPField field in srcItem.Fields)
    {
        if (!field.ReadOnlyField && field.InternalName != "Attachments")
        {
            destItem[field.InternalName] = srcItem[field.InternalName];
        }
    }

    foreach (string attachmentName in srcItem.Attachments)
    {
        SPFile file = srcItem.ParentList.ParentWeb.GetFile(srcItem.Attachments.UrlPrefix + attachmentName);
        byte[] data = file.OpenBinary();
        destItem.Attachments.Add(attachmentName, data);
    }

    destItem.Update();
}

Then you can call this function as follows:

/*"web" is an object of type SPWeb*/
SPList srcList = web.Lists["List1"];
SPList destList = web.Lists["List2"]; 
SPListItem srcItem = srcList.GetItemByID(1);
SPListItem destItem = destList.Items.Add(); 
CopyItem(srcItem, destItem);

I just used srcList.GetItemByID(1) as an example. You can use any ListItem as srcListItem. The only thing, one needs to make sure is that both the Lists have the same set of fields.


COPY SPS LIST ITEMS FROM ONE SITE TO ANOTHER PROGRAMMATICALLY

Before executing the code I have created two Sharepoint sites, first is http://fivenumber:5/ and the second http://fivenumber:50/
I have also created custom list in each site, Source List in site http://fivenumber:5/ andDesitination List in http://fivenumber:50/
Here in this scenario I have chosen Console Application template because it doens’t contains any input fields to show as webpart and also to avoid GAC registration, safe controls etc., I felt it will be easy to execute the code in Console.
Source List
Source List
Copied List Items
Copied List Items
Destination List
Destination List
using System;
using System.Collections.Generic;
using System.Text;

using Microsoft.SharePoint;

namespace CopyListItems
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                SPSite mySourceSite = new SPSite("http://fivenumber:5/");
                SPWeb mySourceWeb = mySourceSite.OpenWeb();
                SPList mySourceList = mySourceWeb.Lists["Source List"];
                SPQuery mySourceListQuery = new SPQuery();
                mySourceListQuery.Query = "" +
                                "" +
                                "" +
                                "" +
                                "";
                SPListItemCollection mySourceItemColl = mySourceList.GetItems(mySourceListQuery);
                int count = 0;
                foreach (SPListItem mySourceListItem in mySourceItemColl)
                {
                    string SourceEmpId = mySourceListItem["Employee Id"].ToString();
                    string SourceEmpName = mySourceListItem["Employee Name"].ToString();
                    string SourceDesig = mySourceListItem["Designation"].ToString();
                    string SourceAge = mySourceListItem["Age"].ToString();

                    SPSite myDestinationSite = new SPSite("http://fivenumber:50");
                    SPWeb myDestinationWeb = myDestinationSite.OpenWeb();
                    SPList myDestinationList = myDestinationWeb.Lists["Destination List"];
                    SPListItem myDestinationListItem = myDestinationList.Items.Add();

                    myDestinationListItem["Employee Id"] = SourceEmpId;
                    myDestinationListItem["Employee Name"] = SourceEmpName;
                    myDestinationListItem["Designation"] = SourceDesig;
                    myDestinationListItem["Age"] = SourceAge;
                    myDestinationWeb.AllowUnsafeUpdates = true;
                    myDestinationListItem.Update();
                    myDestinationWeb.AllowUnsafeUpdates = false;
                    count++;
                    Console.WriteLine(count+" item(s) copied");
                }
                Console.WriteLine("Press enter to continue");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.Write(ex);
                Console.WriteLine("Press enter to continue");
                Console.ReadLine();
            }
        }
    }
}
If you have Lookup column in your Source List and want to copy the same data in to Destination List, you have to create an instance for SPFieldLookupValue class like below…..
Let’s suppose ‘Employee Name’ column is lookup field, comment or remove the line # 29 in the above code and replace with below code snippet
  1. SPFieldLookupValue mySourceLookupEmpName = new SPFieldLookupValue(mySourceListItem["Employee Name"].ToString());
  2. string SourceEmpName = mySourceLookupEmpName.LookupId.ToString();

No comments:

Post a Comment