Search This Blog

Thursday, April 7, 2011

Sharepoint Programming Interview Questions with Answers Part 1

Q. How would you retrieve large number of Items form the list ?
Ans. To retrieve large number of items with a better performance we can either use SPQuery or PortalSiteMapProvider Class. Read More with Examples..Retrieving large number of Items from sharepoint list
If you have to reterive a large number of Items and also need a better performance then you should use one of the methods below :

1. Using SPQuery
2. Using PortalSiteMapProvider Class
Lets see the examples for both the methods :
Our Query - Query to get all the Items in a list where Category is "Sp2007"
SPQuery -
// Get SiteColl
SPSite curSite = new SPSite("
http://myPortal");
//Get Web Application
SPWeb curWeb = curSite.OpenWeb();

// Create a SPQuery Object
SPQuery curQry = new SPQuery();

// Write the query
curQry.Query = "<Where><Eq><FieldRef Name='Category'/>
<Value Type='Text'>SP2007 </Value></Eq></Where>";

// Set the Row Limit
curQry.RowLimit = 100;

//Get the List
SPList curList = curWeb.Lists(new Guid("myListGUID"));

//Get the Items using Query
SPListItemCollection curItems = curList.GetItems(curQry);

// Enumerate the resulting items
foreach (SPListItem curItem in curItems)
{

string ResultItemTitle = curItem["Title"].ToString();
}

PortalSiteMapProvider class -
The class includes a method called GetCachedListItemsByQuery that retrieves data from a list based on an SPQuery object that is provided as a parameter to the method call.
The method then looks in its cache to see if the items already exist. If they do, the method returns the cached results, and if not, it queries the list, stores the results in cache and returns them from the method call.


// Get Current Web
SPWeb curWeb = SPControl.GetContextWeb(HttpContext.Current);

//Create the Query
SPQuery curQry = new SPQuery();
curQry.Query = "<Where><Eq><FieldRef Name=\'Category\'/><Value Type=\'Text\'>SP2007</Value></Eq></Where>";


// Get Portal Map Provider
PortalSiteMapProvider ps = PortalSiteMapProvider.WebSiteMapProvider;

PortalWebSiteMapNode pNode = TryCast (ps.FindSiteMapNode (curWeb.ServerRelativeUrl), PortalWebSiteMapNode);
// Get the items
pItems = ps.GetCachedListItemsByQuery(pNode, "myListName_NotID", curQry, curWeb);

// Enumerate all resulting Items
foreach (PortalListItemSiteMapNode curItem in pItems)
{
string ResultItemTitle = curItem["Title"].ToString();

}
Q).Get Item level Permissions using Client Object model SharePoint 2010
Here is a little code snippet to get the info about the users who have permission for a specific item in a list
Retrieving permissions for a Specific item -
private void GetItemPermission()
{
SecurableObject curObj = null;
ListItem curItem = ctx.Web.Lists.GetByTitle(“My List”).GetItemById(ItemId); -> Use ItemId of the Item.
//plug it into our query objectcurObj = curItem as SecurableObject;
IEnumerable roles = null;
roles = ctx.LoadQuery(
curObj.RoleAssignments.Include(
roleAsg => roleAsg.Member,
roleAsg => roleAsg.RoleDefinitionBindings.Include(
roleDef => roleDef.Name, // for each role def, include roleDef’s Name
roleDef => roleDef.Description)));
ctx.ExecuteQuery();
}


Q.Where do you deploy the additional files used in your webpart, like css or javascript files, and how do you use them in your WebPart?
Ans. You can deploy the css or javascript files in _layouts folder in SharePoint's 12 hive. To use them in your webpart, you need to first register them to your webpart page and then specify a virtual path for the file for e.g. _layouts\MyCSS.css See Code examples at
Button Testbutton;
Image img;
string imagePath
;
// Referring External Javascript
ClientScriptManager cs = Page.ClientScript;
// Include the required javascript file.
if (!cs.IsClientScriptIncludeRegistered("jsfile"))
cs.RegisterClientScriptInclude(this.GetType(), "jsfile", "/_wpresources/MyWP/1.0.0.0_9f4da00116c38ec5/jsfile.js");

Test :
Testbutton= new Button();
Testbutton.Text = "Click me";
Testbutton.OnClientClick = "jsfile_Function()"; // specify function name here
this.Controls.Add(Testbutton);

// Refering External CSS
Microsoft.SharePoint.WebControls.CssLink cssLink = new Microsoft.SharePoint.WebControls.CssLink();
cssLink.DefaultUrl = "/_wpresources/MyWP/1.0.0.0_9f4da00116c38ec5/styles.css";
this.Page.Header.Controls.Add(cssLink);

// Using External Image
imagePath = "/_wpresources/MyWP/1.0.0.0_9f4da00116c38ec5/Image.jpg";
img.ImageUrl = imagePath;
img.ID = "image1";

this.Controls.Add(mybutton);
this.Controls.Add(img);


Q.How Do you implement Impersonation in ShrePoint.
Ans. By Using RunWithElevatedPrivileges method provided by SPSecurity class.
example..
Impersonation in Sharepoint (RunWithElevatedPrivileges)
Although not recommended, there may be times when you need your code to perform certain functions that the current user does not have the necessary permissions to perform.
The SPSecurity class provides a method (RunWithElevatedPrivileges) that allows you to run a subset of code in the context of an account with higher privileges than the current user.
The premise is that you wrap the RunWithElevatedPrivileges method around your code. And also In certain circumstances, such as when working with Web forms, you may also need to set the AllowSafeUpdates method to true to temporarily turn off security validation within your code. If you use this technique, it is imperative that you set the AllowSafeUpdates method back to false to avoid any potential security risks.
Code example
{
SPSite mySite = SPContext.Current.Site;
SPWeb myWeb = mySite.OpenWeb();

//Using RunWithElevatedPrivileges
SPSecurity.RunWithElevatedPrivileges(delegate()
{
// Get references to the site collection and site for the current context.
// The using statement makes sures these references are disposed properly.

using (SPSite siteCollection = new SPSite(mySite.ID))
{

using (SPWeb web = siteCollection.OpenWeb(myWeb.ID))
{

web.AllowUnsafeUpdates = true;
try
{
//Your code
}

web.AllowUnsafeUpdates = false;
//siteCollection = null;
//web = null;

}

Q).Programmatically access user profile + client object model SharePoint 2010
Here is a Code snippet for retrieving user profile picture using Client Object model – ECMAScript . I am passing the userId from the front end to a javascript method called “getUserProfile()” to retrieve the user profile info. The method onQuerySucceeded will get you the user Profile info.

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

var web = clientContext.get_web();
var userInfoList = web.get_siteUserInfoList();
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(‘<View><Query><Where><Eq><FieldRef Name=\’ID\’/>’ +’<Value Type=\’Number\’>’ + userID + ‘</Value></Eq>’ +
‘</Where></Query><RowLimit>1</RowLimit></View>’);
this.collListItem = userInfoList.getItems(camlQuery);
clientContext.load(collListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded),Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded(sender, args)
{

var item = collListItem.itemAt(0);
var profile = item.get_item(‘Notes’);
var pictureUrl = item.get_item(‘Picture’).get_url();
var userImage = document.getElementById(‘myImageContainer’); -> Image object
userImage.src = pictureUrl;
var profileDiv = document.getElementById(‘userProfileContainer’);
profileDiv.innerHTML = profile;
}


Q).Change Master page for logged in user SharePoint
This is probably the most asked questions related to sharepoint branding and customization. In this post we will discuss how you can change the master page for your site according to some logic like you can change the master page for a logged in user or simply can switch the application.master page to your custom master page for all applictaion pages.
I achive written a Step-by-step sample code to switch mater page according to logged in user's group.

The Steps to Create a Custom httpModule for Changing master page for a logged in user are :
1. Create a new Class Library project in Visual Studio name it as CustomhttpModule
2. Add the below code in your class file.
using System;
using System.Web;
using System.Web.UI;
using Microsoft.SharePoint;

namespace SwitchMasterPage{
public class CustomHttpModule : IHttpModule
{

public void Init(HttpApplication context)
{
context.PreRequestHandlerExecute += new EventHandler(context_PreRequestHandlerExecute);
}

void context_PreRequestHandlerExecute(object sender, EventArgs e)
{
Page page = HttpContext.Current.CurrentHandler as Page;
if (page != null)
{
// register handler for PreInit event
page.PreInit += new EventHandler(page_PreInit);
}
}

void page_PreInit(object sender, EventArgs e)
{
Page page = sender as Page;

if (page != null)
{
SPSite site = SPContext.Current.Site;

using (SPWeb web = site.OpenWeb())
{
if (web.CurrentUser != null)
{
SPGroupCollection userGroups = web.CurrentUser.Groups; // Check all the groups user belong to
foreach (SPGroup group in userGroups)
{
if (group.Name.Contains(“OurCustomgroupName”)
// Switch the master page.

page.MasterPageFile = “/_catalogs/masterpage/MyCustom.master”;
}}}
}}
public void Dispose() { /* empty implementation */ }
}
}

it’s important to remember that an HttpModule cannot be deployed in a WSS farm for an individual site collection. Instead, an HttpModule must be configured as an all-or-nothing proposition at the Web application level.
3. Now, sign the project and build it.
4. Drag and Drop the signed assembly in GAC.
5. Next, we need to register this CustomhttpModule in our SharePoint webconfig. To do this add the below under <httpModules> tag in your web app’s web.config fie.
<add name=”CustomHttpModule” type=”SwitchMasterPage.CustomHttpModule,  SwitchMasterPage, Version=1.0.0.0, Culture=neutral, PublicKeyToken=7ebdb1031dfc1e406?/>
And you are Done!

Related Post is Sharepoint Programming:
More Interview Questions:SP 2010 Interview Quesions:
More Interview Questions Sharepoint 2010/2007
More interview Questions Shrepoint 2007/2010 Interview Questions with Answers

1 comment:

  1. http://www.techcontents.com/category/sharepoint-interview-questions-and-answers/

    ReplyDelete