Thursday, April 7, 2011

Object Model - SharePoint API

Please use the following URL
http://snahta.blogspot.com/2008_09_01_archive.html

**********************************************************************************
1) Open list & retrive the ListItems
 using (SPSite siteCollection = SPContext.Current.Site)
                {
                    using (SPWeb site = siteCollection.OpenWeb())
                    {
                        SPList oList = site.Lists["List Name"];
                        SPListItemCollection collListItems = oList.Items;
                        foreach (SPListItem oListItem in collListItems)
                        {}
      }
  }


==================================================
2) Set the value to People Picker

 using (SPSite site = new SPSite(SPContext.Current.Web.Site.ID))
        //    {
        //        SPUserCollection usercoll = site.RootWeb.Groups["C1st_DD"].Users;
        //        foreach (SPUser spusr in usercoll)
        //        {
        //            //groups.Add(spusr.LoginName);
        //            SetValueToPeopleEditor(spusr.LoginName);
        //        }
        //    }

OR
SPUserCollection usercoll = site.RootWeb.Groups[GroupName].Users;
private void SetValueToPeopleEditor(SPUserCollection val)
        {
            try
            {
                if (val.Count>0)
                {
                    ArrayList peopleEditorArrayList = new ArrayList();
                    for (int i = 0; i < val.Count; i++)
                    {
                        PickerEntity targetEntity = new PickerEntity();
                        if (val[i].Name != "System Account")
                        {
                            targetEntity.Key = val[i].LoginName;
                            targetEntity.IsResolved = true;
                            peopleEditorArrayList.Add(targetEntity);
                        }
                    }
                    PickerDDMembers.UpdateEntities(peopleEditorArrayList);
                   
                }
            }
            catch (Exception ex)
            {
              
            }
        }
=====================================================
3) Update UserGroup through PeopleEditor data
  protected void UpdateGroup(object sender, EventArgs e)
        {
            using (SPSite site = new SPSite(SPContext.Current.Web.Site.ID))
            {
               
                SPWeb web = site.OpenWeb();
                SPGroup memberGroup=web.Groups[SelectedGroup];
                SPUserCollection usercoll = site.RootWeb.Groups[SelectedGroup].Users;
                if (memberGroup != null)
                {
                   
                    string usersaccounts=PickerDDMembers.CommaSeparatedAccounts;
                    char[] splitter = {','};
                    string[] splituserData = usersaccounts.Split(splitter);
                    if ((memberGroup.Name != "ProgramManger".ToString()) && (memberGroup.Name != "ITSupport".ToString()) && (memberGroup.Name != "FinancialChampion".ToString()))
                    {
                        for (int j = 0; j < usercoll.Count; j++)
                        {
                            if (usercoll[j].Name != "System Account")
                            {
                                memberGroup.Users.Remove(usercoll[j].LoginName);
                            }
                        }
                        for (int i = 0; i < splituserData.Length; i++)
                        {
                            memberGroup.Users.Add(splituserData[i], "", "", "");
                        }
                    }
                    else
                    {
                        if (splituserData.Length > 1)
                        {
                            literror.Text = "Please select only one user for this group";
                        }
                        else
                        {
                            for (int j = 0; j < usercoll.Count; j++)
                            {
                                if (usercoll[j].Name != "System Account")
                                {
                                    memberGroup.Users.Remove(usercoll[j].LoginName);
                                }
                            }
                            memberGroup.Users.Add(splituserData[0], "", "", "");
                        }
                   
                    }
                }
            }
            // Go back to groups listing
            Response.Redirect(_SiteURL + "/_layouts/WHCustomerFirst/RoleGroupMgntDisp.aspx?Group=" + SelectedGroup + "&ipTitle=" + inputformTitle, true);
        }
==================================================
4) Assign the People Editor value to List
  SPSite siteCollection = SPContext.Current.Site;
                SPWeb site = siteCollection.OpenWeb();
                SPList oList = site.Lists["ListName"];
                SPListItem oListItem = oList.Items[0];
  string usersaccounts = PickerAssingedTo.CommaSeparatedAccounts;
  SPUser user = site.SiteUsers[usersaccounts];
  listItem["Assigned_x0020_To"] = AddPrincipal(oListItem, user);

 protected SPFieldUserValueCollection   AddPrincipal(SPListItem item, SPPrincipal principal)
     {
 
         SPFieldUserValueCollection fuvc = new SPFieldUserValueCollection();
         fuvc.Add(new SPFieldUserValue(item.ParentList.ParentWeb, principal.ID, principal.Name));
         //item[column] = fuvc;
         //item.Update();
         return fuvc;
 
     }
===================================================
5) Check the current logged in user belongs to Group or not

private bool IsMember()
    {
        bool isMember;
        SPSite site = SPContext.Current.Site;
        SPWeb web = site.OpenWeb();
        isMember = web.IsCurrentUserMemberOfGroup(web.Groups["Group Name"].ID);
        web.Close();
        site.Close();
        return isMember;
    }
=====================================================
6) Set the List Date value to DateTime Control
 strCompDate = oListItem["Completion Date"].ToString();
        DateTimeControlName.SelectedDate = Convert.ToDateTime(strCompDate);
====================================================
7) Insert the DateTimeControl selected date to List
 listItem["TaskDueDate"] = DateTimeControlDueDate.SelectedDate;

====================================================
8)   Renaming List Form Toolbar Items:
The following function can be used to achieve both tasks, just call the function passing the old and new names of the item. For instance if you need to rename "Add Item" to "Add Program", use renameFormMenuItems("Add Item","Add Program");. In case you need to remove the text and leave the image, call the function passing an empty string as the new name as follows: renameFormMenuItems("Delete Item","");.


renameFormMenuItems("New Item","New Program");
renameFormMenuItems("Edit Item","Edit Program");
renameFormMenuItems("Delete Item","");
function renameFormMenuItems(oldName,newName)
{
 var anchorTag;
 var allAnchorTags = document.getElementsByTagName('a');   

 if(oldName.length!=0)
 {
  for (var j = 0; j < allAnchorTags.length; j++)
  {
   anchorTag= allAnchorTags[j];   

   if (anchorTag.innerText.indexOf(oldName)!=-1)
   {                  
     
     anchorTag.innerText=newName;
     try
     {
      if(newName.length!=0)
       {             
    anchorTag.parentNode.previousSibling.firstChild.
          firstChild.alt=newName;     
      }
      else
      {
         anchorTag.parentNode.previousSibling.firstChild.
    firstChild.alt=oldName;    
      }
     }
     catch(err)
     {
     }         
   }    
  }
 }
}
==================================================
9) Get the Email address based on user AccountID
SPSite site = new SPSite(siteURL);
       SPWeb web = site.OpenWeb();
       SPUser user = web.AllUsers["Userid"];
       string email = user.Email;
==================================

10) Adding a List Item to a Custom List

using (SPWeb web = siteCollection.AllWebs["webname"])
{

SPList list = web.Lists["Custom List"];
 
SPListItem item = list.Items.Add();
 
item["Title"] = "New List Item";

item.Update();
}
=======================================
11)   Adding a List Item to a Document Library with an attachment

// Creates document in given list (root folder).
02.// Returns true if the file was created, false if it already
03.// exists or throws exception for other failure
04.protected bool CreateDocument( string sFilename, string sContentType, string sList)
05.{
06.   
try
07.   
{
08.       
SPSite site = SPContext.Current.Site;
09.

10.       
using (SPWeb web = site.OpenWeb())
11.       
{
12.           
SPList list = web.Lists[sList];
13.           
// this always uses root folder
14.           
SPFolder folder = web.Folders[sList];
15.           
SPFileCollection fcol = folder.Files;
16.

17.           
// find the template url and open
18.           
string sTemplate = list.ContentTypes[sContentType].DocumentTemplateUrl;
19.           
SPFile spf = web.GetFile(sTemplate);
20.           
byte[] binFile = spf.OpenBinary();
21.           
// Url for file to be created
22.           
string destFile = fcol.Folder.Url + "/" + sFilename;
23.

24.           
// create the document and get SPFile/SPItem for
25.           
// new document
26.           
SPFile addedFile = fcol.Add(destFile, binFile, false);
27.

28.           
SPItem newItem = addedFile.Item;
29.           
newItem["ContentType"] = sContentType;
30.           
newItem.Update();
31.           
addedFile.Update();
32.           
return true;
33.       
}
34.   
}
35.   
catch (SPException spEx)
36.   
{
37.       
// file already exists?
38.       
if (spEx.ErrorCode == -2130575257)
39.           
return false;
40.       
else
41.           
throw spEx;
42.   
}
43.}

-------------------------------------------------------------
Hide Save Button in SharePoint Survey : Please the following code in the script tag (edit the NewForm.aspx and EditForm.aspx in sharepoint desinger)

_spBodyOnLoadFunctionNames.push("setValue");
function setValue() {
hideButton("Save");
}
//This function hides a button on the page
function hideButton(valueDef){
var frm = document.forms[0];
for (i=0;i< frm.elements.length;i++) {
if (frm.elements[i].type == "button" && frm.elements[i].value == valueDef) {
frm.elements[i].style.display = "none";
}
}
}

=======================================
Add, Update and Delete List Items using C#

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
          for (int i = list.Items.Count - 1; i >= 0; i--)
                {
                    list.Items.Delete(i);
                }



            oSPWeb.AllowUnsafeUpdates = false;
       }
}

No comments:

Post a Comment