"The day you stop learning SharePoint is the day you stop using it."

Using SPSecurity.RunWithElevatedPrivileges with SPContext class

Using SPSecurity.RunWithElevatedPrivileges with SPContext class.

If you have implemented your code similar to the Code Snippet 1 then you might run into exception. Many developers implement their code, similar to the Code Snippet 1 and runs into exception such as Access Denied, “sign in as a different user”. This is because… the below code is not the correct way of using SPSecurity.RunWithElevatedPrivileges

When you declare SPSite elevatedSite = SPContext.Current.Site; or SPWeb elevatedWeb = SPContext.Current.Web;

these statements runs with the current login user permission and not the System Account. Therefore you might face an Access Denied exception when updating a list or any content since the code is running under current login user credentials who might have no add/contribute access on the list. No matter if you have declared
SPContext under SPSecurity.RunWithElevatedPrivileges, still the code will execute with the current login user permission.

Code Snippet 1 (Incorrect way):

SPSecurity.RunWithElevatedPrivileges(delegate()
{
      SPSite spSite = SPContext.Current.Site;

      using (SPWeb spWeb = spSite.OpenWeb())
      {
         // Performing administrative actions here will give Access Denied exception.
      }
});


Code Snippet 2 (Correct Way):

Guid spSiteGUID = SPContext.Current.Site.ID;
Guid spWebGUID = SPContext.Current.Site.OpenWeb().ID;

SPSecurity.RunWithElevatedPrivileges(delegate()
{
    using (SPSite elevatedSiteColl = new SPSite(spSiteGUID))
    {
       using (SPWeb elevatedWeb = elevatedSiteColl.OpenWeb(spWebGUID))
       {
         //your code…
       }
   
    }
});

The above Code Snippet 2 automatically disposes the SPContext object and the SPSite and SPWeb objects are also automatically disposed once they leave the code block. No need to dispose SPSite and SPWeb objects explicitly when they are declared in using statement.

So the bottom line is SPContext does not works under SPSecurity.RunWithElevatedPrivileges.
Share:

Easiest way to populate a drop-down list control with SharePoint custom list column values

There are numerous ways to populate a drop-down list control with SharePoint custom list column values. But for me the below seems to be the easiest one.

You should populate the drop-down list on a page load event as given in below code. You can copy the exact below code with few changes as what column values you want to populate and your drop-down list control ID/Name.


I have used here 
SPQuery since I want to order the column values alphabetically, starting from ascending to descending. You can omit the SPQuery statement and directly specify the column value in spList.GetItems() method.

Example: SPListItemCollection spListColl = spList.GetItems("Title"); // Title is the column name. You can mention any column name of your choice.

protected void Page_Load(object sender, EventArgs e)
{
   if (!IsPostBack)
   {
      Guid spSiteGUID = SPContext.Current.Site.ID;
      Guid spWebGUID = SPContext.Current.Site.RootWeb.ID;

      //Use above statement if your site is at root site or else below one.  
      //Guid spWebGUID = SPContext.Current.Site.OpenWeb().ID; 

      SPSecurity.RunWithElevatedPrivileges(delegate()
      {
         using (SPSite elevatedSiteColl = new SPSite(spSiteGUID))
         {
            using (SPWeb elevatedWeb = elevatedSiteColl.OpenWeb(spWebGUID))
            {
               SPList spList = elevatedWeb.Lists["QD Offices"];
               SPQuery spQuery = new SPQuery();
               spQuery.Query = "<OrderBy><FieldRef Name='Country'/></OrderBy>";
               SPListItemCollection spListColl = spList.GetItems(spQuery);
               foreach (SPListItem spItem in spListColl)
               {
                  string listItem = spItem["Title"].ToString();
                  ddl_location.Items.Add(listItem);
               }
            }
         }
      });
   }
}


Cheers !!
Share:

Open InfoPath Web Form from SharePoint Designer trigger email

In this article I will show you how you can create a hyperlink through which you can open a published InfoPath form from an email, triggered by SharePoint Designer 2010 Workflow.

In SP Designer Workflow, select "Set Variable Workflow" action and set the variable to the string specified in the below first image.

Text reference: First select [%Workflow Context:Current Site URL%] by clicking "Add or Change Lookup" button and select Data Source: Workflow Context; Field from source: Current Site URL, then same string as it is till Cases/, then select Current Item:Title, then write "&Source", then again [%Workflow Context:Current Site URL%] and finally write or copy the string "/Cases/Forms/AllItems.aspx&DefaultItemOpen=1"








In the second image, you can see there a link "here", by clicking this click an active InfoPath form will be opened in the web browser. [Just confirm that your InfoPath form is web browser enabled form].




















You can include this "here" link by clicking the small icon next to "Automatic".

Cheers !

Hope this small piece helps you...
Share:

Difference between “Manage Users” and “Share Project Web App” in Project Server 2013

At some point of time I was quite confused why there would be two ways to assign permission to users in Project Server and with different names and settings. These two ways are – “Manage Users” and “Share Project Web App”.

Have you ever found the difference between the two? You are guessing right… YES there is a difference. You must be aware of the fact that Project Server 2013 has two permission modes, one is the SharePoint Permission Mode and the other is Project Server Permission Mode. By default after installing Project Server 2013 setup, the Project Web App is configured in SharePoint Permission Mode.

In SharePoint Permission Mode, the Security category would be missing from PWA Settings.



The “Share Project Web App” only works when your PWA is configured in SharePoint Permission Mode. The “Share Project Web App” does not works in Project Server Permission Mode. What if you want to change your PWA permission mode from SharePoint Permission Mode to Project Server Permission Mode, is it possible? Yes it is and the steps are very simple…

Have a look: http://technet.microsoft.com/en-us/library/jj219486.aspx

The Manage Users is available for Project Server Permission Mode. So when you have changed the permission mode, the Security category in PWA settings would be available now.




So do remember, when you have configured your PWA in Project Server Permission Mode then you must only use Security category to grant access to users and do not use “Share Project Web App.”

Share:

STEPS TO AUTOMATE BACKUP OF SHAREPOINT 2010 SITE COLLECTION

1.     Open the notepad and copy the below script.

Add-PsSnapin Microsoft.SharePoint.PowerShell
Start-SPAssignment -Global

$mySite="http://sitecollectionURL"
$backupLocation="D:\SiteBackup"
$logFile="$backupLocation\BackupLog.log"
$today=Get-Date -format "MM-dd-yyyy HH.mm.ss"

try
{
Backup-SPSite $mySite -Path $backupLocation\SPSite_$today.bak -force
write "$today $mySite successfully backed up">>$logFile   
}

catch
{
write-Host Backup process failed
See $logFile for more information.    
write "$today  Error: $_">>$logFile
}   

Stop-SPAssignment -Global
Remove-PsSnapin Microsoft.SharePoint.PowerShell
write-Host "Task Finished"
  • In the script specify your site collection url at variable $mySite =”http://sitecollectionURL
  • Specify the backup location at variable $backupLocation="D:\SiteBackup"
  • Create a Backup log text file in the same backup location with the name “BackupLog”
  • Provide an appropriate name for the file and save the file with a “.ps1” extension.
You can repeat the process from step 1 to 5 for different site collections. In this way you can have multiple PowerShell scripts for every site collection.
Or you can declare new variables like,
$mySite1=http://siteURL1”         
$mySite2=http://siteURL2

And add additional Backup-SPSite command in the above script.
Example:
Backup-SPSite $mySite1 -Path $backupLocation\Site1_$today.bak –force
                Backup-SPSite $mySite2 -Path $backupLocation\Site2_$today.bak –force 

Example:

Add-PsSnapin Microsoft.SharePoint.PowerShell
Start-SPAssignment -Global

$mySite1=”http://site1.domain.com
$mySite2=”http://site2.domain.com
$mySite3=”http://site3.domain.com
$mySite4=”http://site4.domain.com
$backupLocation="D:\SiteBackup"
$logFile="$backupLocation\BackupLog"
$today=Get-Date -format "MM-dd-yyyy HH.mm.ss"

try
{
Backup-SPSite $mySite1 -Path $backupLocation\Site_IAM_$today.bak –force
write "$today   $mySite1 successfully backed up.">>$logFile   

Backup-SPSite $mySite2 -Path $backupLocation\Site_ArtWork_$today.bak –force
write "$today   $mySite2 successfully backed up.">>$logFile   

Backup-SPSite $mySite3 -Path $backupLocation\Site_ContractsDB_$today.bak –force
write "$today   $mySite3 successfully backed up.">>$logFile   

Backup-SPSite $mySite4 -Path $backupLocation\Site_Partners_$today.bak –force
write "$today   $mySite4 successfully backed up.">>$logFile   
}

catch
{
write "$today    Error: $_">>$logFile
}   
Stop-SPAssignment -Global
Remove-PsSnapin Microsoft.SharePoint.PowerShell

Now schedule the backup task to automate and execute it whenever you require such as daily, weekly, monthly or yearly using Task Scheduler.
  • Start the Windows Task Scheduler by clicking on Start -> Administrative Tools ->Task Scheduler.
  • From Actions, select Create Task.
  • Under the General Tab, provide a name and a description (Ex: Backup of SharePoint Sites….) and choose the “Run whether user is logged on or not” and check the “Run with highest privileges” checkbox.
  • Under the Triggers tab, click New and schedule a Daily or as often as you like to run the task and click OK.
  • Under the Actions tab, click New and keep the Action parameter as Start a program. In the Program/script textbox type powershell.exe and next to Add arguments textbox, provide the path of your script file location (Ex: D:\SPBackup\SPSite_Backup.ps1) click OK and provide the credentials of FARM Admin or at least Site Collection Administrator when prompted.

Share:

Security Token Service not responding in Project Server 2013

I was facing a serious issue from past couple of days… The Project Server 2013 Web App was inaccessible. After monitoring ULS logs and Event Viewer, following exceptions I encountered. These exceptions were continuously occurring and I was not able to find the root cause. Hence after consulting Microsoft Support team, we both managed to get rid of the exceptions and finally the Project Server Web App was accessible.

The HTTP service located at http://localhost:32843/SecurityTokenServiceApplication/securitytoken.svc is unavailable.  This could be because the service is too busy or because no endpoint was found listening at the specified address. Please ensure that the address is correct and try accessing the service again later.

Application pool ‘SecurityTokenServiceApplicationPool’ is being automatically disabled due to a series of failures in the process(es) serving that application pool.

Event 8306 (SharePoint Foundation) of severity ‘Error’ occurred 58 more time(s) and was suppressed in the event log.

Event 6398 (SharePoint Foundation) of severity ‘Critical’ occurred 8 more time(s) and was suppressed in the event log.


Analysis:
Based on the error message: “A listener channel for protocol ‘HTTP’ in worker process ‘5532’ serving application pool ‘SecurityTokenServiceApplicationPool’ reported a listener channel failure.  The data field contains the error number.” and error message:” The Module DLL ‘C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\isapi\spnativerequestmodule.dll’ could not be loaded due to a configuration problem. The current configuration only supports loading images built for a x86 processor architecture.” The issue is probable caused by the failure during the loading of spnativerequestmodule.dll file.

Resolution:
Navigate to IIS Manager-> Application Pools-> right click the ‘SecurityTokenServiceApplicationPool’ and choose “Advanced Settings”. If “Enable 32-Bit Applications” is set to “true”, please set it to “false”, reset IIS and your are done !!
Happy accessing Project Server Web App… :)
Share:

Author's Profile

My photo
India
A SharePoint Enthusiast working as a Project Lead for an IT Software & Consulting Company in Mumbai. I believe in giving back to the community through which I also learn and develop and eventually grow as an individual and professional. This blog is a small contribution to the community where I live in and may help someone who is seeking knowledge like me. Apart from being a SharePoint Enthusiasts, I am a husband, a father and a blogger. I love to travel and explore new landscapes and meet people of various culture. I am passionate about learning new technology trends in IT. I love spending time on my fitness and have a deep enthusiasm for urdu poetry and career counseling.

Popular Posts

Powered by Blogger.

Contact Form

Name

Email *

Message *

Total Pageviews