Thursday, February 28, 2008

Here's a quick way to impersonate a built-in service account (NT AUTHORITY\NETWORK SERVICE or NT AUTHORITY\LOCAL SERVICE) or for that matter the Local System account (NT AUTHORITY\SYSTEM) in a console application. This might be useful for debugging or testing permissions etc. - the default application pool identity for SharePoint virtual servers is the Network Service account.

The trick is to run your code as Local System and from there you can impersonate the service accounts by using the appropriate username with no password. One way to run your code as the Local System account is to create a command line shell by using the technique shown below (taken from this orginal post), and execute your assembly from there. Calling System.Diagnostics.Debugger.Break() in your code allows you to debug.

To create a command-line shell that runs under the local system account, open a new command line window and enter:

c:\sc create testsvc binpath= "cmd /K start" type= own type= interact

followed by:

c:\sc start testsvc

A new command window should have opened up. In that window run your application.exe - you'll see that you're now running as the built-in System user account. After you've finished testing, you can delete the test service you created by entering:

c:\sc delete testsvc

Some sample impersonation code that includes an impersonation class modified slightly from the code in this post follows:

Thursday, February 21, 2008

Following on from this post on moving or copying SharePoint files with FrontPage Remote Procedure Calls (RPC), and this older post on remotely saving files to a SharePoint document library, the code below demonstrates how to remove files programmatically from a remote document library without using the SharePoint API. Documentation about the move method can be found here. The EscapeVectorChars method can be found in the original post. Obviously because this RPC method will remove documents from your site (potentially deleting them permanently), please use with appropriate caution!

Update: You can download a comprehensive c# class library to automate RPC calls - including removing files. See this blog post for more information.