Prasad Bolla's SharePoint Blog

Click Here to go through the Interesting posts within my Blog.

Click Here to go through the new posts in my blog.

Monday, November 28, 2011

SharePoint 2010 Theory Part

What is SharePoint 2010?
SharePoint 2010 is the business collaboration platform for the Enterprise & the Web that enables you to connect & empower people through an integrated set of rich features. Whether deployed on-premises or as hosted services, SharePoint 2010 helps you cut costs with a unified infrastructure while allowing you to rapidly respond to your business needs.

Microsoft.SharePoint.Linq NameSpace
 The Microsoft.SharePoint.Linq namespace, which defines a LINQ to SharePoint provider that translates LINQ queries into Collaborative Application Markup Language (CAML) queries (and therefore gives you the option of replacing your list and CAML queries with LINQ).

Microsoft.SharePoint.Client NameSpace
Three client-side APIs in the Microsoft.SharePoint.Client namespace that enable you to interact with SharePoint sites through scripts that run in the browser from Microsoft .NET Framework managed code, and inside Microsoft Silverlight applications.

Note:-1
Both SharePoint Foundation 2010 and SharePoint Server 2010 contain many additions provided by Business Connectivity Services. These changes make it easier for you to integrate your external business data and processes with both server applications and client applications.

SharePoint 2010 14 hive Structure

SharePoint 2010: 12 Hive + 2 = 14 Hive

If you’re a SharePoint person, you of course have the following path burned into your memory forever.
C:\Program Files\Common Files\Microsoft Shared\Web Server Extension\12
Well pretty soon, you can replace that with:
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14
Apparently, Microsoft thought the number thirteen was unlucky.  Now, I know they are trying to rebrand this as the SharePoint root (or something like that), but we all know that is never going to sick, so I’ll just call it the 14 hive.  Anyhow, this is the new place you’ll be doing a lot of your work.  Although with the new Visual Studio 2010 tools, you’ll find that you won’t need to come to this folder nearly as much.  In this post, I thought I would take a brief moment to point out what I noticed in the 14 hive and make any comments as necessary.  None of the underlying folders really have changed but a few things have been added.
In the root of the 14 Hive, I noticed three new folders
  • UserCode – files used to support sandboxed solutions
  • WebClients – used for the client OM I believe
  • WebServices – many new .svc files
If you are interested in what assemblies are present in the ISAPI folder, here is a quick list.  It sounds like some classes have moved to different DLLs, but I haven't encountered any yet.
  • Microsoft.BusinessData.dll
  • Microsoft.Office.DocumentManagment.dll
  • Microsoft.Office.Excel.Server.Udf.dll
  • Microsoft.Office.Excel.Server.WebServices.dll
  • Microsoft.Office.Policy.dll
  • Microsoft.Office.SecureStoreService.Security.dll
  • Microsoft.Office.Server.dll
  • Microsoft.Office.Server.Search.dll
  • Microsoft.Office.SharePoint.ClientExtensions.dll
  • Microsoft.Office.UserProfiles.dll
  • Microsoft.Office.Word.Server.dll
  • Microsoft.Office.Workflow.Actions.dll
  • Microsoft.Office.Workflow.Tasks.dll
  • Microsoft.SharePoint.Client.dll
  • Microsoft.SharePoint.Runtime.dll
  • Microsoft.SharePoint.dll
  • Microsoft.SharePoint.Linq.dll
  • Microsoft.SharePoint.Portal.dll
  • Microsoft.SharePoint.Publishing.dll
  • Microsoft.SharePoint.Search.dll
  • Microsoft.SharePoint.Search.Extended.Administration.Common.dll
  • Microsoft.SharePoint.Search.Extended.Administration.dll
  • Microsoft.SharePoint.Search.Extended.Administration.ResourceStorage.dll
  • Microsoft.SharePoint.Search.Extended.Administration.Query.dll
  • Microsoft.SharePoint.Security.dll
  • Microsoft.SharePoint.Taxonomy.dll
  • Microsoft.SharePoint.Taxonomy.Intl.dll
  • Microsoft.SharePoint.Workflow.Actions.dll
  • Microsoft.Web.CommandUI.dll
I believe all of these are registered as version 14.0.0.0.  There is a lot of new things in the hive including features, site templates, etc, but not that many structural changes from what I can tell.

SharePoint 2010 Object Model
Some Important things about SharePoint 2010 Object model and its backward compatibility.

Microsoft SharePoint Foundation 2010 and Microsoft SharePoint Server 2010 contain object model upgrades that are designed to be compatible with existing solutions developed for Windows SharePoint Services 3.0 and Microsoft Office SharePoint Server 2007. Some namespaces, classes, and methods are now obsolete, but they are still available and will continue to work as expected in your custom code.

You can synchronize your customizations and applications with the upgraded versions of Microsoft SharePoint Foundation 2010 and Microsoft SharePoint Server 2010 after you have redeployed them.

The object model contains many changes and enhancements, but your custom code will still compile and, with one potential exception, it will run as expected. If in case, any of your customizations rely on list queries that can generate result sets in excess of 5,000 items or that scan all rows of lists that consist of more than 5,000 items, you must change the query size threshold.(See Later in the Post)..

Note: You must Re-compile or re-write your code in below conditions:

* You should rewrite and recompile any code that refers to files and resources in "12" hive.For example, if you have redeployed all of your files into the "14" folder and emptied your "12" folder, any references to files under the "12" folder will not work. You will need to rewrite your code to refer the file
s in "14 Hive" instead of "12 Hive" to make it work.

* You must recompile custom code written for Windows SharePoint Services 3.0 and Office SharePoint Server 2007 that does not run on IIS (such as console applications and services).

* You should recompile custom code written for Office SharePoint Server 2007 if your solution includes a feature receiver that implements the FeatureInstalled, FeatureUninstalling, FeatureActivated, or FeatureDeactivating methods and you are deploying by using either the Stsadm command-line tool or the timer service.


Lets Look at some of the custom solutions that you would be moving to SharePoint 2010.


Moving Using Solution Packages (.wsp Files)

You can simply deploy them as we did in SharePoint 2007. You dont need to recompile them(unless, your code has references to 12 hive). If however, you want to start upgrading your applications so that they use the most current classes and methods, you should recompile your code. The compiler warnings will tell you which elements of the object model are obsolete, and which newer alternatives you should use.


Moving Using Windows Installer Files


If you deploy your custom solutions by using Windows Installer (.msi) packages, be sure to change them so that your custom files are deployed to their correct locations in the "14" folder. This is especially true if you are deploying files to locations other than the TEMPLATE\FEATURES folder.


Moving Site templates
Site templates are deprecated. If you need to redeploy a site template to either SharePoint Foundation 2010 or SharePoint Server 2010, follow these steps:

1. Create a site from the site template.

2. Install SharePoint Foundation 2010 or SharePoint Server 2010 on your existing server farm or on a new server farm. If you install the upgrades on a new server farm, attach the content database that contains the site that you created to the new farm.

3. On the new installation, choose Save Site as Template from the Site Settings page. This creates a solution package with a .wsp file name extension.


CSS Changes :

When you upgrade to either SharePoint Foundation 2010 or SharePoint Server 2010, you are able to choose either backward compatibility mode or the upgraded user interface. You can however, switch between backward compatibility mode and the new interface at the site-collection level or site level.

Since, the UI has changed significantly in both SharePoint Foundation 2010 and SharePoint Server 2010, any customizations(made to SharePoint 2007 CSS) that rely on specific CSS classes and UI elements will work only in backward compatibility mode.

A property SPWeb.UIVersion is also available for developers, to programmatically get or set the UI version (3 for backward compatibility mode and 4 for the new interface).


Themes:


Themes no longer exist in SharePoint Foundation 2010 and SharePoint Server 2010, so any customizations and design work that you have done with themes will not be imported into the new interface.


Custom Actions and Toolbar Additions:

Most custom actions, including those targeted at links and edit control block (ECB) menus, continue to work as expected in the upgraded interface. Because the toolbar is replaced by the ribbon, most custom actions that add buttons to a toolbar will be
placed in the Custom Commands tab of the ribbon.

Note : Any Custom Action Element that uses the ControlAssembly attribute, the ControlClass attribute, or the ControlSrc attribute, however, will not appear in the new interface.


Site definition
:
Migrate sites to a supported, predefined site definition, then apply custom features by using solution deployment.
You can also continue to use a custom site definition. You do not have to create a new site definition based on SharePoint Server 2010.

Event handler : Rewrite and redeploy as a feature.


JavaScript : In some cases, you might have to adjust the scripts to work with the new page model. Verify that it works on an upgraded site, and in both Visual Upgrade modes.


Conclusion:

Because the changes to the API in the upgrades are backward compatible, you should not have to make any changes to your custom code before you redeploy it in either SharePoint Foundation 2010 or SharePoint Server 2010. All deprecated elements of the API continue to be available to you, so that you have time to review the newer elements of the API before incorporating them into your customizations.

What's New in sharePoint 2010 Workflows?
A quick view on whats new with SharePoint 2010 Workflows :

1. SharePoint 2010 workflows are build upon the workflow engine provided .Net Framework 3.5.

2. List and Site workflows - In addition to the SharePoint lists we can now create workflows for SharePoint sites as well. These are called as "Site Workflows".

3. SharePoint Designer 2010 Changes - MS has provided a new graphical workflow designer for designing workflows. These workflows can be deployed in SharePoint Server directly from the designer.

4. Editing Out-of-Box workflows - Another Improvement in SharePoint Designer 2010 workflows is that it now allows you to edit the out-of-the-box workflows that come with SharePoint.

5. Re-usable Workflow - In addition to above, with Designer 2010 you can also create reusable declarative workflows. That means unlike SharePoint 2007 designer workflows, you don't have to bind a workflow to a specific list. You can resuse them by binding it to more than one list or multiple lists.

6. User profile in Workflow - User Profile data can now be bound to properties in workflow. This will make it possible to get information about the SharePoint user profile in the workflow itself.

7. Moving SharePoint Designer Workflows - The resuable designer workflows can now be moved to another SharePoint server or to Visual Studio 2010 with a workflow .wsp file. "Save as Template" command can be used to create the WSP file for the workflow.

8.Changes in List Events - SharePoint 2010 adds four new workflow Event Receivers for list based workflows. The four workflow event receivers available are Starting, Started, Postponed and Completed. These are similar to other SharePoint list\library event receivers and they execute code on the server in response to the event.

9. Workflow Templates - To make development easier, Visual Studio 2010 includes event receiver project types to make using the workflows and events fairly simple.

How to move SharePoint designer workflow with a wsp?
In SharePoint Designer 2010, you can create reusable declarative workflows. That means workflows created in SharePoint designer can now be generic (not tied to a list) and can be moved to other Site collection or sites via .wsp file. The "Save as Template" command can be used to create a WSP file containing a reusable workflow. The workflow can also be moved to Visual Studio 2010 for further Customizations.

Steps to Move Workflow are :

1. Create a SharePoint workflow using SharePoint Designer 2010.

2. After you are done with creating a workflow, Click on "Save as Template" button on Ribbon the bar. This will create a wsp file for you workflow, which will be uploaded in the current site collection itself.

3. Now, Open the Top Level Site or Site collection, in which you created the workflow. Goto View all site content and click on "Site Assets" library. You will see your saved workflow wsp (or soluiotn package) gets upload to this library. However, to deploy it in the site colletcion you will need to download this file and upload into Solution management.

4. To download this wsp you can open up the drop-down menu for this file and Choose Sent To -> Download a Copy.

5. Now to Upload it to Solution management of this or any other site collection goto
Site Actions -> Site Settings -> Under Galleries click on Solution gallery. Then Click on Solution tab(in ribbon bar) and click on Upload Solution and browse to the aboved saved file. Once the solution is uploaded click on "Activate solution" to activate it.

5. Since the workflow is deployed as a feature, you will now activate the workflow feature for the site where you want to use the Workflow. To do this goto Site Settings of that site and click on "Manage Features" now simply activate the workflow to use it in the Site.

Please note that another option in ribbon bar "Converted to be Globally Reusable" will only save your workflow to be globaly reusable. It will not create wsp file to be deployed in another farm. Also, the workflows created at the root level of the site collection can only be converted to be Globally Reusable but other ones created in sub sites cannot.

What is Business Connectivity Services in SharePoint ?
SharePoint 2010 provides a new set of technologies known as Business Connectivity Services for retrieving, editing, updating, and deleting data from external systems(for e.g. data from ERP or CRM database). BCS enhances the SharePoint platform’s capabilities with out-of-box features, services and tools that streamline development of solutions with deep integration of external data and services.

How is BCS Different from BDC in SharePoint 2007 ?
Even though the BDC made it relatively easy to create read-only solutions that display data in the Business Data List Web Part, it was not so simple to create a solution that enabled users to make changes and write that data back to the external store.

BCS, on the other hand, provides you with Read-Write capable connectivity from Client and Server to Database, WCF/Web Services and .Net Sources.

A Developer can now use SharePoint Designer 2010 and VS 2010 rapid development tools to access external data. For e.g. you can now create read-write connections to external database from SharePoint designer and then can create webpart\other solutions to surface that data.

The BCS data can further be used in other SharePoint Fetaures such as Business Intelligence,Collaboration and in Enterprise Search.

SharePoint 2007 Object Model vs SharePoint 2010 Object Model
In Sharepoint Object model there are two Important namespaces.

In SharePoint 2007 - The Microsoft.Office.Server namespace is the root namespace of all Office Server objects and Microsoft.SharePoint is the root namespace for all WSS objects.

Hive :

In SharePoint 2007 - It has "12 hive" structure where all SharePoint resources are deployed.

In SharePoint 2010 - Microsoft has apparently added three new folders to its hive and calling it as "14 Hive"
* UserCode – files used to support sandboxed solutions
* WebClients – used for the client Object Model
* WebServices – New .svc files


Foundation :

SharePoint 2007 : Wss 3.0 was required for accessing all common SharePoint API's

SharePoint 2010 : SharePoint Foundation 2010 is required to provide base API's.


API's
:

SharePoint 2007 : No API was available for Code to Interact with SharePoint site through Client side scripts (side Note : You can do it by calling Sharepoint web services using javascript )

SharePoint 2010 : MS has introduced Microsoft.SharePoint.Client namespace that enable you to interact with SharePoint sites through scripts that run in the browser from Microsoft .NET Framework managed code, and inside Microsoft Silverlight applications.

STSADM Vs PowerShell
Stsadm Tool : Microsoft Office SharePoint Server 2007 includes the Stsadm tool for command-line administration of Office SharePoint Server 2007 servers and sites.Stsadm is located at the following path on the drive where SharePoint Products and Technologies is installed: %COMMONPROGRAMFILES%\microsoft shared\web server extensions\12\bin. You must be an administrator on the local computer to use Stsadm.

Windows PowerShell : Windows PowerShell™ command-line interface is a new command-line tool and supporting scripting language from Microsoft that complements Cmd.exe in the Windows administration context. In the SharePoint administration context, Windows PowerShell supersedes the Stsadm.exe administration tool.


Return Parameter :

Windows PowerShell :Unlike most command-line tools, which accept and return text, Windows PowerShell is built on the Microsoft .NET Framework and accepts and returns .NET Framework objects.


Access to File System :


Stsadm : It does not allow you to access file system,registry ans so on..

Windows PowerShell :Like many shells, Windows PowerShell gives you access to the file system on the computer. In addition, Windows PowerShell providers enable you to access other data stores, such as the registry and the digital signature certificate stores etc..

SharePoint Foundation Vs SharePoint Server 2010
Used For :

SharePoint Foundation 2010 :
Is is for smaller organizations or departments looking for a low-cost entry-level or pilot solution for secure, Web-based collaboration.


SharePoint Server 2010 : SharePoint Server 2010 builds on the Microsoft SharePoint Foundation 2010 infrastructure to provide a true enterprise portal platform.Any features that are available in SharePoint Foundation 2010 are also available in SharePoint Server 2010.


Features :

SharePoint Foundation 2010 : Coordinate schedules, organize documents, and participate in discussions through team workspaces, blogs, wikis, and document libraries on the platform that is the underlying infrastructure for SharePoint Server.

SharePoint Server 2010 : In addition to all the Features in SharePoint Foundation 2010, the server includes some additional features for every component available in Foundation 2010. Like Along with the BCS, sharePoint 2010 server also includes External data in search, Secure Store service,External Data Web Parts,Profile pages,External data in workflow,Rich client integration and lot more...

SharePoint 2007 LookUp Column Vs SharePoint 2010 LookUp Column
Cascade Delete
SharePoint 2007 : The Lookup column in SharePoint 2007 does not support cascade delete. i.e. if If an Item\Value in the the look-up list is deleted, then all those items referencing that value (as look-up value) will not be delete. This will rather present you with various errors and can also cause errors on the Site page if your are using one of them as filters.

SharePoint 2010 : If an Item\Value in the the look-up list is deleted, then all those items referencing that value (as look-up value) in other lists will also be deleted.


Restrict Delete


SharePoint 2007 : Does not have option to restrict deleting of lookup list items\values.

SharePoint 2010 : Choosing this option would restrict the users from deleting an item in the column in the Look-up list, if the value is being used in some other lists.


Number of columns displayed


SharePoint 2007 : This will only display the chosen lookup column in the referencing list.

SharePoint 2010 : You can now display additional columns from the look-up list, along with the chosen lookup field.

SSP VS Service Applications
Differences between SSP and Service Application are :

What are :

SSP : A Web application that contain all the services proived by sharepoint, and can be shared by various web applications. Some of the services are Search, Infopath,User Profiles etc.

Service Application : The Services that use to be together in SSP, now run independently as a Service Application.


Build -In :

SSP : Shared Services Provider (SSP) was only a part of Office SharePoint Server 2007.

Service Applications : The service application architecture is however, built into Microsoft SharePoint Foundation 2010 itself.


SSP Administration Site :

SSP : They require a SSP administration site to configure the associations with web applications.

Service Application : They are running independently and can be individually associated with the one or more web applications.


Web application's Burden :


SSP : Any Web application associated with the SSP has to take the burden of all the shared services in that SSP.

Service Application : Each web application now have a "Service application group" where they can just add the Services that they need.


Replication :

SSP : The Services where configured in SSP itself and were not replicated. All web applications will use one set of srevices.

Service Application : If the service is needed to be shared between few web applications, the service is re-configured and added into each web application's custom service connection group.

SharePoint 2010 WebPart Tutorial
Webparts as you know are Reusable components that can be deployed and added to many different sharepoint site pages. In this post we will talk about custom and Out-of-box webparts in SharePoint 2010.

In sharePoint 2010 we can create two kind of custom WebParts :

1. Visual WebPart - While creating a Visual webpart you will have a design interface available with you, where you can simply drag and drop checkboxes, labels or your own custom controls to make up the webpart UI. To add the business logic, a code behind file is also attached to the webpart.

Technically, a Visual webpart in SharePoint 2010 is a ascx User Control that is hosted inside a standard asp.net webpart. If you notice that the webpart class does not now inherit form a Microsoft.SharePoint.webpartpages.webparts or System.Web.UI.WebControls.WebParts instead it inherits from UserControl namespace.

2. Standard AsP.NET WbeParts - Here you will have to build uo your user interface and logic in a class file. Unlike, visual webpart standad asp.net webparts in SharePoint 2010 does not gives you any drag and drop design surface for developing WebPart UI. This type of webpart Inherits from Standard ASP.Net webpart instead of UserControl or SharePoint.webpart.


WebPart Packaging -
Visual Studio 2010 package and deploy webparts when you press Clt + F5. It has a packaging and deployment processor which will create the needed solution package for your webpart and will deploy it in your sharepoint site. You can then add the webparts on any sharepoint site page from webpart gallery.

See WebPart examples at this Video :
SharePoint 2010 webparts

Lets talk about Out-of-Box webparts - In sharePoint 2010 many new Out-of-Box webparts are available for better representation of SharePoint data. You will initially see few categories in the Add Webpart pane but if you go to Site Actions->galleries and WebParts, you can add various other webparts available into your categories.

SharePoint 2010 EBooks

Solution Packages in SharePoint 2010
First of all if you do not know what is this solution package then here is a simple definition : A solution package is a distribution package or a container that is use to deploy your custom SharePoint Server 2010 development work to the SharePoint Web servers.

In SharePoint 2010, user have many options to create and deploy solution packages for their custom development work, let me start with the most used method to create a solution package

1. Create Package using Visual Studio 2010 -
Developers can build their SharePoint solutions in Visual Studio 2010 and produce .wsp files by using the automated build process. After you build your thing in VS 2010 using the SharePoint related templates available, you can just hit ctrl + F5. This will create a .wsp file and will also deploy it to the SharePoint server you are developing on.

Create a package - To Create a package in VS 2010, In Solution Explorer, click the project that you want to package. Then, on the Build menu, click Package.

Where is the .wsp - In Solution Explorer, click the Show All Files button. This shows all project items, including excluded and hidden items.Expand the bin node and
Expand the Debug or Release node to get your .wsp file.

Modify solution Package - When you create a SharePoint solution, Visual Studio adds the default SharePoint Features (or items) to the solution package. Before final deployment, you can add and remove SharePoint project items and Features using the SharePoint package. To open Package Designer In your Solution Explorer, right-click Package and then click View Designer.
Use Add\Remove (>) or(<) button to add the items into the solution package.

In addition to select files for packaging, the Package designer allows you to set various properties for the deployment. Some of the properties that you can set are :

1. Name - It is a Required Property. The default name of the package is set to ProjectName.

2. Reset WebServer - Optional. Select if you want to restart the Web server after the .wsp file is installed on the SharePoint server.

3. Deployment Server Type - This is a Required Field. By default, the scope is set to ApplicationServer.

4. Items in the Solution - All SharePoint project items and Features that can be added to the package.

5. Items in the Package - Optional. All SharePoint items and Features that you want to deploy in your package.

After, VS 2010 lets see at other options to create a solution Package in SharePoint 2010.

2. Solution Package by Using MSBuild - Using MSbuild you can build, clean, and validate a SharePoint package (.wsp) using command-line MSBuild tasks on a development computer. For this you need to Open a Visual Studio command prompt window -> Cd to your Project folder -> Type the command
"msbuild /t:Package ProjectName.csproj" to create a package for the project. ProjectName is a name for the solution

Custom RssFeed WebPart
I created a WebPart where RSS feed form a SharePoint Blog Posts list was consumed and modified to display, the two recently updated blog posts. Also, the post opens up in a new window on Click of the Post title.

"rss_text" in the below code will return your feed (two recently updated posts).

So here is the code to extract data from feed.

First,
1. Create a WebPart.
2. In CreateChildControls Call the Below method DisplayRSS() and pass the Posts list Rss Feed url( Get the RSS feed link from "View RSS" option in the Posts lists).

protected string DisplayRSS(string ListRssUrl)
{
try
{
string rss_text = "";
string title = "";
string link = "";
string description = "";

XPathDocument doc = new XPathDocument(ListRssUrl);
XPathNavigator nav = doc.CreateNavigator();
XPathNodeIterator items = nav.Select("//item");

int items_to_show = 2;
int count = 0;
while (items.MoveNext() && count < items_to_show)
{
XPathNavigator navCurrent = items.Current;

try
{
title = navCurrent.SelectSingleNode("title").InnerXml;
link = navCurrent.SelectSingleNode("link").InnerXml;
description = navCurrent.SelectSingleNode("description").InnerXml;

}
catch{ }

CleanUp(ref title,ref description); // Calling a FeedClean Function

if (description != "")
{
description = "- " + description;
description += "...";
}

rss_text += "<a href='" + link + "' target='_blank'>" + title + "</a> " + description;

if (count < items_to_show - 1)
rss_text += "<br/><br/>";

rss_text += "</div>";

count++;
}
return rss_text;
}
catch
{ }
}

protected void CleanUp(ref string title,ref string description)
{
title = title.Replace("\n", " ");
title = title.Replace("\r", " ");

description = description.Replace("<", "<");
description = description.Replace(">", ">");

description = Regex.Replace(hover_description, @"<(.\n)*?>", string.Empty); // To Remove all the html tags from the RSS feed.

title = title.Trim();
description = description.Trim();
}

Custom RssFeed WebPart in SharePoint 2010
Here are the steps and the code snippet for creating a custom webpart to display items or news via rss feed.
1. Open the VS and add a new blank solution.
2. Now in your Solution say “RssFeedPackage” add a new item then choose add a webpart. Lets name it as RSSFeedWebPart.
Please note : You can directly create a webpart solution and do not necessarily have to add it as an item. I did this because I wanted to add some more features in the same solution.
3. Next, you need to add some logic to the RSSWebPart WebPart. Edit the RSSWebPart.cs class to include the code below. I have added a custom property to receive the Rss feed url for the webpart.
Code goes like this :
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
namespace RssFeedPackage
{
[ToolboxItemAttribute(false)]
public class RSSFeedWebPart: WebPart
{
[WebBrowsable(true)] [Personalizable(PersonalizationScope.Shared)]
public string RSSUrl
{
get; set;
}
protected override void RenderContents(HtmlTextWriter writer)
{
RSSFeed feed = new RSSFeed(RSSUrl);
HyperLink newLink = new HyperLink();
foreach (RSSItem singleRssItem in feed)
{
newLink.Text = singleRssItem.Title;
newLink.NavigateUrl = singleRssItem.Href;
newLink.Target = “rssSite”;
newLink.RenderControl(writer);
writer.WriteBreak();
}
base.RenderContents(writer);
}
}
}
//Code for RSSFeed class
internal class RSSFeed : List
{
internal RSSFeed(string RssURL)
{
try
{
XmlDocument rssDoc = new XmlDocument();
XmlTextReader xRead = new XmlTextReader(RssURL);
rssDoc.Load(xRead);
XmlNodeList xNodes = rssDoc.SelectNodes(“./rss/channel/item”);
foreach (XmlNode xNode in xNodes)
{
this.Add(new RSSItem(xNode)) ;
}
}
catch (Exception)
{
this.Add(new RSSItem());
}
}
}
//Code for RSSItem
internal class RSSItem
{
public string Title { get; internal set; }
public string Href { get; internal set; }
internal RSSItem()
{
Title = “Feed not available at this time” ;
Href = “~” ;
}
internal RSSItem(XmlNode xNode)
{
Title = xNode.SelectSingleNode(“./title”).InnerText;
Href = xNode.SelectSingleNode(“./link”).InnerText;
}
}
4. Now build and deploy the webpart.
5. Finally, Insert the webpart in your webpart page and specify the Rssurl in Edit this WebPart -> RssUrl box.

 How does Client object model works ?
When we use SharePoint client API’s 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 ECMAScript objects for ECMAScript).

How many types of Client Object model extension are available in 2010 and when would you use one or the other.
To develop rich client side solutions, three set of client-side APIs has been introduced in the Microsoft.SharePoint.Client namespace. The three APIs are targeted for three different types of clients.
1. .net Managed applications – These are used when we have to create console applications or window applications, web applications which are not running inside SharePoint Contex.
2. For Silverlight applications
3. ECMAScript – It is a client object model extension for using with JavaScript or JScript. This is used for creating applications which are hosted inside SharePoint. For example, web part deployed in SharePoint site can use this JavaScript API for accessing SharePoint from browser using JavaScript.

What is difference between Load() and LoadQuery() methods ?
Load method populates the client object directly with what it gets data from the server i.e. a collection object like ListItemCollection etc. but LoadQuery returns the data as a completely new collection in  IEnumerable format. Other major difference is that the Collections that you load using the Load() method are eligible for garbage collection only when the client context variable itself goes out of scope where as, in  these collections go out of scope at the end of  IEnumerable<List> list.

How can you write efficient and better performing client object applications ?
You can always use Lambda expressions in your queries to return only specific properties that will be used in your block. You can also use LoadQuery() method and specify multiple levels of properties to load for e.g. while returning specific properties of the lists using LoadQuery(), you can also specify the fields to return from each list to optimize the data access.

What are the Authentication methods for your client object model application ?
Basically there are three (3) authentication options you can use when you’re working with the Client Object Model in SharePoint 2010:
* Anonymous
* Default
* FormsAuthentication
You can specify clientContext.Authentication = Anonymous\Default\FormsAuthentication, If you do not choose an authentication method in your code, the application will default to using the client’s Windows Credentials (DefaultCredentials).

Authentication setUp in Client Object Model
Basically there are three (3) authentication options you can use when you’re working with the Client Object Model in SharePoint 2010:
* Anonymous
* Default
* FormsAuthentication
You can specify clientContext.Authentication = Anonymous\Default\FormsAuthentication
If you do not choose an authentication method in your code, the application will default to using the client’s Windows Credentials (DefaultCredentials). If you are trying to access sharepoint remotely using client application you will have to pass proper credentials.
Lets see some examples :
Windows Network credentials
NetworkCredential credentials = new NetworkCredential(“username”, “pwd”, “domain”);
Anonymous access Authentication
clientcontext.AuthenticationMode = SP.ClientAuthenticationMode.Anonymous;
Form Based Authentication
SP.FormsLoginInfo fbaLogin = new SP.FormsAuthenticationLoginInfo(“isha”, “MyPassword”);
clientcontext.AuthenticationMode = SP.ClientAuthenticationMode.FormsAuthentication;
clientcontext.FormsAuthenticationLoginInfo = fbaLogin;

How do you access ECMAScript object model API’s
The ECMAScript library is available in a number of JS files in the LAYOUTS folder. The main file among number of .js files is SP.js. When you include this file in the APSX page using a ScriptLink control, all other required JS files are loaded automatically. By linking SP.js to your page, the SP namespace gets registered. SP is the SharePoint namespace that contains all objects. For debugging purposes every js file also has a ‘debug’ equivalent in the same folder.

What is the purpose of calling clientContext.ExecuteQuery()
xecuteQuery gives you the option to minimize the number of roundtrips to the server from your client code. All the components loaded into the clientcontext are executed in one go.

Why would you use LINQ over CAML for data retrieval?
Unlike CAML, with LINQ to SharePoint provider, you are working with strongly typed list item objects. For example, an item in the Announcements list is an object of type Announcement and an item on a Tasks list is an object of type Task. You can then enumerate the objects and get the properties for your use. Also, you can use LINQ syntax and the LINQ keywords built into C# and VB for LINQ queries.

Can we use our custom master page with the application pages in SharePoint 2010
With 2010, you can now set whether the pages under _Layouts use the same Master Page as the rest of your site. You can enable or disable this functionality through the web application settings in Central Administration. This however, is not applicable to your custom application pages. If you want your custom applictaion page to inherit the site master page you must derive it from Microsoft.SharePoint.WebControls.LayoutsPageBase class.

 What are WebTemplates and Site Definitions
Site definitions consist primarily of multiple XML and ASPX files stored on a front-end Web server in folders under the %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\SiteTemplates directory.
Custom Web templates on the other hand, are stored in the database, and are created using an existing site, with or without its specific content, as a model. This provides a means for reusing sites that you have customized.In some ways, Web templates continue to depend, throughout their lifecycle, on the site definition that is their ultimate foundation.

How do you write to SharePoint ULS logs in 2010
n SharePoint Foundation, ULS exposes configurable settings in two ways, through the – Object model and Windows PowerShell cmdlets. For writing to SharePoint ULS logs developers can can use Diagnostics Service, which will make the customized categories viewable in the administrative UI for our errors.
or they can use the number of cmdlets available for accessing ULS logs using powershell. Some of the cmdlets are Get-SPDiagnosticConfig ,Get-SPLogEvent etc.

Writing errors to ULS logs and event logs Sharepoint 2010
In SharePoint Foundation, ULS exposes configurable settings in two ways, through the:
* Object model
* Windows PowerShell cmdlets

Using Object Model - Developers can either write to Sharepoint ULS logs or to event Logs using SharePoint 2010 object model.
For writing to SharePoint ULS logs - We can use Diagnostics Service, which will make the customized categories viewable in the administrative UI for our errors.


example -

using Microsoft.SharePoint.Administration;
SPDiagnosticsService diagSvc = SPDiagnosticsService.Local;
diagSvc.WriteTrace(0, new SPDiagnosticsCategory(“Add category”, TraceSeverity.Monitorable,EventSeverity.Error),TraceSeverity.Monitorable,”Writing to the ULS log: {0}”,new object[] { “Error in WebPart!”});

For Writing to Event Log :

using Microsoft.SharePoint.Administration;
WriteEvent(0, new SPDiagnosticsCategory(“Add Category”, TraceSeverity.Monitorable, EventSeverity.Error),EventSeverity.Monitorable,”Writing to the Event log: {0}”,new object[] { “Error in WebPart!”});


Using Powershell - Microsoft SharePoint Foundation 2010 also provides the ability to use Windows PowerShell cmdlets for manipulating Unified Logging Service (ULS) log settings.
There are number of cmdlets available. I have listed some of the them below :
Get-SPDiagnosticConfig  – Retrieves Diagnostic Configuration values.
Set-SPDiagnosticConfig – Allows setting Diagnostic Configuration values.
Get-SPLogLevel – Returns IDiagnosticsLevel2 objects or displays a list of diagnostics levels.
Set-SPLogLevel – Allows the user to set the trace and event level for a set of categories.
Clear-SPLogLevel – Resets the trace and event levels back to their default values.
New-SPLogFile – Ends the current log file and starts a new one.
Get-SPLogEvent – Reads/queries ULS trace logs.
Merge-SPLogFile – Combines trace log files from all farm servers into a single file.

What does CMDUI.XML contain?
The definitions for the out-of-the-box ribbon elements are split across several files in the SharePoint root, with TEMPLATE\GLOBAL\XML\CMDUI.XML being the main one.

Runwithelevatedprivileges in Sharepoint 2010
In this post you will learn how to use Runwithelevatedprivileges with LINQ in SharePoint 2010. In the code below you will see how a user who does not have permissions( not even read permissions) to a list can add an item in the list and with his user name as an author (created by) of the item. To assign a current user as an Author of the item we have first retrieved the real credentials, and then elevated the privileges.
private void CreateItem(SPList hiddenList)
{
SPUser user = ((LayoutsPageBase)Page).Web.CurrentUser;
Guid siteID = hiddenList.ParentWeb.Site.ID;
Guid webID = hiddenList.ParentWeb.ID;
Guid listID = hiddenList.ID;
SPSecurity.RunWithElevatedPrivileges(() =>
{
using (SPSite site = new SPSite(siteID))
{
using (SPWeb web = site.OpenWeb(webID))
{
web.AllowUnsafeUpdates = true;
SPList elevatedList = web.Lists[listID];
SPListItem item = elevatedList.Items.Add();
SPFieldUserValue currentUser = new SPFieldUserValue(item.ParentList.ParentWeb, user.ID, user.Name);
item["Author"] = currentUser;
item["Editor"] = currentUser;
item.Update();
}}}
);
}}

Delete Content Types in Asset Library Programmatically in Sharepoint 2010
A quick tip on how to delete the default content types in Asset library and adding your own custom content type using SharePoint 2010 object model. The default content types included with the AssetLibrary definition are Audio, video and Image.
SPSite oSite = new SPSite(“http://blrs2r8-11″);
SPWeb oWeb = oSite.OpenWeb();
SPListTemplate Otemplate = oWeb.ListTemplates["Asset Library"];
SPList oList = oWeb.Lists[oWeb.Lists.Add("NewList", "New List from Code", Otemplate)];
oList.ContentTypes["Video"].Delete();
oList.ContentTypes["Audio"].Delete();
oList.ContentTypes["Image"].Delete();
SPContentType oCtype = oWeb.ContentTypes["Custom Content Type"];
oList.ContentTypes.Add(oCtype);
oList.Update();

Using SPPageStatusSetter to Show Status SharePoint 2010
In this post you will learn how to display a Status of an item ( i.e. if item has been added, updated, deleted or whatever…) in your status bar that renders just below the ribbon and the top navigation menu.
Well, the thought process is to include the SPPageStatusSetter control in a web part and then dynamically adding this web part to list view page from an event receiver along with status bar message. The reason behind this approach is because you cannot get the current page context in event receiver to include SPPageStatusSetter control to any page. In Nutshell, we will create a webpart with the SPPageStatusSetter control and will set the message(for the SPPageStatusSetter via property) in our event receiver.
Create a WebPart – Create an empty SharePoint project. Add a web part item and an event receiver item. Now in the web part code add a custom property and add the SPPageStatusSetter control. The message(status) for the SPPageStatusSetter control will be set through the custom property of web part from event reciever.
Web part Code :
public class StatusBarWebpart : WebPart
{
SPPageStatusSetter statusBar;
string oMessage;
public StatusBarWebpart()
{ }
[Category("Custom Properties")][Browsable(false)]
public string Message
{
get
{
return oMessage;
}
set
{
oMessage = value;
}
}
protected override void CreateChildControls()
{
statusBar = new SPPageStatusSetter();
statusBar.AddStatus(“Action”, Message, SPPageStatusColor.Blue);
Controls.Add(statusBar);
}
protected override void RenderContents(HtmlTextWriter writer)
{
writer.Write(“Status Bar demo”);
RenderChildren(writer);
}
}
Now we will add
Now add the custom web part which contains the SPPageStatusSetter control dynamically in the events and make sure that you change the status of the SPPageStatusSetter control in every event through the custom property of the web part.
public class EventRecieverStatus : SPItemEventReceiver
{
///
/// An item is being added.
///
StatusBarWebpart.StatusBarWebpart owp;
public override void ItemAdded(SPItemEventProperties properties)
{
base.ItemAdded(properties);
SPWeb web = properties.Web;
string oUrl = properties.List.DefaultViewUrl;
Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager coll = web.GetLimitedWebPartManager(oUrl, System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
if (coll.WebParts.Count > 1)
{
owp = (StatusBarWebpart.StatusBarWebpart)coll.WebParts[1];
if (owp != null)
{
owp.Message = “Item Added”;
coll.SaveChanges(owp);
}
}
else
{
owp = new StatusBarWebpart.StatusBarWebpart();
owp.Message = “Item Added”;
owp.Hidden = true;
coll.AddWebPart(owp, “Left”, 1);
coll.SaveChanges(owp);
}
}
///
/// An item is being updated.
///
public override void ItemUpdated(SPItemEventProperties properties)
{
base.ItemUpdated(properties);
SPWeb web = properties.Web;
string oUrl = properties.List.DefaultViewUrl;
Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager coll = web.GetLimitedWebPartManager(oUrl, System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
if (coll.WebParts.Count > 1)
{
owp = (StatusBarWebpart.StatusBarWebpart)coll.WebParts[1];
if (owp != null)
{
owp.Message = “Item Updated”;
coll.SaveChanges(owp);
}
}
else
{
owp = new StatusBarWebpart.StatusBarWebpart();
owp.Message = “Item Updated”;
owp.Hidden = true;
coll.AddWebPart(owp, “Left”, 1);
coll.SaveChanges(owp);
}
}
}

Retrieve data using Search web service search.asmx SharePoint 2010
Did you ever need to use Search service to retrieve data from search 2010 ‘s search in your .net custom application? Well here is little code snippet for doing just that.
The code snippet will return search results as a dataset.
public static DataSet GetSearchResults()
{
string xmlTemplate = ““;
xmlTemplate += “

Removing configuration Settings from Web config in SharePoint 2010
The following example shows how to remove a configuration setting from sharepoint 2010 web config file. To know how to add a setting in web config file see the Post how to access SharePoint web config Programmatically
example :
SPWebConfigModification configModFound = null;
SPWebApplication webApplication = SPWebApplication.Lookup(new Uri(“http://SPSite/”));
Collection modsCollection = webApplication.WebConfigModifications;
// Find the most recent modification of a specified owner
int modsCount1 = modsCollection.Count;
for (int i = modsCount1 – 1; i > -1; i–)
{
if (modsCollection[i].Owner == “User Name”)
{
configModFound = modsCollection[i];
}
}
// Remove it and save the change to the configuration database
modsCollection.Remove(configModFound);
webApplication.Update();
// Reapply all the configuration modifications
webApplication.Farm.Services.GetValue().ApplyWebConfigModifications();

how to access SharePoint web config Programmatically
In SharePoint 2010, you can easily access SharePoint's Web.Config file using SPWebConfigModification class of the Microsoft.SharePoint.Administration namespace.
It can be used in the situations where you might need to write an assembly to SafeControls element in your web config file using object model or may be something else.Well, the cool thing is these modifications are written to the web.config files on every front-end web server when the SPWebService.ApplyWebConfigModifications method is called.

Below is an example shows how to use the SPWebConfigModification class to register a custom assembly.

SPWebService service = SPWebService.ContentService;

SPWebConfigModification myModification = new SPWebConfigModification();
myModification.Path = "configuration/SharePoint/SafeControls";
myModification.Name = "SafeControl[@Assembly='MyCustomAssembly'[@Namespace='MyCustomNamespace'][@TypeName='*'][@Safe='True']";
myModification.Sequence = 0;
myModification.Owner = "User Name";
myModification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
myModification.Value = "";
service.WebConfigModifications.Add(myModification);

/*Call Update and ApplyWebConfigModifications to save changes*/
service.Update();
service.ApplyWebConfigModifications();

Calling the ApplyWebConfigModifications method schedules a timer job to deploy the changes throughout the server farm. To apply a web.config modification to a specific Web application, add the modification to the collection of web.config modifications for the Web application (WebConfigModifications). For example, you can use oWebSite.Site.WebApplication.WebConfigModifications.Add(MyModification) to add a web.config modification to the parent Web application of a specific Web site. You must still call ApplyWebConfigModifications even if you add a web.config modification to a single Web application.

Assign users Permission to a list item in workflow sharepoint 2010
Code behind will assign “Full access” and “Design” permissions for a given list item to users XXY and XXZ (we get via People and group fields) in workflow code.
using System;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Collections;
using System.Drawing;
using System.Linq;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Workflow;
using Microsoft.SharePoint.WorkflowActions;
namespace Mynamespace_UpdateItemPermissions
{
public sealed partial class Wrk_UpdateItemPermissions : SequentialWorkflowActivity
{
public Guid webID;
public Guid siteID;
public Guid listID;
public int itemID;
public Guid workflowId = default(System.Guid);
public SPWorkflowActivationProperties workflowProperties = new SPWorkflowActivationProperties();
public Comm_UpdateReisItemPermissions()
{
InitializeComponent();
}
private void AddUserRoleToItem (string AUserNameField, string ARoleName, SPListItem @AListItem, SPWeb @AWeb)
{
String UserName = AListItem[AUserNameField].ToString();
if (UserName == “”)
return;
SPUser User = AWeb.SiteUsers.GetByID (int.Parse(UserName.Substring(0, UserName.IndexOf(‘;’))));
SPRoleAssignment roleAssignment = new SPRoleAssignment (User.LoginName, “”, “”, “”);
SPRoleDefinition roleDefinition = AWeb.RoleDefinitions[ARoleName];
roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
AListItem.RoleAssignments.Add(roleAssignment);
}
private void SetReisItemPermissionsEx(object sender, EventArgs e)
{
SPSite site = new SPSite(siteID);
SPWeb web = site.OpenWeb(webID);
SPList list = web.Lists[listID];
SPListItem listItem = list.GetItemById(itemID);
listItem.BreakRoleInheritance(false);
foreach (SPRoleAssignment role in listItem.RoleAssignments)
{
role.RoleDefinitionBindings.RemoveAll();
role.Update();
}
AddUserRoleToItem(“XXZ”, “Full Control”, listItem, web);
AddUserRoleToItem(“XXY”, “Design”, listItem, web);
listItem.Update();
site.Close();
}
private void onWorkflowActivated1_Invoked(object sender, ExternalDataEventArgs e)
{
webID = workflowProperties.WebId;
siteID = workflowProperties.SiteId;
listID = workflowProperties.ListId;
itemID = workflowProperties.ItemId;
}
}
}

Add links to Top Navigation Sharepoint 2010 programmatically
Here is a short console application to add a link (For e.g. in our case : a link to a subsite created in Sharepoint 2010) to a parent site top level navigation using object model. So its kind of a way of programmatically doing what “Display this site on the top link bar of the parent site” does.
using System;
using System.Linq;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Navigation;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
using (SPSite site = new SPSite(“http://SPSite”))
{
using (SPWeb child = site.OpenWeb(“SubSite”))
{
// Verify that this is not the root of a site collection.
if (!child.IsRootWeb)
{
// Use links from parent on the child’s top link bar.
child.Navigation.UseShared = true;
// If the parent web’s top link bar is not inherited,
// add a link to the child on the parent’s top link bar.
if (!child.ParentWeb.Navigation.UseShared)
{
// Get the parent’s top link bar.
SPNavigationNodeCollection topnav = child.ParentWeb.Navigation.TopNavigationBar;
// Query for an existing link to the child.
SPNavigationNode node = topnav.Cast().FirstOrDefault(n => n.Url.Equals(child.ServerRelativeUrl));
// No link, so add one.
if (node == null)
{
// Truncate long a title.
string linkTitle = child.Title;
if (linkTitle.Length > 15)
linkTitle = linkTitle.Substring(0, 12) + “…”;
// Create the node.
node = new SPNavigationNode(linkTitle, child.ServerRelativeUrl);
// Add it.
node = topnav.AddAsLast(node);
}
}
}
}
}
Console.Write(“\nPress ENTER to continue….”);
Console.ReadLine();
}
}
}

Show Ribbon on all pages sharepoint 2010 programmatically
Here is example that will enable ribbon on all the pages and will also enable a customtab
SPRibbon ribbon = Microsoft.SharePoint.WebControls.SPRibbon.GetCurrent(this.Page);
string sAbsolutePath = SPContext.Current.Site.UpgradeRedirectUri.AbsolutePath;
if (ribbon != null)
{
ribbon.Minimized = false;
ribbon.CommandUIVisible = true;
const string initialTabId = “Ribbon.CustomTab”;
if (!ribbon.IsTabAvailable(initialTabId))
ribbon.MakeTabAvailable(initialTabId);
ribbon.InitialTabId = initialTabId;
}

Deploy User Control with webpart Sharepoint 2010
The basic code used to load a custom control in a visual webpart made in VS 2010 is shown below
using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
namespace SimpleWebPart.VisualWebPart1
{
public class VisualWebPart1 : WebPart
{
protected const string _ascxPath = @”~/_CONTROLTEMPLATES/SimpleWebPart/VisualWebPart1/CustomUserControl.ascx”;
public VisualWebPart1()
{
}
protected override void CreateChildControls()
{
try
{
Control control = this.Page.LoadControl(_ascxPath);
Controls.Add(control);
}
finally
{
base.CreateChildControls();
}
}
protected override void Render(HtmlTextWriter writer)
{
base.Render(writer);
}
}
}

Creating dashboards in Sharepoint 2010 – Tutorial
Creating Dashboards – II
To create a dashboards in SharePoint 2010, you would use the newly integrated part of the SharePoint Server 2010 Enterprise called PerformancePoint. PerformancePoint Services is a performance management service that you can use to monitor and analyze your business or you can say that, PerformancePoint Services is Microsoft’s dashboard delivery tool, which now is part of the SharePoint Server 2010 Enterprise platform. PerformancePoint Services enables you to create rich, context-driven dashboards that aggregate data and content to provide a complete view of how your business is performing at all levels.
What will PerformancePoint give me?
It provides you with flexible and easy-to-use tools for building Key Performance Indicators (KPIs), Scorecards, Analytic Charts and Grids, Reports, Filters and Dashboards.Each of these components are unique to PerformancePoint Services and provide functionality that interacts with a server component that handles the hard parts like data connectivity and security.
What is PerformancePoint Services as a service application -
As you know that In SharePoint Server 2010 services are no longer contained within a Shared Service Provider (SSP) instead you can create a service application for each service and can share them with various existing web applications. To understand better, PerformancePoint Services will be one of the Service that will stay in the application server with a database something like “PerformancePoint Services Service database” in the Sql server box.

What is Secure Store Service:
– This service application stores the password for the PerformancePoint Services unattended account.
What are the Features of PerformancePoint Services –
* With PerformancePoint Services, the dashboards and dashboard items are stored and secured within SharePoint lists and libraries, providing you with a single security and repository framework. The new architecture also takes advantage of SharePoint Server scalability, collaboration, backup and recovery, and disaster recovery capabilities.
* The Decomposition Tree is a new visualization report type available in PerformancePoint Services. You can use it to quickly and visually break down higher-level data values from a multi-dimensional data set to understand the driving forces behind those values. The Decomposition Tree is available in scorecards and analytic reports and ultimately in dashboards.
* You can access more detailed business information with improved scorecards. Scorecards have been enhanced to make it easy for you to drill down and quickly access more detailed information. PerformancePoint scorecards also offer more flexible layout options, dynamic hierarchies, and calculated KPI features.
* Better Time Intelligence filtering capabilities that you can use to create and use dynamic time filters that are always up to date. Other improved filters improve the ability for dashboard users to quickly focus in on information that is most relevant.
* Ability to include and link PerformancePoint Services Web Parts together with other PerformancePoint Services Web parts on the same page.
* Easier to author and publish dashboard items by using Dashboard Designer.
* The KPI Details report is a new report type that displays contextually relevant information about KPIs, metrics, rows, columns, and cells within a scorecard. The KPI Details report works as a Web part that links to a scorecard or individual KPI to show relevant metadata to the end user in SharePoint Server.
* Create analytics reports to better understand underlying business forces behind the results. Analytic reports have been enhanced to support value filtering, new chart types, and server-based conditional formatting.
What is this Dashboard Designer ?
PerformancePoint Dashboard Designer is the design tool you will use to build key performance indicators (KPIs), indicators, scorecards, reports, filters, data sources, and dashboards. It also enables you to deploy your finished dashboards to SharePoint.

Prerequisites for creating dashboards –

1. Activate the SharePoint Server Publishing Infrastructure feature. PerformancePoint Services uses this feature to perform dashboard publishing.
2. Activate PerformancePoint Services Site Collection Features feature. This feature adds PerformancePoint content types and a Business Intelligence Center site template.
3. Activate the SharePoint Server Enterprise Site Collection Features feature. This feature enables Excel Services, Visio Services, and Access Services, included in the SharePoint Server Enterprise License.
4. Create a new Business Intelligence Center site by clicking Site Actions ➪ New Site, and then choose Business Intelligence template.
5. Create an Unattended Service Account.
In PerformancePoint Services, you create the unattended account directly in the PerformancePoint Services application settings.
In this case, the password is stored in Secure Store Service and the actual username is stored in the PerformancePoint Services database.
An unattended account can be created using the following steps:
1. Browse to the Central Administration Site.
2. From the Application Management category, choose Manage service applications.
3. From the list of existing service applications, click PerformancePoint Service Application.
4. Click the PerformancePoint Service Application Settings link.
5. Specify the unattended service account for PerformancePoint and click OK.

Create a dashboard in Sharepoint 2010
In continuation with my earlier Post about performance point and the prerequisites for creating a dashboard. In this post we will look at the steps to create a new dashboard and a scorecard.
To get started Open the Dashboard Designer. To do this follow the Steps below
1. In Internet Explorer, navigate to the Business Intelligence Center site that you must have created.
2. Click the Create Dashboards link, and then click Start using PerformancePoint Service link.
3. From the PerformancePoint Services page, click the big button that says Run Dashboard Designer. This will download and install the PerformancePoint Dashboard Designer to your workstation.
Once the executable fi le is downloaded and installed on your computer, the PerformancePoint Dashboard Designer appears. Once the Dashboard Designer is installed, you have an empty workspace. A workspace is a primary container for all of the elements that you can use to build your dashboard, and it keeps its content synched with the site from which it was launched.
Creating Your Dashboard -
Before we get started with building a dashboad lets just create a Dashboard Datasource first. To understand better read the Post Datasources for Creating Dashboards.

To create a Dashboard Datasource follow the below steps :
Update Create dashboard with SharePoint List Create dashboard with SQL datasource
1. Right – click the Data Connections folder in the Workspace Browser, and then select New ➪ Data Source.
2. From the Select a Data Source Template menu, choose the Analysis Services template to create a datasource that connects to Microsoft SQL Server Analysis Services, and click OK. Next Configure the Connection Settings.
3. Watch for Cache Lifetime setting. The value of this textbox (in minutes) indicates the interval of refreshing the dashboard information from the backend datasource.
4. Click Test Data Source to make sure that your connection settings are correct.
5. Switch to the Properties tab and change the Name of your datasource.
6. Save the new datasource by right – clicking it in the Workspace Browser, and then selecting Save.
Creating KPI –
Now that we have our connection ready lets create our key performance indicator (KPI). In order to create a new KPI to track what ever you wanna track for your company, you need to follow these steps:
1. Right – click the PerformancePoint Content folder and select New ➪ KPI.
2. In the Select a KPI Template dialog, select Blank KPI, and then click OK.
3. And once you have your KPI created, you can define your actual and Target values. Also, select the data source and the measure.
4. Click OK to close the dialog.
5. Select the Target row, and click the Set Scoring Pattern and Indicator button in the Thresholds area.
6. Next, In the Edit Binding Settings dialog, select the fi rst option (Band by normalized value of Actual/Target) from the Banding method drop – down, and then click Next.
7. In the Select an Indicator step, select an indicator to use for the target that clearly shows whether the goal is met. You can choose from a collection of indicator templates available in PerformancePoint Dashboard Designer. Once you are done, click Next.
8. In the last step of the wizard, leave the value intact and click Finish.
9. Save the KPI by right – clicking it in the Workspace Browser, and then selecting Save.

Create dashboard with list in SharePoint 2010
In Continuation with my previous posts on how to create a dashboard and a KPI and about various data sources for dashboard, in this post I will add the steps to create a Dashboard with SharePoint List as a Datasource
Important things to remember -
1. The data from the SharePoint lists can only be read by using PerformancePoint Services; any editing of the data must be done from SharePoint Server.
2. You can connect to any kind of SharePoint list.
Steps to create a SharePoint list datasource are :
1. Right-Click the Data Connections folder in the Workspace Browser, and then select New ➪ Data Source.
2. In the Category pane of the Select a Data Source Template dialog box, click Tabular List and then click SharePoint list. Click OK.
3. In the left navigation pane (workspace browser), type a name for your data source.
4. In the center pane, click the Editor tab. In the Data Source Settings section, select the method on which to authenticate to the data source.
5. In the Cache Lifetime drop-down list, type the refresh rate (in minutes) for the cache. Data from this data source will update at this interval.
6. In the Connection Settings section, type the URL to the SharePoint site.
7. In the SharePoint Site List drop-down, select a List collection.
8. In the List drop-down list, select the desired SharePoint list from the collection.
9. Click Test Data Source to confirm that the connection is configured correctly.

Datasources for Creating Dashboards
ome notes on various Datasources that would be used while creating dashboards.
In PerformancePoint Services you must create a connection to the data source or sources you want to use in your dashboard. All data used in PerformancePoint Services is external data, living in data repositories outside of PerformancePoint. After you establish a data connection, you will be able to use the data in the various PerformancePoint feature areas.
Lets the types of Databases that you can use and there fetaure
1. SharePoint Lists – Data contained in a SharePoint List on a SharePoint Site can be used in PerformancePoint Services by creating a SharePoint List data source in Dashboard Designer. Please Note that the data from SharePoint Lists can only be read. Modification to SharePoint List data must be done from SharePoint.
See how to create a SharePoint List datasource Create dashboard with SharePoint List
2. Excel Services – Data in Excel files published to Excel Services on a SharePoint Site can be used in PerformancePoint Services by creating an Excel Services data source. Supported published data can only be read in PerformancePoint Services. Published parameter values can be modified from the Dashboard Designer. If you use an Excel Services parameter in calculating a KPI, it is easy to make additional changes. PerformancePoint Servicessupports the following Excel Services components: Named Ranges, Tables and Parameters.
3. Excel workbooks – You may use the content of an actual Excel file as a data source in PerformancePoint ServicesPerformancePoint Service by creating an Excel Workbook data source connection and select only the data that is to be used. The original Excel file will be independent from the PerformancePoint copy. PerformancePoint Services 2010 supports Excel 2007 and Excel 2010 workbooks as data sources.
4. SQL Server tables – You can create a data source connection to a SQL Server database and use the data within PerformancePoint Services. SQL tables and SQL views are supported data sources within PerformancePoint Services.

Sharepoint 2010 create dashboard with SQL datasource
Adding another post in a series of posts about creating dashboards and using various datasources in Sharepoint 2010. In this post however, we will learn how to create a data source connection for SQL server table for your dashboard.
Read the Tutorials first
Creating dashboards in Sharepoint 2010 – Tutorial
Create Dashboard Steps
Datasources for Creating Dashboards

Please Note : PerformancePoint Services accesses external data sources by using a delegated Windows identity. Consequently, external data sources must reside within the same domain as the SharePoint Server 2010 farm. If external data sources do not reside within the same domain, authentication to the external data sources will fail.
To Create a SQL Server table data source connection
1. Launch Dashboard Designer.
2. Click the Create tab, and then click Data Source.
3. In the Category pane of the Select a Data Source Template dialog box, click Tabular List and then click SQL Server table. Click OK.
4. In the left navigation pane (workspace browser), type in a name for your data source.
5. In the center pane, click the Editor tab. In the Data Source Settings section, select the method by which to authenticate to the data source.
6. In Refresh Interval, specify the duration (in minutes) before data is refreshed from the source.
7. In the Connection Settings section, select the method by which to connect to the data source.
To use a standard connection:
1. Select Use standard connection
2. Type the full path for the server to which you want to connect. This populates the options in the database list.
3. In the Database box, select a database name.
To use a specific connection string:
1. Select Use the following connection.
2. Type a connection string with the full path of the server and database to which you want to connect.
3. In the Table drop-down list, select the specific table that you want to use.
8. Click Test Data Source to confirm that the connection is configured correctly.

.Net 4 with SharePoint Foundation 2010
Since this has been asked a million times in various forums. Here is the Final word from Michael Foertsch (secretsofsharepoint.com/cs).
The SharePoint Foundation 2010 object model is not accessible using the .NET Framework 4 (or later). Calling any object or method in the object model using any framework version other than .NET 3.5 will throw the following exception:
System.PlatformNotSupportedException
Microsoft SharePoint is not supported with version 4.0.30319.1 of the Microsoft .Net Runtime.
Of course, you can always access the SharePoint objects using the web services interface from your .NET 4 application, but this will only allow limited functionality of the complete object model.

Create publishing pages sharepoint 2010 programmatically
Below is an example of Adding a New Publishing Page to the SharePoint 2010 Site Pages Library
PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web);
string pageName = “MyCustomPage.aspx”;
PageLayout[] pageLayouts = publishingWeb.GetAvailablePageLayouts();
PageLayout currPageLayout = pageLayouts[0];
PublishingPageCollection pages = publishingWeb.GetPublishingPages();
PublishingPage newPage = pages.Add(pageName,currPageLayout);
newPage.ListItem[FieldId.PublishingPageContent] = “This is my content”;
newPage.ListItem.Update();
newPage.Update();
newPage.CheckIn(“This is just a comment”);
In the code above a PageLayout instance with index 0 is selected from all the available page layouts. By using the PageLayout instance, a new page of type PublishingPage is added to the site pages library. Afterward, the content of a field, identified by FieldId.PublishingPageContent, is set to a HTML text value, followed by an update and check-in.

Programmatically get resource files in sharepoint 2010
In this post we will learn how to access resource files saved in sharePoint 2010′s 14 hive in our webpart.  I have a resource file below as an example
<data name=”Button.Text” xml:space=”preserve”>
<value>Click me</value>
</data>
<data name=”Button.Tooltip” xml:space=”preserve”>
<value>Click me tooltip</value>
</data>
You can use this button in your CreatechildControls of your webpart as below
protected override void CreateChildControls()
{
Button b = new Button();
ResourceManager rm = new ResourceManager(“WebParts.ResourceWebPart.NonVisualWebPart”, this.GetType().Assembly);
b.Text = rm.GetString(“Button.Text”);
b.OnClientClick = “ShowAlert(this)”;
Controls.Add(b);
base.CreateChildControls();
}

Defining Features in onet.xml sharepoint
To define which features should be used with your Site definition you need to specify site-scoped and web-scoped features separately. In the below example we have added site-scoped features (the basic Web Part feature and three-state workflow that comes with SharePoint) that enables basic functionalities and in the web-scoped section, first reference is to a custom project list feature containing the list definition. and next two features are SharePoint standard elements that contain several list templates, such as custom list or calendar and the mobility redirect feature.
The configuration is
<Configuration ID=”0″ Name=”Production” CustomMasterUrl=”_catalogs/masterpage/custom.master” MasterUrl=”_catalogs/custom.master”>
<Lists>
<List FeatureId ….
</List>
</Lists>
<Modules>
<Module Name=”Default” />
<Module Name=”Reports” />
</Modules>
<SiteFeatures>
<!– BasicWebParts Feature –>
<Feature ID=”023BSES71-1U5D-4B2H-R340-BE5123EBDA57″ />
<!– Three-state Workflow Feature –>
<Feature ID=”FGE5D250-621E-4743-95SA-87B472322DC7″ />
</SiteFeatures>
<WebFeatures>
<!– Custom ProjectList Feature –>
<Feature ID=”7346F624-0SE1-4H6D-H2A2-80HS744FD8BC” />
<!– TeamCollab Feature –>
<Feature ID=”00BFEA71-4EA5-48D4-A4AD-7SD5C011ABE5″ />
<!– MobilityRedirect –>
<Feature ID=”F41CC622-37E5-4943-B6A8-74UJDB3FD8A4″ />
</WebFeatures>
</Configuration>

Programmatically add audience for web parts sharepoint 2010
In this Post we will set the audience for a WebPart which Web Parts page, you can use the SPLimitedWebPartManager object to get the Web Part whose property you want to edit.
using (SPWeb site = (SPWeb)properties.Feature.Parent)
{
// Get SPLimitedWebPartManager for “default.aspx” page.
using (SPLimitedWebPartManager webPartManager = site.GetLimitedWebPartManager(“default.aspx”, PersonalizationScope.Shared))
{
AudienceManager audienceManager = new AudienceManager(ServerContext.Current);
// Assign the GUID for “Sample Audience” to the AuthorizationFilter property of the first Web Part on the page.
webPartManager.WebParts[0].AuthorizationFilter = string.Format(“{0}, {1};;;;”,audienceManager.GetAudience(“Sample Audience”).AudienceID);
// Save the changes to the Web Part.
webPartManager.SaveChanges(webPartManager.WebParts[0]);
}}

Programmatically retrieve social ratings in sharepoint 2010
Here is an example of how to retrieve social ratings
Using Object model -
string GetRatingForThisURL = “http://MySharePoint/Pages/NewWebPart.aspx”;
Uri myUri = new Uri(GetRatingForThisURL);
using (SPSite site = new SPSite(“http:/SharePointSite”))
{
SPServiceContext context = SPServiceContext.GetContext(site);
SocialRatingManager mySocialRatingManager = new SocialRatingManager(context);
SocialRating aRating = mySocialRatingManager.GetRating(myUri);
Console.WriteLine(aRating.Url + “: ” + aRating.Rating);
}

Using WebService -

string GetRatingForThisURL = “http://MySharePoint/Pages/NewWebPart.aspx”;
ServiceReference1.SocialDataService mySocialDataService = new ServiceReference1.SocialDataService();
mySocialDataService.Credentials = System.Net.CredentialCache.DefaultCredentials;
mySocialDataService.Url = “http://MySharePoint/_vti_bin/socialdataservice.asmx”;
SocialRatingDetail details = mySocialDataService.GetRatingOnUrl(GetRatingForThisURL);
Console.Write(“The rating for ” + GetRatingForThisURL + ” is ” + details.Rating.ToString());
Console.Read();

Add,Delete,Retrieve list item REST Sharepoint 2010
Here is a quick example below of adding an item to the Announcements list using REST in SharePoint 2010. For adding, you call the specific AddTo method for your list, such as AddToAnnouncements and for updating and deleting, you use the UpdateObject and DeleteObject methods and pass in the object you want to update or delete.
RESTReference.HomeDataContext context = new RESTReference.HomeDataContext(new Uri(“http://MySharePointSite/_vti_bin/listdata.svc”));
private void Add_Click(object sender, EventArgs e)
{
//Add a new Announcement
RESTReference.AnnouncementsItem newAnnounce = new RESTReference.AnnouncementsItem(); // Announcement type object.
newAnnounce.Title = “My New Announcement! ” + DateTime.Now.ToString();
context.AddToAnnouncements(newAnnounce);
context.SaveChanges();
}
private void Retrieve_Click(object sender, EventArgs e)
{
//Populate grid using LINQ
context.Credentials = CredentialCache.DefaultCredentials;
var q = from a in context.Announcements
select a;
this.announcementsItemBindingSource.DataSource = q; -> announcementsItemBindingSource a grid object
}

Add quick launch links Programmatically in Sharepoint 2010
As you may know that the Navigation property of the Microsoft.SharePoint.SPWeb class gets a Microsoft.SharePoint.Navigation.SPNavigation object that contains all the navigation properties for a specified site and the QuickLaunch property of the SPNavigation object returns the collection of navigation nodes found in the Quick Launch area. The things are no different in SharePoint 2010 you can add a new link in your quick launch by adding a new SPNavigationNode type node to SPNavigationNodeCollection.
Code example :
SPSite siteCollection = SPControl.GetContextSite(Context);
SPWeb site = siteCollection.AllWebs["MySitecoll"];
SPWeb subSite = site.Webs["MyWeb"];
SPNavigationNodeCollection nodes = subSite.Navigation.QuickLaunch;
SPNavigationNode navNode = new SPNavigationNode(“New Link”, “/Pages/mylib/Allitems.aspx”, false);
nodes.AddAsFirst(navNode);
The third parameter of the SPNavigationNode constructor is set to true if the URL for the new link is external to the SharePoint Foundation deployment.
Also please note: You must add a Microsoft.SharePoint.WebControls.FormDigest control to the page making the post.

Programmatically Show\Hide or Change links in quick launch bar
You can programmatically Show\Hide or Change Url for the links in Quick Launch bar according to the logged in User or Whatever your condition is. In this post however, we will just Change the Url for one of links in quick launch bar, according to the logged in user's group. The Code is written in a User Control which will later be added to the master page. Adding the Control in the master page does add some overhead but will allow the code to run on each sharepoint page.

Initial requirement -

Change the Url for one of the links called "Your Department" in quick launch bar according to the logged in user's group.

Steps :

1. Create Webapplication project and add a Web UserControl in it.

2. Add References to Microsoft.SharePoint dll.

Use the below method in Page load to Change the url:

private void ChangeLink(string NewLink)
{

SPSite site = SPContext.Current.Site;
SPWeb myWeb = site.RootWeb;

SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite siteCollection = new SPSite(site.ID))
{
using (SPWeb web = siteCollection.OpenWeb(myWeb.ID))
{
web.AllowUnsafeUpdates = true;

SPNavigationNodeCollection nodes = web.Navigation.QuickLaunch;

foreach (SPNavigationNode node in nodes)
{
CheckURL(node,web, NewURl);
}

web.AllowUnsafeUpdates = false;
} }
});

}

private void CheckURL(SPNavigationNode Node,SPWeb web,string NewURl)
{

if (Node.Children.Count > 0)
{
SPNavigationNodeCollection childNodes = Node.Children;
foreach (SPNavigationNode cNode in childNodes)
{
if (cNode.Title.ToString() == "Your Department")
{
cNode.Url = NewURl;
cNode.Update();
}
}
}
}

In above Code CheckURL method will navigate through each link in the quick launch bar to find the one with name "Your Department". If the link is found we can simply use cNode.Url and cNode.Update() to update the url.

3. After, you are done writing the logic, just Sign the Project and Build it. Dont forget to drop the signed dll in GAC.

4.. Finally, add the user Control in the Master Page and Test it.

List all the web parts on sharepoint page client object model sharepoint 2010
In this example you will learn how to get and set  Title information for webparts on the default.aspx page using Ecmascript.
ClientContext oClientContext = new ClientContext(“http://SPSite”);
File oFile = oClientContext.Web.GetFileByServerRelativeUrl(“Default.aspx”);
LimitedWebPartManager limitedWebPartManager = oFile.GetLimitedWebPartManager(PersonalizationScope.Shared);
oClientContext.Load(limitedWebPartManager.WebParts,
wps => wps.Include(
wp => wp.WebPart.Title));   //-> Can include more properties
oClientContext.ExecuteQuery();
if (limitedWebPartManager.WebParts.Count == 0)
{
throw new Exception(“No Web Parts on this page.”);
}
WebPartDefinition oWebPartDefinition = limitedWebPartManager.WebParts[1];
WebPart oWebPart = oWebPartDefinition.WebPart;
oWebPart.Title = “My New Web Part Title”;
oWebPartDefinition.SaveWebPartChanges();
oClientContext.ExecuteQuery();
}

Programmatically Create Relation between Sharepoint 2010 lists
In this we will create two lists in SharePoint 2010 and setup the Relation between the lists by adding the lookup column. Please note that the belwo example is a console application.
string lookupFieldName = “RelatedField”;
using (SPSite site = new SPSite(“http://SpSite”))
{
using (SPWeb web = site.OpenWeb())
{
SPListCollection lists = web.Lists;
//Creating Parent list
Guid SourceListId = lists.Add(“Parent List”,”", SPListTemplateType.GenericList);
Console.WriteLine(“Parent List Done…”);
//Creating Child List
Guid TargetListId = lists.Add(“Child List”,”",SPListTemplateType.GenericList);
Console.WriteLine(“Child List Done…”);
SPList SourceList = lists[SourceListId];
SPList TargetList = lists[TargetListId];
SPFieldCollection Fields = TargetList.Fields;
//Adding a lookup Field in Child List
Fields.AddLookup(lookupFieldName, SourceList.ID, true);
Console.WriteLine(“Lookup Field Created”);
//Adding the Restrict behaviour
SPFieldLookup NewLookupField = Fields[lookupFieldName] as SPFieldLookup;
NewLookupField.Indexed = true;
NewLookupField.LookupField = “Title”;
NewLookupField.RelationshipDeleteBehavior = SPRelationshipDeleteBehavior.Restrict;
NewLookupField.Update();
Console.WriteLine(“Lookup field integrity enforced”);
//Adding Items in the List
SPListItem NewSourceItem = SourceList.Items.Add();
NewSourceItem["Title"] = “Parent Data”;
NewSourceItem.Update();
Console.WriteLine(“Source listitem created”);
SPListItem NewTargetItem = TargetList.Items.Add();
NewTargetItem["Title"] = “Child Data”;
NewTargetItem[lookupFieldName] = new SPFieldLookupValue(1, “Source Data”);
NewTargetItem.Update();
Console.WriteLine(“Parent listitem created”);
TargetList.Update();
SourceList.Update();
}
}

Programatically get the enforce relationship behavior for lookup field Sharepoint 2010
The code below helps to check weather the field in your current list is a Lookup field to someother list and determine its enforce relationship behavior.
To do this we will use a console application and will use GetRelatedFields() on parent list which will Return a collection of objects with information about a lookup field in another list that points to a field in this list.
Code :
using (SPSite site = new SPSite(“http://SPsite”))
{
using (SPWeb web = site.OpenWeb())
{
SPRelatedFieldCollection RelatedFields = web.Lists["Authors"].GetRelatedFields();
foreach (SPRelatedField RelatedField in RelatedFields)
{
Console.WriteLine(“Field <{0}>{5} bound to <{1}>{5} SPRelationshipDeleteBehavior.{3}{5}Web <{4}>“, web.Lists[RelatedField.ListId].Fields[RelatedField.FieldId].InternalName,
web.Lists[RelatedField.ListId].Title,
RelatedField.LookupList,
RelatedField.RelationshipDeleteBehavior,
site.AllWebs[RelatedField.WebId].Title,
Environment.NewLine);
}
}
}

Programmatically get versions for files in sharepoint 2010 document library
Here is code snippet to get Versions or should say version information for files in Sharepoint 2010 document library. The Code was written in a Console application.
This code assumes that you have a document library called “Mydocumentlib” set up with atleast one document and versioning enabled. In the below code the outer foreach loop inspects all the files, while the inner loop retrieves all the versions for each file.
using (SPSite site = new SPSite(“http://SharePointSite”))
{
using (SPWeb web = site.OpenWeb())
{
SPList docs = web.Lists["Mydocumentlib"];
foreach (SPFile file in docs.RootFolder.Files)
{
Console.WriteLine(“File {0} has next version {1}. Version History:”, file.Url, file.UIVersionLabel);
foreach (SPFileVersion v in file.Versions.Cast().Reverse())
{
Console.WriteLine(” Version {0} checked in at {1} with this comment: ‘{2}’”, v.VersionLabel, v.Created, v.CheckInComment);
}
}
}}

Programmatically get document Version History using client object model sharepoint 2010
Here is the Code snippet to get version history of a document using .net managed client object model
public void GetVersions()
{
ClientContext clientContext = new ClientContext(“http://SPSite”);
Web site = clientContext.Web;
clientContext.Load(site);
clientContext.ExecuteQuery();
File file = site.GetFileByServerRelativeUrl(“/Shared Documents/mydocument.doc”);
clientContext.Load(file);
clientContext.ExecuteQuery();
ListItem currentItem = file.ListItemAllFields;
clientContext.Load(currentItem);
clientContext.ExecuteQuery();
FileVersionCollection versions = file.Versions;
clientContext.Load(versions);
clientContext.ExecuteQuery();
if (versions != null)
{
foreach(FileVersion _version in versions)
{
Console.WriteLine(“Version : {0}”,_version.VersionLabel);
}
}}
Related Post :Programmatically get versions for files in Sharepoint 2010

Get files from document library Silverlight client object model
Here is a detailed code snippet for creating a silverlight applictaion that will display all the files\documents from a document library in a webpart using silverlight Client Object model.
To begin with
1. In Visual Studio 2010 create a new Blank Solution. Select .NET Framework 3.5.
2. Next, from the File menu open click on Add -> New Project.
3. In the New Project dialog box, expand the Installed Templates left hand menu to Visual C# -> Silverlight, and choose the Silverlight Application project type in the project type list in the middle section of the screen. Make sure that you have .NET Framework 3.5 selected. Click Ok to continue on Silverlight Application dialog box.
4. Next, add the required references to the Silverlight client object model. To do this browse to “C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\ClientBin” and select Microsoft.SharePoint.ClientSilverlight.dll and Microsoft.SharePoint.Client.Silverlight.Runtime.dll
5. In the solution explorer open the App.xaml.cs and add the following references to the top of the page.
using Microsoft.SharePoint.Client;
using System.Threading;
6. Next in the same file App.xaml.cs, under Applictaion_Startup method add the below to get the refrence to the current sharepoint site and to ensure that we are in sync with the current SharePoint site.
ApplicationContext.Init(e.InitParams, Synchronizationcontext.Current);
7. Next, lets open up our MainPage.xaml and Add two StackPanels under the existing grid.
<StackPanel Orientation=”Vertical” VerticalAlignment=”Top”>
<StackPanel Name=”mypanel” />
</StackPanel>
8. Now, Open MainPage.xaml.cs and add the following using statements to the top of the file:
using Microsoft.SharePoint.Client;
9. Next, add the following code to get all the files from your SharePoint document library in the silverlight webpart.
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
}
ClientContext clientCtx;
Microsoft.SharePoint.Client.List docs;
int FileCounter= 0;
private void LayoutRoot_Loaded(object sender, RoutedEventArgs e)
{
clientCtx = new ClientContext(ApplicationContext.Current.Url);
clientCtx.Load(clientCtx.Web);
clientCtx.Load(clientCtx.Web.Lists);
docs = clientCtx.Web.Lists.GetByTitle(“My Documents”);
clientCtx.Load(docs);
clientCtx.Load(docs.Rootfolder);
clientCtx.Load(docs.Rootfolder.Files);
clientCtx.ExecuteQueryAsync(loadSiteData, null); // We will move to loadSiteData method on success
}
void loadSiteData(Object sender, ClientRequestSucceededEventArgs e)
{
//This method starts on a background thread, but we need to work on UI to display our files Therefore we call Dispatcher.BeginInvoke() to perform the UI updating on the main thread
Dispatcher.BeginInvoke(addFiles);
}
void addFiles()
{
foreach (File doc in docs.Rootfolder.Files)
{
clientCtx.Load(doc);
clientCtx.ExecuteQueryAsync(addFiletoUI, null); // We will move to loadSiteData method on success
}
}
void addFiletoUI(Object sender, ClientRequestSucceededEventArgs e)
{
Dispatcher.BeginInvoke(addFile);
}
void addFile()
{
string filename = docs.Rootfolder.Files[FileCounter].Name;
string fileUrl = docs.Rootfolder.Files[FileCounter].ServerRelativeUrl;
HyperlinkButton fLink= new HyperlinkButton();
fLink.Content = filename;
fLink.NavigateUri = new Uri(fileUrl , UriKind.Relative);
mypanel.Children.Add(fLink);
FileCounter++;
}
}
10. Build and deploy the webpart.
11. Goto SharePoint site and add a silverlight webpart. Point the webpart to “”/_layouts/ClientBin/YourSilverlightApp_Name.xap” and your Done! yeh!

Programmatically get versions for files in sharepoint 2010 document library
Here is code snippet to get Versions or should say version information for files in Sharepoint 2010 document library. The Code was written in a Console application.
This code assumes that you have a document library called “Mydocumentlib” set up with atleast one document and versioning enabled. In the below code the outer foreach loop inspects all the files, while the inner loop retrieves all the versions for each file.
using (SPSite site = new SPSite(“http://SharePointSite”))
{
using (SPWeb web = site.OpenWeb())
{
SPList docs = web.Lists["Mydocumentlib"];
foreach (SPFile file in docs.RootFolder.Files)
{
Console.WriteLine(“File {0} has next version {1}. Version History:”, file.Url, file.UIVersionLabel);
foreach (SPFileVersion v in file.Versions.Cast().Reverse())
{
Console.WriteLine(” Version {0} checked in at {1} with this comment: ‘{2}’”, v.VersionLabel, v.Created, v.CheckInComment);
}
}
}}

Programmatically Check in\Check out documents in Sharepoint 2010
In this post we will see an example of how to check out and check in one or all the documents in a SharePoint 2010 document library programmatically.
I have created a console application to the task
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
namespace CheckinCheckoutDemo
{
class MyDemo
{
static void Main(string[] args)
{
using (SPSite site = new SPSite(“http://SPSite”))
{
using (SPWeb web = site.OpenWeb())
{
SPDocumentLibrary docs = (SPDocumentLibrary)web.Lists["Mydocumentlibrary"]; -> Your Document library name
foreach (SPFile file in docs.RootFolder.Files)
{
if (file.CheckOutType == SPFile.SPCheckOutType.None)
{
file.CheckOut(); -> Checking out the file
}
}
// Getting the above Checked Out file.
foreach (SPCheckedOutFile file in docs.CheckedOutFiles)
{
Console.WriteLine(file.LeafName); -> Writing names of checked out files
}
// Check in and add a comment.
foreach (SPFile file in docs.RootFolder.Files)
{
if (file.CheckOutType != SPFile.SPCheckOutType.None)
{
file.CheckIn(“Programmatically Checked In”); -> checking In and adding a comment
}
}}}

Create list from list template sharepoint 2010 programmatically
Creating a list using existing Custom List template -
_web.Lists.Add(“MyCustomList”, “My list description”, _siteCollection.GetCustomListTemplates(_web)["ListTemplateName"]);
or
SPSite siteCollection = SPContext.Current.Site;
SPWeb _web= SPContext.Current.Web;
SPListTemplateCollection listTemplates = siteCollection.GetCustomListTemplates(_web);
SPListTemplate listTemplate = listTemplates["ListTemplateName"];
mySite.Lists.Add(“Custom List”, “A list created from a custom list template in the list template catalog”, listTemplate);
_web – > SPweb object
siteCollection -> site collection or SPSite object
ListTemplateName -> Name of your Custom List Template
Creating a list using Out-of-Box List template -
_web.Lists.Add(“MyCustomList”, “My list description”, SPListTemplateType.GenericList);
Programmatically saving a List as a Template in SharePoint 2010 -
SPList mySourcelist = _web.Lists["MyCustomlist"];
mySourcelist.SaveAsTemplate(“listTemplatename.stp”,”MyListTemplate”, “My List Template Desc”, false);
mySourcelist.Update();

Passing parameters to the dialog sharepoint 2010 Client Object model
To answer both the questions our guest user sharepointgeek has posted a fairly simple example. The example below will get the selected items from your current list and add it to the myitems string seprated by “|”. Then we create an option variable and construct the url passing the selected items and listname as parameters.
var ctx = SP.ClientContext.get_current();
var items = SP.ListOperation.Selection.getSelectedItems(ctx);
var myItems = ”;
var k;
for (k in items)
{
myItems += ‘|’ + items[k].id;
}
var options = {
url: ‘/_layouts/Customdialog/mydialog.aspx?items=’ + myItems + ‘&source=’ + SP.ListOperation.Selection.getSelectedList(),
tite: ‘Move Documents’,
allowMaximize: false,
showClose: false,
width: 800,
height: 600,
dialogReturnValueCallback: demoCallback };
SP.UI.ModalDialog.showModalDialog(options);”

Location and GroupID Properties for StandardMenu – Chart
This a small chart that you might need while creating Custom Action menus in SharePoint 2010.
As you may know that to define a custom action for a particular menu, you must first identify the menu. The property Location defines the menu—for example, Microsoft.SharePoint.SiteSettings or Microsoft.SharePoint.StandardMenu. The GroupID property however, defines an area within the menu.

Location GroupID Description
Microsoft.SharePoint.StandardMenu ActionsMenu Actions in list\document library views
Microsoft.SharePoint.StandardMenu ActionsMenuForSurvey Site actions menu for surveys
Microsoft.SharePoint.StandardMenu NewMenu New menu in list\document library views
Microsoft.SharePoint.StandardMenu NewMenu New menu in list\document library views
Microsoft.SharePoint.StandardMenu PersonalActions Menu showing “Welcome username”,”Sign in” items
Microsoft.SharePoint.StandardMenu SettingsMenu Settings menu in list\document library views
Microsoft.SharePoint.StandardMenu SettingsMenuForSurvey Site settings links for surveys
Microsoft.SharePoint.StandardMenu  SiteActions Site actions menu
Microsoft.SharePoint.StandardMenu  UploadMenu Upload menu in list\document library views

Access BCS entities and methods Programmatically SharePoint 2010
This post we will see an example for accessing Business Connectivity Services or BCS entities and its methods using Client object model.
Assumptions – Already have an External content type setup
private static void BrowseCatalogDetails()
{
Console.WriteLine(“Now Browsing the all the entities in the catalog:”);
AdministrationMetadataCatalog catalog = AdministrationMetadataCatalog.GetCatalog(siteUrl);
EntityCollection entities = catalog.GetEntities(“*”, “*”, true);
Console.WriteLine(“\nEntities in the system:”);
foreach (Entity entity in entities)
{
Console.WriteLine(entity.Name);
}
// Browsing through the first entity
var entityEnum = entities.GetEnumerator();
entityEnum.MoveNext();
Entity firstEntity = entityEnum.Current;
Console.WriteLine(“\nMethods on the first Entity:”);
foreach (var method in firstEntity.Methods)
{
Console.WriteLine(method.Name);
}
}
The above code is to access the SharePoint entity catalog. To get a specific entity use
IEntity entity = catalog.GetEntity(siteUrl, “MyexternalContentType”);

Get data from bcs external content type in SharePoint 2010 Programmatically
Here is short example of how to execute a method on an entity Programmatically. Assuming you already have a External content type “My External content type” setup to a Sql database lets look at a console application
private static void ExecuteMethod()
{
Console.WriteLine(“\nNow Executing methods”);
using (SPSite site = newSPSite(siteUrl))
{
using (newSPServiceContextScope(SPServiceContext.GetContext(site)))
{
BdcService service = SPFarm.Local.Services.GetValue();
IMetadataCatalog catalog = service.GetDatabaseBackedMetadataCatalog(SPServiceContext.Current);
IEntity entity = catalog.GetEntity(siteUrl, “My External content type”);
ILobSystemInstance LobSysteminstance = entity.GetLobSystem().GetLobSystemInstances()[0].Value;
IMethodInstance method = entity.GetMethodInstance(“Read List”, MethodInstanceType.Finder);
IEntityInstanceEnumerator handle = entity.FindFiltered(method.GetFilters(), LobSysteminstance);
Console.WriteLine(“Title in My External content type:”);
while (handle.MoveNext())
{
Console.WriteLine(handle.Current["Title"].ToString());
}
}}}

Programmatically create user groups Sharepoint 2010
Create a group -
//Add the group to the SPWeb web
web.SiteGroups.Add(“Mygroup”, “ikapoor”, “ikapoor”, “My Readers Group”);
//Associate the group with SPWeb
web.AssociatedGroups.Add(web.SiteGroups["Mygroup"]);
web.Update();
//Assignment of the roles to the group.
SPRoleAssignment assignment = new SPRoleAssignment(web.SiteGroups["Mygroup"]);
SPRoleDefinition _role = web.RoleDefinitions["Read"];
assignment.RoleDefinitionBindings.Add(_role );
web.RoleAssignments.Add(assignment);
Adding users to your new group -
SPUser spUser = spWeb.EnsureUser(“domain\ikapoor”);
if (spUser != null)
{
SPGroup spGroup = spWeb.Groups["Mygroup"];
if (spGroup != null)
spGroup.AddUser(spUser);
}

Programatically Create User Groups Client object model SharePoint 2010
Here is the Code snippet for Creating a Group and assigning it a permission level or role  using Client Object model . To add the users to this group using Client OM see my Post Here
See adding groups using server object model @Create user groups Sharepoint 2010
Create a User Group –
//get the connection
ClientContext ctx = new ClientContext(“http://SPSite”);
//create the group
GroupCreationInformation grp = new GroupCreationInformation();
grp .Title = “Your New Group”;
grp .Description = “This is a custom group created using the client object model”;
//add it to the list of site groups
Group newgrp = ctx.Web.SiteGroups.Add(grp);
//Get a role.
RoleDefinition rd = ctx.Web.RoleDefinitions.GetByName(“Permission level Name”); // – > To Create a Custom Role definition or Permission level see my post Here
//create the role definition binding collection
RoleDefinitionBindingCollection rdb = new RoleDefinitionBindingCollection(ctx);
//add the role definition to the collection
rdb.Add(rd);
//create a RoleAssigment with the group and role definition
ctx.Web.RoleAssignments.Add(grp, rdb);
//execute the query to add everything
ctx.ExecuteQuery();

Programmatically create custom permission level using Client object model SharePoint 2010
Create Custom Permission level using Client Object model –
ClientContext ctx = new ClientContext(“SPSiteurl”);
//create a new base permission
BasePermissions perms = new BasePermissions();
var _basePerm = | SPBasePermissions.AddListItems| SPBasePermissions.EditListItems;
perms.Set((PermissionKind)Enum.Parse(typeof(PermissionKind), _basePerm));
//create the construct for a new role definition
RoleDefinitionCreationInformation rdInfo = new RoleDefinitionCreationInformation();
//set the perms
rdInfo.BasePermissions = perms;
//set a descriptionrdInfo.Description = “Custom Role definition created with the client object model”;
//set the name
rdInfo.Name = “My custom Permission level”;
//add the definition to the web collection
RoleDefinition rd = ctx.Web.RoleDefinitions.Add(rdInfo);
//execute to create
ctx.ExecuteQuery();
Now Assign a user this custom role definition –
/get the group
RoleDefinition rd = ctx.Web.RoleDefinitions.GetByName(“My custom Permission level”);
//get the user object
Principal usr = ctx.Web.EnsureUser(“domain\isha”);
//create the role definition binding collection
RoleDefinitionBindingCollection rdb = new RoleDefinitionBindingCollection(ctx);
//add the role definition to the collection
rdb.Add(rd);
//create a RoleAssigment with the user and role definition
ctx.Web.RoleAssignments.Add(usr, rdb);

Programatically add users to a group Client object model SharePoint 2010
Create Users and Add them to a Group -
//get the connection
ClientContext ctx = new ClientContext(“http://SPSite”);
//get the group
Group grp = ctx.Web.SiteGroups.GetById(GroupId); -> get group id ( See Post Get all users and groups client object model sharepoint 2010
//create the user object
UserCreationInformation usr = new UserCreationInformation();
usr.LoginName = “Domain\isha”;
usr.Email = “ikapoo@Oursite.com”;
usr.Title = “Programmer”;
//add it to the group
grp.Users.Add(usr);
//execute the query to add the user
ctx.ExecuteQuery();

Get List Views in SharePoint 2010 client object model programmatically
Here is a short example of how to get list views using Client object model in SharePoint 2010
Dim objmyList As SP.List = g_objCore.Security.Web.Lists.GetByTitle(“**Your List Name*”)
Dim objmyView As SP.View = objmyList.Views.GetByTitle(“*Your View Name*”)
Dim objViewFldColl As SP.ViewFieldCollection = objmyView.ViewFields
g_objCore.Security.ClientContext.Load(objViewFldColl)
g_objCore.Security.ClientContext.ExecuteQuery()
Now you can iterate through objViewFldColl to get the Fields in the View

Add custom menu item in Site Actions sharepoint 2010
The best Practice to add a Custom menu Item in SharePoint 2010′ s Site Actions menu is by creating a Feature and installing that as a wsp in the SharePoint 2010 environment.
In this post you will how to create a feature and solution package for adding a Custom action item in Site Action menu.
Steps are :
1. Create a new Project in VS 2010 and under SharePoint (left) select Empty Project.
2. Now enter the url of your SharePoint site for debugging and select deploy as a farm solution.
3. Now, once you have the project open, right click on the Feature folder and Add a new feature.
4. SharePoint automatically adds a feature and names it as Feature1. You can however change the feature name to something like CustomActionFetaure.
5. With this you will have a feature designer opened in front of you set the Title description and scope of the feature.
6. Now right click on the Project and add a new Item. In the Add New Item dialog, select Empty Element to create a blank element file.
7. Add the below Code to the element.xml file
<Elements xmlns=”http://schemas.microsoft.com/sharepoint/”>
<CustomAction
Id=”myCustomAction”
GroupId=”PersonalActions”
Location=”Microsoft.SharePoint.StandardMenu”
Sequence=”1000″
Title=”Open custom page”
Description=”Open my custom page”
ImageUrl=”_layouts/1033/images/myimage.png”>
<UrlAction Url=”~site/_layouts/CustomPage.aspx”/>
</CustomAction>
</Elements>
8. Build the Project. Open the feature.xml file and verify that if contains the reference to the element.xml file.
9. Now Deploy the wsp and activate the feature in your site.

Programmatically use MediaWebPart Client object model Sharepoint 2010
The code below uses ECMAScript (JavaScript, JScript) object model to access the media player.
Here are the steps :
1. The first thing to consider is to add a reference to the below script file in your project.
2. Add a media player webpart on your page.
3. The ECMAScript for setting up the properties for the media player webpart are :
//Gets the media player.
function getMediaPlayer()
{
var p = document.getElementById(“MediaPlayerHost”)
var obj = p.getElementsByTagName(“object”);
return obj[0].Content.MediaPlayer;
}
//Initialize the media player object and set values for its properties. Customize MediaUrlField and PreviewURLField values for your local environment.
function init()
{
var serverStr = window.location.href;
serverStr = serverStr.substr(7);
serverStr = serverStr.substr(0, serverStr.indexOf(“/”));
document.getElementById(“MediaURLField”).value = “http://” + serverStr + “/documents/test.wmv”;
document.getElementById(“PreviewURLField”).value = “http://” + serverStr + “/documents/test.jpg”;
document.getElementById(“TitleField”).value = “API Test Page”;
document.getElementById(“TemplateURLField”).value = “http://” + serverStr + “/Style%20Library/XAML/AlternateMediaPlayer.xaml”;
}
//Set properties of the media player, including media URL, preview image URL, template URL, title, autoplay, whether to repeat, and default display mode.
function SetMediaSource()
{
var elm = document.getElementById(“MediaURLField”);
var p = getMediaPlayer();
p.MediaSource = elm.value;
}
function SetPreviewImageSource()
{
var elm = document.getElementById(“PreviewURLField”);
var p = getMediaPlayer();
p.PreviewImageSource = elm.value;
}
function SetMediaTitle()
{
var elm = document.getElementById(“TitleField”);
var p = getMediaPlayer();
p.MediaTitle = elm.value;
}
function SetTemplateSource()
{
var elm = document.getElementById(“TemplateURLField”);
var p = getMediaPlayer();
p.TemplateSource = elm.value;
}
function SetAutoPlay()
{
var elm = document.getElementById(“autoPlayCB”);
var p = getMediaPlayer();
p.AutoPlay = elm.checked;
}
function SetLoop()
{
var elm = document.getElementById(“loopCB”);
var p = getMediaPlayer();
p.Loop = elm.checked;
}
function SetDisplayMode()
{
var elm = document.getElementById(“DisplayModeSelect”);
var p = getMediaPlayer();
p.DisplayMode = elm.value;
}

Treeview Control in Sharepoint 2010
n this post you will learn how to Programmatically use the Treeview control in Sharepoint 2010.
At First, we will create an application page in VS 2010 to contain a drop-down list bind to all the Navigation Providers in SharePoint 2010 and a TreeView Control to display the selected navigation providers in a Treeview hierarchy. Lets follow the Steps -
Steps -
1. Create a new Application Page in Vs 2010.
2. Add the below code to the aspx of the application page
<%@ Page Language=”C#” AutoEventWireup=”true” DynamicMasterPageFile=”~masterurl/default.master”
CodeFile=”NavigationProviders.aspx.cs” Inherits=”NavigationProviders” CodeFileBaseClass=”Microsoft.SharePoint.WebControls.LayoutsPageBase” %>
<asp:Content ContentPlaceHolderId=”PlaceHolderMain” runat=”server”>
<asp:DropDownList id=”ddlNavProviders” runat=”server” AutoPostBack=”True” OnSelectedIndexChanged=”ddlNavProviders_SelectedIndexChanged” />
<asp:TreeView id=”navTreeView” runat=”server”></asp:TreeView>
</asp:Content>
3. Add the Code behind – The code-behind class first initializes DropDownList with all the navigation providers defined in web.config. By selecting a navigation provider, the SiteMapDataSource pointing to the selected provider is bound to the TreeView.
using System;
using System.Web;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
public partial class NavigationProviders : LayoutsPageBase
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// Init the DropDown element with all available navigation providers
ddlNavProviders.DataSource = SiteMap.Providers;
ddlNavProviders.DataTextField = “Name”;
ddlNavProviders.DataBind();
}
}
protected void ddlNavProviders_SelectedIndexChanged(object sender,EventArgs args)
{
// Bind the selected navigation provider to the TreeView
SiteMapDataSource ds = new SiteMapDataSource();
ds.Provider = SiteMap.Providers[ddlNavProviders.SelectedItem.Text];
navTreeView.DataSource = ds;
navTreeView.DataBind();
}
}

Save infopath 2010 form data to Sharepoint list programmatically
In continuation with my previous post where I created an application page and added the xmlformview control to the page, in this post i will show you how to save the data in the infopath form hosted inside the xmlformview control ( on our cutsom applictaion page) on OnSubmitToHost of the xmlformview.
In this post you will learn how to retrieve user submitted data in infopath form fields (fields are FirstName and LastName) and how to save the whole form in SharePoint library with the name created using FirstName and LastName fields.
Lets first modify the xmlformviewcontrol – Adding the OnSubmitToHost
<fv:XmlFormView ID=”formView” runat=”server” EditingStatus=”Editing” OnSubmitToHost=”FormView_SubmitToHost” Width=”700px”></fv:XmlFormView>
Code for submit to host
protected void FormView_SubmitToHost(object sender, SubmitToHostEventArgs e)
{
SPWeb web = SPContext.Current.Web;
web.AllowUnsafeUpdates = true;
// Load the XML and save it as a byte array
System.Xml.XPath.XPathNavigator navigator = formView.XmlForm.MainDataSource.CreateNavigator();
Byte[] formBytes = System.Text.Encoding.UTF8.GetBytes(navigator.OuterXml);
// Create XmlDocument from the form XML
XmlDocument doc = new XmlDocument();
XmlNamespaceManager nsm = new XmlNamespaceManager(doc.NameTable);
nsm.AddNamespace(“my”, “http://schemas.microsoft.com/office/infopath/2003/myXSD/2009-09-29T22:54:17″);
doc.LoadXml(navigator.OuterXml);
// Load name information from the XML
XmlNode nodeLastName = doc.SelectSingleNode(“/my:myform/my:UserInformation/my:LastName”, nsm);
string name = (nodeLastName != null) ? nodeLastName.InnerText : string.Empty;
XmlNode nodeFirstName = doc.SelectSingleNode(“/my:RoomBooking/my:UserInformation/my:FirstName”, nsm);
string firstname = (nodeFirstName != null) ?nodeFirstName.InnerText : string.Empty;
// Generate file name
string filename = String.Format(“{0}{1}_{2}.xml”, name, firstname, DateTime.Now.ToString(“yyyyMMdd”));
// Open library and save XML
SPFolder formLibrary = web.GetFolder(LIBRARY_NAME);
formLibrary.Files.Add(filename, formBytes);
web.AllowUnsafeUpdates = false;
}

Infopath 2010 form drop-down list change event get data programmatically
A short code snippet to get the data from a datasource on change event of a drop-down list in Infopath 2010 form.
In the code below the method InternalStartup() is called to register the event change for the dropdown and the method mydropdown_Changed() is called to access the actual datasource “MyDATASOURCE” for retrieving the values for Field1 or sharepoint Title column from the sharepoint list datasource(MyDATASOURCE).
The parameter passed to the Datasource via the webservice is ID of the drop-down item.
using Microsoft.Office.InfoPath;
using System;
using System.Xml;
using System.Xml.XPath;
namespace Getdatanamespace
{
public partial class FormCode
{
public void InternalStartup()
{
EventManager.XmlEvents["/my:myform/my:table1/my:mydropdown"].Changed += new XmlChangedEventHandler(mydropdown_Changed);
}
public void mydropdown_Changed(object sender, XmlEventArgs e)
{
XPathNavigator form = MainDataSource.CreateNavigator();
// Set parameter for web service request and query connection
DataSources["MyDATASOURCE"].CreateNavigator().SelectSingleNode(“/dfs:myFields/dfs:queryFields/q:SharePointListItem_RW/q:ID”,NamespaceManager).SetValue(e.NewValue); ->> sending the ID as a parameter to the webservice call which will access the datasource
DataSources["MyDATASOURCE"].QueryConnection.Execute();
// Create navigator on web service response
XPathNavigator resultnav = DataSources["MyDATASOURCE"].CreateNavigator();
// Set fields with values from web service response
XPathNavigator Field1 = form.SelectSingleNode(“/my:myform/my:table1/my:field1″, NamespaceManager);
Field1.SetValue(resultnav.SelectSingleNode(“/dfs:myFields/dfs:dataFields/d:SharePointListItem_RW/d:Title”,NamespaceManager).Value);
}
}
}

add xmlformview control on sharepoint page programmatically
In the below code snippet I am adding an xmlformview control on an SharePoint 2010 application page and using the code behind for that page to load the xml form and to set the properties for the xmlformview control.
ApplicationPage Aspx page -
<%@ Page Language=”C#” AutoEventWireup=”true” CodeFile=”MyFormPage.aspx.cs”  Inherits=”MyFormPage”  EnableSessionState=”True” %>
<%@ Register tagprefix=”fv” namespace=”Microsoft.Office.InfoPath.Server.Controls”  assembly=”Microsoft.Office.InfoPath.Server, Version=14.0.0.0, Culture=neutral,
PublicKeyToken=71e9bce111e9429c” %>
<%@ Register tagprefix=”Server” namespace=”Microsoft.Office.InfoPath” assembly=”Microsoft.Office.InfoPath, Version=14.0.0.0, Culture=neutral,
PublicKeyToken=71e9bce111e9429c” %>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
<title>FormViews</title>
</head>
<body style=”margin: 0px;overflow:auto;padding:20px”>
<form id=”form1″ runat=”server” enctype=”multipart/form-data”>
<fv:XmlFormView ID=”formView” runat=”server” EditingStatus=”Editing” Width=”700px”>
</fv:XmlFormView>
</form>
</body>
</html>
Please Note that to correctly display the forms, XmlFormView needs to know the location of the form to display, the location of the form template used to render the form, and finally, the location for saved forms to be stored. The properties XmlLocation, XsnLocation, and SaveLocation are used to pass this information to
the XmlFormView object.
Now, Lets look at the Code behind for the application Page. The code behind below uses the On_Load method to display the actual Infopath form. Before loading the form the Onload method reads the request parameter i.e. “action” and decides weather an existing form should be loaded using the XmlLocation parameter or the template should be assigned by the XsnLocation ( if action== new).
Code Behind -
using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.Office.InfoPath.Server.Controls;
namespace formviewdemo
{
public partial class MyFormPage: LayoutsPageBase
{
protected void Page_Load(object sender, EventArgs e)
{
string action = Request.Params["action"];
if (action == “new”)
{
// Set the template location for new forms
String templateLib = “FormServerTemplates”;
String xsnName = “template.xsn”; ->> form template Name
formView.XsnLocation = String.Format(“{0}/{1}/{2}”, SPContext.Current.Web.Url, templateLib, xsnName);
}
else
{
// Set the XML location for an existing form ( in the sharepoint library)
String lib = “TestForms”;
String name = “example.xml”; ->> name of the infopathform
formView.XmlLocation = String.Format(“{0}/{1}/{2}”, SPContext.Current.Web.Url, lib, name);
}}
}}

Infopath 2010 form drop-down list change event get data programmatically
A short code snippet to get the data from a datasource on change event of a drop-down list in Infopath 2010 form.
In the code below the method InternalStartup() is called to register the event change for the dropdown and the method mydropdown_Changed() is called to access the actual datasource “MyDATASOURCE” for retrieving the values for Field1 or sharepoint Title column from the sharepoint list datasource(MyDATASOURCE).
The parameter passed to the Datasource via the webservice is ID of the drop-down item.
using Microsoft.Office.InfoPath;
using System;
using System.Xml;
using System.Xml.XPath;
namespace Getdatanamespace
{
public partial class FormCode
{
public void InternalStartup()
{
EventManager.XmlEvents["/my:myform/my:table1/my:mydropdown"].Changed += new XmlChangedEventHandler(mydropdown_Changed);
}
public void mydropdown_Changed(object sender, XmlEventArgs e)
{
XPathNavigator form = MainDataSource.CreateNavigator();
// Set parameter for web service request and query connection
DataSources["MyDATASOURCE"].CreateNavigator().SelectSingleNode(“/dfs:myFields/dfs:queryFields/q:SharePointListItem_RW/q:ID”,NamespaceManager).SetValue(e.NewValue); ->> sending the ID as a parameter to the webservice call which will access the datasource
DataSources["MyDATASOURCE"].QueryConnection.Execute();
// Create navigator on web service response
XPathNavigator resultnav = DataSources["MyDATASOURCE"].CreateNavigator();
// Set fields with values from web service response
XPathNavigator Field1 = form.SelectSingleNode(“/my:myform/my:table1/my:field1″, NamespaceManager);
Field1.SetValue(resultnav.SelectSingleNode(“/dfs:myFields/dfs:dataFields/d:SharePointListItem_RW/d:Title”,NamespaceManager).Value);
}
}
}

Comparing SharePoint 2010 Search – Foundation VS Server Vs FAST
Here is a little comparison chart for describing Search capabilities in Search Foundation 2010 Vs  SharePoint Server 2010 Vs FAST Search Server 2010
Feature SharePoint Foundation 2010 SharePoint Server 2010 FAST Search Server 2010
Basic Search Yes Yes Yes
Document preview N No Yes
Indexing sites Yes Yes Yes
Indexing external content No Yes Yes
People search No Yes Yes
Query federation No Yes Yes
UI-based administration Limited Yes Yes
Visual best bets No Limited Yes

Check in documents with Powershell SharePoint 2010
A simple script shared at @ http://secretsofsharepoint.com/cs/ site for Checking in the documents in a document library using a powershell script.
function CheckInDocument([string]$url)
{
$spWeb = Get-SPWeb $url
$getFolder = $spWeb.GetFolder(“Shared Documents”)
$getFolder.Files | Where { $_.CheckOutStatus -ne “None” } | ForEach
{
Write-Host “$($_.Name) is Checked out To: $($_.CheckedOutBy)”
$_.CheckIn(“Checked In By Administrator”)
Write-Host “$($_.Name) Checked In” -ForeGroundColor Green
}
$spWeb.Dispose()
}
Here’s an example on running the function:
CheckInDocument http://SP

Exception handling Client object model sharepoint 2010
In this post I will show you examples for how to handle exceptions while using Client object model. Both .Net managed client and ECMAscript are explained below.
To overcome the need for multiple server requests, depending on exceptions, an ExceptionHandlingScope class has been introduced in SharePoint 2010. This class includes methods to wrap code in a scope and handle exceptions that occur within the batch processing of the commands given to the ClientContext instance.
Lets look at an example.The example below queries a list named NonExistentList and updates its Description property. When executing this code for the first time and assuming that the list does not exist, an exception will be thrown when calling ExecuteQuery. This exception will be caught, and within the catch block, this list will be created.

.Net Object Model

public void exceptionExample()
{
ClientContext ctx = new ClientContext(“http://clserver”);
ExceptionHandlingScope exScope = new ExceptionHandlingScope(ctx);
using (exScope.StartScope())
{
using (exScope.StartTry())
{
// Get list NonExistingList and update its description
List myList = ctx.Web.Lists.GetByTitle(“NonExistingList”);
myList.Description = “This is a new description”;
myList.Update();
}
using (exScope.StartCatch())
{
// Create new list NonExistingList
ListCreationInformation listCreationInfo = new ListCreationInformation();
listCreationInfo.Title = “NonExistingList”;
listCreationInfo.Description = “Created within catch block”;
listCreationInfo.TemplateType = (int)ListTemplateType.GenericList;
List oList = ctx.Web.Lists.Add(listCreationInfo);
}
using (exScope.StartFinally())
{
// Update description of list NonExistingList
List myList = ctx.Web.Lists.GetByTitle(“NonExistingList”);
myList.Description = “This is a description created by the final block”;
myList.Update();
}
}
ctx.ExecuteQuery();
}
The whole client code block is wrapped within an ExceptionHandlingScope.StartScope method, which defines the beginning of the client object
operations. Then, each logical block (i.e. the blocks that retrieve, create, and update the list) is wrapped into its own scope operation (StartTry, StartCatch, and StartFinally). Only if an exception occurs within the StartTry code block will the StartCatch block be executed. The StartFinally code block will always be executed, irrespective of whether an exception occurs.
Using ECMAScript
function exceptionExample()
{
this.ctx = new SP.ClientContext.get_current();
var exScope = new SP.ExceptionHandlingScope(this.ctx);
var startScope = exScope.startScope();
var tryScope = exScope.startTry();
// Get list NonExistingList and update its description
var myList = ctx.get_web().get_lists().getByTitle(“NonExistingList”);
myList.set_description(“This is a new description”);
myList.update();
tryScope.dispose();
var catchScope = exScope.startCatch();
// Create new list NonExistingList
var listCreationInfo = new SP.ListCreationInformation();
listCreationInfo.set_title(“NonExistingList”);
listCreationInfo.set_description(“Created within catch block”);
listCreationInfo.set_templateType(SP.ListTemplateType.genericList);
ctx.get_web().get_lists().add(listCreationInfo);
catchScope.dispose();
var finallyScope = exScope.startFinally();
// Update description of list NonExistingList
var myList = ctx.get_web().get_lists().getByTitle(“NonExistingList”);
myList.set_description(“This is a description created by the final block”);
myList.update();
finallyScope.dispose();
startScope.dispose();
this.ctx.executeQueryAsync( Function.createDelegate(this, this.onSucceededCallback),
Function.createDelegate(this, this.onFailedCallback));
}
The usage of the ExceptionHandlingScope in JavaScript is nearly the same as in C#. Because there is no using construct in JavaScript, you have to dispose of the scope objects manually by calling scope.dispose.

Sharepoint 2010 Administrator Interview Questions
Q. What are the Hardware and Software requirements for SharePoint 2010.
Ans.

Hardware requirements :
# Processor 64-bit, four-core, 2.5 GHz minimum per core.
# RAM 4 GB for developer or evaluation use, 8 GB for single server and multiple server farm installation for production use.
# Hard disk 80 GB for installation
For production use, you need additional free disk space for day-to-day operations. Add twice as much free space as you have RAM for production environments.
Software requirements :
# The 64-bit edition of Windows Server 2008 Standard with SP2. If you are running Windows Server 2008 without SP2, the Microsoft SharePoint Products and Technologies 2010 Preparation Tool installs Windows Server 2008 SP2 automatically.
Q. What Has Changed with SSP in SharePoint 2010.
Ans. In SharePoint 2010 Shared Service Providers (SSP's) are replaced by Service Applications. Services are no longer combined into a SSP. They are running independent as a service application. The service application architecture is now also built into Microsoft SharePoint Foundation 2010, in contrast to the Shared Services Provider (SSP) architecture that was only part of Office SharePoint Server 2007.
A key benefit here is that all services are installed by default and there is no SSP setup.
Additional improvements for the service application model include:
• The services architecture is extensible, allowing third-party companies to build and add services to the platform.
• Services are managed directly in Central Administration (rather than a separate administration site).
• Services can be monitored and managed remotely.
• Services can be managed and scripted by Windows PowerShell™.
• Shared services communications take place over HTTP(S). Shared services do not directly access databases across farms.
 • Most new services are built on the Windows Communications Framework. They have optimization built into their protocol, using binary streams instead of XML for data transfer. Test results show improvements in network throughput with this change.
Q. What are the advantages of Service Applications over SSP ?
Ans. The key limitation of the SSP architecture was that it was configured by using a set of services, and all Web applications associated with the SSP bore the overhead of all the services even if they weren’t being used. To change the service configuration for a particular Web application, a new SSP would have to be created.
The service application architecture on the other hand, allows a set of services to be associated with a given Web application and a different set of services to be associated with another Web application. Also, the same service application can be configured differently in different Web applications; therefore, Web sites can be configured to use only the services that are needed, rather than the entire bank of services.
Q. Can we create a Single set of Services that will be shared across the farm?
Ans. Similar to the SSP model in Office SharePoint Server 2007, a single set of services can be shared by all sites in a farm. By publishing a service application (from the sharing group, under Service application tab), you can share it across server farms. This capability does not apply to all service applications, and some services can be shared only within a single server farm.
Q. What are Managed Accounts?
Ans. To reduce the load of managing various service accounts in Microsoft SharePoint Server 2010, the concept of managed accounts has been introduced. Much like managed accounts in Windows Server 2008, they allow SharePoint Server to take control of all the service accounts you use. After SharePoint Server has control of these accounts, it can either manage their passwords — automatically changing them as necessary — or it can notify you when an accounts password is about to expire, allowing you to make the change yourself.
Q. What are the Methods of Backup and Recovery in SharePoint 2010?
Ans. Microsoft SharePoint Server 2010 provides a broad range of levels for performing backups, including the entire farm, farm configuration information, site collections, subsites, or lists.
SharePoint Server 2010 uses two different tools to configure backup and recovery.
1. Central Administration : Central Administration provides a user interface where SharePoint Administrators will be prompted via menu structures to select the information that needs to be backed up. (see the Image below)
2. Windows PowerShell : Windows PowerShell is a command line tool that provides SharePoint administrators a way to perform backup and recovery with additional options such as file compression or working with SQL snapshots.
Listed below are a few of the benefits available when working with Windows PowerShell:
• Windows PowerShell scripts can be developed and scheduled (with Windows Task Scheduler), whereas Central Administration is used for single-use backups and restores.
• Windows PowerShell has the advantage of running against SQL snapshots instead of the production database. One of the parameters of the Windows PowerShell command will cause a SQL snapshot to be generated, and then Windows PowerShell will run the action against the snapshot instead of the production database. This will reduce the resource impact of the backup operation on the production environment.
• With Windows PowerShell, SharePoint administrators will have more granular control of options for the backup or restore.
Q. How to Export a Site or List in SharePoint 2010?
Ans. SharePoint Server 2010 provides several new features that provide a granular level of backup for various components of site content. This includes content at the site, subsite, and list level.
Through Central Administration(Granular level Back-up) a SharePoint Administrator can configure a backup of a subsite or list. An Administrator can choose a site and a specific list to be exported.The administrators can also choose to export security and select the different versions that will be exported with the list.

Old Questions

  • what is SharePoint?

    Portal Collaboration Software.

  • what is the difference between SharePoint Portal Server and Windows SharePoint Services?

    SharePoint Portal Server is the global portal offering features like global navigation and searching. Windows SharePoint Services is more content management based with document libraries and lists. You apply information to certain areas within your portal from Windows SharePoint Services or directly to portal areas.

  • what is a document library?

    A document library is where you upload your core documents. They consist of a row and column view with links to the documents. When the document is updated so is the link on your site. You can also track metadata on your documents. Metadata would consist of document properties.

  • what is a meeting workspace?

    A meeting workspace is a place to store information, attendees, and tasks related to a specific meeting.

  • what is a document workspace?

    Document workspaces consist of information surrounding a single or multiple documents.

  • what is a web part?

    Web parts consist of xml queries to full SharePoint lists or document libraries. You can also develop your own web parts and web part pages.

  • what is the difference between a document library and a form library?

    Document libraries consist of your core documents. An example would be a word document, excel, powerpoint, visio, pdf, etc… Form libraries consist of XML forms.

  • what is a web part zone?

    Web part zones are what your web parts reside in and help categorize your web parts when designing a page.

  • how is security managed in SharePoint?

    Security can be handled at the machine, domain, or sharepoint level.

  • how are web parts developed?

    Web parts are developed in Visual Studio .Net. VS.Net offers many web part and page templates and can also be downloaded from the Microsoft site.

  • what is a site definition?

    It’s a methods for providing prepackaged site and list content.

  • what is a template?

    A template is a pre-defined set of functions or settings that can be used over time. There are many templates within SharePoint, Site Templates, Document Templates, Document Library and List Templates.

  • how do you install web parts?

    Web Parts should be distributed as a .CAB (cabinet) file using the MSI Installer.

  • what is CAML?

    tands for Collaborative Application Markup Language and is an XML-based language that is used in Microsoft Windows SharePoint Services to define sites and lists, including, for example, fields, views, or forms, but CAML is also used to define tables in the Windows SharePoint Services database during site provisioning.

  • what is a DWP?

    he file extension of a web part.

  • what is the GAC?

    Global Assembly Cache folder on the server hosting SharePoint. You place your assemblies there for web parts and services.

  • what are the differences between web part page gallery, site gallery, virtual server gallery and online gallery?

    Web Part Page Gallery is the default gallery that comes installed with SharePoint. Site Gallery is specific to one site. Virtual Server gallery is specific to that virtual server and online gallery are downloadable web parts from Microsoft.

  • what is the difference between a site and a web?

    The pages in a Web site generally cover one or more topics and are interconnected through hyperlinks. Most Web sites have a home page as their starting point. While a Web is simply a blank site with SharePoint functionality built in; meaning you have to create the site from the ground up.

  • What is Microsoft Windows SharePoint Services? How is it related to Microsoft Office SharePoint Server 2007?

    Windows SharePoint Services is the solution that enables you to create Web sites for information sharing and document collaboration. Windows SharePoint Services — a key piece of the information worker infrastructure delivered in Microsoft Windows Server 2003 — provides additional functionality to the Microsoft Office system and other desktop applications, and it serves as a platform for application development.
    Office SharePoint Server 2007 builds on top of Windows SharePoint Services 3.0 to provide additional capabilities including collaboration, portal, search, enterprise content management, business process and forms, and business intelligence.

  • What is Microsoft SharePoint Portal Server?

    SharePoint Portal Server is a portal server that connects people, teams, and knowledge across business processes. SharePoint Portal Server integrates information from various systems into one secure solution through single sign-on and enterprise application integration capabilities. It provides flexible deployment and management tools, and facilitates end-to-end collaboration through data aggregation, organization, and searching. SharePoint Portal Server also enables users to quickly find relevant information through customization and personalization of portal content and layout as well as through audience targeting.

  • What is Microsoft Windows Services?

    Microsoft Windows Services is the engine that allows administrators to create Web sites for information sharing and document collaboration. Windows SharePoint Services provides additional functionality to the Microsoft Office System and other desktop applications, as well as serving as a plat form for application development. SharePoint sites provide communities for team collaboration, enabling users to work together on documents, tasks, and projects. The environment for easy and flexible deployment, administration, and application development.

  • What is the relationship between Microsoft SharePoint Portal Server and Microsoft Windows Services?

    Microsoft SharePoint Products and Technologies (including SharePoint Portal Server and Windows SharePoint Services) deliver highly scalable collaboration solutions with flexible deployment and management tools. Windows SharePoint Services provides sites for team collaboration, while Share Point Portal Server connects these sites, people, and business processes—facilitating knowledge sharing and smart organizations. SharePoint Portal Server also extends the capabilities of Windows SharePoint Services by providing organizational and management tools for SharePoint sites, and by enabling teams to publish information to the entire organization.

  • Who is Office SharePoint Server 2007 designed for?

    Office SharePoint Server 2007 can be used by information workers, IT administrators, and application developers.
    is designed

  • What are the main benefits of Office SharePoint Server 2007?


    Office SharePoint Server 2007 provides a single integrated platform to manage intranet, extranet, and Internet applications across the enterprise.
    * Business users gain greater control over the storage, security, distribution, and management of their electronic content, with tools that are easy to use and tightly integrated into familiar, everyday applications.
    * Organizations can accelerate shared business processes with customers and partners across organizational boundaries using InfoPath Forms Services–driven solutions.
    * Information workers can find information and people efficiently and easily through the facilitated information-sharing functionality and simplified content publishing. In addition, access to back-end data is achieved easily through a browser, and views into this data can be personalized.
    * Administrators have powerful tools at their fingertips that ease deployment, management, and system administration, so they can spend more time on strategic tasks.
    * Developers have a rich platform to build a new class of applications, called Office Business Applications, that combine powerful developer functionality with the flexibility and ease of deployment of Office SharePoint Server 2007. Through the use of out-of-the-box application services, developers can build richer applications with less code.

  • What is the difference between Microsoft Office SharePoint Server 2007 for Internet sites and Microsoft Office SharePoint Server 2007?

    Microsoft Office SharePoint Server 2007 for Internet sites and Microsoft Office SharePoint Server 2007 have identical feature functionality. While the feature functionality is similar, the usage rights are different.
    If you are creating an Internet, or Extranet, facing website, it is recommended that you use Microsoft Office SharePoint Server 2007 for Internet sites which does not require the purchase client access licenses. Websites hosted using an “Internet sites” edition can only be used for Internet facing websites and all content, information, and applications must be accessible to non-employees. Websites hosted using an “Internet sites” edition cannot be accessed by employees creating, sharing, or collaborating on content which is solely for internal use only, such as an Intranet Portal scenario. See the previous section on licensing for more information on the usage scenarios.

  • What suites of the 2007 Microsoft Office system work with Office SharePoint Server 2007?

    Office Outlook 2007 provides bidirectional offline synchronization with SharePoint document libraries, discussion groups, contacts, calendars, and tasks.
    Microsoft Office Groove 2007, included as part of Microsoft Office Enterprise 2007, will enable bidirectional offline synchronization with SharePoint document libraries.
    Features such as the document panel and the ability to publish to Excel Services will only be enabled when using Microsoft Office Professional Plus 2007or Office Enterprise 2007.
    Excel Services will only work with documents saved in the new Office Excel 2007 file format (XLSX).

  • How do I invite users to join a Windows SharePoint Services Site? Is the site secure?

    SharePoint-based Web sites can be password-protected to restrict access to registered users, who are invited to join via e-mail. In addition, the site administrator can restrict certain members' roles by assigning different permission levels to view post and edit.

  • Can I post any kind of document?

    You can post documents in many formats, including .pdf, .htm and .doc. In addition, if you are using Microsoft Office XP, you can save documents directly to your Windows SharePoint Services site.

  • Can I download information directly from a SharePoint site to a personal digital assistant (PDA)?

    No you cannot. However, you can exchange contact information lists with Microsoft Outlook.

  • How long does it take to set up the initial team Web site?

    It only takes a few minutes to create a complete Web site. Preformatted forms let you and your team members contribute to the site by filling out lists. Standard forms include announcements, events, contacts, tasks, surveys, discussions and links.

  • Can I create custom templates?

    Yes you can. You can have templates for business plans, doctor's office, lawyer's office etc.

  • How can I make my site public? By default, all sites are created private.

    If you want your site to be a public Web site, enable anonymous access for the entire site. Then you can give out your URL to anybody in your business card, e-mail or any other marketing material. The URL for your Web site will be:
    http:// yoursitename.wss.bcentral.com
    Hence, please take special care to name your site.
    These Web sites are ideal for information and knowledge intensive sites and/or sites where you need to have shared Web workspace.
    Remember: Under each parent Web site, you can create up to 10 sub-sites each with unique permissions, settings and security rights.

  • How do the sub sites work?

    You can create a sub site for various categories. For example:
    * Departments - finance, marketing, IT
    * Products - electrical, mechanical, hydraulics
    * Projects - Trey Research, Department of Transportation, FDA
    * Team - Retention team, BPR team
    * Clients - new clients, old clients
    * Suppliers - Supplier 1, Supplier 2, Supplier 3
    * Customers - Customer A, Customer B, Customer C
    * Real estate - property A, property B
    The URLs for each will be, for example:
    * http://yoursitename.wss.bcentral.com/finance
    * http://yoursitename.wss.bcentral.com/marketing
    You can keep track of permissions for each team separately so that access is restricted while maintaining global access to the parent site.

  • How do I make my site non-restricted?

    If you want your site to have anonymous access enabled (i.e., you want to treat it like any site on the Internet that does not ask you to provide a user name and password to see the content of the site), follow these simple steps:
    # Login as an administrator
    # Click on site settings
    # Click on Go to Site Administration
    # Click on Manage anonymous access
    # Choose one of the three conditions on what Anonymous users can access:
    ** Entire Web site
    ** Lists and libraries
    ** Nothing
    Default condition is nothing; your site has restricted access. The default conditions allow you to create a secure site for your Web site.

  • Can I get domain name for my Web site?

    Unfortunately, no. At this point, we don't offer domain names for SharePoint sites. But very soon we will be making this available for all our SharePoint site customers. Please keep checking this page for further update on this. Meanwhile, we suggest you go ahead and set up your site and create content for it.

  • What are picture libraries?

    Picture libraries allow you to access a photo album and view it as a slide show or thumbnails or a film strip. You can have separate folder for each event, category, etc

  • What are the advantages of a hosted SharePoint vs. one that is on an in-house server?

    * No hardware investment, i.e. lower costs
    * No software to download - ready to start from the word go
    * No IT resources - Anyone who has used a Web program like Hotmail can use it
    * Faster deployment

  • Can I ask users outside of my organization to participate in my Windows SharePoint Services site?

    Yes. You can manage this process using the Administration Site Settings. Simply add users via their e-mail alias and assign permissions such as Reader or Contributor.

  • Are there any IT requirements or downloads required to set up my SharePoint site?

    No. You do not need to download any code or plan for any IT support. Simply complete the on-line signup process and provide us your current and correct email address. Once you have successfully signed up and your site has been provisioned, we will send a confirmation to the email address you provided.

  • I am located outside of the United States. Are there any restrictions or requirements for accessing the Windows SharePoint Services?

    No. There are no system or bandwidth limitations for international trial users. Additionally language packs have been installed which allow users to set up sub-webs in languages other than English. These include: Arabic, Danish, Dutch, Finnish, French, German, Hebrew, Italian, Japanese, Polish, Portuguese (Brazilian), Spanish and Swedish.

  • Are there any browser recommendations?

    Yes. Microsoft recommends using the following browsers for viewing and editing Windows SharePoint Services sites: Microsoft Internet Explorer 5.01 with Service Pack 2, Microsoft Internet Explorer 5.5 with Service Pack 2, Internet Explorer 6, Netscape Navigator 6.2 or later.

  • What security levels are assigned to users?

    Security levels are assigned by the administrator who is adding the user. There are four levels by default and additional levels can be composed as necessary.
    * Reader - Has read-only access to the Web site.
    * Contributor - Can add content to existing document libraries and lists.
    * Web Designer - Can create lists and document libraries and customize pages in the Web site.
    * Administrator - Has full control of the Web site.

  • How secure are Windows SharePoint Services sites hosted by Microsoft?

    Microsoft Windows SharePoint Services Technical security measures provide firewall protection, intrusion detection, and web-publishing rules. The Microsoft operation center team tests and deploys software updates in order to maintain the highest level of security and software reliability. Software hot-fixes and service packs are tested and deployed based on their priority and level of risk. Security related hot-fixes are rapidly deployed into the environment to address current threats. A comprehensive software validation activity ensures software stability through regression testing prior to deployment.

  • What is the difference between an Internet and an intranet site?

    An internet site is a normal site that anyone on the internet can access (e.g., www.msn.com, www.microsoft.com, etc.). You can set up a site for your company that can be accessed by anyone without any user name and password.
    An intranet (or internal network), though hosted on the Web, can only be accessed by people who are members of the network. They need to have a login and password that was assigned to them when they were added to the site by the site administrator.

  • What is a workspace?

    A site or workspace is when you want a new place for collaborating on Web pages, lists and document libraries. For example, you might create a site to manage a new team or project, collaborate on a document or prepare for a meeting.

  • What are the various kinds of roles the users can have?

    A user can be assigned one of the following roles
    * Reader - Has read-only access to the Web site.
    * Contributor - Can add content to existing document libraries and lists.
    * Web Designer - Can create lists and document libraries and customize pages in the Web site.
    * Administrator - Has full control of the Web site.

  • Can more than one person use the same login?

    If the users sharing that login will have the same permissions and there is no fear of them sharing a password, then yes. Otherwise, this is discouraged.

  • How customizable is the user-to-user access?

    User permissions apply to an entire Web, not to documents themselves. However, you can have additional sub webs that can optionally have their own permissions. Each user can be given any of four default roles. Additional roles can be defined by the administrator.

  • Can each user have access to their own calendar?

    Yes there are two ways to do this,
    * by creating a calendar for each user, or
    * by creating a calendar with a view for each user

  • How many files can I upload?

    There is no restriction in place except that any storage consumed beyond that provided by the base offering may have an additional monthly charge associated with them.

  • What types of files can I upload / post to the site?

    The only files restricted are those ending with the following extensions: .asa, .asp, .ida, .idc, .idq.  Microsoft reserves the right to add additional file types to this listing at any time.  Also, no content that violates the terms of service may be uploaded or posted to the site.

  • Can SharePoint be linked to an external data source?

    SharePoint data can be opened with Access and Excel as an external data source. Thus, SharePoint can be referenced as an external data source. SharePoint itself cannot reference an external data source.

  • Can SharePoint be linked to a SQL database?

    This is possible via a custom application, but it not natively supported by SharePoint or SQL Server.

  • Can I customize my Windows SharePoint Services site?

    YES! Windows SharePoint Services makes updating sites and their content from the browser easier then ever.
    SharePoint includes tools that let you create custom lists, calendars, page views, etc. You can apply a theme; add List, Survey and Document Library Web Parts to a page; create personal views; change logos; connect Web Parts and more.
    To fully customize your site, you can use Microsoft FrontPage 2003. Specifically, you can use FrontPage themes and shared borders, and also use FrontPage to create photo galleries and top ten lists, utilize standard usage reports, and integrate automatic Web content.

  • Will Microsoft Office SharePoint Server 2007 run on a 64-bit version of Microsoft Windows?

    Windows SharePoint Services 3.0, Office SharePoint Server 2007, Office Forms Server 2007, and Office SharePoint Server 2007 for Search will support 64-bit versions of Windows Server 2003.

  • How  Office SharePoint Server 2007  can help you?


    Office SharePoint Server 2007 can help us: Manage content and streamline processes. Comprehensively manage and control unstructured content like Microsoft Office documents, Web pages, Portable Document Format file (PDF) files, and e-mail messages. Streamline business processes that are a drain on organizational productivity.
    Improve business insight. Monitor your business, enable better-informed decisions, and respond proactively to business events.
    Find and share information more simply. Find information and expertise wherever they are located. Share knowledge and simplify working with others within and across organizational boundaries.
    Empower IT to make a strategic impact. Increase responsiveness of IT to business needs and reduce the number of platforms that have to be maintained by supporting all the intranet, extranet, and Web applications across the enterprise with one integrated platform.

    Office SharePoint Server 2007 capabilities can help improve organizational effectiveness by connecting people, processes, and information.
    Office SharePoint Server 2007 provides these capabilities in an integrated server offering, so your organization doesn't have to integrate fragmented technology solutions itself.

  • What are the features that the portal components of Office SharePoint Server 2007 include?

    The portal components of Office SharePoint Server 2007 include features that are especially useful for designing, deploying, and managing enterprise intranet portals, corporate Internet Web sites, and divisional portal sites. The portal components make it easier to connect to people within the organization who have the right skills, knowledge, and project experience.

  • What are the advanced features of MOSS 2007?

    * User Interface (UI) and navigation enhancements
    * Document management enhancements
    * The new Workflow engine
    * Office 2007 Integration
    * New Web Parts
    * New Site-type templates
    * Enhancements to List technology
    * Web Content Management
    * Business Data Catalog
    * Search enhancements
    * Report Center
    * Records Management
    * Business Intelligence and Excel Server
    * Forms Server and InfoPath
    * The “Features” feature
    * Alternate authentication providers and Forms-based authentication  

    What are the features of the new Content management in Office SharePoint 2007?

    The new and enhanced content management features in Office SharePoint Server 2007 fall within three areas:
    * Document management
    * Records management
    * Web content management
    Office SharePoint Server 2007 builds on the core document management functionality provided by Windows SharePoint Services 3.0, including check in and check out, versioning, metadata, and role-based granular access controls. Organizations can use this functionality to deliver enhanced authoring, business document processing, Web content management and publishing, records management, policy management, and support for multilingual publishing.
    Does a SharePoint Web site include search functionality?
    Yes. SharePoint Team Services provides a powerful text-based search feature that helps you find documents and information fast.

  • Write the features of the search component of Office SharePoint Server 2007?

    The search component of Office SharePoint Server 2007 has been significantly enhanced by this release of SharePoint Products and Technologies. New features provide:
    * A consistent and familiar search experience.
    * Increased relevance of search results.
    * New functions to search for people and expertise.
    * Ability to index and search data in line-of-business applications and
    * Improved manageability and extensibility.

  • What are the benefits of Microsoft Office SharePoint Server 2007?


    * Provide a simple, familiar, and consistent user experience.
    * Boost employee productivity by simplifying everyday business activities.
    * Help meet regulatory requirements through comprehensive control over content.
    * Effectively manage and repurpose content to gain increased business value.
    * Simplify organization-wide access to both structured and unstructured information across disparate systems.
    * Connect people with information and expertise.
    * Accelerate shared business processes across organizational boundaries.
    * Share business data without divulging sensitive information.
    * Enable people to make better-informed decisions by presenting business-critical information in one central location.
    * Provide a single, integrated platform to manage intranet, extranet, and Internet applications across the enterprise.

  • Will SharePoint Portal Server and Team Services ever merge?

    The products will come together because they are both developed by the Office team.

  • What does partial trust mean the Web Part developer?

    If an assembly is installed into the BIN directory, the code must be ensured that provides error handling in the event that required permissions are not available. Otherwise, unhandled security exceptions may cause the Web Part to fail and may affect page rendering on the page where the Web Part appears.

  • How can I raise the trust level for assemblies installed in the BIN directory?

    Windows SharePoint Services can use any of the following three options from ASP.NET and the CLR to provide assemblies installed in the BIN directory with sufficient permissions. The following table outlines the implications and requirements for each option.
    Option Pros Cons
    Increase the trust level for the entire virtual server. For more information, see "Setting the trust level for a virtual server" Easy to implement.
    In a development environment, increasing the trust level allows you to test an assembly with increased permissions while allowing you to recompile assemblies directly into the BIN directory without resetting IIS. This option is least secure.
    This option affects all assemblies used by the virtual server.
    There is no guarantee the destination server has the required trust level. Therefore, Web Parts may not work once installed on the destination server.
    Create a custom policy file for your assemblies. For more information, see "How do I create a custom policy file?" Recommended approach.
    This option is most secure.
    An assembly can operate with a unique policy that meets the minimum permission requirements for the assembly.
    By creating a custom security policy, you can ensure the destination server can run your Web Parts.
    Requires the most configuration of all three options.
    Install your assemblies in the GAC
    Easy to implement.
    This grants Full trust to your assembly without affecting the trust level of assemblies installed in the BIN directory.
    This option is less secure.
    Assemblies installed in the GAC are available to all virtual servers and applications on a server running Windows SharePoint Services. This could represent a potential security risk as it potentially grants a higher level of permission to your assembly across a larger scope than necessary
    In a development environment, you must reset IIS every time you recompile assemblies.
    Licensing issues may arise due to the global availability of your assembly.

  • Does SharePoint work with NFS?

    Yes and no. It can crawl documents on an NFS volume, but the sharepoint database or logs cannot be stored there.

  • How is SharePoint Portal Server different from the Site Server?

    Site Server has search capabilities but these are more advanced using SharePoint. SPS uses digital dashboard technology which
    provides a nice interface for creating web parts and showing them on dashboards (pages). SS doesn't have anything as advanced as that. The biggest difference would be SPS document management features which also integrate with web folders and MS Office.

  • What would you like to see in the next version of SharePoint?

    A few suggestions:
    # SPS and STS on same machine
    # Tree view of Categories and Folders
    # General Discussion Web Part
    # Personalization of Dashboards
    # Role Customization
    # Email to say WHY a document has been rejected for Approval
    # More ways to customize the interface
    # Backup and restore an individual Workspaces
    # Filter for Visio
    # Better way to track activity on SPS

  • Why Sharepoint is not a viable solution for enterprise wide deployments?

    Document management does not scale beyond a single server, but scales great within a single server. For example, a quad Xeon machine with 4GB of RAM works great for a document management server that has about 900,000 - 1,000,000 document, but if you need to store 50,000,000 document and want to have them all in one single workspace then it does not scale at all. If you need a scenario like this, you need to plan your deployment right and it should scale for you, it just does not right out of the box.
    If you are using your server as a portal and search server most for the most part it scales great. You can have many different servers crawl content sources and have separate servers searching and serving the content.
    If you have < 750,000 documents per server and fewer than 4 content sources and fewer than 50,000 users, SPS should scale just fine for your needs with the proper planning.

  • What are the actual advantages of SharePoint Portal Services (SPS) over SharePoint Team Services (STS)?

    SharePoint Portal Services (SPS) has MUCH better document management. It has check-in, check-out, versioning, approval, publishing, subscriptions, categories, etc. STS does not have these features, or they are very scaled back. SharePoint team Services (SPS) has a better search engine, and can crawl multiple content sources. STS cannot. STS is easier to manage and much better for a team environment where there is not much Document Management going on. SPS is better for an organization, or where Document Management is crucial.

  • How Does SharePoint work?

    The browser sends a DAV packet to IIS asking to perform a document check in. PKMDASL.DLL, an ISAPI DLL, parses the packet and sees that it has the proprietary INVOKE command. Because of the existence of this command, the packet is passed off to msdmserv.exe, who in turn processes the packet and uses EXOLEDB to access the WSS, perform the operation and send the results back to the user in the form of XML.

  • How do I open an older version of a document?

    Normally, all previous versions are located in the shadow, so if you right click a published document from within the web folders, go to properties and then the third tab, versions you can view older versions.
    If you want to do this in code:
    <pre>
    strURL = "url of the last published version"
    Set oVersion = New PKMCDO.KnowledgeVersion
    Set prmRs = oVersion.VersionHistory(strURL)
    Set oVersion = Nothing
    </pre>
    prmRS will contain a recordset, which contains the url to the old versions in the shadow.

  • Why do the workspace virtual directories show the error “stop sign” symbol in the IIS snap-in?

    If World Wide Web Publishing Service (W3SVC) starts before Microsoft Exchange Information Store (MSExchangeIS), “stop sign” symbols appear under the Default Web Site folder of the Internet Information Services console in Microsoft Management Console (MMC).
    There is a dependency between the local paths of the SharePoint Portal Server virtual directories and the MSExchangeIS. You must start MSExchangeIS first, followed by W3SVC.
    Complete the following steps to prevent the stop signs from appearing each time you restart:
    # Change the Startup type for W3SVC to Manual.
    # Restart the server. The MSExchangeIS service starts automatically.
    # Start W3SVC.

  • What newsgroups are available?

    There are two,
    * microsoft.public.sharepoint.portalserver and
    * microsoft.public.sharepoint.portalserver.development.

  • What is SharePoint from a Technical Perspective?

    Technically SharePoint illustrates neatly what Microsoft's .net strategy is all about: integrating Windows with the Web. Microsoft has previously made accessing stuff on a PC easier, (Windows) then on a network (NT) and now on the web (.NET). SharePoint is an application written to let a user access a web accessible directory tree called the Web Storage System.
    SharePoint was written with a set of technologies that allow the programmer to pass data, functions, parameters over HTTP, the web's medium. These are XML, XSL and SOAP, to name a few I understand the basics of!
    To the user it looks easy, like Hotmail, but every time they click a button or a link, a lot has to happen behind the scenes to do what they want to do quickly and powerfully. Not as easy as you might think, but SharePoint does it for you. Accessing this Web storage system and the server itself is also done using technologies like ADO, CDO, PKMCDO, LDAP, DDSC, ADSC. More on these later. SharePoint is a great example of how the Internet Platform can be extended and integrated into an existing well adopted technology, Windows.

  • What is SharePoint from an Administration Perspective?

    Administering SharePoint mainly consists of setting it up, which is much easier than you expect, adding the content, which can be just dragging and dropping in whole directory structures and files, and then organizing the files better by giving them categories or other metadata. This is done either through the Web interface or through the SharePoint Client: a program what means you can access SharePoint as a Web folder and then right-click files to select options like "edit profile". Or add files by dragging them in individually or in bulk.
    Setting the security is also important, using NT accounts, either NT4 or Active Directory (or both in mixed mode) you can give users access to files/folders the same way as you do in standard Windows. Users can be grouped and the groups given access privileges to help manage this better. Also SharePoint has 3 Roles that a User or Group can be given on a particular item. Readers can see the item (i.e. document/file or folder) but not change it, Authors can see and edit items and coordinators can set security privileges for the part of the system they have control over. Thus, you could set 12 different coordinators for 12 different folder trees, and they could manage who can do what within that area only.

  • What is SharePoint from a Users Perspective?

    From a Users perspective SharePoint is a way of making documents and folders on the Windows platform accessible over the web. The user visits the SharePoint Portal web page, and from there they can add documents, change documents & delete documents. Through this Portal, these documents are now available for discussion, collaboration, versioning and being managed through a workflow. Hence the name "Share-Point". Details about the document can be saved too, such as: who wrote it, when, for whom, its size, and version, category or target audience. These can then be used to find the document through SharePoint's Search facility. Even documents not "in" SharePoint can be included in the search engine's index so they become part of the portal. All in all, it's a great way to get stuff up on the web for users with average technical skills, and for administrators to manage the content.

  • What are the various Sharepoint 2003 and Exchange integration points?

    Link to Outlook

    This is a button on contacts or events lists that lets Outlook 2003 add a pst file named Sharepoint Folders and it links to the data on the site. It’s read-only, but you could make the home page for that PST be the Sharepoint site for easier viewing. The link to outlook feature seems more to be where some can public a calendar, but not want too much collaboration. For example, a holiday schedule, company meeting schedule, etc, can be made available for people to be able to view from Outlook without having to go to a web browser. Another nice thing about OL2K3 is that you can compare these calendars with others side by side.

    Searching Public Folders


    With SPS you can index Exchange’s public folders with the search engine so that all that precious public folder content is searchable. You’ll want to look at content sources and indexing in Sharepoint administration.

    Displaying Public Folders in a web part


    Since exchange web-enables public folders, you can create a web part that displays that content. IE, http://exchangeserver/Public/IT/Helpdesk will display the IT/Helpdesk public folder via OWA. So you add the Page Viewer web part to a page and point it at that URL. The key here is to add ?cmd=contents to the end of the url if you don’t want the navigator pane on the left.

    Smart web parts


    Some of the web parts that come with SPS allow you to add a web part to a page that actually takes the users outlook info (calendar, inbox, contacts, tasks) and put them into the page.

  • Can SharePoint compare two document versions?

    "In Word 2003, you can compare documents side by side. Open two documents. Then, from the Window menu of one of them, select the Compare Side By Side command. If you have only two documents open, the command will automatically choose to compare them. If you have three or more documents open, you'll have to select which document to compare with the current file.
    A floating toolbar with two buttons will open. If the button on the left is selected, Word will scroll both documents at the same time. Press the button on the right side of the toolbar to return to where the cursor was located when you started comparing."

  • What are the integration differences between SPS 2003 and the various Office versions?

    SPS webpage can detect you have installed the Office 2003 and run local dll to implement some SPS function, e.g. multi-file upload only works when you have office 2003 installed.
    Integration with Office XP is gone.
    You will get guys telling you that you can integrate with SPSv2 if you install a backwards compatible document library - but that’s really just putting a bit of SPS 2001 on the server.
    Believe me, check-in, check-out, which are themselves very basic, are not available from inside Office XP, or even from the context menu in Windows Explorer.
    The ONLY option you have is to use the web interface to check-in or check-out.


  • SharePoint 2010 Interview Questions for Administrators
    Q. What are the Hardware and Software requirements for SharePoint 2010.

    Ans.


    Hardware requirements :


    # Processor 64-bit, four-core, 2.5 GHz minimum per core.

    # RAM 4 GB for developer or evaluation use, 8 GB for single server and multiple server farm installation for production use.

    # Hard disk 80 GB for installation

    For production use, you need additional free disk space for day-to-day operations. Add twice as much free space as you have RAM for production environments.


    Software requirements :


    # The 64-bit edition of Windows Server 2008 Standard with SP2. If you are running Windows Server 2008 without SP2, the Microsoft SharePoint Products and Technologies 2010 Preparation Tool installs Windows Server 2008 SP2 automatically.

    For more see : Prerequisites for SharePoint 2010


    Q. What Has Changed with SSP in SharePoint 2010.

    Ans.
    In SharePoint 2010 Shared Service Providers (SSP's) are replaced by Service Applications. Services are no longer combined into a SSP. They are running independent as a service application. The service application architecture is now also built into Microsoft SharePoint Foundation 2010, in contrast to the Shared Services Provider (SSP) architecture that was only part of Office SharePoint Server 2007.

    A key benefit here is that all services are installed by default and there is no SSP setup.

    Additional improvements for the service application model include:
    • The services architecture is extensible, allowing third-party companies to build and add services to the platform.

    • Services are managed directly in Central Administration (rather than a separate administration site).

    • Services can be monitored and managed remotely.

    • Services can be managed and scripted by Windows PowerShell™.

    • Shared services communications take place over HTTP(S). Shared services do not directly access databases across farms.

    • Most new services are built on the Windows Communications Framework. They have optimization built into their protocol, using binary streams instead of XML for data transfer. Test results show improvements in network throughput with this change.


    Q. What are the advantages of Service Applications over
    SSP ?

    Ans.
    The key limitation of the SSP architecture was that it was configured by using a set of services, and all Web applications associated with the SSP bore the overhead of all the services even if they weren’t being used. To change the service configuration for a particular Web application, a new SSP would have to be created.

    The service application architecture on the other hand, allows a set of services to be associated with a given Web application and a different set of services to be associated with another Web application. Also, the same service application can be configured differently in different Web applications; therefore, Web sites can be configured to use only the services that are needed, rather than the entire bank of services.


    Q. Can we create a Single set of Services that will be shared across the farm?

    Ans.
    Similar to the SSP model in Office SharePoint Server 2007, a single set of services can be shared by all sites in a farm. By publishing a service application (from the sharing group, under Service application tab), you can share it across server farms. This capability does not apply to all service applications, and some services can be shared only within a single server farm.


    Q. What are Managed Accounts?

    Ans.
    To reduce the load of managing various service accounts in Microsoft SharePoint Server 2010, the concept of managed accounts has been introduced. Much like managed accounts in Windows Server 2008, they allow SharePoint Server to take control of all the service accounts you use. After SharePoint Server has control of these accounts, it can either manage their passwords — automatically changing them as necessary — or it can notify you when an accounts password is about to expire, allowing you to make the change yourself.


    Q. What are the Methods of Backup and Recovery in SharePoint 2010?

    Ans.
    Microsoft SharePoint Server 2010 provides a broad range of levels for performing backups, including the entire farm, farm configuration information, site collections, subsites, or lists.

    SharePoint Server 2010 uses two different tools to configure backup and recovery.

    1. Central Administration : Central Administration provides a user interface where SharePoint Administrators will be prompted via menu structures to select the information that needs to be backed up. (see the Image below)


    2. Windows PowerShell :
    Windows PowerShell is a command line tool that provides SharePoint administrators a way to perform backup and recovery with additional options such as file compression or working with SQL snapshots.

    Listed below are a few of the benefits available when working with Windows PowerShell:

    • Windows PowerShell scripts can be developed and scheduled (with Windows Task Scheduler), whereas Central Administration is used for single-use backups and restores.

    • Windows PowerShell has the advantage of running against SQL snapshots instead of the production database. One of the parameters of the Windows PowerShell command will cause a SQL snapshot to be generated, and then Windows PowerShell will run the action against the snapshot instead of the production database. This will reduce the resource impact of the backup operation on the production environment.

    • With Windows PowerShell, SharePoint administrators will have more granular control of options for the backup or restore.

    For more info See : Windows PowerShell Tutorial



    Q. How to Move content Databases using PowerShell ?

    Ans.
    To attach\detach an existing content database use

    Mount-SPContentDatabase "<ContentDb>" –DatabaseServer "<DbServer>" –WebApplication http://WebapplicationName

    <ContentDb> is the content database to be attached.

    <DbServer> is the name of the database server.

    http://WebapplicationName is the name of the Web application to which the content database is being attached.

    To detach a content database:

    Dismount-SPContentDatabase "<ContentdBName>"

    See more Commands at
    Windows Powershell Common Commands


    Q. How to Export a Site or List in SharePoint 2010?

    Ans.
    SharePoint Server 2010 provides several new features that provide a granular level of backup for various components of site content. This includes content at the site, subsite, and list level.

    Through Central Administration(Granular level Back-up) a SharePoint Administrator can configure a backup of a subsite or list. An Administrator can choose a site and a specific list to be exported.The administrators can also choose to export security and select the different versions that will be exported with the list.

    SharePoint 2010 Windows PowerShell Commands
    To Open the Windows PowerShell Session :

    1. On the Start menu, click All Programs.

    2. Click Microsoft SharePoint 2010 Products.

    3. Click SharePoint 2010 Management Shell

    Note : You should have SharePoint_Shell_Access role on the configuration database and you should be a member of the WSS_ADMIN_WPG local group on the computer where SharePoint Server 2010 is installed.


    Some of the Common Commands and Operations are:


    Create Web Application Variable

    $webapp = Get-SPWebApplication "http://WebapplicationUrl"


    Create SharePoint Site Variable (Instance of SPSite)

    $siteurl = "http://MySharePointSite"

    $Oursite=new-object Microsoft.SharePoint.SPSite($siteurl)

    Here we have created a variable Oursite, which contains an instance of type SPSite. Now you can use it to display all webs in the site collection.

    $Oursite.AllWebs more // List all Webs in the Site


    Create Service Application Variable

    $spapp = Get-SPServiceApplication -Name "ServiceApplicationDisplayName"


    Create a Webapplication:

    New -SPWebApplication -ApplicationPoolName <Name of the application pool> -Name <Name of the new Web application> [ -Port <Port on which the Web application can be accessed>] [-HostHeader <Valid URL assigned to the Web application that must correlate to the alternate access mapping configuration>] [-URL <Load-balanced URL for the Web application>][ -ApplicationPoolAccount <User account that this application pool will run as>]

    Delete WebApplication


    Remove-SPWebApplication –identity -URL <http://sitename> -Confirm


    Create\Delete a Site Collection:


    Create a Site collection:

    Get-SPWebTemplate

    $template = Get-SPWebTemplate "STS#0"

    New-SPSite –Url "<URL for the new site collection>" –OwnerAlias "<domain\user>" –Template $template

    Here $template is a Variable to store the type of template we want to use while creating a site collection.

    Delete a Site Collection:

    Remove-SPSite –Identity <URL> –GradualDelete

    Here <URL > is a site Collection Url .



    Back\Restore a content database

    To Backup :

    Backup -SPFarm -Directory <Backup folder> -BackupMethod -Item <Content database name> [-Verbose]

    Backup folder - is a folder to save your backup.

    BackupMethod – Can Specify between Full or Differential.


    To Restore:

    Restore -SPFarm -Directory <Backup folder> -RestoreMethod Overwrite -Item <Content database name> [-BackupId] [-Verbose]

    If you don’t know the BackupID you can display all the backups using the below command and get the GUID of the Backup.

    Get-SPBackupHistory -Directory <Backup folder>

    You can check all the Backup-Restore Operations Here


    Deploy WebPart Soluiton Package

    Install -SPWebPartPack -LiteralPath "PathToCABorwspFile" -Name "NameOFWebPart"

    PathToCABorwspFile- is the full path to the CAB file that is being deployed.

    NameOFWebPart- is the name of the Web Part that is being deployed.


    Install Activate and Deactivate Feature using Windows Powershell


    Install Feature :

    $MyFeatureId = $(Get -SPFeature -limit all where {$_.displayname -eq "myfeatureName"}).Id

    Install -SPFeature $MyFeatureId


    Activate\Enable Feature :

    $singleSiteCollection = Get -SPSite -Identity http://MySingleSiteCollectionURL

    Enable -SPFeature $MyFeatureId -Url $singleSiteCollection.URL


    Deactivate\Disable Feature :

    $singleSiteCollection = Get-SPSite -Identity http://MySingleSiteCollectionURL

    Disable -SPFeature $MyFeatureId -Url $singleSiteCollection.URL


    Command TO List all the PowerShell Commands
    Get-Command –PSSnapin “Get-Command –PSSnapin “Microsoft.SharePoint.PowerShell” format-table name > C:\SP2010_PowerShell_Commands.txt

    SharePoint 2010 Windows PowerShell Commands Part2
    Some more PowerShell Commands

    Site Collection Commands

    Create Site Collection :

    Get-SPWebTemplate
    $template = Get-SPWebTemplate "STS#0"
    New-SPSite -Url "" -OwnerAlias "" -Template $template

    Delete Site Collection :

    Remove-SPSite -Identity "URL of site Collection" -GradualDelete

    Change Site collection Quotas :
    Set-SPSite -Identity "SiteCollection Url" -MaxSize Quota

    Add site Collection Administrators :


    Set-SPSite -Identity "" -SecondaryOwnerAlias ""

    Lock or unlock a site collection :

    Set-SPSite -Identity "Site Collection Url" -LockState ""

    is one of the following vales :

    # Unlock: To unlock the site collection and make it available to users.

    # NoAdditions: To prevent users from adding new content to the site collection. Updates and deletions are still allowed.

    # ReadOnly: To prevent users from adding, updating, or deleting content.

    # NoAccess: To prevent access to content completely. Users who attempt to access the site receive an access-denied message.

    Create a site :


    New-SPSite "http://sitecollection/sites/Subsite -OwnerAlias "DOMAIN\UserName" –Language 1033

    What is Windows Powershell ?
    Windows PowerShell is a new Windows command-line shell designed especially for system administrators. In the SharePoint administration context, Windows PowerShell is another administration tool that supersedes the existing Stsadm.exe.

    How is Windows Powershell different from Stsadm ?
    Unlike stsadm, which accept and return text, Windows PowerShell is built on the Microsoft .NET Framework and accepts and returns .NET Framework objects. In addition to that it also gives you access to the file system on the computer so that you can access registry,digital signature certificate etc..

    What are cmdlet's?
    Windows PowerShell introduces the concept of a cmdlet which are simple build in commands, written in a .net language like C# or VB.

    Can you Create PowerShell scripts for deploying components in SharePoint ?
    If you are creating a webpart with VS 2010 then you can deploy it using ctrl + f5. However, to activate the webpart feature you can write a powershell script (.ps1) and execute it after dpeloyment.

    Where is Powershell located in sharePoint ?
    n the Start menu, click All Programs -> Click Microsoft SharePoint 2010 Products -> Click SharePoint 2010 Management Shell.

    If you need going to install a webpart or any custom solution in SharePoint 2010 using PowerShell What permissions do you need?
    In order to use Windows PowerShell for SharePoint 2010 Products, a user must be a member of the SharePoint_Shell_Access role on the configuration and content database. In addition to this, the user must also be a member of the WSS_ADMIN_WPG local group on the computer where SharePoint 2010 Products is installed.

    Permissions for Windows PowerShell - SPShellAdmin
    In order to use Windows PowerShell for SharePoint 2010 Products, a user must be a member of the SharePoint_Shell_Access role on the configuration and content database. In addition to this, the user must also be a member of the WSS_ADMIN_WPG local group on the computer where SharePoint 2010 Products is installed.

    To add a user as SharePoint_Shell_Access on the SharePoint database use the below powershell cmdlet :

    Add-SPShellAdmin

    Please Note that to run the above cmdlet you must have
    * Membership in the securityadmin fixed server role on the SQL Server instance
    * Membership in the db_owner fixed database role on all affected databases
    * and local administrative permission on the local computer.

    In addition to above some important things to Note:

    * The user gets added to the WSS_Admin_WPG group on all Web servers when the user is added to the SharePoint_Shell_Access role.

    * If the target database does not have a SharePoint_Shell_Access role, the role is automatically created.

    * If you use the database parameter, the user is added to the role on the farm configuration database, the Central Administration content database, and the specified database. Using the database parameter is the preferred method because most of the administrative operations require access to the Central Administration content database. The cmdlet is something like below :

    Add-SPShellAdmin -UserName Domainname\User -database {Database GUID}

    How to list all the commands in PowerShell ?
    Get-Command * commands gets you all the Powershell commands.

    Adding a content database using PowerShell in SharePoint 2010
    To attach an existing content database:

    Mount-SPContentDatabase "<ContentDb>" –DatabaseServer "<DbServer>" –WebApplication http://WebapplicationName

    <ContentDb> is the content database to be attached.

    <DbServer> is the name of the database server.

    http://WebapplicationName is the name of the Web application to which the content database is being attached.

    To detach a content database:

    Dismount-SPContentDatabase "<ContentdBName>"

    Where is the name of the content database.

    Server Architecture SharePoint 2010

    Server Architecture SharePoint 2010
    Order
    Object
    SharePoint Object
    1
    Farm
    SpFarm
    2
    Servers
    SpServer
    3
    Services
    SpService
    4
    WebService
    SpWebService
    5
    CFSIS
    SpServiceApplication
    6
    Instances of Services & CFSIS on the server
    SpServiceInstance
    7
    Database Service Instance
    SpServiceInstance
    SpDatabaseServiceInstance
    8
    Web Applications
    SpWebApplication
    SpAdministratorWebApplication
    9
    Content Databases
    SpDatabase
    SpContentDatabase
    10
    Site Collections
    SpSite

    The SPFarm object is the highest object within the SharePoint Foundation object model hierarchy. The Servers property gets a collection representing all the servers in the deployment, and the Services property gets a collection representing all the services.
    2. Each SPServer object represents a physical server computer. The ServiceInstances property provides access to the set of individual service instances that run on the individual computer.
    3. Each SPService object represents a logical service installed in the server farm. Derived types of the SPService class include, for example, objects for Windows services, such as the timer service, search, the database service, etc. and also objects for Web services, such as the basic content publishing Web service which supports the Web applications.
    4. An SPWebService object provides access to configuration settings for a specific logical service or application. The WebApplications property gets the collection of Web applications that run the service.

    If the service implements the Service Application Framework of SharePoint Foundation, then it can be split into multiple configured farm-scoped instantiations (CFSIs). Each of these provides the functionality of the service but each has its own individual permission and provisioning settings.
    6. Each instance of a service, or a CFSI, that is running on a specific server is represented by an SPServiceInstance object.
    7. An SPDatabaseServiceInstance object represents a single instance of a database service running on the database server computer. The SPDatabaseServiceInstance class derives from the SPServiceInstance class and thus inherits the Service property, which provides access to the service or application that the instance implements. The Databases property gets the collection of content databases used in the service.
    8. Each SPWebApplication object represents a Web application hosted in an Internet Information Services (IIS) Web site. The SPWebApplication object provides access to credentials and other farm-wide application settings. The Sites property gets the collection of site collections within the Web application, and the ContentDatabases property gets the collection of content databases used in the Web application.
    9. An SPContentDatabase object inherits from the SPDatabase class and represents a database that contains user data for a Web application. The Sites property gets the collection of site collections for which the content database stores data, and the WebApplication property gets the parent Web application.
    10. An SPSiteCollection object represents the collection of site collections within the Web application.


    Site Architecture & Object Model Overview

    Site Architecture & Object Model Overview
    1.       First there will be a Site Collection
    2.       Under sitecollection there will be a Top-Level Website
    3.       Under Top-Level website there will be Subsites
    4.       Under subsite another Subsite
    5.       Under Subsite you will have Lists
    6.       Under Lists you will have fields
    7.       Under Fields you will have Listitems.


    Each SPSiteobject, despite its singular name, represents a set of logically related SPWeb objects (see below). Such a set is commonly called a "site collection," but SPSite is not a standard Microsoft .NET collection class, in contrast to SPWebCollection. Rather, it has members that can be used to manage the site collection. The AllWebs property provides access to the SPWebCollection object that represents the collection of all Web sites within the site collection, including the top-level site. The SPSite.OpenWebmethod of the SPSite class returns a specific Web site.
    2. Each site collection includes any number of SPWeb objects, and each object has members that can be used to manage a site, including its template and theme, as well as to access files and folders on the site. The Webs property returns an SPWebCollection object that represents all the subsites of a specified site, and the Lists property returns an SPListCollection object that represents all the lists in the site.
    3. Each SPList object has members that are used to manage the list or access items in the list. The GetItems method can be used to perform queries that return specific items. The Fields property returns an SPFieldCollection object that represents all the fields, or columns, in the list, and the


    Items property returns an SPListItemCollection object that represents all the items, or rows, in the list.
    4. Each SPField object has members that contain settings for the field.
    5. Each SPListItem object represents a single row in the list.

    No comments:

    Post a Comment