Skip to main content

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

Comments

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

    ReplyDelete

Post a Comment

Popular posts from this blog

Tab Control in Asp.Net

Scenerio: I need your help in designing tab control in   asp.net .My requirement is I need a tab control in   asp.net (C#) like  for example goto my computer ,right click c drive and select properties.we get tabs like general,security etc....... like that i need to design one tab control(no need of any rightclick) in my web page and the database table columns should come as tabs and inseide the tab data of that particular column should come.   Example:Employee master tab1:Employee name.........his name in the tab tab2:Age.............his age tab3:Address........his address   Solution:   You can do this using a simple div <style type="text/css"> .tabs         {             position: relative;             height: 20px;             margin: 0;   ...

AI and Microsoft: Revolutionizing Efficiency in Nonprofit Organizations

  How AI and Microsoft Enhance Efficiency in Nonprofit Organizations In today’s fast-paced world, nonprofit organizations face unique challenges—limited resources, increasing demands, and the constant need to do more with less. But what if technology could be the game-changer they need? In my latest research paper,  "How AI and Microsoft Enhance Efficiency in Nonprofit Organizations" , I explore how cutting-edge technologies like Artificial Intelligence (AI) and Microsoft’s innovative tools are revolutionizing the way nonprofits operate. From streamlining administrative tasks to enhancing donor engagement and optimizing resource allocation, AI and Microsoft’s solutions are empowering nonprofits to focus on what truly matters—their mission. This paper dives deep into real-world examples, practical applications, and the transformative potential of these technologies. Whether you’re a nonprofit professional, a tech enthusiast, or simply curious about the intersection of technolo...

Social tagging overview in Sharepoint 2010

A tag is a word or phrase that identifies an individual piece of information according to a set of attributes or criteria. Tags make it easy to find and share information about a specific subject or task. Social tagging helps users categorize information in ways that are meaningful to them. Social tagging can improve the quality of search results by filtering against specific tags, and it can also connect individuals who want to share information with other users who have like interests. This article describes the social tagging features in Microsoft SharePoint Server 2010. This article does not describe how to configure social tagging features. It also does not discuss how to implement social tagging features as part of an overall social media strategy for an enterprise. About using social tagging features Social tagging features help users to share information and to retrieve relevant, high-quality content more efficiently. Such sharing encourages collaboration and b...