Tuesday, 31 August 2010

Alternative of using _spBodyOnLoadFunctionNames

I am very sure that most of the Sharepoint developers must have used _spBodyOnLoadFunctionNames to inject javascript methods on the sharepoint list forms(NewForm/EditForm/DispForm).

Downside of using _spBodyOnLoadFunctionNames is the time taken to execute my javascript function. Even though my function is very small, there is delay in executing my method.

Reason for the Delay:

Delay occurs because sharepoint first loads all the controls on the form and subsequently executes the embedded javascript functions. So if number of controls are high, it will take substantial time to execute my custom javascript method. Delay would be more in case of Sharepoint 2010 pages because it has more number of inbuilt javascript functions to execute while loading the page.

Solution:

In order to avoid the delay we have to execute our function "onload" event of any control and following steps can be considered to achieve this functionality.

1. Create your javascript function
function MyMethod()
{
// My method logic
}

2.Create a "img" element anywhere on your page(Since we can not capture "onload event" of most of the controls).
3. Set the image source to "/_layouts/images/blank.gif" so that nothing is visible on the page.

4. Call your javascript function on "onload event of the img.


<IMG SRC="/_layouts/images/blank.gif" width="1" height="18" onload="MyMethod();"/>

Note: Mentioned issue is quite visible in case you are trying to hide/show some buttons/controls of the page on load of the page.

Thursday, 26 August 2010

Create ListItem using Client Object Model

Client Object model is very powerful feature of Sharepoint 2010.
You can use Client object model from remote computer to access sharepoint site and do CRUD operation.

Below is the sample code to create listitem using Sharepoint client object model.

// Create ClientContext Object
using (ClientContext clientContext = new ClientContext("http://sitename"))
{
// Give the credential
clientContext.Credentials = new System.Net.NetworkCredential("username", "password", "domainname");
Web site = clientContext.Web;
List list = clientContext.Web.Lists.GetByTitle("ListName");
// To use site object load it first
clientContext.Load(site);
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
ListItem listItem = list.AddItem(itemCreateInfo);
listItem["Title"] = "Created through Client Object Model";
listItem.Update();
// Execute the query to push data on the server.
clientContext.ExecuteQuery();
}

Tuesday, 24 August 2010

Error: System.IO.FileNotFoundException in client application

Recently, I was trying to create a console application and using Sharepoint object Model. My console application and sharepoint web application was on the same machine.
While creating the SPSite object I was getting following error.

"The Web application at http://sitename/ could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application."

The error was very much misleading, after struggling a bit I found that by default client application's platform target was set to X86 i.e 32 bit so it was not able to access the webapplication which is targeted as 64 bit. So to overcome this issue I had to change my platform target to "AnyCPU" or X64.

Ironically, it was working fine when I was using "Sharepoint Client Object Model"

Saturday, 21 August 2010

What is Restricted/Allowed under Sandboxed Solutions

You can target your solution as sandboxed only if all of your solution component fall within following SharePoint items:

 Web Parts (code only; not visual Web Parts)
 Event receivers
 Content types
 List templates
 List instances
 Custom actions
 InfoPath forms

You can not target your solution as sandboxed, in case any of your solution components fall within following SharePoint items:

 Visual Web Parts (they contain web controls that have to be deployed to disk)
 Business data connectivity models
 Application pages
 User controls
 Call web services in an intranet or over the Internet
 Access data outside the site collection where the solution has been deployed
 Read and write files with your code
 Run code that is not marked to allow partially trusted callers
 Use objects above SPSite (e.g., SPFarm)
 Use security-related functions (RunWithElevatedPreviledges)
 Impersonation of Users
 Custom Workflow or programmatically invoking SharePoint Designer workflow
 Programmatically accessing Taxonomy data/ Metadata Management


Looking at the above allowed/restricted items, it is quite evident that Sandbox solutions would provide more security and control but lesser features. Whereas farm based solution would not restrict any thing but it would developer’s prerogative to handle the security and avoid malicious code, which would result into more number of code reviews and unit testing

Opening the Sandbox

Few months back when I started exploring Sharepoint 2010, I was spellbound of so many new features like Metadata Management, Developer Dashboard,Powershell integration,Client Object Model, great development environment through Visual Studio 2010 and one of them is Sandbox Solution. At first glance Sandbox Solutions looked really great to me.

Why Sandbox came into picture

Earlier to Sharepoint 2010, if you are creating a sharepoint application using Sharepoint Object Model, code needs to be thoroughly reviewed and tested before it goes to Production Server to avoid any malicious code. Testing and code review is a big effort which is directly proportional to number of features or LOC of my application. I found Sandbox Solutions to be a real solution to the mentioned problem. Also it provides a good peace of mind to Sharepoint administrator because now they can do better monitoring and resource allocation per Site Collection. Apart from this they can validate the solution before it gets deployed.

After digging more I found that Sandbox Solutions are great but it can’t cater to all kind of Sharepoint applications.Sandboxed solutions run with lower trust level for hosted environments. A sandboxed solution cannot access the full SharePoint object model; it is limited to a subset of the Microsoft.SharePoint namespace. Sandboxed solutions run in a safe and monitored process with restricted access to resources.

Tuesday, 17 August 2010

How to impersonate Site administrator privileges

When we run a piece of code within SPSecurity.RunWithElevatedPrivileges, it run in context with Sharepoint System account. So if you want to run a piece of code under a specific user account/role we have to impersonate that specific user account.

To impersonate a specific user, you need the usertoken of the impersonated user and you have to pass it while creating the SPSite object.

SPUserToken userToken = Web.SiteAdministrators["loginname"].UserToken;
using(SPSite site = new SPSite("SiteURL", userToken))
{
SPWeb Web = mySite.RootWeb;
// Perform activities which require administrative privileges

}

Query List/Document Library in Specific Folder

To query SharePoint List or Document Library in specific Folder “ FolderServerRelativeUrl ” as part of the CAML Query Code Snippet ...