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 Questions



SharePoint 2010 Questions
Q. How will you deploy files such as Css, js in SharePoint 2010?

Ans. The most preferable way to deploy files in SharePoint is by using the solution package. In SharePoint 2010 you can create an empty project with VS 2010 and then add a new SharePoint Mapped folder  in it. This will give the desired location in 14 hive where you can then add a file to deploy.

Can you display a page as a modal dialog?

Ans. Yes, any page can be displayed as modal dialog. A Modal dialog takes options as a parameter and we can speciy the url for any page usually saved in _layouts.

Q. Can you display the modal dialog from a webpart?

Ans. Yes a modal dialog can be displayed from within a webpart code since its a JavaScript block that can be registered on the page.

Q. What is difference between an Application page and a Custom aspx page in SharePoint 2010. If you have to deploy a page with some code in it which one would you prefer?

Ans.
Application Page – You would typically use an applictaion page when you need some content that is merged with SharePoint master page. A master page enables application pages to share the same appearance and behavior as other pages on a site. Application page generally gets deployed in _layouts and inhertirs the look and feel of the site that you are using.
A Custom .net aspx page on the other hand would need content and master page tags in your page to make it inherit the look and feel of the site.
I would prefer deploying an application page with code as it is much easier and has built-in templates available in VS 2010.

Q. What is Docuement Set and how is it useful to the end users?

Ans. A Document Set is a group of related documents that can be created in one step and then managed as a single entity. This can be seen as a folder of documents with a cover letter(welcome page) and which can share common data between its documents (share document set info\columns).
Document Set is very useful when it comes to managing the documents for a single project or task. For e.g. a manager while working on a project wants to create a single folder\entity with all the documents related to that project. He also wants that each document shares the project info (for e.g. Project Id, Manager name etc.) and can be checked in\checked out individually. Document Set will also allow him to add a cover letter\welcome page to the entity(or his set of documents) and use some basic document features like record version history, start a workflow, e-mail document set etc.

Q. What are Projected Fields in SPQuery and when would you use that?

Ans. In SharePoint 2010, Referential integrity can now be implemented using Lookup columns. Joins and ProjectedFields properties of SPQuery were introduced to facilitate this. Projected Fields are the fields which you can access when a list is joined by a lookup solumns. These are additional columns from a parent lookup column list.

Q. What is WebProvisioned event receiver and when would you use that?

Ans. WebProvisioned event receiver is fired after the site has been created and is fully provisioned(asynchronous). For e.g. if you want to update the site title of logo after its been created or if you want to add a new list\library after the out-of-box site has been created you can use the WebProvisioned event handler.

Q. If you have to add a new Ribbon button to one of the existing tabs how will you identify the location?

Ans. The Its typically Ribbon.Tabs.group.Controls._children.

Q. How does Client object model works ?

Ans. 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).

Q. How many types of Client Object model extension are available in 2010 and when would you use one or the other.

Ans. 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.

Q. What is difference between Load() and LoadQuery() methods ?

Ans. 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.

Q. How can you write efficient and better performing client object applications ?

Ans. 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.

Q. What are the Authentication methods for your client object model application ?

Ans. 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). For more details see Authentication Setup in SharePoint 2010 Client object model

Authentication Setup in Client object model – Sharepoint 2010

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;
See the related forum Post form bases authentictaion using client object model

Q. How do you access ECMAScript object model API’s ?

Ans. 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.

Q. What is the purpose of calling clientContext.ExecuteQuery() ?

Ans. ExecuteQuery 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
Q. Why would you use LINQ over CAML for data retrieval?

Ans. 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.

Q. Can we use our custom master page with the application pages in SharePoint 2010 ?

Ans. 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.

Q. What are WebTemplates and Site Definitions ?

Ans. 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.

Q. How do you write to SharePoint ULS logs in 2010 ?

Ans. In 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.
See examples @ Writing errors to ULS logs and event logs Sharepoint 2010


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.

Q. What does CMDUI.XML contain?

Ans. 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.

Q. What has Changed in SharePoint 2010 Object model?

Ans. Microsoft has replaced the “12 hive” structure that we had in SharePoint 2007 with “14 Hive” structure in 2010.
It has apparently added four new folders to its hive.
The Folders are :
* Policy
* UserCode
* WebClients
* WebServices

for details see 14 hive directory structure

Q. How would you deploy WebPart Using Windows PowerShell?

Ans. At the Windows PowerShell command prompt (PS C:\>), type the below command :
Install -SPWebPartPack -LiteralPath “FullPathofCabFile” -Name “Nameof WebPart”

Q. How would you re-deploy the old custom solutions in SharePoint 2010.What Changes are needed to the old Solution files.

Ans. SharePoint 2010 object model contains many changes and enhancements, but our custom code will still compile and, will run as expected. You should however, rewrite and recompile any code that refers to files and resources in “12 hive”.


Q. How would you add a link in the Ribbon?

Ans. You can add any link or Custom Action under any of the existing tabs of the ribbon or can create a new a new tab and place your links under it.

Q. What are the Disadvantages of Using LINQ in your Code?

Ans. LINQ translates the LINQ queries into Collaborative Application Markup Language (CAML) queries thus adding an extra step for retrieving the items.

Q. What is different with SharePoint 2010 workflows ?

Ans. Some of the additions in workflow model are :
1. SharePoint 2010 workflows are build upon the the workflow engine provide .Net Framework 3.5.
2. In addition to the SharePoint lists we can now create workflows for SharePoint sites as well.
3. SharePoint Designer 2010 also has a new graphical workflow designer for designing workflows and deploying them directly to SharePoint.
4. Another Improvement in SharePoint Designer 2010 is that it now allows you to edit the out-of-the-box workflows that come with SharePoint.

What is Windows Powershell ?
Ans. 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.

Q. How is Windows Powershell different from Stsadm ?

Ans. 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?
Ans. Windows PowerShell introduces the concept of a cmdlet which are simple build in commands, written in a .net language like C# or VB.

Q. Can you Create PowerShell scripts for deploying components in SharePoint ?

Ans. 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.

Q. Where is Powershell located in sharePoint ?

Ans. On the Start menu, click All Programs -> Click Microsoft SharePoint 2010 Products -> Click SharePoint 2010 Management Shell.

Q. If you need going to install a webpart or any custom solution in SharePoint 2010 using PowerShell What permissions do you need?

Ans. 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. See Details
Permissions for Windows PowerShell – SPShellAdmin

Q. How to list all the commands in PowerShell ?

Ans. Get-Command * commands gets you all the Powershell commands.

Change SharePoint Web Application url

To Change the Web Application url for an existing webapp was a challenge in SharePoint. I tried renameweb stsadm operation but it did not solve the purpose.
So at the end the best possible way was to Extend the web application.
Here are the Steps that i followed –
1. Extend the Web application.
2. Add new url in Host header.
3. Once done creating Modify your AAM settings and add the new url as default.

Now you can access your new web app with the new url.

Retrieve, delete databases Not in Sync with SSP SharePoint

In this post i will list out some important commands that will help you eliminate\fix the databases which are not in sync with SSP.
To List out all databases which are not in sync from last 10 days-

stsadm -o sync  -listolddatabases 10

The result will list out GUID and Date\Time of all the databases.
To fix the Synchronization errors on a content database.-
stsadm -o preparetomove -contentdb sqlservername:dbname -oldcontentdb GUID
In the above command you need to specify the sqlserver name and the dbname that you need to fix. Also, provide the
GUID for the same database.

This command is used when the preparetomove operation is not run prior to moving the content database.
To Delete these unwanted databases -

stsadm -o sync -deleteolddatabases 10

This will delete entries in SSP for anything that is not in sysnc for more than 10 days.

Enable\Disable Ribbon button by Users Group Sharepoint 2010 -II

In this post we will see a detailed example of how to enable and disable a ribbon button according to the Logged in user’s group. The idea here is to enable the ribbon button if the current user is a part of a pre-specified group (say ListOwners) and disable the same if the user is not one of the added users of the group.
The example uses “EnabledScript” attribute of the CommandUIHandler of the ribbon button to decide whether the button should be enabled or disabled for the loggedin user.
Code Overview -
1.  The below example enables the ribbion button if the current user is a part of a pre-specified group (say ListOwners)
2. The button remains\gets disabled if the user does not exist in the specified group.
3. A separate JavaScript file CheckUserInGroup.js which is deployed in /_layouts/RibbonScripts contains the EnableIfUserInGroup() function. This function is called in EnabledScript and it executes to check if the user exists in the pre-specified group.
Lets Start with creating a Ribbon button first  -
Steps -
1. Create a empty project.
2. Deploy it as a Farm solution.
3. Right click on the feature and click “Add feature”.
4. Right click on the project and add a new “Empty Element” item.
5. Next add the below code to add a custom Ribbon button to your document library.
<Elements xmlns=”http://schemas.microsoft.com/sharepoint/” >
<CustomAction
Id=”ButtonForGroupUsersOnly”
Location=”CommandUI.Ribbon”
RegistrationId=”101″
RegistrationType=”List”
Title=”Owners Group Button”>
<CommandUIExtension>
<CommandUIDefinitions>
<CommandUIDefinition
Location=”Ribbon.Library.ViewFormat.Controls._children”>
<Button Id=”Ribbon.Library.ViewFormat.UsersBtn”
Command=”usersBtnCommand”
LabelText=”Group Users Button”
Image32by32=”/_layouts/1033/IMAGES/buttonIcon.jpg”
TemplateAlias=”o1″ />
</CommandUIDefinition>
</CommandUIDefinitions>
<CommandUIHandlers>
<CommandUIHandler
Command=”usersBtnCommand”
CommandAction=”javascript:OwnerBtnscript();“/>  –> Refer Your Function here. This runs after your button is clicked
EnabledScript=”javascript:EnableIfUserInGroup();” -> Enable Ribbon function here
</CommandUIHandlers>
</CommandUIExtension>
</CustomAction>

//Referencing the Script
<CustomAction
Id=”OwnersButton.Script”
Location=”ScriptLink”
ScriptSrc =”/_layouts/RibbonScripts/CheckUserInGroup.js”/>
</Elements>

The Group Users Button created in the above code will be in the disabled mode on page load. The code in EnableIfUserInGroup(); will determine if the current  user is added to the specified group and the button needs to be enabled.
The CustomAction ScriptLink refers to the path of the CheckUserInGroup.js file which contains EnableIfUserInGroup(); and other JavaScript functions.

EnableIfUserInGroup() which will enable\disable the Ribbon button.
6. Next add a Javascript file in your project “CheckUserInGroup.js” and add it under Layouts -> RibbonScripts folder. Create Layouts folder using Add-> “Sharepoint Layouts Mapped Folder” .
7. Next, the following goes in your CheckUserInGroup.js file
<script src=”/_layouts/SP.js” type=”text/ecmascript”></script>
<script type=”text/javascript”>

// The below is called by EnabledScript in ribbon button
function EnableIfUserInGroup() {
var _userInGroup;

if (UserExistInGroup == null)
CheckUser();
else {
_userInGroup = UserExistInGroup;
UserExistInGroup = null;
return _userInGroup;
}
}

// The below checks if the user exists in the group
function CheckUser()
{
var clientContext = new SP.ClientContext();
var groupCollection = clientContext.get_web().get_siteGroups();

// Get the Our Group’s ID
var _group = groupCollection.getById(10);
->> ID of the Group that we are checking against e.g. ListOwners group
var users = _group.get_users();
->> Get all Users of the group
clientContext.load(_group);
clientContext.load(users,’Include(loginName)’);

this._currentUser = clientContext.get_web().get_currentUser(); ->> Get current user
clientContext.load(this._currentUser,’Include(loginName)’);

clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
RefreshCommandUI();
->> Refreshes the Ribbon again to pick up the new value for UserExistInGroup
}

//The below Checks  if User is the member of the specified group
function onQuerySucceeded() {
if(users.count >0)
{
UserExistInGroup = false;

for(var i=0; i < users.count; i++)
{
if(users[i].get_loginName() == this._currentUser.get_loginName())
{
UserExistInGroup = true;
}
}
}}

function onQueryFailed(sender, args) {
alert(‘Request failed. ‘ + args.get_message() + ‘\n’ + args.get_stackTrace());
}
</script>

8. Next Build and deploy.

Get current loggedin user in Sharepoint using Javascript

This a script that gets the current logged-in user’s name from the welcome menu and populates it in a People Picker control.
Firstly, to run the function on page sharepoint load user  spBodyOnLoadFunctionNames something like below.
_spBodyOnLoadFunctionNames.push(“AddCurrentUserToPP”);
Next add this script in any content editor webpart or just on your custom page.
function AddCurrentUserToPP()
{
var currentUser = GetUser();
if(currentUser != null)
{
var pp = GetPeoplePickerText(document.getElementById(‘PeoplePickerId’).parentNode);

//set the People picker field to current user
if(pp != null)
pp.innerText = currentUser;
}
}

function GetUser()
{
var tags = document.getElementsByTagName(‘a’);
for (var i=0; i < tags.length; i++)
{
if(tags[i].innerText.substr(0,7) == ‘Welcome’)
{
return tags[i].innerText.substr(8,tags[i].innerText.length);
}
}

}
function GetPeoplePickerText(container)
{
var result  = “”;

var _divs = container.getElementsByTagName(“DIV”);
for(var k=0; k < divs.length; k++)
{
if(divs[k].id.indexOf(identifier) > 0 && divs[k].id.indexOf(“UserField_upLevelDiv”) > 0)
{
result = divs[k];
break;
// You can also access the text in the control by using the below
var innerSpans = divs[k].getElementsByTagName(“SPAN”);
for(var j=0; j < innerSpans.length; j++)
{ if(innerSpans[j].id == ‘content’)
{ return innerSpans[j].innerHTML;}
}

}
return result;
}





No comments:

Post a Comment