Monday, September 3, 2012

SP 2010 Start up Simple Console App

SharePoint 2010 Start up Simple Console App

Start VS2010, and follow the steps  to write your first console application in SharePoint 2010. The basic aim of this post is to familiar with the Object Model SharePoint uses i.e.SPFarm, SPWebApplication, SPSite, SPWeb, SPList etc.
  •  On your SharePoint development machine, create a new Console Application in Visual Studio 2010. Make sure your target framework is .NET 3.5. This is because SharePoint 2010 is built on .NET 3.5 SP1.
  • Add a reference to Microsoft.SharePoint.dll. You will find this reference under the .NET tab of the Add References Dialog within Visual Studio. Look for Microsoft.SharePoint.
  • Use code snippet shown below.
Note: Please change the url ( “http://sp-pc”)  with your own,  before running the code snippet given below.
Complete Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
namespace SharepointConsoleApp
class Program
static void Main(string[] args)
using (SPSite site = new SPSite(“http://sp-pc”))
Console.WriteLine(” Site Properties :: Title ” + site.RootWeb.Title);
Console.WriteLine(” Site Properties :: site.AverageResourceUsage  ” + site.AverageResourceUsage);
Console.WriteLine(” Site Properties :: site.ContentDatabase.DatabaseConnectionString   ” + site.ContentDatabase.DatabaseConnectionString);
Console.WriteLine(” Site Properties :: site.HostName   ” + site.HostName);
Console.WriteLine(” Site Properties :: site.ID (GUID)  ” + site.ID);
Console.WriteLine(” Site Properties :: site.Owner.LoginName   ” + site.Owner.LoginName);
Console.WriteLine(” Site Properties :: site.Owner.Name   ” + site.Owner.Name );
Console.WriteLine(” Site Properties :: site.Owner.IsSiteAdmin    ” + site.Owner.IsSiteAdmin);
Console.WriteLine(” Site Properties :: site.Owner.Sid     ” + site.Owner.Sid);
Console.WriteLine(” Site Properties :: site.Owner.Xml     ” + site.Owner.Xml);
Console.WriteLine(” Site Properties :: site.Port  ” + site.Port);
Console.WriteLine(” Site Properties :: site.PortalName   ” + site.PortalName);
Console.WriteLine(” Site Properties :: site.PortalUrl    ” + site.PortalUrl);
Console.WriteLine(” Site Properties :: site.Protocol   ” + site.Protocol);
Console.WriteLine(” Site Properties :: site.ServerRelativeUrl   ” + site.ServerRelativeUrl);
Console.WriteLine(” Site Properties :: site.SystemAccount.LoginName   ” + site.SystemAccount.LoginName);
Console.WriteLine(” Site Properties :: site.Url   ” + site.Url);
Console.WriteLine(” Site Properties :: site.WebApplication.DisplayName  ” + site.WebApplication.DisplayName);
Console.WriteLine(” Site Properties :: site.WebApplication.Id   ” + site.WebApplication.Id);
Console.WriteLine(” Site Properties :: site.WebApplication.Name    ” + site.WebApplication.Name);
int counter = 0;
foreach(string name in  site.WebApplication.Sites.Names)
Console.WriteLine(” Site Properties :: site.WebApplication.Sites.Names[" + counter +"]    ” + name );
Console.WriteLine(” Site Properties :: site.WebApplication.Farm.DisplayName    ” + site.WebApplication.Farm.DisplayName);
Console.WriteLine(” Site Properties :: site.WebApplication.Farm.Id (GUID)    ” + site.WebApplication.Farm.Id);
Console.WriteLine(” Site Properties :: site.WebApplication.Farm..Name     ” + site.WebApplication.Farm.Name);
Console.WriteLine(” Site Properties :: site.WebApplication.Farm..Name     ” + site.WebApplication.Farm.Servers.FirstOrDefault() );


Site Properties :: Title Home
Site Properties :: site.AverageResourceUsage  0
Site Properties :: site.ContentDatabase.DatabaseConnectionString   Data Source=SP-PC\SharePoint;Initial Catalog=WSS_Content;Integrated Security=True;Enlist=False;Connect Timeout=15
Site Properties :: site.HostName   sp-pc
Site Properties :: site.ID (GUID)  e33c7cae-5cc4-4c46-b634-11f6bf6b1d00
Site Properties :: site.Owner.LoginName   SP-PC\administrator
Site Properties :: site.Owner.Name   SP-PC\administrator
Site Properties :: site.Owner.IsSiteAdmin    True
Site Properties :: site.Owner.Sid   S-1-5-21-1559381635-1802688237-1039693252-500
Site Properties :: site.Owner.Xml     <User ID=”1″ Sid=”S-1-5-21-1559381635-1802688237-1039693252-500″ Name=”SP-PC\administrator” LoginName=”SP-PC\administrator” Email=”” Notes=”" IsSiteAdmin=”True” IsDomainGroup=”False”
Flags=”0″ />
Site Properties :: site.Port  80
Site Properties :: site.PortalName
Site Properties :: site.PortalUrl
Site Properties :: site.Protocol   http:
Site Properties :: site.ServerRelativeUrl   /
Site Properties :: site.SystemAccount.LoginName   SHAREPOINT\system
Site Properties :: site.Url   http://sp-pc
Site Properties :: site.WebApplication.DisplayName  SharePoint – 80
Site Properties :: site.WebApplication.Id   9157d552-44c9-48f3-8a11-1ff9f2493bc1
Site Properties :: site.WebApplication.Name    SharePoint – 80
Site Properties :: site.WebApplication.Sites.Names[0]
Site Properties :: site.WebApplication.Sites.Names[1]    my
Site Properties :: site.WebApplication.Farm.DisplayName    SharePoint_Config_b00efd1d-c9f5-4107-a4ee-29bf2e16da4f
Site Properties :: site.WebApplication.Farm.Id (GUID)
Site Properties :: site.WebApplication.Farm..Name     SharePoint_Config_b00efd1d-c9f5-4107-a4ee-29bf2e16da4f
Site Properties :: site.WebApplication.Farm..Name     SPServer Name=SP-PC

SP 2010 - SharePoint Object Model - basic coding ex's (List, Library)

SP 2010 - SharePoint Object Model

Here we are only discussing the Server Object Model. Server Object Model classes are used for Server-side programming and will be executed on the SharePoint Server Farm.
For programming against the SharePoint items, we need to retrieve the properties and the methods to operate on them. The SharePoint Object Model provides various classes to accomplish this. In this article we can discuss the Object Model with the core classes involved with little amount of coding.

Please note that there are 2 Object Models in SharePoint 2010:
  1. Server Object Model
  2. Client Object Model
Here we are discussing only about the Server Object Model. Server Object Model classes are used for server-side programming and will be executed on the SharePoint Server Farm.


The Server Object Model classes are residing in the Microsoft.SharePoint assembly. The general classes are available in the Microsoft.SharePoint namespace and the administration classes inside the Microsoft.SharePoint.Administration namespace.

Core Classes

Following are the important classes and their corresponding SharePoint items.
SharePoint Item
Site Collection
Web site
Document Library
Content Type
SharePoint Exception

Now we can start experimenting with some of the above classes. To begin we can create a SharePoint Console Application. Use the New Project > SharePoint > Console Application project item.

Accessing the List Items in a List

For proceeding with this example, create a list derived from the Contacts template and name it as "My Contacts". 

Add some items inside it with the First Name and Last Name set.

Use the following code inside the Console application and execute it.
using (SPSite site = new SPSite("http://appes-pc/my/personal/dotnet")) // Site Collection
    using (SPWeb web = site.OpenWeb()) // Site    {
        SPList list = web.Lists["My Contacts"]; // List        int i = 1;
        foreach (SPListItem item in list.Items)
            Console.WriteLine("Item: " + (i++).ToString());
            Console.WriteLine(item.GetFormattedValue("First Name"));
            Console.WriteLine(item.GetFormattedValue("Last Name"));

If you receive any build errors regarding a namespace, change the Project Properties > Target to .Net Framework 3.5.

Now try building the application and it should work fine. You will see the following output.

Please note the use of Title and Name properties and the GetFormattedValue() method.

Accessing the items in a Library

Now we can proceed with accessing the document library items programmatically. For proceeding you need to create a document library inheriting from the Document Library template and name it "My Docs". Upload one or two documents into it. We are proceeding to get the file name and length in this example.

Enter the following code in the console application.
using (SPSite site = new SPSite("http://appes-pc/my/personal/dotnet")) // Site Collection{
    using (SPWeb web = site.OpenWeb())                    // Site    {
        SPDocumentLibrary library = web.Lists["My Docs"as SPDocumentLibrary// Library        int i = 1;
        foreach (SPListItem item in library.Items)
            Console.WriteLine("Item: " + (i++).ToString());

Executing the application, you will see the following results.



The SPControl class acts as the base class while developing server controls. It reseides in the namespace Microsoft.SharePoint.WebControls.

SPControl provides static methods that returns reference to the current site, web, web application, module. The methods are:


The SPException class can be used to handle an exception in a try catch block. It represents the exceptions thrown by the server object model.
    // Code here}
catch (SPException ex)
    // Handle Exception}


The SPUser class can be used to access user information for a SharePoint site. Enter the following code to get the number of users and their names.
using (SPSite site = new SPSite("http://appes-pc/my/personal/dotnet"))
    using (SPWeb web = site.OpenWeb())
        foreach (SPUser user in web.AllUsers)
            Console.WriteLine("User: " + user.Name);

On running the code you will see the results based on your machine users.



You can add a new list item or library item using the Items.Add() method. For updating and deleting use the item.Update() and item.Delete() methods respectively. More code coverage on these areas will be provided later.



In this article we have explored the SharePoint Object Model and some basic coding examples with List and Library.

Sandboxed Solution Vs Farm Solution

Sandboxed Solution Vs Farm Solution

Whenever you create a solution for a SharePoint you must have to specify the trust level for the solution. There  are two trust levels defined in the SP2010 i.e.
  1. Sandboxed Solution (or User Solution)
  2. Farm Solution
Figure: Trust Level options
Sandboxed Solutions:
  • Are more restrictive solutions i.e. provide limited functionality
  • A solution that runs in  secure sandbox i.e. in a separate process then wpw3.exe.
  • Are secure by default and are protected by CAS policies i.e. deploying sandboxed solution does not affect other solutions
  • Easy monitoring
  • Are deployed to Site Collection level
  • One limitation is that, they can’t access the File system
  • SPUCHostService.exe, also known as the Sandboxed Code Service, runs on each server on the farm that you are going to allow to work in the sandbox
  • SPUCWorkerprocess.exe process is the sandbox worker process, redeploying Sandboxed solution does not required to restart application pool
  • Can be validated using the sandboxed solution validation by the farm administrator
Farm Solutions:
  • Have no restrictions i.e. provide unrestricted functionality
  • A solution that runs in a wpw3.exe (process)
  • Are less secure in nature, can be protected by implementing custom CAS ploicies
  • Difficult monitoring
  • Can be deployed to any object hierarchy
  • No limitations in accessing File system
  • When deployed, they could run any kind of code and they could make any kinds of changes to the servers.

Elements of a SharePoint Solution

Elements of a SharePoint Solution.

The following items are the basic elements of any SharePoint solutions:
  • The project file
  • Project properties
  • References
  • Features folder
  • Package folder
  • Key file (strong-named key)
Solution Explorer showing Elements of SharePoint Solution
Elements of SharePoint Solution
Features Node
  • Contains one or more SharePoint project Features
  • A Feature is a ‘container’ for an additional function to SharePoint
  • Deployed to a specific scope
  • Scope can be : Farm, Web Application, Site (Collection), Web (site)
  • Project items added are also added to the feature node
  • Double-clicking the feature node displays the Feature Designer
  • Feature Designer
    • Creates Features
    • Sets Scopes
    • Establish Feature Dependencies
    • Manually edit the Feature Manifest
    • Overriding the generated manifest will disable the Designer, and then all further changes will need to be done manually
Package Node
  • Groups and view the hierarchical Package tree
  • Groups the SharePoint Items into a Solution Package
  • The Package node contains a single file that serves as the distribution mechanism for the SharePoint project.
  • This Package file is also known as a solution package, is .CAB-based with a .WSP extension.
  • A solution package is a deployable, reusable file that contains a set of features, site definitions, and assemblies that apply to SharePoint sites, and that you can enable or disable individually.
  • The Package node also always contains a file that is named Package.wspdef, an XML definition file for the package.
  • Once a package is deployed to the SharePoint server, the SharePoint administrator can install it and activate its features.
  • Double-clicking the Package node opens it in the Package Designer. You can then view or change its contents.
Key file (strong-named key)
  • Assembly signing (also called strong-name signing) gives an application or component a unique identity that other software can use to identify and refer explicitly to it.
  • A strong name consists of its simple text name, version number, culture information (if provided), plus a public/private key pair.
  • For the purpose of assembly signing, Visual Studio supports only Personal Information Exchange (.pfx) and Strong Name Key (.snk) files stored in the project system on the local computer.