User Impersonation with SharePoint

Recently I had to create a custom web part where all users needed the ability to fill out a text box with some feedback and then submit it to a list where it could be reviewed. This is a pretty simple control to implement if the users that will be submitting the form have “Contribute” permissions on the list that the form will be submitted to, but what happens if users with “Read” permissions should also have the ability to fill out the form?

Fortunately, SharePoint makes it super simple to write custom code that can impersonate other users.

SPWeb web = SPContext.Current.Web;
SPSite site = SPContext.Current.Site;
// Get the user token of the user to impersonate
SPUserToken sysAdminToken = site.SystemAccount.UserToken;
// Open site collection as System Admin
using (SPSite siteAsAdmin = new SPSite(site.Url, sysAdminToken))
{
    // Open web as System Admin
    using (SPWeb webAsAdmin = siteAsAdmin.OpenWeb(web.ServerRelativeUrl))
    {
        // Do something as impersonated user
    }
}
We can take it a step further and have the System Admin account create a list item and then stamp it with the correct user’s name.


SPWeb web = SPContext.Current.Web;
SPSite site = SPContext.Current.Site;
// Get the user token of the user to impersonate
SPUserToken sysAdminToken = site.SystemAccount.UserToken;
// Open site collection as System Admin
using (SPSite siteAsAdmin = new SPSite(site.Url, sysAdminToken))
{
    // Open web as System Admin
    using (SPWeb webAsAdmin = siteAsAdmin.OpenWeb(web.ServerRelativeUrl))
    {
        // Get the List to send the fields to
        SPList list = webAsAdmin.GetList("/Lists/myList");
        if (list != null)
        {
            // Set Allow Unsafe Updates, so that the System Admin can update 'Editor' and 'Author' fields
            bool allowUnsafeUpdates = webAsAdmin.AllowUnsafeUpdates;
            webAsAdmin.AllowUnsafeUpdates = true;
            string[] fieldNames = new[] {"Author", "Editor"};
            // Create an empty list item
            SPListItem item = list.AddItem();
            // Apply some values to the fields
            item["Comments"] = "Some Text Value";
            item["Title"] = string.Format("Post from: {0}", currentUser.Name);
            // Get and loop through each user field specified in the fieldNames variable
            foreach (SPField field in fieldNames.Select(name => item.Fields.GetFieldByInternalName(name)))
            {
                // Check if the fields are Read Only, if they are make them read-write.
                // this is where the AllowUnsafeUpdates comes into play.
                bool readOnly = field.ReadOnlyField;
                if (readOnly)
                {
                    field.ReadOnlyField = false;
                    field.Update();
                }
                // Set the 'Author' and 'Editor' fields equal to the user who submitted the form.
                item[field.Id] = currentUser.ID;
                // Set the fields back to Read Only
                if (readOnly)
                {
                    field.ReadOnlyField = true;
                    field.Update();
                }
            }
            // Update the fields, including the Author and Editor
            item.UpdateOverwriteVersion();
        }
    }
}

It is important to note, that you should be very careful when impersonating other users.

Posted in Lists and Libraries, SharePoint, Web Parts | Leave a comment

Could not enlist Send Port HRESULT: 0xC00CE557

A quick tip today – I came across an error while trying to enlist one of my send ports while deploying a BizTalk application using the amazing BizTalk Deployment Framework.

“Could not enlist Send Port ‘X’. Exception from HRESULT: 0xC00CE557 (Microsoft.BizTalk.SnapIn.Framework)

Untitled picture

Read More »

Posted in BizTalk | Tagged , , , , , | Leave a comment

Top 5 Free Mobile Application Testing Platforms

The testing phase of mobile development is critical to the success of  any application, and with the multitude of variations in both hardware and operating systems, this stage is arguably the most difficult to manage and execute properly.  Fortunately there are a handful of useful tools that assist with the distribution and testing of mobile applications with the majority of these being free or free try.  Each platform offers a unique set of functionality, so the best way to choose is experimenting with each one.  Here are some of the best mobile testing platforms available today:

Read More »

Posted in Android, Windows Phone, iOS | Tagged | Leave a comment

Failed to Validate BAM Portal Web Site (BAMPortal)

I have recently encountered an error while trying to reinstall BAM Tool and the BAM Portal on a Microsoft BizTalk Server 2013 installation.  I encountered the following error while attempting to configure the BAM Portal in the Microsoft BizTalk Server Configuration window.

Read More »

Posted in BAM, BizTalk | Tagged , , , , , | Leave a comment

Change SharePoint Central Admin Top Bar Text

Overview

To help make it abundantly clear which central admin site someone is logged into, I wanted to change the top bar text to something other than “SharePoint”.  Turns out you can do that using the SuiteBarBrandingElement value on the Central Administration Web Application object  from PowerShell.

Code:

Add-PSSnapin microsoft.sharepoint.powershell $ca = Get-SPWebApplication -IncludeCentralAdministration | ` ?{$_.IsAdministrationWebApplication -eq $true} $ca.SuiteBarBrandingElementHtml = "<div class='ms-core-brandingText'>SP2013 Shared Services Farm (PRODUCTION)</div>" $ca.Update()

Result:

image

Posted in SharePoint, Tips and Tricks | Leave a comment

Office 365 and SharePoint Online FAQ

Recently had to field some questions regarding Office 365 and SharePoint online. Thought it would be beneficial for others looking for similar information. Leave a comment if you have additional input on any of these or have other questions regarding this topic:

Read More »

Posted in Features, SharePoint, Tips and Tricks | Tagged , , | Leave a comment

Is your federated user repeatedly prompted for credentials during One Drive for Business Sync?

We had issues where federated users were continually prompted from their username and password when trying to sync their OneDrive for Business account.  Even if you typed the password correctly authentication still failed.  We were directed to this KB Article

Our specific problem was resolved by disabling Extended Protection for Authentication Read More »

Posted in Architecture and Development, Cloud, Diagnostics and Monitoring | 1 Comment

Setting Compatibility Mode Of A WPF Web Browser

Recently I needed to use the WebBrowser control in a C Sharp WPF application. But after adding the web browser and navigating to the web page I was met with a horribly mangled version of it. Yet in Internet Explorer the same web page displayed correctly and as you may or may not know, the WebBrowser control uses Internet Explorer. I then discovered that checking Compatibility Mode in Internet Explorer changed the page to match the WebBrowser controls! It turns out the WebBrowser control was defaulting to a rendering engine (IE7) that I did not want!

Read More »

Posted in .NET Framework | Tagged , , , , | Leave a comment

Build 2014

//build was a great event this year. Given that I’m the mobile guy I’m particularly excited that they started the day 1 keynote with Windows Phone and Windows 8 announcements.

Windows Phone 8.1

Microsoft announced their latest version of Windows Phone, version 8.1, this new version is due out this summer and is compatible with all existing Windows Phone 8.0 devices. In addition manufacturers, such as Nokia, are coming out with new devices tailored to Windows Phone 8.1.

Read More »

Posted in What's New, Windows 8, Windows Phone | Tagged , , | Leave a comment