Skip to content

Instantly share code, notes, and snippets.

@jjaramillo
Created December 23, 2011 00:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jjaramillo/1512544 to your computer and use it in GitHub Desktop.
Save jjaramillo/1512544 to your computer and use it in GitHub Desktop.
A file to open connections to a sharepoint site from a desktop application. This is intended to run on the application server.
using System;
using System.Text;
using System.Web;
using Microsoft.SharePoint;
public class SPConnection
{
private SPSite _site;
private SPWeb _web;
private string _siteUrl;
private string _loginName;
/// <summary>
/// Gets the SP Web.
/// </summary>
/// <value>The sp web.</value>
public SPWeb SpWeb
{
get { return _web; }
}
/// <summary>
/// Initializes a new instance of the <see cref="SPConnection"/> class.
/// </summary>
/// <param name="siteUrl">The site URL.</param>
/// <param name="loginName">Name of the login.</param>
public SPConnection(string siteUrl, string loginName)
{
this._siteUrl = siteUrl;
this._loginName = loginName;
}
/// <summary>
/// Opens the connection to the sharepoint site.
/// </summary>
public void OpenConnection()
{
SPSite spSite = new SPSite(_siteUrl);
SPUser user = spSite.RootWeb.AllUsers[_loginName];
SPUserToken userToken = spSite.UserToken;
_site = new SPSite(_siteUrl, userToken);
_web = _site.OpenWeb();
spSite.Dispose();
// Ensure HttpContext.Current
if (HttpContext.Current == null)
{
HttpRequest request = new HttpRequest("", _web.Url, "");
HttpContext.Current = new HttpContext(request,
new HttpResponse(System.IO.TextWriter.Null));
}
// SPContext is based on SPControl.GetContextWeb(), which looks here
if (HttpContext.Current.Items["HttpHandlerSPWeb"] == null)
HttpContext.Current.Items["HttpHandlerSPWeb"] = _web;
}
/// <summary>
/// Closes the connection to the sharepoint site.
/// </summary>
public void CloseConnection()
{
_web.Dispose();
_site.Dispose();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment