Search This Blog

Tuesday, December 4, 2012

Sharepoint 2010 : Operation is not valid due to the Current State Object

Error: -------

Solution :

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)
                using (SPSite spSite = new SPSite(site))
                    spSite.AllowUnsafeUpdates = true;
                    using (SPWeb spWeb = spSite.OpenWeb())
                        spWeb.AllowUnsafeUpdates = true;
                        StringBuilder deletebuilder = BatchCommand(spWeb.Lists[list]);


        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()));
            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


Next I Click on Site columns under Galleries.


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.


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


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.


I fill out the form as shown.


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.


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.


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.


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


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


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.


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


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.


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


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.


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


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.


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.


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


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


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


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.


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


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.


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


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


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


I fill out the form as shown.


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.


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


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)

            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);
                    string dirURL = string.Format(@"{0}/{1}", objDestinationFolder.Url, objItem.Folder.Name);
                    SPFolder objNewFolder = objDestinationFolder.SubFolders.Add(dirURL);

                    //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;

                                objDestinationList = DestinationWeb.Lists[ListName];
                                //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.AllowUnsafeUpdates = false;

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

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

Friday, October 26, 2012

What is property bag in SharePoint 2010?

Total Answers : 5

Answer 1
Property bag is basically properties attached on web site ,site collection , web application and farm level.
You can check out the codeplex tool here for more understanding -
You also have a list of cmdlets from Powershell for property bag -
Answer 2
Share-Point property bags provide an easy-to-use storage mechanism for any serializable configuration data. Below is the sample code:
SPWeb web = SPContext.Current.Site.RootWeb;

//To store data in property bag


//To retrieve data stored in property bag                 
if (web.Properties.ContainsKey("TestKey"))
  string strResult=web.Properties["TestKey"];
We must ensure that any data we store in Property Bags is serializable. If you attempt to persist non-serializable types in property bags,the configuration database or the content database may get corrupted. So, it is recommended you use "Application Setting Manager" to store\retrieve values in property bags
Answer 3
One of the uses of SharePoint Manager 2010 ( is to view and update the property bags. This is nice in that it doesn't require a feature deployed to the environment so I use either this or the pbs2010 feature that @Deepu Nair recommended.
Answer 4
To interact with the PropertyBags in code you simply refer to the object's Propeties member.
There are PropertyBags available for the SPFarm, SPWebApplication, SPSite, and SPWeb.
To set a value: site.Properties["PropertyName"] = "foo";
To read a value: string myProperty= site.Properties["PropertyName"].ToString();
Answer 5
$url= Read-Host 'Enter the site Name'
$site = New-Object Microsoft.SharePoint.SPSite($url)
$rootWeb = $site.RootWeb

Write-Host -foregroundcolor Green "The current Site"$rootWeb 

$value= Read-Host 'Enter the property name'
$Adminurl = "propertyName"

$rootWeb.AllowUnsafeUpdates = $true;
$Currentvalue = $rootWeb.Properties[$Adminurl]
Write-Host -foregroundcolor Green "The current value of the property bag is "$Currentvalue

if (!$rootWeb.Properties.ContainsKey($Adminurl))
         $rootWeb.Properties.Add($Adminurl, $value);
         $rootWeb.Properties[$Adminurl] = $value;


       $rootWeb.AllowUnsafeUpdates = $false;

$UpdatedValue =  $rootWeb.Properties[$Adminurl]
Write-Host -foregroundcolor Green "Value of the property bag is updated with " $UpdatedValue

if ($rootWeb -ne $null)

If ($site -ne $null)

Write-Host -foregroundcolor Green "Script has finished executing "

Using c#:

SPSite site = SPContext.Current.Site;
    using (SPWeb spWebRoot = site.RootWeb)

        // unsafe updates are required to be able to write to the property bag
        string key = "administrationurl";
        string myValue = "nikh";
        spWebRoot.AllowUnsafeUpdates = true;

        // you must check to see if the collection has a value in the assigned key already

        if (!spWebRoot.AllProperties.ContainsKey(key))

        spWebRoot.Properties.Add(key, myValue);


        spWebRoot.AllProperties[key] = myValue;

        // update the properties

        spWebRoot.AllowUnsafeUpdates = false;

Wednesday, October 17, 2012

Manage visual upgrade (SharePoint Server 2010)


On migrating from MOSS to SharePoint 2010 using detach/attach method. After successful migration on SharePoint 2010 by default migrated sites will render in MOSS look fell. To upgrade it SharePoint 2010 look feel need to do below steps.

Navigate to -> Site actions -> select visual upgrade menu item.

in the above approach you have to repeat this for all sites that was migrated from MOSS.

Revert sites to previous user interface

If a site collection owner or site owner finalizes the new user interface by mistake, or if they have a problem that they cannot solve, you can revert back to the previous user interface by using Windows PowerShell. This procedure shows you how to revert one or all sites in a site collection to the previous user interface.

To revert sites to the previous user interface by using Windows PowerShell

  1. Verify that you meet the following minimum requirements: See Add-SPShellAdmin.

  2. On the Start menu, click All Programs.

  3. Click Microsoft SharePoint 2010 Products.

  4. Click SharePoint 2010 Management Shell.

  5. To revert a specific site in a site collection to the previous UI, at the Windows PowerShell command prompt, type the following command:

    Get-SPSite http://machinename/sites/V3UI | Get-SPWeb "webname" | Foreach{$_.UIVersionConfigurationEnabled=1;$_.UIVersion=3;$_.Update();}

    To reverts all sites in a site collection to the previous user interface, at the Windows PowerShell command prompt, type the following command:

    Get-SPSite http://machinename/sites/V3UI | Foreach{$_.UIVersionConfigurationEnabled=1;$_.UIVersion=3;$_.Update();}

For more information, see Get-SPSite.

To overcome the above we run PowerShell command to automate it.


Upgrade Visual  from MOSS to SP 2010

Add-PSSnapin “Microsoft.SharePoint.PowerShell”
$site = Get-SPWeb “http://YourSp201oSite”
$site.UIVersion = 4
$site.UIVersionConfigurationEnabled = False

Toggle/revert from SP 2010 UI to MOSS

Add-PSSnapin “Microsoft.SharePoint.PowerShell”
$site = Get-SPWeb “http://YourSp201oSite”
$site.UIVersion = 3
$site.UIVersionConfigurationEnabled = true

Tuesday, October 16, 2012

Exception from HRESULT: 0x80041054

The following error "Exception from HRESULT: 0x80041054" related to ForeFront Protection 2010 for SharePoint and if you check the log [Windows Log] you will find the following error "The SharePoint service is running but the Forefront VSAPI Library is not registered"

so to fix this error from SharePoint Side just go to Central administration >> Security >> Manage antivirus settings >> then Uncheck all check boxex and then browse the site

Tuesday, October 9, 2012

Error occurred in deployment step 'Recycle IIS Application Pool': Provider load failure

This is a windows service-related issue. Either a service has been stopped, disabled due to error or is otherwise in a faulted state. If any of the following PowerShell commands fail check if any of the services have been disabled via the service manager.

restart-service sptimerv4
restart-service spusercodev4
restart-service spadminv4
restart-service TrustedInstaller
restart-service Winmgmt -force

or iisreset /noforce worked without requiring Visual Studio restart

SiteMapNode target="_blank" I want some of my menu choices to open
up in a page in a new window ie _blank as target. How do I do

(Will not work)<sitemapnode url="" title="Google" target="_blank">

(WORKS!)<sitemapnode url="javascript:var'','google');" title="Google" />


Friday, October 5, 2012

What's new in SharePoint 2013

This documentation is preliminary and is subject to change.

Published: July 16, 2012

Conceptual overview topic

Learn about new features and functionality in SharePoint 2013 Preview, including the new Cloud App Model, development tools, platform enhancements, mobile apps, and more.

Applies to:  SharePoint Server 2013 Preview | SharePoint Foundation 2013 Preview 

SharePoint 2013 Preview introduces a Cloud App Model that enables you to create apps. Apps for SharePoint are self-contained pieces of functionality that extend the capabilities of a SharePoint website. An app may include SharePoint components such as lists, workflows, and site pages, but it can also surface a remote web application and remote data in SharePoint. An app has few or no dependencies on any other software on the device or platform where it is installed, other than what is built into the platform. This characteristic enables apps to be installed simply and uninstalled cleanly. Apps have no custom code that runs on the SharePoint servers. Instead, all custom logic moves "up" to the cloud or "down" to client computers. Additionally, SharePoint 2013 Preview introduces an innovative delivery model for apps for SharePoint that includes components like the SharePoint Store and the App Catalog.

Apps for SharePoint  SharePoint Store  App Catalog

SharePoint 2013 Preview makes it easy for any web developer, including those who work on non-Microsoft platform stacks, to create SharePoint solutions. What makes this possible is that SharePoint 2013 Preview is based on common web standards like HTML, CSS, and JavaScript. Furthermore, implementation relies on established protocols like the Open Data protocol (OData), and OAuth.

HTML/JavaScript  OData  REST  OAuth

The current release reflects enormous strides in optimizing the existing development tools like Visual Studio and SharePoint Designer, in addition to providing the release of newly developed web-based tool "Napa" Office 365 Development Tools for developing apps. The new unified project system in Visual Studio lets you develop apps for SharePoint, apps for Office, apps for SharePoint that include apps for Office, or apps for Office that are hosted by SharePoint. In addition to the SharePoint project templates that were provided in earlier versions, Visual Studio 2012 now includes a new app project template in the Apps folder named Apps for SharePoint 2013. Several new properties have been added to the Properties window and Properties pages to support app for SharePoint projects. Other improvements include full support for development against the Cloud App Model, including OData and OAuth support, and full support for development against the Windows Azure Workflow Manager Client platform.

Napa Office 365 Development Tools  Visual Studio  SharePoint Designer

On a broader scale, SharePoint 2013 Preview has been improved and enhanced to support the new cloud-based architecture and app-driven development framework. From the SharePoint APIs at the lowest level to connectivity to social media integration, SharePoint 2013 Preview is designed and executed to support a rich application development experience. In addition to the use of Representational State Transfer (REST) endpoints for web services, there is a broad new API for both server and client development. Remote event receivers and now supported in addition to client-side rendering.

REST endpoints  New client and server APIs  Client-side rendering  Remote event receivers

With SharePoint 2013 Preview, you can combine Windows Phone 7 applications with on-premises SharePoint services and applications, or with remote SharePoint services and applications that run in the cloud (such as those that use SharePoint Online), to create powerful applications that extend functionality beyond the traditional desktop or laptop and into a truly portable and much more accessible environment. The new mobility features in SharePoint 2013 Preview are built on existing Microsoft tools and technologies, such as SharePoint, Windows Phone 7, Visual Studio, and Microsoft Silverlight. You can create SharePoint-powered mobile applications for Windows Phone using the new SharePoint phone application wizard template in Visual Studio, which lets you create simple list-based mobile applications. You can integrate new features introduced in SharePoint 2013 Preview, such as the Geolocation field type and “push" notifications from SharePoint Server, into your mobile applications.

Visual Studio app templates  Push notifications  Location and maps

New and improved social and collaboration features make it easy for users to communicate and to stay engaged and informed. The improved My Site social feed helps users keep up to date with the people and content that they care about. The new Community Site feature provides a rich community experience that lets users easily find and share information and find people who have similar interests.

Interactive feed  Community site  Follow people  Follow sites

Search functionality in SharePoint 2013 Preview includes several enhancements, custom content processing with the Content Enrichment web service, and a new framework for presenting search result types. Additionally, there have been significant enhancements made to the keyword query language (KQL).

Consolidated search platform  Rich results framework  KQL enhnacements

Windows Azure Workflow Manager Client is a redesigned workflow infrastructure that is built on Windows Workflow Foundation 4 and brings new power and flexibility to workflow authoring in SharePoint 2013 Preview. A fully declarative authoring environment enables information workers to use SharePoint Designer 2013 Preview to author powerful workflows, and a new set of Visual Studio 2012 workflow project templates let developers access more sophisticated features like custom actions. Perhaps most importantly, Workflow Manager Client is fully integrated with the model for apps for SharePoint. In addition, workflows execute in the cloud, not in SharePoint, which provides enormous flexibility in designing workflow-based apps for SharePoint.

Executin in the cloud  Workflow 4-based infrastructure  Declarative authoring  Designer and project templates

In SharePoint 2013 Preview, you can now use .NET client, Silverlight, Windows Phone, and JavaScript APIs, in addition to the newly expanded set of .NET server managed APIs, to customize Enterprise Content Management (ECM) experiences and behavior.

Design Manager  Managed navigation  Cross-site publishing  EDiscovery

Business Connectivity Services (BCS) enables SharePoint to access data from external data systems such as SAP, ERP, and CRM, in addition to other data-driven applications that are exposed through WCF services or OData endpoints. BCS in SharePoint 2013 Preview has been improved and enhanced in many ways, including OData connectivity, external events, external data in apps, filtering and sorting, support for REST, and others.

OData connector  External data in apps  External events in SharePoint  

SharePoint Server 2013 Preview includes several services for working with data in your SharePoint sites. New for SharePoint is the Machine Translation Service, which translates sites, documents, and streams for multilingual support. SharePoint Server 2013 Preview also includes Access Services and a new data access model. For converting files and streams to other formats, SharePoint Server 2013 Preview has Word Automation Services and PowerPoint Automation Services (a new feature for SharePoint). SharePoint also provides data analysis tools, like PerformancePoint Services and Visio Services, that enable business intelligence, and powerful new features in Excel Services.

Translation Services  PowerPoint Automation Services  Enhanced Access Services  Enhanced Excel Services



July 16, 2012

Initial publication