Tuesday, March 24, 2015

Rename or Move a SharePoint list along with content using Http request (Without SP server side code)



The option to rename or Move a SharePoint list along with content is not available with SharePoint Client object model (CSOM) and the same can be achieved using the http request to SharePoint. Refer the code below.


string sourceUrl = "https://contoso.sharepoint.com/teams/site1/lists/List1";

string targetUrl = "https://contoso.sharepoint.com/teams/site1/lists/List1-move";

// Create the HttpWebRequest object.

HttpWebRequest request = (System.Net.HttpWebRequest)HttpWebRequest.Create(sourceUrl);


 
// FOR SHarePoint online- Set fedauth Authentication Cookie

if (IsSPOSite(sourceUrl)) {

SecureString securestring = new SecureString();

foreach (char c in "password".ToCharArray()) securestring.AppendChar(c);

SharePointOnlineCredentials SPOcredentials = new SharePointOnlineCredentials("someone@mycompany.com", securestring);

// Get the auth cookie

string fedAuthCookie = SPOcredentials.GetAuthenticationCookie(new Uri("https://contoso.sharepoint.com"));

request.Headers.Add("Cookie", fedAuthCookie); }

// on-premise

else {

request.UseDefaultCredentials = true; }


 
 
// Specify the method.

request.Method = "MOVE";

// Specify the destination URI.

request.Headers.Add("Destination", targetUrl );

// if a resource already exists at the destination URI, it will not be overwritten.

request.Headers.Add("Overwrite", "F");

// Send the MOVE method request.

WebResponse Response = request.GetResponse();

// Close the HttpWebResponse object.

Response.Close();

 


  
public static bool IsSPOSite(string clientContextUrl) 
{

// SPO site

if (clientContextUrl.ToLower().Contains(".com")) 
{

return true; }

else {

return false; } 
}
 
 

Wednesday, July 3, 2013

SharePoint Client Object model - Observations and limitiations

best practices

SharePoint Client object models provide an object-oriented system for interoperating with SharePoint data from a remote computer or from the browser. They use underlying SharePoint web services to interact with SharePoint objects. SharePoint Client OM has provided access to a subset of the types and members of the SharePoint server-side object model which provides ability to perform most of the common scenarios. SharePoint Client object model (Javascript & Managed client OM) is a great way to communite with SharePoint data from outside of SharePoint but need to understand some of the limitations of the client OM.

  1. When you host the application that uses the CSOM outside the SharePoint server (web application outside SharePoint server which uses SharePoint Client OM) , then user credentials cannot be used until we use constraint delegation. It uses only the application pool identity of the web application because of double hop issue and not the actual user credentials.


  1. Update SharePoint list items using client OM from other web app outside SharePoint

It updates the modified information of the items with the App pool account and special handling is required to update the modified information with the actual logged in user



User userInfo = site.RootWeb.EnsureUser(HttpContext.Request.LogonUserIdentity.Name);

// Update Modified by Information

fileitem["Editor"] = userInfo;

fileitem.Update();



  1. Access SharePoint using client OM from other web app outside SharePoint

The SharePoint in build security cannot be used and only app pool identity is being used to verify the access against SharePoint objects. Client object model doesn’t support to check the permission of the list item for the current user before updating the same.

Server side code

DoesUserHavePermissions(SPBasePermissions) method is available in the following objects to verify the user’s permission

  • SPWeb

  • SPList

  • SPListItem

public bool DoesUserHavePermissions(

SPUser user,

SPBasePermissions permissionMask

)

It also has overrides to pass the SPUser to get the permission for that user. Managed client OM doesn’t have that.


Client OM code

In client OM Microsoft.SharePoint.Client , the DoesUserHavePermissions method is available only at the Web level and not at the ListItem & List level. Custom code required to check the permissions for the user.

Below code checks the permission for the APP POOL account in case of web application hosted in a different server and not the current Logged in user.

private static bool DoesUserHasPermission(ClientContext context, ListItem listItem, PermissionKind permKind)

{


// Load the permissions before checking

context.Load(listItem, t => t.EffectiveBasePermissions);

context.ExecuteQuery();


return listItem.EffectiveBasePermissions.Has(permKind);


}





  1. SPUtility.CreateISO8601DateTimeFromSystemDateTime (); equivalent in SharePoint Client Object Model (CSOM). This is being used in CAML query and need to filter some data fetched from list based on Date.



Server side code:

string dateString = Microsoft.SharePoint.Utilities.SPUtility.CreateISO8601DateTimeFromSystemDateTime(DateTime.Now);



Client OM:

Format the string using string formatter

string dateString = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ssZ");



  1. Performance issue

  • Every time when you need to read the property, the object on which the property belongs needs to be executed. Multiple round trips to server which impacts performance

In the below code, targetListItem.File needs to be executed to read a property. This needs to be done to all items in the collection.

ListItemCollection collPageListItem = pagesList.GetItems(camlQuery);

// Load the List item collection and execute

clientContext.Load(collPageListItem);

clientContext.ExecuteQuery();


foreach (ListItem targetListItem in collPageListItem)

{

// TO Read the file Property server relative URL, NEED TO excute targetListItem.File Object

clientContext.Load(targetListItem.File);

clientContext.ExecuteQuery();


SpPagesMetadata pagesItem = new SpPagesMetadata();

pagesItem.PageId = targetListItem.Id;


// TO Read the file Property server relative URL, NEED TO execute targetListItem.File Object

pagesItem.PageUrl = targetListItem.File.ServerRelativeUrl;

}



Optimized approach,

Load all the required values in the context and ExecuteQuery once which reduces round trips to the server

// Load the item and it's file at one time

clientContext.Load(collPageListItem);

clientContext.Load(collPageListItem, items => items.Include(item =>item.File.ServerRelativeUrl));

clientContext.ExecuteQuery();



Load only the required values E.g In the above code, we use only the ServerRelativeUrl property from the file object and hence load that alone.



  1. Differences in SPWeb and Web objects

SPWeb object has some differences to get the SPweb context. In server side code, we can create the instance of SPWeb without passing the exact web url.



Server side code:

SPWeb spWeb = spSite.OpenWeb(”/staffing/Pages/default.aspx”, false)

Second boolean value that specifies whether the exact URL must be supplied. If it’s false, it will handle itself.



Client OM code:

Microsoft.SharePoint.Client.Web web = site.OpenWeb(”/staffing”);



Need to provide only the web site relative url. No second parameter to handle the above case.

  1. SPSiteDataQuery Not available with client OM



Unlike the server side code, Site data query is not available in the Client OM and hence search SharePoint across multiple sub sites with a single query is not possible. Need to loop thru each sub site to perform search.



  1. SPRoleAssignmentCollection



To remove all role assignment i.e. to remove a permission from an list item in SharePoint is straight forward with server side code and whereas in client managed object model, it’s little different. Also, we can’t remove the permission without knowing the SharePoint group or user.



Server code

SPSecurity.RunWithElevatedPrivileges(delegate()

{

listItem.BreakRoleInheritance(true);

while (listItem.RoleAssignments.Count > 1)

{

listItem.RoleAssignments.Remove(0); // Index

listItem.RoleAssignments.RemoveById(0); // based on ID


}

});



Client OM code

To remove the role Assignment using client object model, following code will be used.

//Delete the Permission for the user or Group

fileitem.RoleAssignments.GetByPrincipal(rcmGroupInfo).DeleteObject();



clientContext.ExecuteQuery();





  1. Elevated privileges

RunWithElevatedPrivileges is not available in the client object model and hence user context cannot be elevated to run the code.

  1. To download a file from document library

Server side code

Using SpFile.OpenBinaryStream method

using (SPWeb web = site.OpenWeb())

{

SPFile file = web.GetFile(“/documents/testdocument.docx”);

System.IO.Stream strm = file.OpenBinaryStream();

}



Client code

Client OM doesn’t have the method with File object and hence need to use FileInformation class.

FileInformation has OpenBinaryDirect method to get the stream without executing the query.

ClientContext clientContext = new ClientContext("http://SpSiteUrl");

Site site = clientContext.Site;


// Execute the query before getting the stream to create the context

clientContext.ExecuteQuery();


// Get the file stream, This directly calls and get the file stream. Need NOT call Excecute query

FileInformation fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, "/Documents/ Technical%20Design.docx");


// Access the stream for further processin

System.IO.Stream stream = fileInfo.Stream;

Tuesday, July 2, 2013

SharePoint client Object model

SharePoint client Object model has the JavaScript and managed client object model which will be used in different scenarios.

* JavaScript client object which will be used in Jquery or Jscript and the custom js file will be hosted in SharePoint server or SharePoint document library.

* Managed client object model which will be used with Rich internet application like Silverlight app (can be used with in SharePoint using Silverlight web parts) and can also be used outside SharePoint using console/ windows application executed from client machine or MVC application hosted outside SharePoint.


Sample code to query a SharePoint list using Javascript based SharePoint client OM

function clientOMSample() {
var cCtxt = new SP.ClientContext.get_current();
// get the site and web.
var site = cCtxt.get_site();
var web = site.get_rootWeb();

// get the list by name
var lstColl = web.get_lists();
var thisList = lstColl.getByTitle(“customlist”);
var cQry = new SP.CamlQuery();
var query = "";
cQry.set_viewXml(query);
var listItemColl = thisList.getItems(cQry);
cCtxt.load(listItemColl);


var asyncCallback = function (s, a, data) { data.func(s, a, data); };
// Call the executeQueryAsync method to execute the pending requests in the server cCtxt.executeQueryAsync(
Function.createCallback(asyncCallback, {func: onGetItemsQuerySucceeded, listItemColl: listItemColl}),
Function.createCallback(asyncCallback, { func: onGetItemsQueryFailed, listItemColl: listItemColl }));
}

function onGetItemsQuerySucceeded (s, a, data) {
var listItems = data.listItemColl.getEnumerator();
// Additional process goes here
}
function onGetItemsQueryFailed (s, a, data) {
// Handle error.
}

$(document).ready(function () {
// Call the function only when the sp.js is completely loaded
ExecuteOrDelayUntilScriptLoaded(clientOMSample, "sp.js");
});


Sample code to Updaye a SharePoint list item using Managed client OM

ClientContext clientContext = new ClientContext("http://spSiteUrl");
Site site = clientContext.Site;
// Get the current user and update the modified by information
User userInfo = site.RootWeb.EnsureUser(HttpContext.Request.LogonUserIdentity.Name);

// Get the File (Page from pages library) using the Url
Microsoft.SharePoint.Client.Web web = site.OpenWeb("/subsite");
Microsoft.SharePoint.Client.File filePage = web.GetFileByServerRelativeUrl("/subsite/Pages/default.aspx");

clientContext.Load(userInfo);
clientContext.ExecuteQuery();
Microsoft.SharePoint.Client.ListItem fileitem = filePage.ListItemAllFields;

// Update the file properties
fileitem["FieldName"] = "Test Contact Name";
// Update Modified by Information IF REQUIRED
fileitem["Editor"] = userInfo;

fileitem.Update();  
clientContext.ExecuteQuery();

                       

Tuesday, February 9, 2010

Access denied error while Editing List Items in SharePoint(MOSS 2007)

Sometimes, we get access denied error while editing (Edit properties) the list item even though we have access to the Sharepoint list.
Also, View History link on the Sharepoint list item throws access denied issue

Solution
This is a issue with Sharepoint and we need to execute the code to the SP libraries to fix the problem. The source code for this app is as follows. Put this in a console app and pass the site URL and list name as parameters.
This is working code and solved our production issue.

string RenderXMLPattenAttribute = "RenderXMLUsingPattern";
string weburl = "http://localhost/sites/Test/";
string listName = "Test Library";
SPSite site = new SPSite(weburl);
SPWeb web = site.OpenWeb();
Console.WriteLine(web.Name);
SPList list = web.Lists[listName];
SPField f = list.Fields.GetFieldByInternalName("PermMask");
string s = f.SchemaXml;
Console.WriteLine("schemaXml before: " + s);
XmlDocument xd = new XmlDocument();
xd.LoadXml(s);
XmlElement xe = xd.DocumentElement;
if (xe.Attributes[RenderXMLPattenAttribute] == null)
{
XmlAttribute attr = xd.CreateAttribute(RenderXMLPattenAttribute);
attr.Value = "TRUE";
xe.Attributes.Append(attr);
}
string strXml = xe.OuterXml;
Console.WriteLine("schemaXml after: " + strXml);
f.SchemaXml = strXml;
Console.WriteLine("Process completed");
Console.ReadLine();

Tuesday, January 26, 2010

SharePoint (MOSS 2007) Incoming Email is not working. EMAIL is not picked up from the DROP (C:\inetpub\mailroot\Drop) folder

EMAIL is not picked up from the DROP (C:\inetpub\mailroot\Drop) folder and got the error(exception) in Event viewer
A critical error occurred while processing the incoming e-mail drop folder . The error was: Value cannot be null.
Parameter name: path.
The Execute method of job definition Microsoft.SharePoint.Administration.SPIncomingEmailJobDefinition (ID df74919a-8a3d-4019-869c-fc5599909785) threw an exception. More information is included below.
Value cannot be null.
Parameter name: path



Solution

1. Check whether SMTP service and SharePoint Timer service is running on the SharePoint server
2. Give access to WSS_ADMIN_WPG (Full control) and WSS_WPG (Read/Write) to the DROP (C:\inetpub\mailroot\Drop ) folder
3. Check access for the SharePoint site (apps.ul.com) also for timer account to update the email into the document library which is configured.
4. Change the incoming drop folder settings on the Sharepoint Central administration site

Central administration -> Operations -> Incoming email settings. Change the email drop folder to (C:\inetpub\mailroot\Drop) folder

Saturday, November 14, 2009

Error and Resolution using SharePoint List web service

Problem #1
I have used the following code to connect to SharePoint list and upload data
Reference the SharePoint web service as ListService
http://servername:9000/_vti_bin/lists.asmx


ListService.ListsSoapClient addlist = new ListService.ListsSoapClient();
addlist.ClientCredentials.Windows.ClientCredential = System.Net.CredentialCache.DefaultNetworkCredentials;
addlist.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
addlist.Endpoint.Address = new System.ServiceModel.EndpointAddress(sharePointServerUrl + "/_vti_bin/Lists.asmx");
// Input Data for the list
XmlDocument doc = new XmlDocument();
XmlElement batch = doc.CreateElement("Batch");

// NEw in the above XMl for new Element addtion
XmlElement result = addlist.UpdateListItems("share Point ListName" , batch);
Issue #1
I got the Error message "Exception of type 'Microsoft.SharePoint.SoapServer.SoapServerException' was thrown. "
Solution #1
The sharePoint list name in the UpdateListItems method was incorrect and changed that, then worked well for me.

Issue #2
XmlElement result = addlist.UpdateListItems("share Point ListName" , batch);
result.InnerText shows "0x81020014One or more field types are not installed properly. Go to the list settings page to delete these fields." and the list was not updated properly
Solution #2
The issue is due to the non usage of internal names for the field names. So check the internal name of the fields in the list and changed accordingly as below. In the input XML (batach.InnerXml) , use Field Name='Last_x0020_Name' (This is the internal name of the field) instead of Field Name='Last Name'. Use internal names for the field instead of display names. This worked for me.
Also check the case of the internal field name( LastName and Lastname are different). Use the correct casing in field name to work properly.
Issue #3
addlist.UpdateListItems("share Point ListName" , batch);
Error while updating the list item
0x80070005The operation failed because an unexpected error occurred. (Result Code: 0x80070005)
Solution #3
The list doesn't have update access to the user. Providing access to the list solves this issue

Tuesday, May 12, 2009

Smartpart in SharePoint (MOSS) 2007 - Easy Web User Controls

The SmartPart is a generic webpart that can contain an ASP.NET user control. Nothing new you would say, but the SmartPart can give your user control access to the SharePoint object model.

Smart Part allows developers to code simple (or complex) Web User Controls (.ascx files) utilizing the full set of visual development tools in VS and then deploy the result to a SharePoint (MOSS) 2007 site by just configuring the url of the user controls.

Need for SmartPart and it's benefits

  • The SmartPart is a SharePoint Webpart that can host any ASP.NET user control. Creation webparts by using the VS.NET designer(user control) instead of coding everything by hand.
  • It complies with sharepoint object model since it's a type of web part.
  • Easy to deploy user controls in MOSS sites
  • Simple configuration
  • Supports AJAX and hence we can create AJAX enabled Smartpart eaily.

The following steps shows the steps to create and deploy the smartpart in MOSS site

Step 1: Create a SmartPart
TO create a smartpart, we need to create a library project using visual studio editor and add the following code. Add the reference to Microsoft.SharePoint.dll.

using System;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebPartPages;
namespace SmartpartSample
{
/// <summay>
/// Description for UserControlContainer.
/// </summay>

[DefaultProperty("Text"),
ToolboxData("<{0}:UserControlContainer runat=server>"),
XmlRoot(Namespace = "SmartpartSample")]
public class SmartpartSample : Microsoft.SharePoint.WebPartPages.WebPart
{
private const string defaultText = "";
private string _userControl = defaultText;
private Control _control = null;

[Browsable(true),
Category("User Control"),
DefaultValue(defaultText),
WebPartStorage(Storage.Personal),
FriendlyName("User Control (.ascx)"),
Description("Path to the User Control (.ascx)")]

public string UserControl
{
// This property has the URL of the user control to be displayed in the web part
get
{
return _userControl;
}
set
{
_userControl = value;
}
}
/// <summay>
/// This method gets the custom tool parts for this Web Part by overriding the
/// GetToolParts method of the WebPart base class. You must implement
/// custom tool parts in a separate class that derives from
/// Microsoft.SharePoint.WebPartPages.ToolPart.

///An array of references to ToolPart objects.
/// </summay>
public override ToolPart[] GetToolParts()
{
// These tool parts are to set the properities of the smart part
ToolPart[] toolparts = new ToolPart[2];
WebPartToolPart wptp = new WebPartToolPart();
CustomPropertyToolPart custom = new CustomPropertyToolPart();
toolparts[0] = custom;
toolparts[1] = wptp;
wptp.Expand(Microsoft.SharePoint.WebPartPages.WebPartToolPart.Categories.Appearance);
custom.Expand("User Control");
return toolparts;
}

/// <summay>
/// Load the UserControl
/// </summay>

protected override void CreateChildControls()
{
base.CreateChildControls();
try
{
if (_userControl != defaultText)
{
_control = this.Page.LoadControl(_userControl);
}
else
{
_control = new LiteralControl(string.Format("To link to content, open the tool pane and then type a URL in the Link text box.", 1, 129, this.ID));
}
}
catch (System.Exception ex)
{
_control = new LiteralControl(string.Format("Error: unable to load {0}
Details: {1}", _userControl, ex.Message));
}
if (_control != null)
{
// Add to the Controls collection to support postback
this.Controls.Add(_control);
}
}

/// <summay>
/// Render this Web Part to the output parameter specified.
/// </summay>

/// The HTML writer to write out to
protected override void RenderWebPart(HtmlTextWriter output)
{
EnsureChildControls();
if (_control != null)
{
_control.RenderControl(output);
}
}
}
}

Step 2: Adding the smart part into MOSS Site
1. Place the dll of the smart part project into the bin folder present in the virtual directory folder of the MOSS site.
2. Add a safe control entry for the smart part in the web.config file of the MOSS Site.

<SafeControl Assembly="Assembly Name of the SmartPart, Version=1.0.0.0, Culture=neutral" Namespace="Namespace of the SmartPart" TypeName="*" Safe="True" />

3. Modify the trust level to WSS_Medium in the web.config as shown below.
<trust level="Full" originUrl="" />

4. Open the SharePoint portal where the web parts have to be deployed.

5. Click on Site Actions->Site Settings->Modify All Site Settings

6. Click on Web parts option under Galleries

7. Click on New tab on the Web Part Gallery page.

8. Click on the checkboxes against the Smart part which we have deployed using the above mentioned steps.

9. Click the “Populate Gallery” button.

Step 3: Placing the User Controls and link to MOSS site

1. Copy the User controls to the UserControls folder in the Virtual directory of the MOSS Site.

2. If the UserControls folder is not available create the same.

Step 4: Using the smart in the site pages

1. Create a new page in the MOSS site and edit the page.

2. Add the Smart Part to the page and edit the properties of the smart part.

3. In the properties window of the smart part provide the user control path to be loaded in that page.

4. The path of the usercontrol file should be in this format “~\UserControls\UserControl File Name”.

5. Click on OK button, now the User control should be visible on the page.

6. Exit the page edit mode.

Tuesday, May 5, 2009

Frequently asked interview questions in MOSS 2007 - Part II

This article explains the frequently asked interview questions in MOSS 2007 (SharePoint) with answers. This covers basic and advanced concepts of MOSS

If you have not gone through the first part of the FAQs, click here (Part One)

1. What all elements of SharePoint to which Workflows can be applied?
While workflow associations are often created directly on lists and document libraries, a workflow association can also be created on a content type that exists within the Content Type Gallery for the current site or content types defined within a list. Workflows are applied at

  • At the level of a list (or document library)
  • At the level of a content type defined at site scope
  • At the level of a content type defined at list scope

2. What are the ways to initiate the workflow?
The following ways in which the workflows can be initiated

  • Automatic (without User Interface and no user inputs)
  • Manual (standard WSS UI interface - Out of the box user interfaces)
  • Manual (Custom UI Interface developed using .net or InfoPath forms)

3. What are the types of input forms that can be created for a workflow?
You can create four different types of input forms including

  • Association form
  • Initiation form
  • Modification form
  • Task edit form.
Create a Custom Workflow in MOSS with input forms is available here
Note that these forms are optional when you create a workflow template.

4. What are ways to create input forms for workflow?
Two different approaches can be used to develop custom input forms for a WSS workflow template.
  • You can create your forms by using custom application pages, which are standard .aspx pages deployed to run out of the _layouts directory. (The disadvantage with this approach is lot of code required when compared to InfoPath approach).
  • Using Microsoft Office InfoPath 2007 (The disadvantage with this approach is dependent on MOSS and it cannot run in a standalone WSS environment)


5. What is the difference between method activity and event activity in Workflow?

A method activity is one that performs an action, such as creating or updating a task.

An event activity is one that runs in response to an action occurring.

6. What does SPExport/SPImport class do?

This class is available in Microsoft.SharePoint.Deployment namespace.SPExport Supports export of specified content from a source Windows SharePoint Services site collection to a CAB file (with .cmp file extension or custom file extension) in XML format.

SPImport class Supports importing specified content into a Windows SharePoint Services site collection using a migration package (.cmp) file in XML format.Using these APIs, we can Export and Import

To learn more about these APIs, Click here


7. What are the defaults SharePoint permission groups available? How this is different from windows security groups?

Following SharePoint groups are provided by default.

  • Reader - Has read-only access to the Web site.
  • Contributor - Can add content to existing document libraries and lists.
  • Web Designer - Can create lists and document libraries and customize pages in the Web site.
  • Administrator - Has full control of the Web site.

The permissions can be applied at

  • Site collection level
  • Web site/ sub site level
  • Library or list levelList item or page level

We can add Windows user accounts and Windows security groups to your SharePoint groups for providing access.

8. What are the different types of search queries in SharePoint?

Search in Windows SharePoint Services supports three types of search syntax for building search queries:

  • Keyword Query syntax (search terms are passed directly to the Search service using OOB web parts like Search Web part)
  • SQL syntax (extension of SQL syntax for querying crawl databases by customizing the CoreResultsWebPart)
  • URL syntax (search parameters are encoded in URL, and posted directly to the search page E.g http://localhost/search/Results.aspx?q=keyword)

To learn more about search queries click here

9. What is the relationship between Microsoft SharePoint Portal Server and Microsoft Windows Services?

Microsoft SharePoint Products and Technologies (including SharePoint Portal Server and Windows SharePoint Services) deliver highly scalable collaboration solutions with flexible deployment and management tools. Windows SharePoint Services provides sites for team collaboration, while Share Point Portal Server connects these sites, people, and business processes—facilitating knowledge sharing and smart organizations. SharePoint Portal Server also extends the capabilities of Windows SharePoint Services by providing organizational and management tools for SharePoint sites, and by enabling teams to publish information to the entire organization.


10. What does SPWeb.EnsureUser method do?

Checks whether the specified login name belongs to a valid user of the Web site, and if the login name does not already exist, adds it to the Web site.

e.g

SPSite site = new SPSite("http://localhost");

SPWeb myweb = site.OpenWeb("");

SPUser usr = myWeb.EnsureUser("username");


11. While creating a Webpart, which is the ideal location to Initialize my new controls?

Override the CreateChildControls method to include your new controls. To make sure that the new controls are initialized. call 'EnsureChildControls' in the webparts Render method. You can control the exact Rendering of your controls by calling the .Render method in the webparts Render method.


12. How to query from multiple lists ?

Use SPSiteDataQuery to fetch data from multiple lists.

13. What are User Defined functions in Excel Services Calculation?

User-defined functions (UDFs) are custom functions that extend the calculation and data-import capabilities of Excel. Developers create custom calculation packages to provide:

  • Functions that are not built into Excel.
  • Custom implementations to built-in functions.
  • Custom data feeds for legacy or unsupported data sources, and application-specific data flows.

To use custom functions in a class as an Excel Services UDF class, you must mark your UDF class and method with the Microsoft.Office.Excel.Server.Udf.UdfClass and Microsoft.Office.Excel.Server.Udf.UdfMethod attributes.UDF assemblies are disabled by default.To Enable UDF Assemblies,Each Excel Services trusted location in the Shared Services Provider (SSP) has an AllowUdfs flag to true.


14. What are the sources of User Profiles information in SharePoint?

User Profile information can be imported from Active Directory through master connection.

In addition to Active Directory, importing profile information from all of the following data sources using Business Data Catalogue (BDC)

  • LDAP directory (which is not Active Directory)
  • Databases such as SQL Server
  • Enterprise applications (like SAP or PeopleSoft)


15. What is the use of query.ViewAttributes OR how can you force SPQuery to return results from all the folders of the SharePoint list?

If you use SPQuery on any SPlist, it will bring back results from the current folder only (One level only).If you want to get results from all the folders in the list (including sub folders) then you need to specify the scope of the query by the use of ViewAttributes.

e.g. SPList oList = oWebsite.Lists["DocLib_Name"];

SPView oView = oList.Views["View_Name"];

SPQuery oQuery = new SPQuery(oView);

oQuery.ViewAttributes = "Scope=\"Recursive\"";




Friday, May 1, 2009

Frequently asked interview questions in MOSS 2007

This article explains the frequently asked interview questions in MOSS 2007 (SharePoint) with answers

1. What MOSS (SharePoint) offers?

  • A framework that allows building business sites rapidly.
  • Lots of Out of the box features, Workflows and site templates already built-in Excellent integration with Word, Excel, PowerPoint etc
  • Audience Targeting and Document collaboration
  • Enterprise Search for content and people search
  • Wikis and Blogs
  • Really Simple Syndication (RSS) support

2. Is SharePoint supports Globalization?

Yes. Install different language packs for SharePoint. To learn about installing language pack, click here

3. Does SharePoint search results supports audience filtering?

The default SharePoint search results based on

  • Security of the items
  • Input keyword

The default search doesn’t support filter based on audience targeting. But we can customize coreresultswebpart to do that. To learn more about customizing core results web part is here


4. What is Shared Service Provider (SSP) in MOSS?

In MOSS 2007 there is this new concept of Shared Services Providers (SSP). The idea being that there are certain services that really make sense to centrally manage and share. A good example is user profiles. With a SSP we can import all of the profile information from AD (thru master connection) once as well as BDC (Business Data Catalog) and then our various web applications can consume the data. So maybe we have http://mossapp1/ and http://mossapp2/ it doesn't make sense for each one to maintain identical profile information, they should share.

The major services of SSP

  • Profiles and Audiences
  • My Sites
  • Search configuration
  • Excel Services
  • BDC (Business Data Catalog)
  • Manage usage analytics

5. Some of Out of the box web parts and its usage?

Web Part is a modular unit of information that consists of a title bar, a frame, and content. Web Parts are the basic building blocks of a Web Part Page. Web Part Page is a special type of Web page that contains one or more Web Parts.

Some of the major web parts are

  • Content Editor Web Part to add formatted text, tables, hyperlinks, and images to a Web Part Page. The Content Editor Web Part is intended for adding HTML content to a Web Part Page.

  • Page Viewer Web Part is to display a Web page, file, or folder on a Web Part Page. You enter a hyperlink, file path, or folder name to link to the content. You can use the Page Viewer Web Part only in a browser that supports the HTML IFRAME element. Displaying a file or folder requires Microsoft Internet Explorer.

  • Content Query Web Part (CQW or CQWP) is to display SharePoint content from another source like SharePoint list, pages library on a SharePoint page.

  • A Summary Link Web Part and a Summary Link field control both provide an easy way to build a page of links to various resources, both inside and outside of your site. You can control the appearance, organization, and presentation of the links that you add to a Summary Link Web Part or field control.

  • A Table of Contents Web Part is a configurable component that you can add to a Web Part Page. You use the Table of Contents Web Part to automatically generate a site map that point to various parts of your Office SharePoint Server 2007 site collection. When you add a Table of Contents Web Part to a page, you specify which part of your site collection the Web Part should generate links to, how the links are presented, and how the links are organized.

  • My Inbox web part Shows Inbox, open e-mail messages and even forward, reply, etc.
    Search Core Results Web Part, one of the most important ones displaying the search results to the user.

  • Excel Web Access web part is a feature of MOSS enterprise Edition. This web part is used to display an excel file from a Trusted file location. This comes as part of Excel services.

  • A Key Performance Indicator (KPI) web part is a visual cue that communicates the amount of progress made toward a goal. This article explains how to create KPIs by using Microsoft Office SharePoint Server 2007 KPI lists and how to display KPIs on Web pages.

6. What are the Components of Excel Services in MOSS?

There are three major components of Excel services

  • Excel Web Access
  • Excel Web Services
  • Excel Calculation Services

7. Personalization in MOSS and it’s different models

Personalization means providing a user centered experience of the Portal. Keeping user settings and preferences same every time the user logs in.

There are three main features in MOSS 2007 personalization model.

User profiles allow you to search and connect with people within your organization based on information published about them. MOSS 2007 provides a new search scope for searching people. Index Server crawls the user profile store to get the user’s information.


Audience Targeting: MOSS 2007 allows you to target content to people according to their membership in a particular audience. It supports targeting to rules-based audiences, distribution lists, and Windows SharePoint Services groups. Except for Windows SharePoint Services groups, these audiences can span one or more portal sites in a deployment.
Using targeting, you can target content in the portal site for viewing by one or more specific audiences. By default, you can display targeted content on the home page and on personalization sites.


My Site is a collection of Profile pages, personal sites, and personalization sites created in the Office SharePoint Server 2007 site. The Profile page of the My Site displays your user profile information. Your personal site provides personalized and customized information. Office SharePoint Server 2007 also supports personalization sites. Personalization sites display targeted content to users based on their membership in a particular audience or by slicing data.


8. What is WSS?

Windows SharePoint Services (WSS) is a set of components and services that is considered part of the Windows Server 2003 operating system. However, licensing and support for WSS is controlled by the Windows platform team, not the Office team.

Microsoft Windows SharePoint Services 3.0 is a versatile technology that organizations and business units of all sizes can use to increase the efficiency of business processes and improve team productivity. With tools for collaboration that help people stay connected across organizational and geographic boundaries, Windows SharePoint Services gives people access to information they need.
Built on Microsoft Windows Server 2003, Windows SharePoint Services also provides a foundation platform for building Web-based business applications that can flex and scale easily to meet the changing and growing needs of your business. Robust administrative controls for managing storage and Web infrastructure give IT departments a cost-effective way to implement and manage a high-performance collaboration environment. With a familiar, Web-based interface and close integration with everyday tools including the Microsoft Office system, Windows SharePoint Services is easy to use and can be deployed rapidly.


9. What are the different Workflow Types in MOSS?

Windows Workflow Foundation supports two fundamental workflow styles. You can create workflows of either type for Windows SharePoint Services 3.0.

A sequential workflow represents a workflow as a procession of steps that execute in order until the last activity completes. However, sequential workflows are not purely sequential in their execution. Because they can receive external events, and include parallel logic flows, the exact order of activity execution can vary somewhat.

A state machine workflow represents a set of states, transitions, and actions. One state is denoted as the start state, and then, based on an event, a transition can be made to another state. The state machine can have a final state that determines the end of the workflow.

10. What are content types?

A content type is a flexible and reusable WSS type definition that defines the columns and behavior for an item in a list or a document in a document library.

For example, you can create a content type for a customer presentation document with a unique set of columns, an event handler, and its own document template. You can create a second content type for a customer proposal document with a different set of columns, a workflow, and a different document template.


11. What is the difference between Synchronous and Asynchronous events in MOSS?

Synchronous calls ending with 'ing' E.g. ItemDeleting

  • Occur before the event.
  • Event Handler code execute BEFORE action is committed
  • WSS waits for code to return
  • Option to cancel and return error code

Asynchronous calls ending with 'ed' E.g. ItemDeleted

  • Occur after the event.
  • Event Handler code executes AFTER action is committed
  • WSS does not wait for code to return
  • Executed in its own Worker thread.

Events in MOSS occurs at

  • Site Level - E.g SiteDeleted & SiteDeleting
  • List Level - E.g FieldAdded & FieldAdding
  • List Item Level - E.g ItemAdded & ItemAdding

12. What is ServerUpdate() ?

Any changes in the list, i.e. new addition or modification of an item, the operation is complete by calling the Update method. But if a List is set to maintain versions and you are editing an item, but don't want to save it as a new version, then use the SystemUpdate method instead and pass in 'false' as the parameter.

13. What does AllowUnsafeUpdates do ?

If your code modifies Windows SharePoint Services data in some way, you may need to allow unsafe updates on the Web site, without requiring a security validation. You can do by setting the AllowUnsafeUpdates property.


using(SPSite mySite = new SPSite("http://localhost")){

using(SPWeb myWeb = mySite.OpenWeb())

{myWeb.AllowUnsafeUpdates = true;

SPList interviewList = myWeb.Lists["listtoinsert"];

SPListItem newItem = interviewList.Items.Add();
newItem["test"] = "test";

newItem.Update();}}


14. What does RunWithElevatedPrivileges do?

Executes the specified method with Full Control rights even if the user does not otherwise have Full Control.

Assume that you have a Web Part in which you want to display information obtained through the Windows SharePoint Services object model, such as the name of the current site collection owner, usage statistics, or auditing information. These are examples of calls into the object model that require site-administration privileges. Your Web Part experiences an access-denied error if it attempts to obtain this information when the current user is not a site administrator. The request is initiated by a nonprivileged user. you can still successfully make these calls into the object model by calling the RunWithElevatedPrivileges method provided by the SPSecurity class.
SPSecurity.RunWithElevatedPrivileges(delegate() {

// Add custom code here

});


15.What is a SharePoint Feature? What files are used to define a feature?

A SharePoint Feature is a functional component that can be activated and deactivate at various scopes throughout a SharePoint instances, such as at the farm, site collection, web level etc.

Features have their own receiver architecture, which allow you to trap events such as when a feature is installing, uninstalling, activated, or deactivated. The element types that can be defined by a feature include menu commands, link commands, page templates, page instances, list definitions, list instances, event handlers, and workflows.

The two files that are used to define a feature are the feature.xml and manifest file (elements.xml).

  • The feature XML file defines the actual feature and will make SharePoint aware of the installed feature.
  • The manifest file contains details about the feature such as functionality.

Go to FAQs Part II