GET USER PROFILE using CLIENT OBJECT MODEL SharePoint 2010

May 14, 2013

Retrieving user profile picture using Client Object model – ECMAScript . I am passing the userId from the front end to a javascript method called “getUserProfile()” to retrieve the user profile info. The method onQuerySucceeded will get you the user Profile info.

function getUserProfile(userID)
{
var clientContext = new SP.ClientContext.get_current();

var web = clientContext.get_web();

var userInfoList = web.get_siteUserInfoList();

var camlQuery = new SP.CamlQuery();

camlQuery.set_viewXml(‘<View><Query><Where><Eq><FieldRef Name=\’ID\’/>’ +’<Value Type=\’Number\’>’ + userID + ‘</Value></Eq>’ +

‘</Where></Query><RowLimit>1</RowLimit></View>’);

this.collListItem = userInfoList.getItems(camlQuery);

clientContext.load(collListItem);

clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded),Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded(sender, args)
{

var item = collListItem.itemAt(0);

var profile = item.get_item(‘Notes’);

var pictureUrl = item.get_item(‘Picture’).get_url();

var userImage = document.getElementById(‘myImageContainer’); -> Image object

userImage.src = pictureUrl;

var profileDiv = document.getElementById(‘userProfileContainer’);

profileDiv.innerHTML = profile;
}

 

Add, Update and Delete list items using ECMAScript

May 14, 2013

Add item to SharePoint list

To add an item to the list, use the ListItemCreationInformation object,set the properties using set_item, call the update and ExecuteQueryAsync methods

function AddListItem(){

    var ListName = "MyList";
    var context = new SP.ClientContext.get_current(); // the current context is taken by default here
    //you can also create a particular site context as follows
    //var context = new SP.ClientContext('/Sites/site1');
    var lstObject = context.get_web().get_lists().getByTitle(ListName);
    var listItemCreationInfo = new SP.ListItemCreationInformation();
    var newItem = lstObject.addItem(listItemCreationInfo);
    newItem.set_item('Title', 'This is new item');
    // set values to other columns of the list here
    newItem.update();
    context.executeQueryAsync(Function.createDelegate(this, this.onSuccess),
        Function.createDelegate(this, this.onFailure));
     function onSuccess() {
        alert('Item created: ' + newItem.get_id());
    }
    function onFailure(sender, args) {
        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }
}

Update Item of SharePoint list

function UpdateListItem()

{
var ListName = "MyList";
var context = new SP.ClientContext.get_current(); // the current context is taken by default here
//you can also create a particular site context as follows
//var context = new SP.ClientContext('/Sites/site1');
var lstObject = context.get_web().get_lists().getByTitle(ListName);
this.lstObjectItem = lstObject.getItemById(1);
lstObjectItem.set_item('Title', 'This is updated item');
lstObjectItem.update();
lstObject.set_description("Updated description using ECMAScript");
lstObject.update();
context.executeQueryAsync(Function.createDelegate(this, this.onSuccess),
Function.createDelegate(this, this.onFailure));
}
function onSuccess() {
alert('Item udated');
}
function onFailure(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

Delete Item from SharePoint list

function DeleteListItem()

{
var ListName = "MyList";
var context = new SP.ClientContext.get_current(); // the current context is taken by default here
//you can also create a particular site context as follows
//var context = new SP.ClientContext('/Sites/site1');
var lstObject = context.get_web().get_lists().getByTitle(ListName);
this.lstObjectItem = lstObject.getItemById(1);
lstObjectItem.deleteObject();
context.executeQueryAsync(Function.createDelegate(this, this.onSuccess),
Function.createDelegate(this, this.onFailure));
}
function onSuccess() {
alert('Item Deleted');
}
function onFailure(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
Reference to ‘sp.js’ file should be there in the page where you are using ECMAScript

Logging in Powershell in SharePoint 2010

May 14, 2013

$DATE = get-date

$LogPath = "C:\Custom\Projects\AdiCodes"
$LogFileName = "AdisGroupSiteNewLog.log"
$FilePath = $LogPath + "\" + $LogFileName
$logFileCreated = $False
function write-log([string]$label, [string]$logMsg)
{
    if($logFileCreated -eq $False)
    {
        write-host "Creating log file..."
        if((Test-Path -path $LogPath) -ne $True)
        {
            write-host "Provide proper values to LogPath folder" -ForegroundColor Red
        }
        else
        {
            Add-Content -Path $FilePath -Value $logHeader
            $script:logFileCreated  = $True
            write-host "Log file created..."
        }
    }
    else
    {
        [string]$info = [System.String]::Format("[$Date] {0}: {1}",$label, $logMsg)
        Add-Content -Path $FilePath -Value $info
    }
}
try
{
    $siteUrl = "http://dummySite"
    write-log "Accessing web with url" $siteUrl
    $web = Get-SPWeb -identity $siteUrl
}
catch
{
write-host "Error: Please check the log file"  -ForegroundColor Red
write-log ("!!ERROR!!",$error[0])
}

Export to Excel feature for SharePoint Data View Web Part

May 9, 2013

Below code provides Export to Excel Functionality in SharePoint sites. It is simple JavaScript which requires a Data View Web Part and that’s it…

<Script Language=”Javascript”>
function isIE() // Function to Determine IE or Not
{
return /msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent);
}

function exportToExcel() // Function to Export the Table Data to Excel.
{
var isIEBrowser = isIE();
if(isIEBrowser== false)
{
alert(‘Please use Internet Explorer for Excel Export Functionality.’);
return false;
}
else
{
var strTableID = “detailsTable”; // It’s the Table ID of Table in Webpart
var detailsTable = document.getElementById(strTableID);
var objExcel = new ActiveXObject(“Excel.Application”);
var objWorkBook = objExcel.Workbooks.Add;
var objWorkSheet = objWorkBook.Worksheets(1);

for (var intRowIndex=0;intRowIndex<detailsTable.rows.length;intRowIndex++)
{
for (var intColumnIndex=0;intColumnIndex<detailsTable.rows(intRowIndex).cells.length;intColumnIndex++)
{
if(intColumnIndex != 3)
objWorkSheet.Cells(intRowIndex+1,intColumnIndex+1) = detailsTable.rows(intRowIndex).cells(intColumnIndex).innerText;
}
}
objExcel.Visible = true;
objExcel.UserControl = true;
}
}
</Script>
<button onclick=”exportToExcel();”>Export to Excel File</button>
Here only one thing you need to do is Set a Table ID for the Data in Dataview webpart and update it in the javascript.

Using the SharePoint 2010 Client Object Model in JavaScript

May 2, 2013

Why use the SharePoint Client Object Model for JavaScript?

Using the COM allows developers to create a web page that can interact with SharePoint without requiring a page refresh. In the background, the page uses JavaScript to communicate with SharePoint via the COM to retrieve or update data in SharePoint. JavaScript can then update the page to reflect the updated data from SharePoint.

 

Accessing SharePoint

The first thing to note about the COM with JavaScript is that it is disconnected from SharePoint in the sense that in order to retrieve or update data in SharePoint, asynchronous calls to the server must be made. Because of its asynchronous nature, the page can continue to be responsive to the user while the data is being retrieved or updated in the background. This can be both an asset and a liability if not handled properly.

In order to access the COM in a webpage, a reference to the JavaScript file containing the COM code must be included. There are 3 JavaScript files which contain the code for the COM: SP.js, SP.Core.js, and SP.Runtime.js. SharePoint provides the SharePoint:ScriptLink server control tag for referencing JavaScript files. Using the ScriptLink control will:

  • assure that the JavaScript file is loaded only once
  • assure that dependency files are also loaded

In a SharePoint Application page, the ScriptLink tag should be declared within thePlaceHolderAdditionalPageHead Content Placeholder.

<asp:Content ID=”PageHead” ContentPlaceHolderID=”PlaceHolderAdditionalPageHead”runat=”server” />
<SharePoint:ScriptLink Name=”SP.js” LoadAfterUI=”true” runat=”server” />
</asp:Content>

 

How to retrieve a ListItem from a SharePoint List

The following code sample shows how to connect to create a connection to SharePoint and access the Root Web.

var ListItem;

function GetListItemById(listName, listItemId)
{
var SPContext = new SP.ClientContext.get_current();
var web = SPContext.get_web();

var list = web.get_lists().getByTitle(listName);
ListItem = list.getItemById(listItemId);

SPContext.load(ListItem, “Id”, “Title”);
SPContext.executeQueryAsync(GetListItemById_Success, GetListItemById_Fail);
}

function GetListItemById_Success(sender, args)
{
var id = ListItem.get_id();
var title = ListItem.get_item(“Title”);
alert(“Updated List Item: \n Id: ” + id + ” \n Title: ” + title);
}

// Display an appropriate error message
function GetListItemById_Fail(sender, args)
{
alert(“GetListItemById Failed. \n” + args.get_message() + “\n” + args.get_stackTrace());
}

Let’s break down the code. First, we declare a global variable which will contain the data returned from SharePoint via the COM. Since we must use asynchronous calls to SharePoint, the data must be stored somewhere that is accessible by the CallBack function that will be called once the data has been retrieved from SharePoint.

var SPContext = new SP.ClientContext.get_current();

Next, the code creates an object which will facilitate the communication between JavaScript and SharePoint. This is done by accessing the current property of the SP.ClientContext object by calling theget_current() method.

Note: In JavaScript, COM properties are access by calling a function which is named “get_” + the name of the property. For example, the id property which all COM objects have is accessed by calling the object’s get_id() method.

var web = SPContext.get_web();
var list = web.get_lists().getByTitle(listName);

Next, the Root Web property of the SPClientContext object can be accessed by calling the get_web()method. The Web has a SharePoint Lists collection property which is accessed by calling get_lists()method.

ListItem = list.getItemById(listItemId);

Then to identify the specific List, a call is made to the getByTitle() method passing in the name of the List. Finally, to identify a specific List Item in the List, a call is made to the getItemById() method passing in the List Item’s ID value.

At this point, there still has been no data retrieved from SharePoint. The code has simply been identifying which data will be retrieved.

Since it is the List Item data that will be retrieved and accessed in the CallBack function, it must be assigned to a global variable that can be accessed later by the CallBack function.

SPContext.load(ListItem, “Id”, “Title”);

Now that the specific data to be retrieved has been identified, we need to tell it specifically what data to return. It is the client context object’s load() method which specifies which data will be retrieved. Theload() method’s first parameter is the object to return data for, followed by the names of the List Fields to return.

Note: While it is possible to call the load() method without specifying the List Fields, this will return data for every Field in the List, including hidden fields. Since loading all of the List Fields can add 10 times the amount of data needed, it will always be in your best interest to specify the specific Fields to load.

SPContext.executeQueryAsync(GetListItemById_Success, GetListItemById_Fail);

Finally, a call to the executeQueryAsync() method will initiate the actual call to the server. This method takes the 2 CallBack functions to call. The first will be called if the data is successfully retrieved from SharePoint, while the second will be called in the case there was an error retrieving the data.

function GetListItemById_Success(sender, args)
function GetListItemById_Fail(sender, args)

Each CallBack function can take the sender and args parameters which return additional information about the results of the server call.

var id = ListItem.get_id();
var title = ListItem.get_item(“Title”);

In the “success” CallBack function, the objects and their properties which were specified in the load()method can now be accessed using the object’s get_item() method passing in the name of the field.

 

How to create a ListItem in a SharePoint List

function CreateListItem(listName, title)
{
var SPContext = new SP.ClientContext.get_current();
var web = SPContext.get_web();

// Create a new List Item
var SPContext = new SP.ClientContext.get_current();
var list = web.get_lists().getByTitle(listName);
ListItem = list.addItem(new SP.ListCreationInformation());
ListItem.set_item(“Title”, title);
ListItem.update();

SPContext.executeQueryAsync(CreateListItem_Success, CreateListItem_Fail);
}

function CreateListItem_Success(sender, args)
{
alert(“New List Item Created”);
}

// Display an appropriate error message
function CreateListItem_Fail(sender, args)
{
alert(“CreateListItem Failed. \n” + args.get_message() + “\n” + args.get_stackTrace());
}

This example is very similar to the previous one, so I will only point out the differences.

ListItem = list.addItem(new SP.ListCreationInformation());
ListItem.set_item(“Title”, title);

Once the List has been identified, a new List Item is created and added to the List. This is done by creating an instance of the SP.ListCreationInformation class. Then the properties of the new List Item object are set by using the set_item() method passing in the name of the property and the value to set it to.

ListItem.update();
SPContext.executeQueryAsync(CreateListItem_Success, CreateListItem_Fail);

The update() method is called to tell SharePoint to save the changes that were made. Finally the call toexecuteQueryAsync() method is made to send the request to SharePoint.

Note: In this example, the load() method was not called, and therefore there will not be any SharePoint data accessible in the “success” CallBack function. However, the load() method could have been called. In which case, the newly created List Item would be available.

 

How to update a ListItem in a SharePoint List

function UpdateListItem(listName, title)
{
var SPContext = new SP.ClientContext.get_current();
var web = SPContext.get_web();

var list = web.get_lists().getByTitle(listName);
ListItem = list.getItemById(listItemId);

// Update an existing List Item
ListItem.set_item(“Title”, title);
ListItem.update();
SPContext.executeQueryAsync(UpdateListItem_Success, UpdateListItem_Fail);
}

function UpdateListItem_Success(sender, args)
{
alert(“List Item Updated”);
}

// Display an appropriate error message
function UpdateListItem_Fail(sender, args)
{
alert(“UpdateListItem Failed. \n” + args.get_message() + “\n” + args.get_stackTrace());
}

Updating a List Item is simply a combination of identifying an existing List Item as seen in the first example and then setting the property values of the List Item as seen in the second example.

Again, if we actually want to access the values of the List Item as stored in SharePoint after it is updated, a call to the load() method could be made specifying the objects and their fields to retrieve from SharePoint.

 

How to delete a ListItem from a SharePoint List

function DeleteListItem(listName, title)
{
var SPContext = new SP.ClientContext.get_current();
var web = SPContext.get_web();

// Retrieve the List Item
var list = web.get_lists().getByTitle(listName);
ListItem = list.getItemById(listItemId);

// Delete the List Item
ListItem.deleteObject();
SPContext.executeQueryAsync(DeleteListItem_Success, DeleteListItem_Fail);
}

function DeleteListItem_Success(sender, args)
{
alert(“List Item Deleted”);
}

// Display an appropriate error message
function DeleteListItem_Fail(sender, args)
{
alert(“DeleteListItem Failed. \n” + args.get_message() + “\n” + args.get_stackTrace());
}

Again, deleting a List Item is very similar. In order to delete a List Item, the List Item must first be identified as in the first example and then a call made to its deleteObject() method to tell SharePoint to delete the List Item. Finally a call to the executeQueryAsync() method to send the updates to SharePoint.

Power Shell Commands

May 2, 2013
Stsadm will still be functional in SharePoint 2010. Powershell is not DOS based. Its .NET based.
Windows PowerShell™ is the new command-line interface and scripting language specifically designed for system administrators that will be used for Microsoft® SharePoint® Server 2010 administration. Although both Cmd.exe and Stsadm.exe environments will be maintained for backward compatibility, SharePoint Server 2010 command-line administration will use Windows PowerShell.
For practical purposes, you can view Windows PowerShell as complementing Cmd.exe in the Windows administration context and superseding Stsadm.exe for SharePoint administration.
You might ask yourself, What’s so unique about Windows PowerShell? Well, unlike most command-line systems that accept and return text, Windows PowerShell supports and uses XML and objects. XML and object support is a pretty major change that brings entirely new tools and methods to greatly improve control, efficiency, and productivity for developers and administrators.
SPAccessServiceApplication
Get-SPAccessServiceApplication – Gets an {Access Service} application object.
New-SPAccessServiceApplication
Set-SPAccessServiceApplication – Sets a global property for an {Access Services} application.
SPAdminJob
Start-SPAdminJob – Immediately starts any waiting administrative job on the local computer.
SPAlternateURL
Get-SPAlternateURL – Return all alternate URLs that match a given criteria.
New-SPAlternateUrl – Creates a new public or internal URL for the specified Web application zone or resource.
Remove-SPAlternateUrl – Completely deletes the specified alternate URL.
Set-SPAlternateUrl – Configures the specified alternate URL.
SPApplicationContent
Install-SPApplicationContent
SPAssignment
Start-SPAssignment – Initiates a new assignment store.
Stop-SPAssignment – Disposes of objects in the provided Assignment Collection.
SPBackupHistory
Get-SPBackupHistory
SPBlobStorageLocation
Move-SPBlobStorageLocation
SPBrowserCustomerExperienceImprovementProgram
Get-SPBrowserCustomerExperienceImprovementProgram
Set-SPBrowserCustomerExperienceImprovementProgram
SPBusinessDataCatalogAclToChildren
Copy-SPBusinessDataCatalogAclToChildren
SPBusinessDataCatalogEntity
Disable-SPBusinessDataCatalogEntity
Enable-SPBusinessDataCatalogEntity
SPBusinessDataCatalogMetadataObject
Get-SPBusinessDataCatalogMetadataObject
Grant-SPBusinessDataCatalogMetadataObject
Revoke-SPBusinessDataCatalogMetadataObject
Set-SPBusinessDataCatalogMetadataObject
SPBusinessDataCatalogModel
Export-SPBusinessDataCatalogModel
Import-SPBusinessDataCatalogModel
Remove-SPBusinessDataCatalogModel
SPBusinessDataCatalogPartition
Remove-SPBusinessDataCatalogPartition
SPBusinessDataCatalogPartitionData
Clear-SPBusinessDataCatalogPartitionData
Export-SPBusinessDataCatalogPartitionData
Import-SPBusinessDataCatalogPartitionData
SPBusinessDataCatalogServiceApplication
New-SPBusinessDataCatalogServiceApplication
Set-SPBusinessDataCatalogServiceApplication
SPBusinessDataCatalogServiceApplicationProxy
New-SPBusinessDataCatalogServiceApplicationProxy
SPBusinessDataCatalogThrottleConfig
Get-SPBusinessDataCatalogThrottleConfig
Remove-SPBusinessDataCatalogThrottleConfig
Set-SPBusinessDataCatalogThrottleConfig
SPCentralAdministration
New-SPCentralAdministration – Creates a new Central Administration Web application.
Set-SPCentralAdministration
SPCertificate
Get-SPCertificate
New-SPCertificate
Remove-SPCertificate
SPCertificateStore
Get-SPCertificateStore
SPClaimMapping
Add-SPClaimMapping
New-SPClaimMapping
Remove-SPClaimMapping
SPClaimProviderManager
Get-SPClaimProviderManager
SPClaimsObject
New-SPClaimsObject
SPClaimsPrincipal
New-SPClaimsPrincipal
SPConfigurationDatabase
Backup-SPConfigurationDatabase – Performs a configuration only backup.
Connect-SPConfigurationDatabase – Connects the computer to an existing configuration database.
Disconnect-SPConfigurationDatabase
New-SPConfigurationDatabase – Creates a new configuration database.
Remove-SPConfigurationDatabase – Permanently removes the specified configuration database.
SPContentDatabase
Check-SPContentDatabase
Dismount-SPContentDatabase
Get-SPContentDatabase
Initialize-SPContentDatabase
Mount-SPContentDatabase
New-SPContentDatabase
Remove-SPContentDatabase
Set-SPContentDatabase
Upgrade-SPContentDatabase
SPContentDeploymentJob
Get-SPContentDeploymentJob
New-SPContentDeploymentJob
Remove-SPContentDeploymentJob
Set-SPContentDeploymentJob
Start-SPContentDeploymentJob
SPContentDeploymentPath
Get-SPContentDeploymentPath
New-SPContentDeploymentPath
Remove-SPContentDeploymentPath
Set-SPContentDeploymentPath
SPCustomLayoutsPage
Get-SPCustomLayoutsPage
Set-SPCustomLayoutsPage
SPDatabase
Get-SPDatabase – Retrieves all properties of a database.
SPDataConnectionFile
Get-SPDataConnectionFile – Returns a data connection file or a collection of data connection files.
Install-SPDataConnectionFile – Installs the provided data connection file.
Set-SPDataConnectionFile – Sets properties of a data connection file.
Uninstall-SPDataConnectionFile – Removes a data connection file.
SPDataConnectionFileDependent
Get-SPDataConnectionFileDependent – Returns administrator deployed form templates on the server dependent on a Universal Data Connection (UDC).
SPDesignerSettings
Get-SPDesignerSettings
Set-SPDesignerSettings
SPDiagnosticConfig
Get-SPDiagnosticConfig
Set-SPDiagnosticConfig
SPDiagnosticsProvider
Get-SPDiagnosticsProvider
Set-SPDiagnosticsProvider
SPediscoveryHub
Set-SPediscoveryHub
SPEdiscoveryHubSearchScope
Get-SPEdiscoveryHubSearchScope
SPediscoveryHubSite
Get-SPediscoveryHubSite
SPEnterpriseSearchAdministrationComponent
Get-SPEnterpriseSearchAdministrationComponent – Returns the administration component for a shared search application.
Set-SPEnterpriseSearchAdministrationComponent – Sets properties of an administration component for a shared search application.
SPEnterpriseSearchCrawlComponent
Get-SPEnterpriseSearchCrawlComponent – Returns a crawl component for a shared search application.
New-SPEnterpriseSearchCrawlComponent – Creates a crawl component for a shared search application.
Remove-SPEnterpriseSearchCrawlComponent – Deletes a crawl component from a shared search application.
SPEnterpriseSearchCrawlContentSource
Get-SPEnterpriseSearchCrawlContentSource – Returns a crawl content source.
New-SPEnterpriseSearchCrawlContentSource – Creates a new crawl content source for a shared search application.
Remove-SPEnterpriseSearchCrawlContentSource – Deletes a specified crawl content source from a search application.
Set-SPEnterpriseSearchCrawlContentSource – Sets the properties of a crawl content source for a shared search application.
SPEnterpriseSearchCrawlCustomConnector
Get-SPEnterpriseSearchCrawlCustomConnector
New-SPEnterpriseSearchCrawlCustomConnector
Remove-SPEnterpriseSearchCrawlCustomConnector
SPEnterpriseSearchCrawlDatabase
Get-SPEnterpriseSearchCrawlDatabase – Returns a crawl store.
New-SPEnterpriseSearchCrawlDatabase – Adds a crawl store to a shared search application.
Remove-SPEnterpriseSearchCrawlDatabase – Deletes a content crawl store.
Set-SPEnterpriseSearchCrawlDatabase
SPEnterpriseSearchCrawlExtension
Get-SPEnterpriseSearchCrawlExtension – Returns the extension rule for the extension collection.
New-SPEnterpriseSearchCrawlExtension – Adds an extension rule to a shared search application.
Remove-SPEnterpriseSearchCrawlExtension – Removes a file name extension from the list of files that can be crawled.
SPEnterpriseSearchCrawlMapping
Get-SPEnterpriseSearchCrawlMapping – Returns a crawl mapping for the search application.
New-SPEnterpriseSearchCrawlMapping – Creates a crawl mapping rule for a shared search application.
Remove-SPEnterpriseSearchCrawlMapping – Deletes a crawl mapping.
SPEnterpriseSearchCrawlRule
Get-SPEnterpriseSearchCrawlRule – Output an CrawlRule Object.
New-SPEnterpriseSearchCrawlRule – Output an CrawlRule Object.
Remove-SPEnterpriseSearchCrawlRule – Output an CrawlRule Object.
Set-SPEnterpriseSearchCrawlRule – Output an CrawlRule Object.
SPEnterpriseSearchCrawlTopology
Get-SPEnterpriseSearchCrawlTopology – Returns a crawl topology.
New-SPEnterpriseSearchCrawlTopology – Adds a crawl topology to a shared search application.
Remove-SPEnterpriseSearchCrawlTopology – Deletes a crawl topology.
Set-SPEnterpriseSearchCrawlTopology – Sets the properties of a crawl topology on a shared search application.
SPEnterpriseSearchExtendedClickThroughExtractorJobDefinition
Get-SPEnterpriseSearchExtendedClickThroughExtractorJobDefinition
SPEnterpriseSearchExtendedConnectorProperty
Get-SPEnterpriseSearchExtendedConnectorProperty
Set-SPEnterpriseSearchExtendedConnectorProperty
SPEnterpriseSearchExtendedQueryProperty
Get-SPEnterpriseSearchExtendedQueryProperty
Set-SPEnterpriseSearchExtendedQueryProperty
SPEnterpriseSearchIndexPartition
Get-SPEnterpriseSearchIndexPartition – Returns an index partition for a query topology.
Set-SPEnterpriseSearchIndexPartition – Sets properties of an index partition for a query topology.
SPEnterpriseSearchLanguageResourcePhrase
Get-SPEnterpriseSearchLanguageResourcePhrase – Returns a language resource phrase.
New-SPEnterpriseSearchLanguageResourcePhrase – Adds a language resource phrase to a shared search application.
Remove-SPEnterpriseSearchLanguageResourcePhrase – Deletes a language resource phrase from a shared search application.
SPEnterpriseSearchManagerService
Get-SPEnterpriseSearchManagerService – Returns the search manager service.
SPEnterpriseSearchManagerServiceInstance
Get-SPEnterpriseSearchManagerServiceInstance – Returns the service manager service instance.
Start-SPEnterpriseSearchManagerServiceInstance – Starts an instance of a search manager service.
Stop-SPEnterpriseSearchManagerServiceInstance – Stops an instance of a search manager service.
SPEnterpriseSearchManagerServiceProxy
Get-SPEnterpriseSearchManagerServiceProxy – Returns the search manager service proxy.
SPEnterpriseSearchMetadataCategory
Get-SPEnterpriseSearchMetadataCategory – Returns a crawled property category.
New-SPEnterpriseSearchMetadataCategory – Adds a crawled property category to a shared search application.
Remove-SPEnterpriseSearchMetadataCategory – Deletes a crawled property category.
Set-SPEnterpriseSearchMetadataCategory – Sets properties of a crawled property category for a shared search application.
SPEnterpriseSearchMetadataCrawledProperty
Get-SPEnterpriseSearchMetadataCrawledProperty – Returns a crawled property.
New-SPEnterpriseSearchMetadataCrawledProperty – Adds a crawled property category to a shared search application.
Set-SPEnterpriseSearchMetadataCrawledProperty – Sets the properties of a metadata crawled property for a shared search application.
SPEnterpriseSearchMetadataManagedProperty
Get-SPEnterpriseSearchMetadataManagedProperty – Returns a managed property.
New-SPEnterpriseSearchMetadataManagedProperty – Adds a managed property to a shared search application.
Remove-SPEnterpriseSearchMetadataManagedProperty – Deletes a metadata managed property.
Set-SPEnterpriseSearchMetadataManagedProperty – Sets the properties of a metadata managed property.
SPEnterpriseSearchMetadataMapping
Get-SPEnterpriseSearchMetadataMapping – Returns the current state of a managed property mapping.
New-SPEnterpriseSearchMetadataMapping – Adds a managed property mapping to a shared search application.
Remove-SPEnterpriseSearchMetadataMapping – Deletes a metadata mapping from a managed property.
Set-SPEnterpriseSearchMetadataMapping – Sets the properties of a managed property mapping for a shared search application.
SPEnterpriseSearchPropertyDatabase
Get-SPEnterpriseSearchPropertyDatabase – Returns a property store.
New-SPEnterpriseSearchPropertyDatabase – Adds a new property store to a shared search application.
Remove-SPEnterpriseSearchPropertyDatabase – Deletes a property store.
Set-SPEnterpriseSearchPropertyDatabase
SPEnterpriseSearchQueryAuthority
Get-SPEnterpriseSearchQueryAuthority – Returns an authoritative page.
New-SPEnterpriseSearchQueryAuthority – Adds an authoritative page to a shared search application.
Remove-SPEnterpriseSearchQueryAuthority – Deletes an authoritative page.
Set-SPEnterpriseSearchQueryAuthority – Sets the properties of an authoritative page for a shared search application.
SPEnterpriseSearchQueryComponent
Get-SPEnterpriseSearchQueryComponent – Returns a query component.
New-SPEnterpriseSearchQueryComponent – Adds a query component to a query topology.
Remove-SPEnterpriseSearchQueryComponent – Deletes a query component.
Restart-SPEnterpriseSearchQueryComponent
Set-SPEnterpriseSearchQueryComponent
SPEnterpriseSearchQueryDemoted
Get-SPEnterpriseSearchQueryDemoted – Returns a demoted site rule.
New-SPEnterpriseSearchQueryDemoted – Adds a demoted site rule to a shared search application.
Remove-SPEnterpriseSearchQueryDemoted – Deletes a demoted site rule.
SPEnterpriseSearchQueryKeyword
Get-SPEnterpriseSearchQueryKeyword – Returns a keyword term.
New-SPEnterpriseSearchQueryKeyword – Adds a keyword term to a shared search application.
Remove-SPEnterpriseSearchQueryKeyword – Deletes a query keyword.
Set-SPEnterpriseSearchQueryKeyword – Sets the properties of a keyword term for a shared search application.
SPEnterpriseSearchQueryScope
Get-SPEnterpriseSearchQueryScope – Returns a query results scope.
New-SPEnterpriseSearchQueryScope – Adds a query results scope to a shared search application.
Remove-SPEnterpriseSearchQueryScope – Deletes a query scope.
Set-SPEnterpriseSearchQueryScope – Sets the properties of a query results scope for a shared search application.
SPEnterpriseSearchQueryScopeRule
Get-SPEnterpriseSearchQueryScopeRule – Returns a shared scope rule.
New-SPEnterpriseSearchQueryScopeRule – Adds a shared scope rule to a query scope.
Remove-SPEnterpriseSearchQueryScopeRule – Deletes query results scope rules.
Set-SPEnterpriseSearchQueryScopeRule – Sets the properties of a shared scope rule for a query scope.
SPEnterpriseSearchQuerySuggestionCandidates
Get-SPEnterpriseSearchQuerySuggestionCandidates
SPEnterpriseSearchQueryTopology
Get-SPEnterpriseSearchQueryTopology – Returns a query topology.
New-SPEnterpriseSearchQueryTopology – Adds a query topology to a shared search application.
Remove-SPEnterpriseSearchQueryTopology – Deletes a query topology.
Set-SPEnterpriseSearchQueryTopology – Sets the properties of a query topology for a shared search application.
SPEnterpriseSearchRankingModel
Get-SPEnterpriseSearchRankingModel – Returns a ranking model.
New-SPEnterpriseSearchRankingModel – Adds a ranking model to a shared search application.
Remove-SPEnterpriseSearchRankingModel – Deletes a ranking model.
Set-SPEnterpriseSearchRankingModel – Sets the properties of a ranking model for a shared search application.
SPEnterpriseSearchSecurityTrimmer
Get-SPEnterpriseSearchSecurityTrimmer – Returns a custom security trimmer.
New-SPEnterpriseSearchSecurityTrimmer – Adds a custom security trimmer to a shared search application.
Remove-SPEnterpriseSearchSecurityTrimmer – Deletes a custom security trimmer.
SPEnterpriseSearchService
Get-SPEnterpriseSearchService – Returns the search service for the farm.
Set-SPEnterpriseSearchService – Sets the properties of a search service for a farm.
SPEnterpriseSearchServiceApplication
Get-SPEnterpriseSearchServiceApplication – Returns the search service application for a farm.
New-SPEnterpriseSearchServiceApplication – Adds a search service application to a farm.
Remove-SPEnterpriseSearchServiceApplication – Deletes a search service application.
Restore-SPEnterpriseSearchServiceApplication
Set-SPEnterpriseSearchServiceApplication – Sets the properties of a search service application for a farm.
Upgrade-SPEnterpriseSearchServiceApplication
SPEnterpriseSearchServiceApplicationProxy
Get-SPEnterpriseSearchServiceApplicationProxy – Returns the search service application proxy.
New-SPEnterpriseSearchServiceApplicationProxy – Adds a site hit rule for a search application.
Remove-SPEnterpriseSearchServiceApplicationProxy – Deletes a search service application proxy.
Set-SPEnterpriseSearchServiceApplicationProxy – Sets properties of a search service application proxy.
SPEnterpriseSearchServiceInstance
Get-SPEnterpriseSearchServiceInstance – Returns the search service instance for a farm.
Set-SPEnterpriseSearchServiceInstance – Sets the properties of a search service instance.
Start-SPEnterpriseSearchServiceInstance – Starts an instance of a search service.
Stop-SPEnterpriseSearchServiceInstance – Stops an instance of a search service.
SPEnterpriseSearchSiteHitRule
Get-SPEnterpriseSearchSiteHitRule – Returns shared site hit rule.
New-SPEnterpriseSearchSiteHitRule – Output an SiteHitRule Object.
Remove-SPEnterpriseSearchSiteHitRule – Output an SiteHitRule Object.
SPEnterpriseSearchTopology
Export-SPEnterpriseSearchTopology – Saves an existing search topology.
Import-SPEnterpriseSearchTopology – Imports and activates a topology from an XML file.
SPExcelBlockedFileType
Get-SPExcelBlockedFileType
New-SPExcelBlockedFileType
Remove-SPExcelBlockedFileType
SPExcelDataConnectionLibrary
Get-SPExcelDataConnectionLibrary
New-SPExcelDataConnectionLibrary
Remove-SPExcelDataConnectionLibrary
Set-SPExcelDataConnectionLibrary
SPExcelDataProvider
Get-SPExcelDataProvider
New-SPExcelDataProvider
Remove-SPExcelDataProvider
Set-SPExcelDataProvider
SPExcelFileLocation
Get-SPExcelFileLocation
New-SPExcelFileLocation
Remove-SPExcelFileLocation
Set-SPExcelFileLocation
SPExcelServiceApplication
Get-SPExcelServiceApplication – Gets an {Excel Service} application object.
New-SPExcelServiceApplication –
Set-SPExcelServiceApplication – Sets a global property for an {Excel Services} application.
SPExcelUserDefinedFunction
Get-SPExcelUserDefinedFunction
New-SPExcelUserDefinedFunction
Remove-SPExcelUserDefinedFunction
Set-SPExcelUserDefinedFunction
SPFarm
Backup-SPFarm – Creates a backup of an individual database, Web application, or the entire farm.
Get-SPFarm – Returns the local SharePoint farm.
Restore-SPFarm
SPFarmConfig
Get-SPFarmConfig
Set-SPFarmConfig
SPFarmEncryptionKey
Update-SPFarmEncryptionKey – Changes the farm encryption key to a new value and re-encrypts all data currently encrypted with the current farm encryption key with the new one.
SPFeature
Disable-SPFeature – Disables an installed feature at a given scope.
Enable-SPFeature – Enables an installed feature at the given scope.
Get-SPFeature – Returns the features based on a give scope.
Install-SPFeature – Install a feature using the Feature.xml file.
Uninstall-SPFeature – Uninstalls an installed feature definition.
SPFeatureSet
Get-SPFeatureSet
New-SPFeatureSet
Remove-SPFeatureSet
SPFeatureSetMember
Add-SPFeatureSetMember
Remove-SPFeatureSetMember
SPHelpCollection
Get-SPHelpCollection
Install-SPHelpCollection – Install the provided help collection files.
Uninstall-SPHelpCollection
SPIdentityProvider
Get-SPIdentityProvider
New-SPIdentityProvider
Remove-SPIdentityProvider
Set-SPIdentityProvider
SPIisWebServiceApplicationPool
Get-SPIisWebServiceApplicationPool – Returns the specified Internet Information Services (IIS) Application pool.
New-SPIisWebServiceApplicationPool – Creates a new Web service application pool.
Remove-SPIisWebServiceApplicationPool – Completely deletes the specified Web service application pool.
Set-SPIisWebServiceApplicationPool – Changes the account used for the Identity of the specified application pool.
SPIisWebServiceSettings
Get-SPIisWebServiceSettings – Returns the common Web Service settings.
Set-SPIisWebServiceSettings – Configures one or more common settings for all Web services.
SPInfoPathAdministrationFiles
Export-SPInfoPathAdministrationFiles – Saves form templates on the SharePoint Central Administration Web site and UDCX files to a CAB file.
Import-SPInfoPathAdministrationFiles – Imports form templates and UDCX files located on the SharePoint Central Administration Web site.
SPInfoPathFormsService
Get-SPInfoPathFormsService – Returns the forms service settings in the farm.
Set-SPInfoPathFormsService – Sets paramaters for the InfoPath Forms Services.
SPInfoPathFormTemplate
Disable-SPInfoPathFormTemplate – Deactivate a form template from the specified site collection.
Enable-SPInfoPathFormTemplate – Activates a form template in the specified site collection.
Get-SPInfoPathFormTemplate – Returns an InfoPath form template.
Install-SPInfoPathFormTemplate – Installs an InfoPath form template on a farm.
Set-SPInfoPathFormTemplate – Sets properties of an InfoPath form template.
Start-SPInfoPathFormTemplate – Unquieces an InfoPath form template on a farm after an upgrade.
Stop-SPInfoPathFormTemplate – Disables an InfoPath form template on a farm before an upgrade.
Test-SPInfoPathFormTemplate – Validates that a form template can be browser-enabled.
Uninstall-SPInfoPathFormTemplate – Removes a form template from a farm.
Update-SPInfoPathFormTemplate – Upgrades all forms templates on the farm.
SPInfoPathUrl
Update-SPInfoPathUrl – Executes InfoPath XSN/UDC fix-up on SharePoint Services.
SPInfoPathUserAgent
Add-SPInfoPathUserAgent – Adds a user agent to a farm.
Get-SPInfoPathUserAgent – Returns a user agent or all the currently defined user agents for the farm.
Remove-SPInfoPathUserAgent – Removes a user agent.
SPInfoPathWebServiceProxy
Get-SPInfoPathWebServiceProxy – Returns the Web proxy settings for the Web application.
Set-SPInfoPathWebServiceProxy – Sets parameters for an existing SharePoint Web service application.
SPLogEvent
Get-SPLogEvent
SPLogFile
Merge-SPLogFile
New-SPLogFile
SPLogLevel
Clear-SPLogLevel
Get-SPLogLevel
Set-SPLogLevel
SPManagedAccount
Get-SPManagedAccount – Retrieves accounts registered in configuration database.
New-SPManagedAccount – Registers a new managed account.
Remove-SPManagedAccount – Removes a managed account from the farm.
Set-SPManagedAccount – Configures the managed account.
SPManagedPath
Get-SPManagedPath – Returns all managed paths that match the given criteria.
New-SPManagedPath – Creates a new managed path for the given Web application for all host header site collections.
Remove-SPManagedPath – Deletes the specified managed path from the specified host header or Web application.
SPMetadataServiceApplication
Get-SPMetadataServiceApplication – Get a MetadataWebServiceApplication instance
New-SPMetadataServiceApplication – Create a Metadata Shared Service Application
Set-SPMetadataServiceApplication – Set properties on a Metadata Shared Service Application
SPMetadataServiceApplicationProxy
Get-SPMetadataServiceApplicationProxy – Get a MetadataWebServiceApplicationProxy instance
New-SPMetadataServiceApplicationProxy – Create proxy for remote or local Metadata shared service application
Set-SPMetadataServiceApplicationProxy – Update metadata proxy settings
SPMetadataWebServicePartitionData
Clear-SPMetadataWebServicePartitionData
Export-SPMetadataWebServicePartitionData
Import-SPMetadataWebServicePartitionData
SPMobileMessagingAccount
Get-SPMobileMessagingAccount – Retrieves mobile messaging accounts for the specified Web application.
Set-SPMobileMessagingAccount – Configures the specified mobile messaging account.
SPObaSolutionPackage
New-SPObaSolutionPackage
SPObjectSecurity
Get-SPObjectSecurity – Returns the security information for the specified service application.
SPParentFarmTrust
Get-SPParentFarmTrust
New-SPParentFarmTrust
Remove-SPParentFarmTrust
Set-SPParentFarmTrust
SPPassPhrase
Set-SPPassPhrase – Sets the Passphrase to a new value.
SPProcessAccount
Get-SPProcessAccount
SPProduct
Get-SPProduct – Returns a list of the SharePoint related products installed in the farm and the versions of all updates installed for each of them.
SPProfileServiceApplication
New-SPProfileServiceApplication
Set-SPProfileServiceApplication
SPProfileServiceApplicationProxy
New-SPProfileServiceApplicationProxy
Set-SPProfileServiceApplicationProxy
SPProfileServiceApplicationTenant
Add-SPProfileServiceApplicationTenant
Export-SPProfileServiceApplicationTenant
Import-SPProfileServiceApplicationTenant
Remove-SPProfileServiceApplicationTenant
Set-SPProfileServiceApplicationTenant
SPResourceSecurity
Initialize-SPResourceSecurity
SPSearchService
Get-SPSearchService – Returns a search service.
Set-SPSearchService – Sets properties of a search service.
SPSearchServiceInstance
Get-SPSearchServiceInstance – Returns an instance of a search service.
Set-SPSearchServiceInstance – Sets properties of a search service instance.
SPSecureStoreApplication
Get-SPSecureStoreApplication
New-SPSecureStoreApplication
Remove-SPSecureStoreApplication
Set-SPSecureStoreApplication
SPSecureStoreApplicationField
New-SPSecureStoreApplicationField
SPSecureStoreApplicationServerKey
Update-SPSecureStoreApplicationServerKey
SPSecureStoreCredentialMapping
Clear-SPSecureStoreCredentialMapping
Update-SPSecureStoreCredentialMapping
SPSecureStoreGroupCredentialMapping
Update-SPSecureStoreGroupCredentialMapping
SPSecureStoreMasterKey
Update-SPSecureStoreMasterKey
SPSecureStoreServiceApplication
New-SPSecureStoreServiceApplication
Set-SPSecureStoreServiceApplication
SPSecureStoreServiceApplicationProxy
New-SPSecureStoreServiceApplicationProxy
SPSecureStoreTargetApplication
New-SPSecureStoreTargetApplication
SPSecurityTokenService
Get-SPSecurityTokenService
SPServer
Get-SPServer – Returns the server(s) in the farm that match the given identity.
Rename-SPServer – Renames a server that is currently connected to the farm.
SPServiceApplication
Get-SPServiceApplication – Return the specified service application.
Grant-SPServiceApplication – Grants a user account access to the Service Application.
Publish-SPServiceApplication – Share the specified local Service Application outside the farm.
Remove-SPServiceApplication – Deletes the specified service application on the local server.
Revoke-SPServiceApplication – Revokes a user’s access to a service application.
Set-SPServiceApplication
Unpublish-SPServiceApplication – Stop sharing the specified service application outside the farm.
SPServiceApplicationProxy
Get-SPServiceApplicationProxy – Returns an instance of the specified Service Application Proxy.
Remove-SPServiceApplicationProxy – Delete the specified service application proxy.
SPServiceApplicationProxyGroup
Get-SPServiceApplicationProxyGroup – Returns the proxy group for the specified service application.
New-SPServiceApplicationProxyGroup – Creates a new service application proxy group.
Remove-SPServiceApplicationProxyGroup – Completely deletes the specified service application proxy group.
SPServiceApplicationProxyGroupMember
Add-SPServiceApplicationProxyGroupMember – Adds a member to the service application proxy group.
Remove-SPServiceApplicationProxyGroupMember – Removes one or more proxies from the specified service application proxy group.
SPServiceContext
Get-SPServiceContext
SPServiceEndpoint
Get-SPServiceEndpoint
Set-SPServiceEndpoint
SPServiceInstance
Get-SPServiceInstance – Returns the services instance for a specific server or the farm.
Start-SPServiceInstance – Starts the Service Instance for a Service on a specific server or the farm.
Stop-SPServiceInstance – Stops the Service Instance for a Service.
SPSessionStateService
Disable-SPSessionStateService
Enable-SPSessionStateService
Get-SPSessionStateService
Set-SPSessionStateService
SPSharedServiceApplicationInfo
Receive-SPSharedServiceApplicationInfo
SPSingleSignOn
Disable-SPSingleSignOn – Disables the SharePoint Single Sign On service
SPSingleSignOnDatabase
Upgrade-SPSingleSignOnDatabase – Upgrades the SSO 12 data to a Secure Store database
SPSite
Backup-SPSite – Performs a backup of a site collection.
Get-SPSite – Returns all site collections that match the given criteria.
New-SPSite – Creates a new site collection at the specified URL.
Remove-SPSite – Completely deletes an existing site collection and all sub-sites.
Restore-SPSite – Restores a site collection.
Set-SPSite – Configures the specified sites.
SPSiteAdministration
Get-SPSiteAdministration – Returns a site administration object which allows a farm administrator to view certain information about site collections they may not have access to.
Set-SPSiteAdministration – Allows farm administrators to configure any site collection.
SPSiteSubscription
Get-SPSiteSubscription – Returns the site subscription for the given URL or all site subscriptions in the local farm.
New-SPSiteSubscription – Creates a new site subscription.
Remove-SPSiteSubscription – Removes a site subscription along with all contained site collections and settings.
SPSiteSubscriptionConfig
Get-SPSiteSubscriptionConfig
Set-SPSiteSubscriptionConfig
SPSiteSubscriptionMetadataConfig
Get-SPSiteSubscriptionMetadataConfig
Remove-SPSiteSubscriptionMetadataConfig
Set-SPSiteSubscriptionMetadataConfig
SPSiteSubscriptionSettings
Export-SPSiteSubscriptionSettings
Import-SPSiteSubscriptionSettings
Remove-SPSiteSubscriptionSettings
SPSolution
Add-SPSolution
Get-SPSolution
Install-SPSolution
Remove-SPSolution
Uninstall-SPSolution
Update-SPSolution
SPSolutionDeploymentLock
Remove-SPSolutionDeploymentLock
SPStateServiceApplication
Get-SPStateServiceApplication
New-SPStateServiceApplication
Set-SPStateServiceApplication
SPStateServiceApplicationProxy
Get-SPStateServiceApplicationProxy
New-SPStateServiceApplicationProxy
Set-SPStateServiceApplicationProxy
SPStateServiceDatabase
Dismount-SPStateServiceDatabase
Get-SPStateServiceDatabase
Initialize-SPStateServiceDatabase
Mount-SPStateServiceDatabase
New-SPStateServiceDatabase
Remove-SPStateServiceDatabase
Resume-SPStateServiceDatabase
Set-SPStateServiceDatabase
Suspend-SPStateServiceDatabase
SPSubscriptionSettingsServiceApplication
New-SPSubscriptionSettingsServiceApplication
Set-SPSubscriptionSettingsServiceApplication
SPSubscriptionSettingsServiceApplicationProxy
New-SPSubscriptionSettingsServiceApplicationProxy
SPTaxonomySession
Get-SPTaxonomySession – Get a TaxonomySession instance
SPTimerJob
Disable-SPTimerJob
Enable-SPTimerJob
Get-SPTimerJob
Set-SPTimerJob
Start-SPTimerJob
SPTopologyWebServiceApplication
Get-SPTopologyWebServiceApplication
Set-SPTopologyWebServiceApplication
SPTopologyWebServiceProxy
Get-SPTopologyWebServiceProxy
Set-SPTopologyWebServiceProxy
SPUsageApplication
Get-SPUsageApplication
New-SPUsageApplication
Remove-SPUsageApplication
Set-SPUsageApplication
SPUsageDefinition
Get-SPUsageDefinition
Set-SPUsageDefinition
SPUsageLogFile
New-SPUsageLogFile
SPUsageService
Get-SPUsageService
Set-SPUsageService
SPUser
Get-SPUser – Returns the user(s) that match a given search criteria.
Move-SPUser – Migrates a user account in .
New-SPUser – Adds an existing user to a site with the designated permissions.
Remove-SPUser – Removes a user from a web site.
Set-SPUser – Configures properties on an existing user.
SPUserProfilePhotoStore
Update-SPUserProfilePhotoStore
SPUserSolution
Add-SPUserSolution
Get-SPUserSolution
Install-SPUserSolution
Remove-SPUserSolution
Uninstall-SPUserSolution
Update-SPUserSolution
SPVisioExternalData
Get-SPVisioExternalData – Returns the settings for external data connections for a Visio Service application.
Set-SPVisioExternalData
SPVisioPerformance
Get-SPVisioPerformance – Returns the Visio Graphics Services settings for the performance of a Visio Service application.
Set-SPVisioPerformance – Sets performance properties for a Visio Services application.
SPVisioSafeDataProvider
Get-SPVisioSafeDataProvider – Returns the settings of a safe data provider for a Visio Services application.
New-SPVisioSafeDataProvider – Adds a new data provider to a Visio Services application.
Remove-SPVisioSafeDataProvider – Removes a data provider from a Visio Services application.
Set-SPVisioSafeDataProvider – Specifies a description of a safe data provider for a Visio Services application.
SPVisioServiceApplication
Get-SPVisioServiceApplication – Returns properties of a Visio Services application or a collection of Visio Services applications.
New-SPVisioServiceApplication – Adds a new Visio Services application to a farm.
Remove-SPVisioServiceApplication – Removes a Visio Services application from a farm.
Set-SPVisioServiceApplication – Sets the ServiceApplicationPool property of a Visio Services application.
SPVisioServiceApplicationProxy
Get-SPVisioServiceApplicationProxy – Returns properties of a Visio Services application proxy or a collection of Visio Services application proxies.
New-SPVisioServiceApplicationProxy – Adds a new Visio Services application proxy to a farm.
Remove-SPVisioServiceApplicationProxy – Removes a Visio Services application proxy from a farm.
SPWeb
Export-SPWeb – Exports a site collection, Web application, list, or library.
Get-SPWeb – Returns all sub-sites that match the given criteria.
Import-SPWeb – Imports a site collection, Web application, list, or library.
New-SPWeb – Creates a new sub-site under any existing site collection.
Remove-SPWeb – Completely deletes the specified Web.
Set-SPWeb – Configures the specified sub-site.
SPWebAnalyticsServiceApplication
Get-SPWebAnalyticsServiceApplication – Returns the settings for a Web Analytics Service application.
New-SPWebAnalyticsServiceApplication – Adds a new Web Analytics Service application to the farm.
Set-SPWebAnalyticsServiceApplication – Sets properties of a Web Analytics Service application.
SPWebAnalyticsServiceApplicationProxy
New-SPWebAnalyticsServiceApplicationProxy – Adds a new Web Analytics Service application proxy to the farm.
SPWebApplication
Get-SPWebApplication – Returns all Web applications that match the given criteria.
New-SPWebApplication – Creates a new Web application within the local farm.
Remove-SPWebApplication – Deletes the specified Web application.
Set-SPWebApplication – Configure the specified Web application.
SPWebApplicationExtension
New-SPWebApplicationExtension – Creates a new zone instance for the Web application.
SPWebApplicationHttpThrottling
Disable-SPWebApplicationHttpThrottling
Enable-SPWebApplicationHttpThrottling
SPWebApplicationHttpThrottlingMonitor
Set-SPWebApplicationHttpThrottlingMonitor
SPWebApplicationHttpThrottlingMonitors
Get-SPWebApplicationHttpThrottlingMonitors
SPWebApplicationSiginRedirectUrl
Set-SPWebApplicationSiginRedirectUrl
SPWebPartPack
Get-SPWebPartPack – Return the Web part packages installed for the specified scope.
Install-SPWebPartPack – Installs the specified Web part package to the specified location.
Uninstall-SPWebPartPack – Uninstall the specified Web part package.
SPWebTemplate
Get-SPWebTemplate – Displays all globally installed site templates that match the given identity.
Install-SPWebTemplate – Installs the given site template.
Set-SPWebTemplate – Changes the title and description of an installed site template.
Uninstall-SPWebTemplate – Uninstall the given site template.
SPWordConversionServiceApplication
New-SPWordConversionServiceApplication – Creates a new service application.
Set-SPWordConversionServiceApplication – Sets parameters on a service application.
SPWordConversionServiceApplicationProxy
New-SPWordConversionServiceApplicationProxy – Creates a new service application proxy.
SPWorkflowConfig
Get-SPWorkflowConfig – Returns workflow settings for the specified Web application.
Set-SPWorkflowConfig – Configures the workflow settings for the specified Web application.

SharePoint 2010 Client object Model With Example.

May 2, 2013

 

The Client Object Model (OM) is a new programming interface for SharePoint 2010 where code runs on a user’s client machine against a local object model and interacts with data on the SharePoint Server. Client OM methods can be called from JavaScript, .NET code or Silverlight code and makes building rich client applications for SharePoint easy. One API to rule them all – Yep, whether its WPF or Windows Forms or Silverlight or Javascript – your code uses Client Object Model to interact with the SharePoint site to access the data. Now, there is something common that everybody can use instead of creating their own wrapper services to access SharePoint data!
DLL used.
1.        Microsoft.SharePoint.Client
2.        Microsoft.SharePoint.Client.Runtime
DLL Path:
Path: C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI\
Create new window application and include give the ref. to above mentioned file. The following code I explain the different-2 ways to fetching the data using SharePoint2010 Client model.
To fetching the data using Client object model we have to create the client context using the ClientContext(@”http://home:8082&#8243;);. ClientContext(@”http://home:8082&#8243;) takes the URL of the site as constructor.
The bettor approach fetch the data you needs.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.SharePoint.Client;
namespace ClientObMO
{
    public partial class UserControl1 : UserControl
    {
        public UserControl1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            //GettextPass1();
            //GetLambdaexvalues();
            // GetLambdaexForUpdatevalues();
            //GetvalueswithIqueryable();
            GetvalueswithIEnumerable();
        }
        // simple way
        public void GettextPass1()
        {
            //var ctx = new ClientContext(@”http://home:8082&#8243;);
            var newtcx = new ClientContext(@”http://home:8082&#8243;);
           // get the context of the web
            var web = newtcx.Web;
            List _List = web.Lists.GetByTitle(“Site Pages”);
            /// only load the list
            ///
            ///this will only load the list and it’s property  you will not able to read the other values
            newtcx.Load(_List);
            //
            newtcx.ExecuteQuery();
            var title = _List.Title;
            var dis = _List.Description;
            MessageBox.Show(“Title:” + title + ” desc:” + dis);
        }
        // Lambda Ex.
        public void GetLambdaexvalues()
        {
            var newtcx = new ClientContext(@”http://home:8082&#8243;);
            var web = newtcx.Web;
            // only get the title and discription  the values you want
            // rest of the values you will get error.
            newtcx.Load(web, X => X.Title, X => X.Description);
            newtcx.ExecuteQuery();
            var title = web.Title;
            var dis = web.Description;
            // following line give error becuase the value not load in lambda ex.
            //var content = web.ContentTypes;
            MessageBox.Show(“Title:” + title + ” desc:” + dis);
        }
        // Lambda Ex with update
        public void GetLambdaexForUpdatevalues()
        {
            var newtcx = new ClientContext(@”http://home:8082&#8243;);
            var web = newtcx.Web;
            newtcx.Load(web, X => X.Title, X => X.Description);
            newtcx.ExecuteQuery();
            var title = web.Title;
            var dis = web.Description;
            // give error for getiing the values
            // MessageBox.Show(web.QuickLaunchEnabled.ToString());
            web.QuickLaunchEnabled = true;
            web.Update();
            newtcx.ExecuteQuery();
            MessageBox.Show(“Title:” + title + ” desc:” + dis);
        }
        // load the data Using  IQueryable
        public void GetvalueswithIQueryable()
        {
            var newtcx = new ClientContext(@”http://home:8082&#8243;);
            var web = newtcx.Web;
            var lists = web.Lists;
            newtcx.Load(
             lists,
             list => list
                 .Include(
                     x => x.Title,
                     x => x.Hidden)
                 .Where(x => x.BaseType == BaseType.GenericList)
              );
            newtcx.ExecuteQuery();
            string str = “\n”;
            foreach (var item in lists)
            {
                str =    str + item.Title + “\n”;
            }
            MessageBox.Show(str);
        }
        // get values with using IEnumerable
        public void GetvalueswithIEnumerable()
        {
            var newtcx = new ClientContext(@”http://home:8082&#8243;);
            var web = newtcx.Web;
            var lists = web.Lists;
            IEnumerable<List> _list = newtcx.LoadQuery(lists.Where(x => x.BaseType ==BaseType.GenericList));
            newtcx.ExecuteQuery();
            string str = “\n”;
            foreach (var item in _list)
            {
                str = str + item.Title + “\n”;
            }
            MessageBox.Show(str);
        }
    }
}

 

SharePoint 2010 Client Object model

May 2, 2013

Client Object model

http://msdn.microsoft.com/en-us/library/ee857094(office.14).aspx

The SharePoint 2010 Client Object Model is a very cool feature of SharePoint 2010 Foundation Server that enables developers to write applications that access SharePoint data from a .NET application running on a client computer, from a Silverlight application, and from JavaScript running client-side in a SharePoint web part.  The client object model enables this without requiring the developer to write or install code on the SharePoint server.  The client object model makes it possible to build new categories of applications that integrate with Microsoft SharePoint Foundation 2010, including writing .NET applications, rich interactive web parts, and Silverlight applications.

I’ve written an MSDN article, Using the SharePoint 2010 Managed Client Object Model, that provides the basics on using the Client Object Model.  Many thanks to Michael Cheng of the client object model team for technically reviewing the article, and providing me with many suggestions that improved it.

The article Using the SharePoint 2010 Client Object Model with the Open XML SDK 2.0provides additional information around uploading and downloading files from a document library, as well as examples that modify Open XML documents using the Open XML SDK.

Using the SharePoint Foundation 2010 Managed Client Object Model

SharePoint 2010

 

Contents

Overview

With the SharePoint Foundation 2010 managed client object model, you can design client applications that access SharePoint content without installing code on the server that runs Microsoft SharePoint Foundation 2010. For example, you can build new categories of applications that include writing applications that are based on the Microsoft .NET Framework, rich interactive Web Parts, Microsoft Silverlight applications, and ECMAScript (JavaScript, JScript) applications that run client-side in a SharePoint Web Part. For example:

  • A team leader creates a SharePoint site that has many lists that are required to manage her team’s mission. She wants to change these lists in an ad-hoc manner—perhaps updating assignments and estimates based on an Open XML spreadsheet, or moving items from one SharePoint list to another. She wants to write a small custom application to help her manage this.
  • A software company that sells a traditional rich client application wants to integrate SharePoint document libraries and lists into their application, and they want this integration to be seamless, or even invisible to their users.
  • A SharePoint developer wants to build a rich Web Part for a SharePoint deployment that brings list content into their custom AJAX web code. He also wants to build an even richer Silverlight application that does the same thing.

What do these people have in common? They can use the SharePoint Foundation 2010 managed client object model to achieve their goals. The SharePoint Foundation 2010 managed client object model lets you write client-side code to work with all the common objects in SharePoint sites. Through the object model, you can add and remove lists, add, update, and delete list items, change documents in document libraries, create sites, manage permissions of items, and add and remove Web Parts from a page.
Previously, there were few options. You could use Web services to interact with SharePoint lists and other features, but this was challenging. If the Web services did not provide the necessary capabilities, you could write server-side code to provide a new Web service (an even more difficult task). Some IT departments disallow server-side code, or allow only code that is written by the IT department so that sometimes that was not an option. The SharePoint Foundation 2010 managed client object model enables new kinds of applications and makes it easier to write client-side code that interacts with SharePoint content.

Using the SharePoint Foundation 2010 Managed Client Object Model

To use the SharePoint Foundation 2010 managed client object model (client object model), you write managed code based on the .NET Framework that uses an API that resembles the object model that is used on a server that is running SharePoint Foundation. The client object model has classes for accessing site collection information, site information, and list and list item information.
In the case of Web Parts, you use an ECMAScript (JavaScript, JScript) programming interface that resembles the .NET Framework API. For Silverlight, you use a subset of the API that is available through the .NET Framework on the client. Although much of the information that is presented in this article is relevant to the JavaScript and Silverlight APIs, this article focuses primarily about how to use the SharePoint Foundation 2010 managed client object model from a client application that is based on the .NET Framework.
The SharePoint Foundation 2010 managed client object model consists of two assemblies that contain five namespaces. If you look at the classes available in those namespaces, you see many classes. Do not worry; many of those classes are used internally by the object model. You are interested only in a subset of them, primarily classes that have direct counterparts to some familiar classes in the SharePoint Foundation server object model.

Table 1. Client-side classes and server-side equivalents

Client

Server

ClientContext SPContext
Site SPSite
Web SPWeb
List SPList
ListItem SPListItem
Field SPField

Notice that the SharePoint Foundation 2010 managed client object model uses the same legacy naming pattern for site collections and sites as the server object model. The Site class represents site collections, and the Web class represents sites. My preference for using these classes is to name the variables so that the variable name indicates whether it is a site collection or a site, even though you must use the Site and Web classes to declare them.
The following example shows how I name variables.

C#

Copy

ClientContext clientContext = new ClientContext(siteUrl);

Site siteCollection = clientContext.Site;

Web site = clientContext.Web;

How the Client-Side Object Model Works

An application that uses SharePoint content interacts with the API in several ways—call methods and get the return values, pass a Collaborative Application Markup Language (CAML) query and get the results, and set or get properties. After you use the API to perform a specific task the SharePoint Foundation 2010 managed client object model bundles up these uses of the API into XML and sends it to the server that runs SharePoint Foundation. The server receives this request, and makes appropriate calls into the object model on the server, collects the responses, forms them into JavaScript Object Notation (JSON), and sends that JSON back to the SharePoint Foundation 2010 managed client object model. The client object model parses the JSON and presents the results to the application as .NET Framework objects (or JavaScript objects for JavaScript). The following diagram shows these interactions.

Figure 1. The SharePoint Foundation 2010 managed client object model

P1

It is important to be aware that you control when the SharePoint Foundation 2010 managed client object model starts to send the XML to the server and receives the JSON back from the server.

The bundling of multiple method calls into a single call to the server is dictated by the realities of network speed, network latency, and desired performance characteristics. If the SharePoint Foundation 2010 managed client object model interacted with the server at every method call, the performance of the system, and the increased network traffic would make the system unworkable.
As I mentioned, you explicitly control when the SharePoint Foundation 2010 managed client object model bundles method calls and sends a request to the server. As part of this process, before you start the interaction with the server, you must explicitly specify what content that you want to retrieve from the server. This is the biggest difference between the SharePoint Foundation 2010 managed client object model and the SharePoint Foundation 2010 object model. But after you understand the model, it is not challenging. The easiest way to start understanding the difference is to see a simple application.

Creating Windows Console Managed Client Object Model Applications

 Note:
I use Windows console applications for the sample code, but you can use the same approach with other application types.

To build the application, you must add references to two assemblies, Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll. Installing SharePoint Foundation installs these assemblies on the server. The two assemblies are located in the following directory:
%ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\ISAPI

 Important:
For SharePoint Foundation Beta and Microsoft SharePoint Server 2010 Beta, you must copy the two assemblies and put them in a convenient location on your development client computer. You must browse to those assemblies to add references to them when you are setting up projects that use the SharePoint Foundation 2010 managed client object model.

To build the application

  1. Start Microsoft Visual Studio 2010.
  2. On the File menu, point to New, and then click Project.
  3. In the New Project dialog box, in the Recent Template pane, expand Visual C#, and then click Windows.
  4. To the right of the Recent Template pane, click Console Application.
  5. By default, Visual Studio creates a project that targets .NET Framework 4, but you must target .NET Framework 3.5. From the list at the upper part of the File Open dialog box, select .NET Framework 3.5.
  6. In the Name box, type the name that you want to use for your project, such asFirstClientApiApplication.
  7. In the Location box, type the location where you want to place the project.P2
    Figure 2. Creating a solution in the New Project dialog box
  1. Click OK to create the solution.

To add references to the Microsoft.SharePoint.Client assembly and Microsoft.SharePoint.Client.Runtime assembly

  1. The classes that you use in a client object model application are located in Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll. As I mentioned, before you add the references, you must copy those assemblies from the server that runs SharePoint Foundation to the client development computer.
  2. On the Project menu, click Add Reference to open the Add Reference dialog box.
  3. Select the Browse tab, navigate to the location where you put the Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll. Select both DLLs, and then click OK as shown in Figure 3.P3
    Figure 3. Adding references to the assemblies

To add the sample code to the solution

  1. In Visual Studio, replace the contents of the Program.cs source file with the following code.

C#

Copy

using System;

using Microsoft.SharePoint.Client;

class DisplayWebTitle

{

static void Main()

{

ClientContext clientContext = new ClientContext(“http://intranet.contoso.com&#8221;);

Web site = clientContext.Web;

clientContext.Load(site);

clientContext.ExecuteQuery();

Console.WriteLine(“Title: {0}”, site.Title);

}

}

  1. Replace the URL in the ClientContext constructor with the URL to the SharePoint site. Build and run the solution. The example prints the title of the site.

Just as with the SharePoint Foundation server object model, you create a context for the SharePoint site that you want to access. You can then retrieve a reference to the site from the context.
The call to the ExecuteQuery method causes the SharePoint Foundation 2010 managed client object model to send the request to the server. There is no network traffic until the application calls the ExecuteQuery method.
An important point to make about this example is that the call to the Load method does not actually load anything. Instead, it informs the client object model that when the application calls the ExecuteQuery method, you want to load the property values of the siteCollection object.
This is the model that all interactions with the server take:

  1. You inform the SharePoint Foundation 2010 managed client object model about the operations that you want to take. This includes accessing the values of properties of objects (for example, objects of the List class, ListItemclass, and Web class), CAML queries that you want to run, and objects such as ListItem objects that you want to insert, update or delete.
  2. Then you call the ExecuteQuery method. No network traffic occurs until you call the ExecuteQuery method. Until that point, your application is only registering its requests.

As you can see from this example, at its simplest, you first set up a query, and then you execute the queries. This causes the client object model to send traffic to the server and receive a response from it. This next section reviews the model in detail and shows why it is designed the way it is, and finally, how you can build applications by using the model.

Overview of the SharePoint Foundation 2010 Managed Client Object Model

There are specific aspects of the client object model that you must examine:

  • Approaches that the client object model takes to minimize network traffic
  • Query construction
  • Techniques to improve server performance
  • How to create, update, and delete client objects
  • How to work with very large lists

Before we delve into any of these subjects, let’s examine the issue of object identity.

Using Object Identities

The key idea behind object identity is that client objects refer to the corresponding in the SharePoint Foundation server object model both before and after they call theExecuteQuery method. They continue to refer to that same object through multiple calls to the ExecuteQuery method.
This means that when setting up the query, the client object model returns objects that you can use to further set up the query before you call the ExecuteQuerymethod. This lets you to write more complex queries before you start causing traffic to and from the server. You can do more interesting things in a single query, and eliminate network traffic.
The following example gets the Announcements list object, and then it retrieves all items of that list by using the simplest possible CAML query.

C#

Copy

using System;

using Microsoft.SharePoint.Client;

class Program

{

static void Main()

{

ClientContext clientContext = new ClientContext(“http://intranet.contoso.com&#8221;);

List list = clientContext.Web.Lists.GetByTitle(“Announcements”);

CamlQuery camlQuery = new CamlQuery();

camlQuery.ViewXml = “<View/>”;

ListItemCollection listItems = list.GetItems(camlQuery);

clientContext.Load(list);clientContext.Load(listItems);

clientContext.ExecuteQuery();

foreach (ListItem listItem in listItems)

Console.WriteLine(“Id: {0} Title: {1}”, listItem.Id, oListItem[“Title”]);

}

}

Notice the sequence in this example:

  1. First the code gets a List object by using the GetByTitle method. Remember, this List object has no data in it; it does not have data in any of its properties until the application calls the ExecuteQuery method.
  2. It then calls the GetItems method on the list object, even though that listobject is not populated with data.
  3. It finally calls the Load method on both the list object and listItems object, and then calls the ExecuteQuery method.

The key point about this is that the client object model remembers that the listobject is the one that the application initialized by using the GetByTitle method, and that the client object model should execute the CAML query on that same listobject after the list object is retrieved from the SharePoint database. Any class that derives from the ClientObject class has these semantics.
And, as mentioned, you can continue to use client objects to set up additional queries after you call the ExecuteQuery method. In the following example, the code loads the list object and calls the ExecuteQuery method. It then uses that list client object to call the List.GetItems method, and then calls the ExecuteQuery method again. The list object retained its identity through the call to ExecuteQuery method.

C#

Copy

using System;

using Microsoft.SharePoint.Client;

class Program

{

static void Main()

{

ClientContext clientContext =

new ClientContext(“http://intranet.contoso.com&#8221;);

List list = clientContext.Web.Lists

.GetByTitle(“Announcements”);

clientContext.Load(list);

clientContext.ExecuteQuery();

Console.WriteLine(“List Title: {0}”, list.Title);

CamlQuery camlQuery = new CamlQuery();

camlQuery.ViewXml = “<View/>”;

ListItemCollection listItems = list.GetItems(camlQuery);

clientContext.Load(listItems);

clientContext.ExecuteQuery();

foreach (ListItem listItem in listItems)

Console.WriteLine(“Id: {0} Title: {1}”,

oListItem.Id, listItem[“Title”]);

}

}

Some properties and methods return objects or value types that do not derive from the ClientObject class. You benefit from using client object identity to access methods and properties only when those methods and properties return client objects or collections of them. For instance, some classes, such as the FieldUrlValueclass and the FieldLookupValue class derive from the ClientValueObject class, and you cannot use properties that return those types until after the call to theExecuteQuery method. Some properties return .NET Framework types such as string or integer, and you also cannot use properties or methods that return those until after the call to the ExecuteQuery method. Because you cannot use the values of any properties until those values are populated in the ExecuteQuery call, you cannot, for example, find an item in a list, and use the value of one of that item’s fields to select items in an additional query. If you try to use a property before it is populated by the ExecuteQuery method, the client object model throws aPropertyOrFieldNotInitializedException exception.

 Caution:
Client object identity is valid only for a single ClientContext object. If you initialize another ClientContext object to the same SharePoint site, you cannot use client objects from one client context with the other one.

A number of later examples in this article use object identity behavior.

 Note:
This example does not do any error handling. If the Announcements list does not exist, the client object model throws an exception in the call to the ExecuteQuerymethod. You should be prepared to catch exceptions when you write code that may fail if you ask for objects that may not exist.

Trimming Result Sets

SharePoint Foundation is often deployed in organizations with many thousands of users. When building an application that accesses SharePoint Foundation over the network, it makes sense to build it so that it uses the least amount of network traffic. There are several ways that the client object model helps you do this. The simplest approach is to use lambda expressions to specify exactly which properties the client object model should return to the application.
The following example shows how to specify that when the client object model loads the site object, it must load only the Title property and Description property. This reduces the size of the JSON response from the server back to the client.

C#

Copy

using System;

using Microsoft.SharePoint.Client;

class Program

{

static void Main()

{

ClientContext clientContext =

new ClientContext(“http://intranet.contoso.com&#8221;);

Web site = clientContext.Web;

clientContext.Load(site,

s => s.Title,

s => s.Description);

clientContext.ExecuteQuery();

Console.WriteLine(“Title: {0} Description: {1}”,

site.Title, site.Description);

}

}

By default, if you do not include these lambda expressions in the call to the Loadmethod, it loads a much larger number of properties (but not them all). The first two examples called the Load method without specifying which properties to load, so that the JSON packet that the server returned was somewhat larger than it needed to be. Although in these small examples, it does not make much difference, when it loads thousands of list items, carefully specifying the required properties reduces network traffic.
Using lambda expressions, you can specify a list of properties to the Load method. Reducing network traffic is not the only benefit you derive from the client object model’s use of lambda expressions. Later on this article describes how to filter result sets using lambda expressions.
Next, I’ll show an example that creates a list and then add some content to it. This will provide sample content to work with for the rest of this article.

Creating and Populating a List

The following example creates a list, and adds some fields and several items to it.

C#

Copy

using System;

using Microsoft.SharePoint.Client;

class Program

{

static void Main()

{

ClientContext clientContext =

new ClientContext(“http://intranet.contoso.com&#8221;);

Web site = clientContext.Web;

// Create a list.

ListCreationInformation listCreationInfo =

new ListCreationInformation();

listCreationInfo.Title = “Client API Test List”;

listCreationInfo.TemplateType = (int)ListTemplateType.GenericList;

List list = site.Lists.Add(listCreationInfo);

// Add fields to the list.

Field field1 = list.Fields.AddFieldAsXml(

@”<Field Type=’Choice’

DisplayName=’Category’

Format=’Dropdown’>

<Default>Specification</Default>

<CHOICES>

<CHOICE>Specification</CHOICE>

<CHOICE>Development</CHOICE>

<CHOICE>Test</CHOICE>

<CHOICE>Documentation</CHOICE>

</CHOICES>

</Field>”,

true, AddFieldOptions.DefaultValue);

Field field2 = list.Fields.AddFieldAsXml(

@”<Field Type=’Number’

DisplayName=’Estimate’/>”,

true, AddFieldOptions.DefaultValue);

// Add some data.

ListItemCreationInformation itemCreateInfo =

new ListItemCreationInformation();

ListItem listItem = list.AddItem(itemCreateInfo);

listItem[“Title”] = “Write specs for user interface.”;

listItem[“Category”] = “Specification”;

listItem[“Estimate”] = “20”;

listItem.Update();

listItem = list.AddItem(itemCreateInfo);

listItem[“Title”] = “Develop proof-of-concept.”;

listItem[“Category”] = “Development”;

listItem[“Estimate”] = “42”;

listItem.Update();

listItem = list.AddItem(itemCreateInfo);

listItem[“Title”] = “Write test plan for user interface.”;

listItem[“Category”] = “Test”;

listItem[“Estimate”] = “16”;

listItem.Update();

listItem = list.AddItem(itemCreateInfo);

listItem[“Title”] = “Validate SharePoint interaction.”;

listItem[“Category”] = “Test”;

listItem[“Estimate”] = “18”;

listItem.Update();

listItem = list.AddItem(itemCreateInfo);

listItem[“Title”] = “Develop user interface.”;

listItem[“Category”] = “Development”;

listItem[“Estimate”] = “18”;

listItem.Update();

clientContext.ExecuteQuery();

}

}

In many cases, where you can create a client object, the application can call an Addmethod that takes as an argument an object that specifies creation information. This example shows how to use ListCreationInformation class to create a Listobject, and how to use the ListItemCreationInformation class for creating a ListItemobject. You often set properties of the creation information class after instantiating it. You can see that the code sets the Title property and TemplateType property of the ListItemCreationInformation object. Note that to create a list, you call the Addmethod, but to create a ListItem object, you call the AddItem method. The Addmethod creates a list in the collection, and the AddItem method creates a single list item.
Creating fields in a list also does not use an Add method, because, when you create fields, you are not really creating an instance of the Field class. You are creating an instance of a class that derives from the Field class. There are many options available for those derived classes, and using an Add method would significantly complicate the design of a FieldCreationInformation class. For this reason, the client object model does not include such a class. Instead, the simplest way to create a field is to specify a bit of XML that defines the field, and pass that XML to the AddFieldAsXml method. There is a Add method that you can use to create a field, but instead of taking a FieldCreationInformation object, it takes anotherField object as a parameter that it uses as a prototype for the field to be created. This is useful in some scenarios.

 Tip:
The Discovering the Schema for Fields section of this article shows you an easy way to discover the XML that you must specify for fields that you want to create.

Note that, of course, no objects are actually added to the SharePoint database until the application calls the ExecuteQuery method.
There is one more item of interest in this example. Notice that after you call theAddItem method, the example sets three indexed properties. The code is setting the values of the fields that were previously added to the list. After setting these properties, the application must call the Update method, informing the client object model that those objects were modified. The client object model does not work correctly if you do not do so. You see the Update method used in later examples, when I show how to modify existing client objects.
Now that you have some data, let us discover some interesting ways to query and change it.

Using CAML to Query Lists

The following example shows how to use CAML to query the list that you created in the last example. This example prints the Development items from our test list.

C#

Copy

using System;

using Microsoft.SharePoint.Client;

class Program

{

static void Main(string[] args)

{

ClientContext clientContext = new ClientContext(“http://intranet.contoso.com&#8221;);

List list = clientContext.Web.Lists.GetByTitle(“Client API Test List”);

CamlQuery camlQuery = new CamlQuery();

camlQuery.ViewXml =

@”<View>

<Query>

<Where>

<Eq>

<FieldRef Name=’Category’/>

<Value Type=’Text’>Development</Value>

</Eq>

</Where>

</Query>

<RowLimit>100</RowLimit>

</View>”;

ListItemCollection listItems = list.GetItems(camlQuery);

clientContext.Load(

listItems,

items => items

.Include(

item => item[“Title”],

item => item[“Category”],

item => item[“Estimate”]));

clientContext.ExecuteQuery();

foreach (ListItem listItem in listItems)

{

Console.WriteLine(“Title: {0}”, listItem[“Title”]);

Console.WriteLine(“Category: {0}”, listItem[“Category”]);

Console.WriteLine(“Estimate: {0}”, listItem[“Estimate”]);

Console.WriteLine();

}

}

}

This example produces the following output.

Copy

Title: Develop proof-of-concept.

Category: Development

Estimate: 42

Title: Develop user interface.

Category: Development

Estimate: 18

You may notice a difference between the lambda expressions that you specify in this example and the lambda expressions in the example that is presented in theTrimming Result Sets section. You must use the Include extension method to specify the properties that you want to load for each item in the collection that we load. Theitems parameter of the lambda expression is of type ListItemCollection, which of course does not contain an indexed property that allows us to specify which properties to load for items in the collection. Instead, you call the Include extension method, which enables us to specify which parameters of that child collection to load. Parameters to lambda expressions in the Include extension method are of the type of the items of the collection. Therefore, you can specify the properties that you want to load for each item in the collection.
Again, it is not completely necessary to understand the exact semantics of this use of lambda expressions. Just remember two coding idioms:
If you are requesting that the client object model load certain properties of a client object (not a collection of them), then specify the properties in the lambda expression that you add directly in the Load method.

C#

Copy

clientContext.Load(site,

s => s.Title,

s => s.Description);

If you are requesting that the client object model load certain properties of each item in a collection of client objects, use the Include extension method, and pass the lambda expressions that specify your desired properties to the Include method.

C#

Copy

clientContext.Load(

listItems,

items => items.Include(

item => item[“Title”],

item => item[“Category”],

item => item[“Estimate”]));

Filtering the Child Collection Returned by Load by Using LINQ

Because the Include extension method returns IQueryable<T>, you can chain from the Include method into the IQueryable<T>.Where extension method. This provides a succinct way to filter the result set. You should only use this capability when querying client object collections other than collections of ListItem objects, because while you could use this technique to filter collections of ListItem objects, using CAML results in better performance. This is important enough to say again:

 Caution:
Never use the IQueryable<T>.Where extension method when querying ListItemobjects. The reason is that the client object model first evaluates the result of the CAML query, retrieves the results, and then filters the resulting collection using LINQ. If you filter a very large list using LINQ instead of CAML, the client object model attempts to retrieve all items in the list before filtering with LINQ and either issues queries that require too much system resources, or the query fails. The reason is not clear unless you know how the client object model works internally. You must use CAML when querying list items.

The following example queries the client object model for all lists that are not hidden. Notice that you must include a using directive for the System.Linqnamespace.

C#

Copy

using System;

using System.Linq;

using Microsoft.SharePoint.Client;

class Program

{

static void Main(string[] args)

{

ClientContext clientContext =

new ClientContext(“http://intranet.contoso.com&#8221;);

ListCollection listCollection = clientContext.Web.Lists;

clientContext.Load(

listCollection,

lists => lists

.Include(

list => list.Title,

list => list.Hidden)

. Where(list => ! list.Hidden)

);

clientContext.ExecuteQuery();

foreach (var list in listCollection)

Console.WriteLine(list.Title);

}

}

On my server, this example produces the following output.

Copy

Announcements

Calendar

Client API Test List

Content and Structure Reports

Customized Reports

Eric’s ToDo List

Eric’s Wiki

Form Templates

Links

Reusable Content

Shared Documents

Site Assets

Site Collection Documents

Site Collection Images

Site Pages

Style Library

Tasks

Team Discussion

Workflow Tasks

Using the LoadQuery Method

The LoadQuery method is similar in functionality to the Load method, except that in certain circumstances, the client object model can process the queries more efficiently and use memory more efficiently. It also allows for a more flexible programming style.
The LoadQuery method has different semantics than the Load method. Whereas theLoad method populates the client object (or client object collection) with data from the server, the LoadQuery method populates and returns a new collection. This means that you can query the same object collection multiple times and keep separate result sets for each query. For instance, you can query for all items in a project list that are assigned to a certain person, and separately query for all items that have an estimated hours that is larger than a certain threshold, and access both result sets at the same time. It also enables you to let these collections go out of scope, and thereby become eligible for garbage collection. Collections that you load using the Load method are eligible for garbage collection only when the client context variable itself goes out of scope. Other than these differences, theLoadQuery method provides the same functionality as the Load method.
The following example uses the LoadQuery method to retrieve a list of all the lists in the site.

C#

Copy

using System;

using System.Collections.Generic;

using Microsoft.SharePoint.Client;

class Program

{

static void Main(string[] args)

{

ClientContext clientContext =

new ClientContext(“http://intranet.contoso.com&#8221;);

Web site = clientContext.Web;

ListCollection lists = site.Lists;

IEnumerable<List> newListCollection = clientContext.LoadQuery(

lists.Include(

list => list.Title,

list => list.Id,

list => list.Hidden));

clientContext.ExecuteQuery();

foreach (List list in newListCollection)

Console.WriteLine(“Title: {0} Id: {1}”,

list.Title.PadRight(40), list.Id.ToString(“D”));

}

}

Notice that the LoadQuery method returns a new list collection that you can iterate through. The new list collection has a type of IEnumerable<List> instead ofListCollection.
There is one aspect of the semantics of the LoadQuery method that you must pay attention to. In the previous example, the original lists variable does not have its property values populated after the ExecuteQuery method returns. If you want that list to be populated, you must explicitly call the Load method, specifying which properties that you want loaded.

Increasing Performance by Nesting Include Statements in LoadQuery

When calling the LoadQuery method, you can specify multiple levels of properties to load. This allows the client object model to optimize its access to the server that runs SharePoint Foundation by reducing the number of times the client object model must call to the server that runs SharePoint Foundation to retrieve the data that you want. The following query retrieves all lists from the site, and all fields from each list. It then prints them to the console and indicates if each list or field is hidden.

C#

Copy

using System;

using System.Collections.Generic;

using Microsoft.SharePoint.Client;

class Program

{

static void Main()

{

ClientContext clientContext =

new ClientContext(“http://intranet.contoso.com&#8221;);

IEnumerable<List> lists = clientContext.LoadQuery(

clientContext.Web.Lists.Include(

list => list.Title,

list => list.Hidden,

list => list.Fields.Include(

field => field.Title,

field => field.Hidden)));

clientContext.ExecuteQuery();

foreach (List list in lists)

{

Console.WriteLine(“{0}List: {1}”,

list.Hidden ? “Hidden ” : “”, list.Title);

foreach (Field field in list.Fields)

Console.WriteLine(”  {0}Field: {1}”,

field.Hidden ? “Hidden ” : “”,

field.Title);

}

}

}

This approach allows the server part of the client object model to be more efficient than if the application first loaded a list of lists, and then loaded fields for each list.

Filtering the Child Collection Returned by LoadQuery by Using LINQ

The LoadQuery method takes an object of type IQueryable<T> as its parameter, and this enables you to write LINQ queries instead of CAML to filter the results. This example returns a collection of all document libraries that are not hidden.

C#

Copy

using System;

using System.Linq;

using System.Collections.Generic;

using Microsoft.SharePoint.Client;

class Program

{

static void Main(string[] args)

{

ClientContext clientContext =

new ClientContext(“http://intranet.contoso.com&#8221;);

ListCollection listCollection = clientContext.Web.Lists;

IEnumerable<List> hiddenLists = clientContext.LoadQuery(

listCollection

. Where(list => !list.Hidden &&

list.BaseType == BaseType.DocumentLibrary));

clientContext.ExecuteQuery();

foreach (var list in hiddenLists)

Console.WriteLine(list.Title);

}

}

Updating Client Objects

Updating client objects by using the client object model is fairly simple. You retrieve the objects, alter properties, call the Update method for each object that you change, and then call the ExecuteQuery method. The following example modifies items in the Client API Test List, increasing the estimate for all development items by 50 percent (a common operation).

C#

Copy

using System;

using Microsoft.SharePoint.Client;

class Program

{

static void Main(string[] args)

{

ClientContext clientContext = new ClientContext(“http://intranet.contoso.com&#8221;);

List list = clientContext.Web.Lists.GetByTitle(“Client API Test List”);

CamlQuery camlQuery = new CamlQuery();

camlQuery.ViewXml =

@”<View>

<Query>

<Where>

<Eq>

<FieldRef Name=’Category’/>

<Value Type=’Text’>Development</Value>

</Eq>

</Where>

</Query>

<RowLimit>100</RowLimit>

</View>”;

ListItemCollection listItems = list.GetItems(camlQuery);

clientContext.Load(

listItems,

items => items.Include(

item => item[“Category”],

item => item[“Estimate”]));

clientContext.ExecuteQuery();

foreach (ListItem listItem in listItems)

{

listItem[“Estimate”] = (double)listItem[“Estimate”] * 1.5;

listItem.Update();

}

clientContext.ExecuteQuery();

}

}

Deleting Client Objects

Deleting client objects is just as easy. However, there is one very important dynamic around deleting client objects from a client object collection. You cannot iterate through the collection, deleting objects. As soon as you delete the first object, it causes the iterator of the client object collection to malfunction. The iterator may throw an exception, or it may quietly finish but not visit all items in the collection. Instead, you must materialize the collection into a List<T> using the ToList method, and then iterate through that list, deleting the client objects.
The following example deletes the test items from our Client API Test List. It shows using the ToList method to materialize the collection before you iterate through it:

C#

Copy

using System;

using System.Linq;

using System.Collections.Generic;

using Microsoft.SharePoint.Client;

class Program

{

static void Main(string[] args)

{

ClientContext clientContext = new ClientContext(“http://intranet.contoso.com&#8221;);

List list = clientContext.Web.Lists.GetByTitle(“Client API Test List”);

CamlQuery camlQuery = new CamlQuery();

camlQuery.ViewXml =

@”<View>

<Query>

<Where>

<Eq>

<FieldRef Name=’Category’/>

<Value Type=’Text’>Test</Value>

</Eq>

</Where>

</Query>

<RowLimit>100</RowLimit>

</View>”;

ListItemCollection listItems = list.GetItems(camlQuery);

clientContext.Load(

listItems,

items => items.Include(

item => item[“Title”]));

clientContext.ExecuteQuery();

foreach (ListItem listItem in listItems.ToList())

listItem.DeleteObject();

clientContext.ExecuteQuery();

}

}

The following code example shows the incorrect approach.

C#

Copy

clientContext.Load(

listItems,

items => items.Include(

item => item[“Title”]));

clientContext.ExecuteQuery();

// The ToList() method call is removed in the following line.

foreach (ListItem listItem in listItems)

listItem.DeleteObject();

clientContext.ExecuteQuery();

Finally, to clean up the Client API Test List, here is an example that deletes the list and its items.

C#

Copy

using System;

using Microsoft.SharePoint.Client;

class DisplayWebTitle

{

static void Main()

{

ClientContext clientContext =

new ClientContext(“http://intranet.contoso.com&#8221;);

clientContext.Web.Lists.GetByTitle(“Client API Test List”)

.DeleteObject();

clientContext.ExecuteQuery();

}

}

Discovering the Schema for Fields

As promised, this section shows an easy way to discover the XML schema that you use to create the fields that you want to create in a list. First, on the SharePoint site, create a list that contains columns that are configured as you want them. Then you can then use the following example to output the XML that creates those fields.
The following example prints the field schemas for the fields that I added to the Client API Test List.

C#

Copy

using System;

using System.Linq;

using System.Xml.Linq;

using Microsoft.SharePoint.Client;

class Program

{

static void Main(string[] args)

{

ClientContext clientContext =

new ClientContext(“http://intranet.contoso.com&#8221;);

List list = clientContext.Web.Lists

.GetByTitle(“Client API Test List”);

clientContext.Load(list);

FieldCollection fields = list.Fields;

clientContext.Load(fields);

clientContext.ExecuteQuery();

foreach (var f in fields)

{

XElement e = XElement.Parse(f.SchemaXml);

string name = (string)e.Attribute(“Name”);

if (name == “Category” || name == “Estimate”)

{

e.Attributes(“ID”).Remove();

e.Attributes(“SourceID”).Remove();

e.Attributes(“ColName”).Remove();

e.Attributes(“RowOrdinal”).Remove();

e.Attributes(“StaticName”).Remove();

Console.WriteLine(e);

Console.WriteLine(“===============”);

}

}

}

}

When you run this after you create the list by using the example program in the section Creating and Populating a List, it produces the following output.

XML

Copy

<Field Type=”Choice” DisplayName=”Category” Format=”Dropdown” Name=”Category”>

<Default>Specification</Default>

<CHOICES>

<CHOICE>Specification</CHOICE>

<CHOICE>Development</CHOICE>

<CHOICE>Test</CHOICE>

<CHOICE>Documentation</CHOICE>

</CHOICES>

</Field>

===============

<Field Type=”Number” DisplayName=”Estimate” Name=”Estimate” />

===============

The example removes attributes that are not required for creating the field.

Accessing Large Lists

SharePoint development guidelines indicate that you should not attempt to retrieve more than 2000 items in a single query. If this is a possibility in your application, consider using the RowLimit element in your CAML queries to limit how much data that the client object model retrieves for your application. Sometimes you must access all items in a list that may contain more than 2000 items. If you must do so, then best practice is to page through the items 2000 at a time. This section presents an approach to paging using the ListItemCollectionPosition property.

C#

Copy

using System;

using System.Linq;

using Microsoft.SharePoint.Client;

class Program

{

static void Main()

{

ClientContext clientContext =

new ClientContext(“http://intranet.contoso.com&#8221;);

List list = clientContext.Web.Lists

.GetByTitle(“Client API Test List”);

// First, add 20 items to Client API Test List so that there are

// enough records to show paging.

ListItemCreationInformation itemCreateInfo =

new ListItemCreationInformation();

for (int i = 0; i < 20; i++)

{

ListItem listItem = list.AddItem(itemCreateInfo);

listItem[“Title”] = String.Format(“New Item #{0}”, i);

listItem[“Category”] = “Development”;

listItem[“Estimate”] = i;

listItem.Update();

}

clientContext.ExecuteQuery();

// This example shows paging through the list ten items at a time.

// In a real-world scenario, you would want to limit a page to

// 2000 items.

ListItemCollectionPosition itemPosition = null;

while (true)

{

CamlQuery camlQuery = new CamlQuery();

camlQuery.ListItemCollectionPosition = itemPosition;

camlQuery.ViewXml =

@”<View>

<ViewFields>

<FieldRef Name=’Title’/>

<FieldRef Name=’Category’/>

<FieldRef Name=’Estimate’/>

</ViewFields>

<RowLimit>10</RowLimit>

</View>”;

ListItemCollection listItems = list.GetItems(camlQuery);

clientContext.Load(listItems);

clientContext.ExecuteQuery();

itemPosition = listItems.ListItemCollectionPosition;

foreach (ListItem listItem in listItems)

Console.WriteLine(”  Item Title: {0}”, listItem[“Title”]);

if (itemPosition == null)

break;

Console.WriteLine(itemPosition.PagingInfo);

Console.WriteLine();

}

}

}

This example produces the following output:

Copy

Item Title: Write specs for user interface.

Item Title: Develop proof-of-concept.

Item Title: Write test plan for user interface.

Item Title: Validate SharePoint interaction.

Item Title: Develop user interface.

Item Title: New Item #0

Item Title: New Item #1

Item Title: New Item #2

Item Title: New Item #3

Item Title: New Item #4

Paged=TRUE&p_ID=10

Item Title: New Item #5

Item Title: New Item #6

Item Title: New Item #7

Item Title: New Item #8

Item Title: New Item #9

Item Title: New Item #10

Item Title: New Item #11

Item Title: New Item #12

Item Title: New Item #13

Item Title: New Item #14

Paged=TRUE&p_ID=20

Item Title: New Item #15

Item Title: New Item #16

Item Title: New Item #17

Item Title: New Item #18

Item Title: New Item #19

Asynchronous Processing

If you are building an application that must attach to SharePoint sites that may not be available, or if you must regularly invoke queries that may take a long time, you should consider using asynchronous processing. This enables your application to continue to be responsive to your user while the query executes in a separate thread. In your main thread, you can set a timer to let you know if the query is taking longer than your desired threshold, you can keep the user posted with the status of the query, and when the query finally finishes, you can display the results.
The JavaScript version of the client object model and the Silverlight version (when it modifies the user interface) use asynchronous processing. The topic Data Retrieval Overview in the SharePoint 2010 SDK contains examples of how to use asynchronous processing using JavaScript and Silverlight.
When building a traditional application that is based on the .NET Framework, such as a Windows Forms or WPF application, you may want to use asynchronous processing. The following example uses the BeginInvoke method to execute a query asynchronously. Notice that the code passes a statement lambda expression to the BeginInvoke method, which makes it convenient to create this pattern, because the statement lambda expression can refer to automatic variables in the method that contains it. You can see that the statement lambda expression has access to the clientContext variable and the newListCollection variable. Microsoft Visual C# closures make the language function as you expect.

C#

Copy

using System;

using System.Collections.Generic;

using Microsoft.SharePoint.Client;

class Program

{

static void Main(string[] args)

{

AsynchronousAccess asynchronousAccess = new AsynchronousAccess();

asynchronousAccess.Run();

Console.WriteLine(“Before exiting Main”);

Console.WriteLine();

Console.WriteLine(“In a real application, the application can”);

Console.WriteLine(“continue to be responsive to the user.”);

Console.WriteLine();

Console.ReadKey();

}

}

class AsynchronousAccess

{

delegate void AsynchronousDelegate();

public void Run()

{

Console.WriteLine(“About to start a query that will take a long time.”);

Console.WriteLine();

ClientContext clientContext =

new ClientContext(“http://intranet.contoso.com&#8221;);

ListCollection lists = clientContext.Web.Lists;

IEnumerable<List> newListCollection = clientContext.LoadQuery(

lists.Include(

list => list.Title));

AsynchronousDelegate executeQueryAsynchronously =

new AsynchronousDelegate(clientContext.ExecuteQuery);

executeQueryAsynchronously.BeginInvoke(

arg =>

{

clientContext.ExecuteQuery();

Console.WriteLine(“Long running query completed.”);

foreach (List list in newListCollection)

Console.WriteLine(“Title: {0}”, list.Title);

}, null);

}

}

The example produces the following output.

About to start a query that will take a long time.

Before exiting Main

In a real application, the application can

continue to be responsive to the user.

Long running query completed.

Title: Announcements

Title: Cache Profiles

Title: Calendar

Title: Client API Test List

Title: Content and Structure Reports

Title: Content type publishing error log

Title: Converted Forms

Title: Customized Reports

Title: Eric’s ToDo List

Title: Eric’s Wiki

Title: Form Templates

Title: Links

SharePoint 2010 – Complete details about Client Object Model

This is the introduction to the Client Object model introduced in the SharePoint 2010. This is going to be a huge help and useful part in SharePoint 2010 for developers and makes lot of customization to the existing SharePoint system.

In eariler versions, I mean till SharePoint 2007 the code runs using the SharePoint object model to run against the server which is running SharePoint. Other than the SharePoint server object model, other way is, simply reference the web service and use that to get and manipulate data. Then what is the need of SharePoint 2010 Client object model[Cleint OM] concept?

What is Client Object Model?

Client Object Model is introduced in SharePoint 2010 which helps to developers to make things easier to develop the client side applications for SharePoint 2010. Client Object Model can run on the client machines (Where SharePoint is not installed) and communicate with the SharePoint server remotely. This is the great advantage for the SharePoint devs as they don’t have to install SharePoint for development any more.

What are the different Client OM supporting in the SharePoint 2010 API? [Client API]

  1. .NET Managed Client – Implemented in .NET CLR. I mean we use this in Web, Windows and Console applications.
  2. Silverlight Client – You can use the SharePoint objects in Silver light coding. Wow, this is going to be a huge advantage to  the Silverlight applications which can be integrated into SharePoint. Before we don’t have access to SharePoint objects inside Silverlight context.
  3. ECMAScript Client – Through javascript too, we can get context and do manipulations to SharePoint objects. Do you think it’s possible? Yes, its a brilliant way of thinking from Microsoft SharePoint team and this will help in great scenarios. Will explain later in this article.

Why Client Object Model comes into the picture? Are there any specialties of them?

The main started point to think by SharePoint team are as follows.

  1. Is it really necessary to have SharePoint installed on server for SharePoint development? – Yes, in SharePoint 2007 you have to install SharePoint on the server to write code and test it.
  2. What is the advantage of writing more web services to serve what the clients are looking for? – This is completely not a feasible solution to give or expose web services for each and every single requirement to get and manipulate data. It has plenty of limitations and if Microsoft exposes 500 web services and you didn’t find what you really need and they are just waste. Instead write whatever you want and use them.
  3. The great thinking and beautiful solution to the people who don’t allow server side coding in the SharePoint sites is ECMAscript client OM. You can create a simple javascript file and deploy into the server to get what you needed. As we know, most of the clients don’t allow server side coding but they want something to be developed. In SharePoint 2007 it’s very difficult to get this job done. But now in SP 2010 very easy.

So, these things take into high priority and makes them to come up with a great solution in the form of Client Object Model. The great advantage of it is completely looks [Syntax] like the SharePoint Object Model. So, nothing new for developers and no confusion. Infact very simple to manage and write code.

SharePoint object model syntax:

Server side syntax Client side syntax
SPContext ClientContext
SPSite Site
SPWeb Web
SPList List

Now, I believe you have understood the Client OM concept. Now, we will discuss a little bit about technical implementation.
SharePoint 2010 provides the client support files to refer the SharePoint objects and communicate with the SharePoint server. Below are the details.

ForManaged Client DLL’s needed : Microsoft.SharePoint.Client.dll, Microsoft.SharePoint.Client.Runtime.dll. Find these files in the 14/ISAPI folder. Usually, the location would be at “C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI”.
Silverlight Microsoft.SharePoint.Client.Silverlight.dll and Microsoft.SharePoint.Client.Silverlight.Runtime.dll. They find at “C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin”.
ECMAScript SP.js file – The file fund at “C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS”.

What we need to do is, add the relted file to the project references if it is Managed client or Silverlight and start using the SharePoint objects in the code. If it is ECMAScript then we just need to declare the line     ExecuteOrDelayUntilScriptLoaded(Initialize, “sp.js”); on the top of js file to use the SP object.
**Initialize is some javascript function.**
My next posts will be the examples of each client OM implementation and how to get, manipulate data for better understanding.

Working With SharePoint Data ‎(8)

Access (CRUD) data by using the Client Object Model

The purpose of this section is how to use sharepoint foundation web application from client object model.

Querying from Client-side Code : We have four ways to query to sharepoint foundation server

1. Querying from the clint object model.

2. querying from REST web service that implement ADO.Net data service framework.

3. Querying from inbuilt web services such as list web service, webs  web service etc.

4. Querying by using owssver.dll assembly

Querying from client object model:- 2 ways to query with client object model.

1. Implement CAML Query with the CAML Query class

2. Query any sharepoint foundation object that implement I<enumerable> with Linq based query.

Using the ADO.NET Data Services Framework

If your client application does not use new client object model and you only need to query on the list data. you can always use ado.net service framework to query on content database by using ADO.net data service framework.

Avoid Using SharePoint Data-Providing Web Services

Avoid Making Direct Calls to owssvr.dll

Using the SharePoint Foundation Client APIs

SharePoint 2010 Client Object Model – The new client-side object model provides remote access to the functionality of the SharePoint Foundation server-side object model. In previous releases of SharePoint Foundation, SOAP web services provided access to only a fraction of the server-side object model, but in SharePoint Foundation 2010, the client object model fills many of the gaps.

ASP.NET Web Services – The legacy web services provide remote access to a SharePoint Foundation deployment through SOAP web services.

SharePoint Foundation REST Interface – The new SharePoint Foundation REST interface exposes lists and libraries as a relational data service, and serves as a standards-based interface for interoperability with other platforms.

WCF Services in SharePoint Foundation 2010 – If the combination of the other client APIs is not sufficient, extend SharePoint Foundation with your own custom web service. By default SharePoint Foundation 2010 supports creating not only custom ASP.NET web services, as in previous releases, but also custom WCF web services.

Walkthrough: Creating and Implementing a Custom WCF Service in SharePoint Foundation – This walkthrough shows how to create a WCF service that uses the server-side object model, and a Windows Forms Application that implements the service and that uses the new client-side object model and REST interface.

SharePoint 2010 Client Object Model

This section of the Microsoft SharePoint 2010 Software Development Kit (SDK) introduces three new client APIs that allow you to interact with SharePoint sites from script that executes in the browser, from code (no earlier than Microsoft .NET Framework 3.5) that executes in a .NET mana

ged application, or from code that executes in a Microsoft Silverlight 2.0 application. The new ECMAScript (JavaScript, JScript), .NET managed, and Silverlight client object models each provide a subset of the server object model that is defined in Microsoft.SharePoint.dll,

SharePoint 2010 Client Object Model Hierarchy and Identity

Microsoft SharePoint Foundation 2010 has three object models for working on the client-side. These are the managed .NET object model, the managed Silverlight object model, and the unmanaged ECMAScript (JavaScript, JScript) object model.

You should be aware of the following important differences between the ECMAScript (JavaScript, JScript) and managed client object models.

  • The method signature may be different, as with the ClientContext()constructor (JavaScript: ClientContext(serverRelativeUrl)). In JavaScript this constructor takes a server-relative URL, but the managed version of this constructor takes either a full URL or a Uri.
  • The two object models use different data value types. The JavaScript object model does not have equivalents for all the data value types in the .NET Framework managed object model. JavaScript regards StringCollection asstring[]. On the other hand, JavaScript has some values that the .NET Framework does not have, such as NaN, or negative and positive infinity.
  • The JavaScript object model allows Forms authentication, but you cannot specify the authentication mechanism to connect to the server. For information about the managed client object models and Forms authentication, see Authentication in the Managed Client Object Models.
  • When you are creating an item and adding it to an existing collection, further updates cannot be performed with that collection while the query is outstanding. This issue pertains to adding an item to a collection; otherwise, multiple clients can simultaneously read and write to existing items within a collection.
  • As part of general security, you cannot use the JavaScript object model on a page to work with Microsoft SharePoint Foundation 2010 data unless the page contains a form digest control, for example, <SharePoint:FormDigest runat=”server”/>.
  • You generally cannot share variables across scopes, so for this reason you cannot use common coding patterns for try/catch/finally statements.
  • RoleDefinitionBindingCollection object used in creating role assignments does not have object identity. Therefore, if you create a newRoleDefinitionBindingCollection object and then try to use it after creating a role assignment, an error is returned.
  • Some case-insensitive comparisons do not work the same way on the client as they do on the server. Some server-side comparisons use the Web site locale to do a comparison, but the client can only use invariant culture to avoid frequent round trips.  SharePoint Foundation 2010 does not support case-insensitive comparisons if the server is using a Web site locale.
  • Due to the limitations of an asynchronous postback, you may find that inline script is not called when the page is in certain modes, for example, when a Wiki page is in edit mode. In this case, use a ScriptManager control and itsRegisterStartupScript() method to register a startup script block for executing your code, instead of using inline script.

 

Server

.NET Managed and Silverlight

JavaScript

Microsoft.SharePoint.SPContext Microsoft.SharePoint.Client.ClientContext SP.ClientContext
Microsoft.SharePoint.SPSite Microsoft.SharePoint.Client.Site SP.Site
Microsoft.SharePoint.SPWeb Microsoft.SharePoint.Client.Web SP.Web
Microsoft.SharePoint.SPList Microsoft.SharePoint.Client.List SP.List
Microsoft.SharePoint.SPListItem Microsoft.SharePoint.Client.ListItem SP.ListItem
Microsoft.SharePoint.SPField (including major derived classes) Microsoft.SharePoint.Client.Field SP.Field
Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager Microsoft.SharePoint.Client.WebParts.LimitedWebPartManager SP.WebParts.LimitedW

 

Server

.NET Managed and Silverlight

JavaScript

Microsoft.SharePoint.SPContext Microsoft.SharePoint.Client.ClientContext SP.ClientContext
Microsoft.SharePoint.SPSite Microsoft.SharePoint.Client.Site SP.Site
Microsoft.SharePoint.SPWeb Microsoft.SharePoint.Client.Web SP.Web
Microsoft.SharePoint.SPList Microsoft.SharePoint.Client.List SP.List
Microsoft.SharePoint.SPListItem Microsoft.SharePoint.Client.ListItem SP.ListItem
Microsoft.SharePoint.SPField (including major derived classes) Microsoft.SharePoint.Client.Field SP.Field
Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager Microsoft.SharePoint.Client.WebParts.LimitedWebPartManager SP.WebParts.LimitedW

 

Server

.NET Managed and Silverlight

JavaScript

Microsoft.SharePoint.SPContext Microsoft.SharePoint.Client.ClientContext SP.ClientContext
Microsoft.SharePoint.SPSite Microsoft.SharePoint.Client.Site SP.Site
Microsoft.SharePoint.SPWeb Microsoft.SharePoint.Client.Web SP.Web
Microsoft.SharePoint.SPList Microsoft.SharePoint.Client.List SP.List
Microsoft.SharePoint.SPListItem Microsoft.SharePoint.Client.ListItem SP.ListItem
Microsoft.SharePoint.SPField (including major derived classes) Microsoft.SharePoint.Client.Field SP.Field
Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager Microsoft.SharePoint.Client.WebParts.LimitedWebPartManager SP.WebParts.LimitedW

 

Server

.NET Managed and Silverlight

JavaScript

Microsoft.SharePoint.SPContext Microsoft.SharePoint.Client.ClientContext SP.ClientContext
Microsoft.SharePoint.SPSite Microsoft.SharePoint.Client.Site SP.Site
Microsoft.SharePoint.SPWeb Microsoft.SharePoint.Client.Web SP.Web
Microsoft.SharePoint.SPList Microsoft.SharePoint.Client.List SP.List
Microsoft.SharePoint.SPListItem Microsoft.SharePoint.Client.ListItem SP.ListItem
Microsoft.SharePoint.SPField (including major derived classes) Microsoft.SharePoint.Client.Field SP.Field
Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager Microsoft.SharePoint.Client.WebParts.LimitedWebPartManager SP.WebParts.LimitedW

Access list data by using the Server object model

Access SharePoint Data by using ADO.NET Data Services

Create and modify a custom content type

Extending SharePoint Search

Implement and debug code that executes in an alternative security context

Work with documents programmatically

Work with the meta data

Design Patterns

August 14, 2012
Patterns Type Description
Creational Patterns Factory This pattern is used to create concrete class instances without specifying the exact class type.
Abstract Factory This pattern is used to create concrete class instances without specifying the exact class type. The Abstract Factory Pattern provides a way to encapsulate a group of individual factories that have a common theme.
Flyweight A pattern used to maximize the sharing of objects resulting in reduced memory consumption.
Singleton This pattern insures that only a single instance of a given object can exist.
Builder This pattern separate the construction of a complex object from its representation so that the same construction process can create different representations..
Structural Patterns Adapter Convert the interface of a class into another interface clients expect. Adapter lets the classes work together that couldn’t otherwise because of incompatible interfaces
Bridge Decouples an abstraction from its implementation so that the two can vary independantly.
Composite Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly.
Decorator Allows an objects behavior to be altered at runtime.
Facade Used to provide a simpler interface into a more complicated portion of code.
Proxy Provides a Placeholder for another object to control access to it.
Behavioral Patterns Chain of Responsibility The chain of responsibility pattern is a way of communicating between objects.
Command Encapsulates a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations.
Iterator Provides a way to sequentially access aggregate objects without exposing the structure of the aggregate.
Mediator The mediator pattern encapsulate the interaction between a set of objects.
Memento Allows you to save the state of an object externally from that object.
Observer Allows a single object to notify many dependent objects that its state has changed.
State Allows an object to change its behavior when its internal state changes.
Strategy Allows multiple algorithms to be used interchangeably at runtime.
Visitor The visitor design pattern enables us to create new operations to be performed on an existing structure.
Template Method Defines the skeleton of an algorithm then lets subclasses implement the behavior that can vary.

Clear SVN objects from Visual Studio project folder

August 14, 2012

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace ClearSVN
{
    class Program
    {
        static void Main(string[] args)
        {
            //DeleteSubFolders(@”c:\svn\MyProject\Trunk”,”.svn”,true);
            DeleteSubFolders(@”E:\FolderPath”, “.svn”, true);
        }

        public static void DeleteSubFolders(string folderPath, string wildcardPattern, bool top)
        {

            String[] list;

             //If we are at the top level, get all directory names that match the pattern

            if (top)

                list = Directory.GetDirectories(folderPath, wildcardPattern, SearchOption.AllDirectories);

            else //Get directories and files for matching sub directories

                list = Directory.GetFileSystemEntries(folderPath, wildcardPattern);

             foreach (string item in list)
            {

                //Sub directories

                if (Directory.Exists(item))
                {

                    //Match all sub directories

                    DeleteSubFolders(item, “*”, false);

                }

                else // Files in directory
                {

                    //Get the attribute for the file

                    FileAttributes fileAtts = File.GetAttributes(item);

                    //If it is read only make it writable

                    if ((fileAtts & FileAttributes.ReadOnly) != 0)
                    {

                        File.SetAttributes(item, fileAtts & ~FileAttributes.ReadOnly);

                    }

                    File.Delete(item);

                }

            }
            //Delete the matching folder that we are in

            if (top == false)
            {

                Directory.Delete(folderPath);

            }

        }

     }
}