That's when I evolved a simple Helper-class for get default sites and such so I could test the webpart outside of WSS and just put it in when needed.
Now i just use Helper.GetDefaultSite() and specifying an application setting ("CM.Debug") with a value of true if I'm of the bars of WSS. Just remeber not to dispose the SPSite or SPWeb if you're within WSS context.
The thing is, when you try to do some actions, such as updating an SPListItem, you will get an error unless you impersonate as yourself. Inside of the GetDefaultSite() I've included a call to GetUserToken() which gets the SPUserToken for you. If you havn't impersonated as yourself, you will get the wonderful error message "Cannot complete this action". Thank you SharePoint for being so precise in your error messages =). Feels like all of their is wrapped inside a try-catch and always return something like that, hehe.
Helper class
public static class Helper
{
public static bool Debug
{
get { return bool.Parse(GetSetting("CM.Debug")); }
}
public static string DebugUrl
{
get { return GetSetting("CM.DebugUrl"); } //http://WSS/sites/yoursite
}
public static SPUserToken GetUserToken()
{
SPSite site = new SPSite(debugUrl);
SPWeb web = site.OpenWeb();
SPUserToken token = null;
if (Debug)
token = web.AllUsers[WindowsIdentity.GetCurrent().Name].UserToken;
else
token = web.CurrentUser.UserToken;
web.Dispose();
site.Dispose();
return token;
}
public static SPSite GetDefaultSite()
{
if (Debug)
return new SPSite(debugUrl, GetUserToken());
else
return SPSite(SPContext.Current.Site.ID);
}
public static string GetSetting(string setting)
{
return System.Web.Configuration.WebConfigurationManager.AppSettings[setting];
}
Example code using Helper
public static Case Load(int id)
{
SPSite site = Helper.GetDefaultSite();
SPWeb web = site.OpenWeb();
SPList list = web.Lists["myCaseList"];
Case loadedCase = new Case();
loadedCase.Loaded = true;
if (list == null)
return null;
foreach (SPListItem item in list.Items)
{
... some code
}
if (Helper.Debug)
{
web.Dispose();
site.Dispose();
}
return loadedCase;
}
Another way to impersonate
System.Security.Principal.WindowsImpersonationContext wic = null;
wic = System.Security.Principal.WindowsIdentity.GetCurrent().Impersonate();
SPSite site = new SPSite(...);
SPWeb web = site.OpenWeb(...);
....
wic.Undo();
Inga kommentarer:
Skicka en kommentar