Wednesday 21 May 2014

Stupid Things i used to do in SharePoint


Reading URL from from picture or hyperlink filed Using SPFieldUrlValue.

var newsLink = item.GetValueByInternalName("NewsLink").ToString();
newsLink = newsLink.Split(new char[] { ',' })[0];
objNewsInfo.NewsLink = newsLink;

you have to read it using  objNewsInfo.NewsLink = new SPFieldUrlValue(newsLink).Url;


Tuesday 20 May 2014

Understanding elevated privileges in Sharepoint

Understanding elevated privileges:

 If your code runs in a farm solution within the SharePoint context, your code is executed by an IIS worker process (w3wp.exe).This process runs using the application pool identity associated with the SharePoint web application. ASP.NET applications, including SharePoint, use impersonation by default. This means that the application pool identity will impersonate the current user to execute code. As a result, your code can only perform actions that are permitted by the permission set of the current user.

When you use SPSecurity.RunWithElevatedPrivileges to invoke code, the worker process reverts to executing code using the application pool identity, rather than the identity of the current user. The application pool identity has full-trust permissions on the SharePoint web application. Consequently, your code is no longer restricted by the permission set of the current user.


Running code with elevated privileges is only applicable to code that runs within the SharePoint context. Code that runs without a SharePoint context—for example, code within a timer job—runs under a process identity rather than a user identity. In these scenarios, elevating privileges would have no effect, because the process is not impersonating the identity of a user. 


Note:

 You code run with elevated privileges only in farm solution,
 sandbox solution is executed withing isolated worker process.



many developer make a big mistake (me as well) and use SPSite object and SPWeb object from current context (SPContext) in elevated method , if you do so the elevated code will revert to running under the identity of current user.




Use SPSecurity.RunWithElevatedPrivileges to run code using the system account:


var dolegaDPO = New SPSecurity.CodeToRunElevated(DoPrivilegedOperation); 

SPSecurity.RunWithElevatedPrivileges(dolegaLODPO ); 
private void DoPrivilegedOperation()
{
  //type your code here
}

OR 



SPSocurity.RunWithElovatodPrivilogos( delegate() {

 //type your code here


});