Wednesday, December 28, 2011

Delete multiple list items from a sharepoint list using Object modeling


In the below code snippet we are going to Delete multiple list items (which returned from a CAML query) from a sharepoint list using Object modeling.

Assumptions::
listItemFieldID  --> List item ID internal field
listItemFieldName --> List item field which you will be querying.
 listItemName --> value of the field

Code::
SPSite ospSite = null;
            SPWeb ospWeb = null;
            SPList ospList = null;
            SPListItemCollection spListItems = null;
            string camlViewQuery = string.Empty,
                           camlFilterQuery = string.Empty,
                           listItemFieldID = "ID";

                //view fields query depends on your requirement
                camlViewQuery = "<FieldRef Name='" + listItemFieldID + "' /><FieldRef Name='" + listItemFieldName + "' />";

                //filter query depends on your requirement
                camlFilterQuery = "<Where><Eq><FieldRef Name='" + listItemFieldName + "'/><Value Type='Lookup'>" + listItemName + "</Value></Eq></Where>";

                using (ospSite = new SPSite(siteUrl))
                {
                    using (ospWeb = ospSite.OpenWeb())
                    {
                        try
                        {
                            ospWeb.AllowUnsafeUpdates = true;
                            ospList = ospWeb.Lists.TryGetList(listName);

                            if (ospList != null && ospList.ItemCount > 0)
                            {
                                SPQuery query = new SPQuery()
                                {
                                    //query the list.
                                    Query = camlFilterQuery,
                                    ViewFields = camlViewQuery,
                                    ViewFieldsOnly = true,
                                };

                                spListItems = ospList.GetItems(query);
                                if (spListItems!= null)
                                {
                                    foreach (SPListItem listItem in spListItems)
                                    {
                                        ospList.Items.GetItemById(Convert.ToInt32(listItem["ID"])).Delete();
                                    }

                                    
                                }
                                ospList.Update();
                                ospWeb.Update();
                                ospWeb.AllowUnsafeUpdates = false;

                            }


                        }
                        catch (Exception ex)
                        {

                        }
                    }
                }

           
 Hope this helps..

Friday, December 9, 2011

Creating a Folder in a SharePoint List and adding Items to it programatically

Below is the code snippet to create a folder in a SharePoint List and adding Items to it.
In the below snippet "lsit" is SPList object in which you are trying to create the folder.


// create a folder under the path specified 
web.AllowUnsafeUpdates =True;
folderItem = list.Items.Add(list.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder);

// set the folder name and update
folderItem["Title"] = "My Folder"
folderItem.Update();

//create a listitem object to add item in the foler
SPListItem listItem = list.Items.Add(folderItem.Folder.ServerRelativeUrl, SPFileSystemObjectType.File, null);

//Set the values for other fields in the list
listItem["Contact ID"] = <<Contact ID>>;
listItem["Contact Name"] = <<Contact Name>>;
listItem.Update();

web.AllowUnsafeUpdates =False;
web.update(); 


Hope this helps..

Add a new list item inside a folder using Sharepoint Webservice Lists.asmx


By using the following batch element you can create an item inside a folder present in a list or library.

<Batch OnError="Continue" RootFolder="http://moss/Lists/myList/FolderName">
  <Method ID="1" Cmd="New">
    <Field Name="ID">New</Field>
    <Field Name="CustomerName">Robert Hay</Field>
    <Field Name="CustomerAddress">Redmond</Field>
    <Field Name="Title">customer2</Field>
  </Method>
</Batch>
 
The important attribute here is the RootFolder. You need to provide the 
URL of the folder where you wish to create the item. So right now the 
RootFolder value is http://moss/Lists/myList/FolderName.
  
 
Hope this helps ..

Tuesday, September 27, 2011

How to programmatically send an email in SharePoint using C#


In this post I will discuss about Sending an e-mail in SharePoint 2010 using C#

public static bool SendMail(string Subject, string Body, bool IsBodyHtml, string From, string To, string Cc, string Bcc)
        {
            bool mailSent = false;
            try
            {
                SmtpClient smtpClient = new SmtpClient();
                smtpClient.Host = SPContext.Current.Site.WebApplication.
                OutboundMailServiceInstance.Server.Address;
                MailMessage mailMessage = new MailMessage(From, To, Subject, Body);
                if (!String.IsNullOrEmpty(Cc))
                {
                    MailAddress CCAddress = new MailAddress(Cc);
                    mailMessage.CC.Add(CCAddress);
                }
                if (!String.IsNullOrEmpty(Bcc))
                {
                    MailAddress BCCAddress = new MailAddress(Bcc);
                    mailMessage.Bcc.Add(BCCAddress);
                }
                mailMessage.IsBodyHtml = IsBodyHtml;
                smtpClient.Send(mailMessage);
                mailSent = true;
            }
            catch (Exception) { return mailSent; }
            return mailSent;
        }

Hope this helps..
Next Post- Programatically set the welcome page in Sharepoint

Wednesday, September 7, 2011

Swap page layout for page,sharepoint 2010

This exercise demonstrates how to change the pagelayout with the new pagelayout.



public static void SwapPageLayout(PublishingWeb publishingWeb, PageLayout oldPageLayout, PageLayout newPageLayout)
        {
            // Replace these variable values and input parameters
            // with your own values.
            //
            // The comment to set when the page is checked in, published, and
            // approved.
            string checkInComment = "Your comments";
            //
            // Validate the input parameters.
            if (null == publishingWeb)
            {
                throw new System.ArgumentNullException("publishingWeb");
            }
            if (null == oldPageLayout)
            {
                throw new System.ArgumentNullException("oldPageLayout");
            }
            if (null == newPageLayout)
            {
                throw new System.ArgumentNullException("newPageLayout");
            }
            // Confirm that the oldPageLayout and newPageLayout are compatible.
            if (oldPageLayout.AssociatedContentType.Id != newPageLayout.AssociatedContentType.Id)
            {
                throw new System.ArgumentException(
                    "The page layouts must render the same type of content",
                    "newPageLayout");
            }

            System.Guid oldPageLayoutId = oldPageLayout.ListItem.File.UniqueId;

            // Set the new PageLayout for all pages that use the old PageLayout.
            PublishingPageCollection publishingPages = publishingWeb.GetPublishingPages();
            foreach (PublishingPage publishingPage in publishingPages)
            {
                if (publishingPage.Layout.ListItem.UniqueId == oldPageLayoutId)
                {
                    if (publishingPage.ListItem.File.CheckOutStatus == SPFile.SPCheckOutStatus.None)
                    {
                        publishingPage.CheckOut();
                    }

                    publishingPage.Layout = newPageLayout;
                    publishingPage.Update();

                    // The PublishingPage has the same SPContentType as its PageLayout.
                    System.Diagnostics.Debug.Assert(
                        publishingPage.ContentType.Parent.Id ==
                        newPageLayout.AssociatedContentType.Id);

                    publishingPage.CheckIn(checkInComment);
                }
            }

        }

Date difference in months asp.net,C#

This exercise will teach how to get the months difference between  From date and  To date.


private static int monthDifference(DateTime startDate, DateTime endDate)
{
int monthsApart = 12 * (startDate.Year - endDate.Year) + startDate.Month - endDate.Month;
return Math.Abs(monthsApart);
}

Hope this helps...

Popular Posts