Search This Blog

Wednesday, November 21, 2012

Sharepoint - Custom List Delete All Items

 if (!IsPostBack)
                {
                    DeleteAllItems(SPContext.Current.Site.Url, "Nalco My Contacts");
}


 public static void DeleteAllItems(string site, string list)
        {
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite spSite = new SPSite(site))
                {
                    spSite.AllowUnsafeUpdates = true;
                    using (SPWeb spWeb = spSite.OpenWeb())
                    {
                        spWeb.AllowUnsafeUpdates = true;
                        StringBuilder deletebuilder = BatchCommand(spWeb.Lists[list]);

                        spWeb.ProcessBatchData(deletebuilder.ToString());
                    }
                }
            });
        }

        public static StringBuilder BatchCommand(SPList spList)
        {
            StringBuilder deletebuilder = new StringBuilder();
            deletebuilder.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");
            string command = "<Method><SetList Scope=\"Request\">" + spList.ID +
                "</SetList><SetVar Name=\"ID\">{0}</SetVar><SetVar Name=\"Cmd\">Delete</SetVar></Method>";

            foreach (SPListItem item in spList.Items)
            {
                deletebuilder.Append(string.Format(command, item.ID.ToString()));
            }
            deletebuilder.Append("</Batch>");
            return deletebuilder;
        }

Monday, November 19, 2012

Site Columns and Custom Lists in SharePoint 2010

For this blog we’ll create them as Site Columns.
We will create 2 ‘choice’ columns; Flavor and Scoops as Site Columns at the top level site of our site collection. We will then use these columns in 2 lists.
When we are done, the advantages of creating each column once and then re using it should be apparent.

Starting at the Top Level Site of a Site Collection I choose Site Actions>Site Settings

media_1316729539375.png

Next I Click on Site columns under Galleries.

media_1316729663576.png

This takes me to the Gallery of all the Available Site Columns for this Site Collection. Although there are many available Site Columns, there isn’t one for Flavor or Scoops so I’ll create them here. I click the Create Link.

media_1316729765991.png

Here I fill in the Site Column form with the values as shown.

media_1316729837814.png

Other than the values indicated, I leave everything else with the defaults.

I’m then taken back to the Site Columns Gallery where I click Create again.

media_1316730003073.png

I fill out the form as shown.

media_1316730057247.png

I leave the default values other than what is shown and click O.K.

Verify the Existence of the new Site Columns by looking under the Custom Columns group.

media_1316730420049.png

Now I can use these for any list or library in this Site Collection.

I click on the Site Actions> More Options to Create a new custom list called Ice Cream Cones.

media_1316730504283.png

Since I have SilverLight installed, I get a cool Silverlight Control to pick my Template. I’m using custom so I click on Blank and Custom to filter the options.

Click on Blank & Custom to filter the options then choose Custom List. I’ll fill in the Name with IceCreamCones then click Create.

media_1316730648465.png

Now I’ll add my Site Columns to the List By clicking on List Settings in the Ribbon.

media_1316730726399.png

In the Columns Section I’ll click Add from existing site columns.

media_1316730814945.png

I’ll filter the choices by choosing Custom Columns from the Select site columns from: drop down list and then I’ll click Add twice to add my Site columns.

media_1316730888615.png

After moving Flavor and Scoops to the Colunns to add side I click O.K.

media_1316730943528.png

I’ll go ahead and leave add to default view checked.

Optionally, I’m going to change the name of the Title column to something meaningful in this context – Name, by clicking on the Title link in the Columns section.

media_1316731069037.png

I’m going to add a few items to this list by clicking on the iceCreamCones link in the quick launch bar.

media_1316731142080.png

I can always go into title description and icons in the list settings area to add spaces to the name of the list later.

I’ll add a few items by clicking Add new item and filling out the new item form.

media_1316731229179.png

I add items by filling out the form. Here is the first one the Bigfoot – 3 Scoops of Chocolate!

media_1316731284603.png

When I’m done I click on Save.

As you can see, adding the Site Columns feels just like adding a regular list column to a user but it’s much more flexible and will be used when creating content types.

media_1316731431169.png

Now I’ll create a recipes list for our employees and use the site columns created earlier in this list as well. First I click Site Actions > More Options.

media_1316731537810.png

Again, I’ll click Blank & Custom to filter the options and then choose Custom List and name it Recipes, then click Create.

media_1316731598497.png

I’ll Click on the List Settings icon in the Ribbon.

media_1316731693269.png

I’m going to create a list column called, cone type which will be choice by clicking Create Column.

media_1316731771764.png

This creates a List Column whose scope is this list and any list created from this list if used as a template. The difference is that a Site Column is available to any list or library in the Site Collection.

I’ll fill out the form as shown leaving the defaults for the rest of the values and click OK.

media_1316731919935.png

Now I’ll add my Site Columns by clicking on Add from existing site columns.

media_1316731982136.png

I’ll filter by Custom Columns in the Select site columns from: drop down list and then click Add to move Flavor and Scoops over to the Columns to add side and click OK.

media_1316732044067.png

I’m going to change the Title Column to ProductNumber by clicking on the Title link under Columns.

media_1316732117304.png

I fill out ProductNumber is the Column name text box and click OK.

media_1316732175592.png

I’m going to create a Name Column which will be a lookup to the iceCreamCones list by clicking on Create Column.

media_1316732257444.png

I fill out the form as shown.

media_1316732306004.png

I’ll ignore the Enforce relationship behavior for this blog post.

I’ll click on the Recipes link in the Quick Launch Bar in order to get to the All items page of the Recipes list so that I can add some items.

media_1316732402065.png

I’ll click Add new item to add a new item.

media_1316732438070.png

That’s it. We created 2 Site Columns, and then created 2 custom lists and added them to these lists. We can reuse these on any list or library in our Site Collection. This example is a great candidate to show the Enforce relationship behavior functionality available in SharePoint 2010 but we’ll save that for another blog.

 

Friday, November 2, 2012

Sharepoint SPItemEventReceiver Adding/Updating/deleting


I am in the process of writing a custom event receiver. The basic flow is as follows:

1. Document is added to Library

2. Based on metadata of document, we check to see if a folder within another document library exists.

3. If the folder does not exist, it is created.

4. The newly added document is copied to the folder residing in another document library.



Create WSP Project and Choose Event Receiver ->ItemsEventsList ->Document Library ->Check Adding,updating,deleting

/// <summary>
       /// An item is being added.
       /// </summary>
        public override void ItemAdding(SPItemEventProperties properties)
        {
            base.ItemAdding(properties);

            using (SPSite oSiteCollectionEvent = new SPSite(properties.SiteId))
            {
                SPWeb oSiteEvent = oSiteCollectionEvent.OpenWeb(properties.RelativeWebUrl);

                SPFolder sourceFolder = oSiteEvent.GetFolder("My Document");

                using (SPSite oSiteCollection = new SPSite("http://dvnap-spdev08:2020/"))
                {
                    SPWeb oWebsite = oSiteCollection.OpenWeb("nalco");

                    oWebsite.AllowUnsafeUpdates = true;
                    //get the folder to the destination
                    SPFolder destinationFolder = oWebsite.GetFolder("My Document");
                    RecursiveCopy(oSiteEvent.Lists["My Document"], sourceFolder, destinationFolder);
                    //CopyListItems("http://dvnap-spdev08:2020","http://dvnap-spdev08:2020/nalco", "My Document");
                }

            }


        }

        private static void RecursiveCopy(SPList objSourceList, SPFolder objSourceFolder, SPFolder objDestinationFolder)
        {
            SPListItemCollection objItems = ((SPDocumentLibrary)objSourceList).GetItemsInFolder(objSourceList.DefaultView, objSourceFolder);

            foreach (SPListItem objItem in objItems)
            {
                //If it's a file copy it.
                if (objItem.FileSystemObjectType == SPFileSystemObjectType.File)
                {

                    byte[] fileBytes = objItem.File.OpenBinary();
                    string DestinationURL = string.Format(@"{0}/{1}", objDestinationFolder.Url, objItem.File.Name);

                    //Copy the file.
                    SPFile objDestinationFile = objDestinationFolder.Files.Add(DestinationURL, fileBytes, true);
                    objDestinationFile.Update();
                }
                else
                {
                    string dirURL = string.Format(@"{0}/{1}", objDestinationFolder.Url, objItem.Folder.Name);
                    SPFolder objNewFolder = objDestinationFolder.SubFolders.Add(dirURL);
                    objNewFolder.Update();

                    //Copy all the files in the sub folder
                    RecursiveCopy(objSourceList, objItem.Folder, objNewFolder);
                }
            }
        }

        public static void CopyListItems(string SourceSiteURL, string DestinationSiteURL, string ListName)
        {
            string DestinationURL = string.Empty;

            using (SPSite SourceSite = new SPSite(SourceSiteURL))
            {
                using (SPWeb SourceWeb = SourceSite.OpenWeb())
                {
                    using (SPSite DestinationSite = new SPSite(DestinationSiteURL))
                    {
                        using (SPWeb DestinationWeb = DestinationSite.OpenWeb())
                        {
                            DestinationWeb.AllowUnsafeUpdates = true;

                            //Get the QA Forms Document libarary from the source web
                            SPList objSourceList = SourceWeb.Lists[ListName];

                            SPList objDestinationList = null;

                            try
                            {
                                objDestinationList = DestinationWeb.Lists[ListName];
                            }
                            catch
                            {
                                //Create a list in the destination web
                                DestinationWeb.Lists.Add(ListName, string.Empty, SPListTemplateType.DocumentLibrary);
                            }

                            objDestinationList = DestinationWeb.Lists[ListName];

                            //Recursively copy all the files and folders
                            RecursiveCopy(objSourceList, objSourceList.RootFolder, objDestinationList.RootFolder);



                            DestinationWeb.Update();
                            DestinationWeb.AllowUnsafeUpdates = false;
                        }
                    }
                }
            }
        }
    

       /// <summary>
       /// An item is being updated.
       /// </summary>
       public override void ItemUpdating(SPItemEventProperties properties)
       {
           base.ItemUpdating(properties);
       }

       /// <summary>
       /// An item is being deleted.
       /// </summary>
       public override void ItemDeleting(SPItemEventProperties properties)
       {
           base.ItemDeleting(properties);
       }