Monday, April 25, 2011

Sharepoint Programming-Part 3

Q)How to get page title and URL in SharePoint 2010 using server object model?

To get the Page Title in SharePoint, you can follow the below approach.
User the below namespace:
using Microsoft.SharePoint;
Then write the below code to get the Title
String Title= SPContext.Current.Item["Title"].ToString();
Similarly you can get the URL in the below way
Sting URL=System.Web.HttpContext.Current.Request.Path;

Q)Generate Random password using C#.Net?

public GenerateRandomPassword()
String strGuid=System.Guid.NewGuid().ToString();
strGuid=strGuid.Substring(0,8); //Here 8 means the password contains 8 characters.

Q)To create a list instance with SP object Model.

using System;
using Microsoft.SharePoint;

class Program {
static void Main() {
using (SPSite site = new SPSite("
http://localhost")) {
using (SPWeb web = site.OpenWeb()) {
string listName = "Litware News";
SPList list = null;
foreach (SPList currentList in web.Lists) {
if (currentList.Title.Equals(listName,
StringComparison.InvariantCultureIgnoreCase)) {
list = currentList;

if (list == null) {
Guid listID = web.Lists.Add(listName,
"List for big news items",
list = web.Lists[listID];
list.OnQuickLaunch = true;

Q)How to use GetList() method?

SPList announcementsList = web.GetList("/Lists/Announcements");

Q)To create and save a new list item.

SPListItem newItem = list.Items.Add();
newItem ["Title"] = "Litware Goes Public!";
newItem ["Body"] = " We all live in exciting times.";
newItem["Expires"] = DateTime.Now + TimeSpan.FromDays(2);

Q) How to enumerate through the fields in a list by using a foreach construct?

foreach (SPField field in list.Fields)
if (!field.Hidden && !field.ReadOnlyField)
5. How to use CAML Query with SPQuery Object?
SPQuery query = new SPQuery();
query.ViewFields = @"";
query.Query =
//Write a query(using CAML)

SPList list = site.Lists["Litware News"];
SPListItemCollection items = list.GetItems(query);
foreach (SPListItem expiredItem in items) {

Q)How to use SPSiteDataQuery ?

SPSiteDataQuery query = new SPSiteDataQuery();
query.Lists = @"";
query.ViewFields = @"";
query.Webs = "";
string queryText =

//Write a query(using CAML)

query.Query = queryText;
DataTable table = site.GetSiteData(query);
foreach (DataRow row in table.Rows) {

Q)Difference between SPquery and SPSiteDataQuery?

SPQuery object return an SPListItemCollection. SPSiteDataQuery object are different, because they return an ADO.NET DataTable object.

Q)Visit through document library in SharePoint Site.

SPWeb site = SPContext.Current.Web;
foreach (SPList list in site.Lists) {
if (list is SPDocumentLibrary && !list.Hidden) {
SPDocumentLibrary docLib = (SPDocumentLibrary)list;
// Add document library to DropDownList control
new ListItem(docLib.Title, docLib.ID.ToString()));

Q)Points about SharePoint List?

You can access a List by its name or by its URL.
When retrieving a list by name, you can use the TryGetList method of the SPListCollection, which returns null if the list does not exist.

When retrieving the list by the URL, you can use the GetList method of the SPWeb object, which throws a System.IO.FileNotFoundException if the list does not exist.

Code Samples:
using (SPSite siteCollection = new SPSite("Site URL"))
using (SPWeb site = siteCollection.OpenWeb)
SPList lstName = site.Lists.TryGetList("NameOfTheList");
if(lstName  != null)
//do your work
//List does not exists
SPList taskList = site.GetList("/Lists/Tasks");
//do your work
//List does not work

Lists maintain items in a Microsoft.SharePoint.SPListItemCollection object, which is accessible via the Items property of SPList.
Items in the collection are returned as Microsoft.SharePoint.SPListItem objects.
You can iterated over using a foreach statement, or directly accessed using either the item’s ID or index.
Each individual SPListItem maintains a Hashtable of values representing the properties of the item

//Add new item to list
SPListItem newItem = list.Items.Add;
newItem["Title"] = "This will be the title";
//Bind the item to gridview
SPListItemCollection items = list.Items;
gridview1.DataSource = items;
//Delete Item by Index
//Update Item by Index
SPListItem updateItem = list.Items[0];
updateItem["Title"] = "Updated Title";

when creating new items in a list, the Update method must be called to save the new item. If the Update method is not called, then the list item will be lost.
if the item was edited by another user before the update is saved, the operation will fail.

Q)Query a List by using CAML in SharePoint

Microsoft.SharePoint.SPQuery object has Query property that accepts a CAML fragment, which defines the query to be performed. A ViewFields property defines the fields to return.

Code Sample:

SPQuery query = new SPQuery;
query.Viewfields = @"<fieldref name="Title"><fieldref name="Expires">";
query.Query =
<fieldref name="Expires">
<value type="DateTime"><today></today></value>
SPList list = SPContext.Current.Web.Lists.TryGetList("Announcements");
SPListItemCollections items = list.GetItems(query);

Each FieldRef element has a Name attribute that specifies the name of the list field to return from the query.
The CAML fragment may contain Where, OrderBy, and GroupBy elements


Where condition may contain:

And,BeginsWith,Contains,Eq,FieldRef,Geq,GroupBy,Gt,IsNotNull,IsNull,Join, Leq,Lt,Neq, Now,Or etc
SPQuery object can be used to query across two lists that are joined by a Lookup field.

Showing you a sample from Inside book:

SPWeb site = SPContext.Current.Web;
SPList listInstructors = site.Lists["Instructors"];
SPList listModules = site.Lists["Modules"];
SPQuery query = new SPQuery;
query.Query = "<where><eq><fieldref name="\"Audience\"/">" +
"<value type="\"Text\"">Developer</value></fieldref></eq></where>";
query.Joins = "<join type="\"Inner\"" listalias="\"classInstructors\"">" +
"<eq><fieldref name="\"Instructor\"" reftype="\"Id\"">" +
"<fieldref list="\"classInstructors\"" name="\"Id\""></fieldref></fieldref></eq></join>";
query.ProjectedFields =
"<field name="Email" type="Lookup" list="classInstructors" showfield="Email">";
query.ViewFields = "<fieldref name="\"Title\""><fieldref name="\"Instructor\"">" +
"<fieldref name="\"Email\"">";
SPListItemCollection items = listModules.GetItems(query);
Q)How to get user profiles details programmatically in sharepoint 2010
The below 2 function will show how to get user profile and how to access the profile properties.

private UserProfile GetUserInfo(string AccountName)
UserProfile profile = null;
SPServiceContext serviceContext = SPServiceContext.Current;
UserProfileManager profileManager = new UserProfileManager(serviceContext);
if (AccountName != string.Empty)
profile = profileManager.GetUserProfile(AccountName);
profile = profileManager.GetUserProfile(SPContext.Current.Web.CurrentUser.RawSid);
return profile;

void GetCurrentUserDetails()
UserProfile userProfile = GetUserInfo("");
lblUserName.Text = GetUserName(userProfile);
if (userProfile[PropertyConstants.FirstName].Value != null)
lblUserName.Text += " (" + userProfile[PropertyConstants.FirstName].Value.ToString() + ")";
imgBtnUserImage.ImageUrl = userProfile[PropertyConstants.PictureUrl].Value.ToString();
catch (Exception ex)
imgBtnUserImage.ImageUrl = "/_layouts/ExpressionsWP/0.jpg";
if (userProfile[PropertyConstants.Department].Value != null)
ltrAddress.Text = userProfile[PropertyConstants.Department].Value.ToString();
if (ltrAddress.Text != string.Empty)
if (userProfile[PropertyConstants.Location].Value != null)
ltrAddress.Text += "," + userProfile[PropertyConstants.Location].Value.ToString();
if (userProfile[PropertyConstants.Location].Value != null)
ltrAddress.Text += userProfile[PropertyConstants.Location].Value.ToString();

Q)SPLimitedWebPartManager Class in SharePoint 2010?

It allows developer with direct access to the collection of Web Parts on a Web Part page.
It allows to add, customize, personalize, and delete Web Part instances
SPLimitedWebPartManager is available in SharePoint solutions deployed at the farm level, but it cannot be used in

sandboxed solutions.Here is a code sample to delete all the web parts in a page.
// Get Web Part Manager for home page
SPWeb site = (SPWeb)properties.Feature.Parent;
SPFile homePage = site.GetFile("default.aspx");
SPLimitedWebPartManager wpm;
wpm = homePage.GetLimitedWebPartManager(PersonalizationScope.Shared);
// delete all Web Parts on page
while (wpm.WebParts.Count > 0) {
SPFile is used to get a web part page.

Q)How to delete or uninstall a custom site defination in sharepoint 2010?

Go to the features directory of 14 hive folder and delete the folder name same with your site defination name.
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\FEATURES
Go to the directory webtemp*.xml file location and delete the corresponding webtemp_[site defination name]. The location is:
C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\1033\XML

Q)HTTP Error 503. The service is unavailable in SharePoint

This error normally comes whenever a user changed the passoword
for the account. So to correct the error follow the below steps:
Go to Start -> All Programs -> Administrative Tools -> Internet
Information Services (IIS) Manager.
Then Click on(+) the server name -> Application Pools then locate
your application pools.
Right click on the Application pool name go to Advance settings ->
Go to process model then Identity Click on the Identity ->Set and
then give the user name, password and confirm password


  1. What's Taking place i'm new to this, I stumbled upon this I have discovered It positively helpful and it has helped me out loads.
    I hope to contribute & aid different customers like its aided me.

    Good job.

    Also visit my web page :: earn cash for doing stuff you normally do on the internet

  2. Ӏ nеed tο get it done cus I won't have the opportunity to get it done if not!

    Have a look at my page ...

  3. Ӏ need to get it done сus Ӏ won't have the opportunity to get it done if not!

    Take a look at my page -

  4. Looks likelу that the cat is οut of the bаg on this.
    .... І'll have to have a look and see whats coming....

    my web blog: small personal loans

  5. Lol I shаred thiѕ too. It's well funny.

    Also visit my web blog :: fast and easy loans

  6. Loοκs lіke the cat's out of the bag on this... have a look to see whats coming....

    Review my web page ... fast cash loans for people with bad credit

  7. Have not yet reаԁ аbout thіs іdea bеfоre,
    I ought to do so veгy soon.

    Hеre iѕ mу blog post; Best payday loans Uk

  8. Ѕpuг of the moment uρdates aге аlways beѕt, the sеntencеs јust ρour out ontο
    the sсrеen.

    Feel fгeе to surf to my wеb site; fast cash today

  9. its sο hot.

    Alsо visit my webpage best uk loans

  10. Oh well. Get yοurself a glass of milk when youre homе, run a bath and let go.

    Hеre iѕ my blog; best personal loan

  11. Dіd you loοκ up аny refеrences beforе you сamе up
    with thiѕ?

    Look into mу ρage - personal loans uk

  12. Noω then еveгybody lets all calm down,
    hаve a гelaxing wаrm bath and a cup of tеa.

    Alsο νіsit my blog :: borrow money fast

  13. Aah I see! I thought that was an optional crazy addition.

    Feеl free to ѵisit mу wеbsitе; best loan deal

  14. How did theѕе replіes get ѕo confused it's drainin reading em.

    My homepage: loans fast

  15. Wе are all a suckеr fοr an octopus.

    Ha ha ha...

    Alsο visit mу weblοg; best value loans

  16. What are youг referenceѕ fоr this artіcle?

    My blog post :: small personal loans

  17. This hаѕ made me contemplate іf theгe's a few ways I could do things more efficiently.

    Feel free to visit my weblog ... Personal Loans

  18. Well done for managing tο gеt by for
    that lοng.

    Alѕо viѕіt my homеpage: best rate loan

  19. Do not rеkon I understand thiѕ 2 b true. Mуt аv to go elswhеre 2 get it.

    mу blog post: best personal loans

  20. Haha І sharеd thiѕ too. It's ace.

    Here is my webpage: best loans uk

  21. I've been looking for a reliable article on this for weeks, and this has been a good help. I'll be getting this гe-tweеted for sure.

    my homepage; personal loans

  22. I am thіnking at what agе you start to get wіser аnd get used to all this

    My site; personal loans uk

  23. Did you eνaluаte any rеferences befoгe you ωrote
    all this doωn?

    Take а look at mу ѕite - cheap personal loans

  24. Simply desire to say your article is as astonishing. The clearness in your post is simply
    cool and i can assume you're an expert on this subject. Fine with your permission allow me to grab your RSS feed to keep up to date with forthcoming post. Thanks a million and please keep up the gratifying work.

    Look into my web blog play and get Minecraft for free

  25. Hi,In many ways this is true of any Web Design Cochin process - navigation is no way near as sexy as that lovely design look! Supermarkets have traditionally spent a lot of time getting those aisles lined up so that you buy items you don't really need.Thanks.....