Wednesday, August 3, 2011

Getting Attachment from List Items

with the help of following Function you can get Attached files of that particular Item

public List<SPFile> GetListItemAttachments(SPListItem listItem)
        {
            try
            {
                List<SPFile> lstSPFile = null;
                SPSecurity.RunWithElevatedPrivileges(delegate
                {
                    using (SPSite oSite = new SPSite(
                       listItem.ParentList.ParentWeb.Site.ID))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {
                            SPFolder folder = listItem.ParentList.RootFolder.
                               SubFolders["Attachments"].SubFolders[listItem.ID.ToString()];
                            if (null != folder)
                            {
                                lstSPFile = new List<SPFile>();
                                foreach (SPFile file in folder.Files)
                                {
                                    lstSPFile.Add(file);
                                }
                            }
                        }
                    }
                });
                return lstSPFile;
            }
            catch
            {
                return null;
            }
        }

Getting SPUser Object from PeoplePicker Field

if you are working on Sharepoint workflows and you want PeoplePicker Value in workflow 
with the help of following code we can get SPUser object.

SPFieldUser userField = (SPFieldUser)_activeWorkflow.ParentItem.Fields.GetField("AssignedTo");
SPFieldUserValue fieldValue = (SPFieldUserValue)userField.GetFieldValue(Convert.ToString(spI["AssignedTo"]));
SPUser user = fieldValue.User;

Adding SPUtility Mail Headers TO,CC,BCC

Using Following Code you can send mail TO,CC,BCC

StringDictionary headers = new StringDictionary();

headers.Add("to", sendTo);
headers.Add("cc", "");
headers.Add("bcc", "");
headers.Add("from", "admin@test.com");
headers.Add("subject", "Testing");
headers.Add("content-type", "text/html");
SPUtility.SendEmail(web,headers, Body);

Automatically Dispose SharePoint objects using C#

Follwoing Code help yoiu to automaticaly Dispose SPSite & SPWeb Object
this is because SPSite & SPWeb implements IDisposable Interface
you can use "Using" for disposing other objects which implements IDisposable Interface.

using(SPSite oSPsite = new SPSite("http://server"))
{
  using(SPWeb oSPWeb = oSPSite.OpenWeb())
   {
       str = oSPWeb.Title;
       str = oSPWeb.Url;
   }