I have inherited fixes and enhancements on a SharePoint 2013 site and I'm a complete SP noob. I have a user control (.ascx file) that lives in the ControlTemplates folder that is referenced on a boatload of pages (which I think may be an issue in and of itself, but a different issue). One thing I've noticed is code like this:
protected void Page_Load(object sender, EventArgs e)
{
SPUser CurrentLoggedInUser = SPContext.Current.Web.CurrentUser;
Guid webID = SPContext.Current.Web.ID;
Guid siteID = SPContext.Current.Site.ID;
using (SPSite site = new SPSite(siteID))
{
site.AllowUnsafeUpdates = true;
using (SPWeb web = site.OpenWeb(webID))
{
FunctionA("hello");
// Do something here
}
}
}
protected void FunctionA(string message)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPUser CurrentLoggedInUser = SPContext.Current.Web.CurrentUser;
Guid webID = SPContext.Current.Web.ID;
Guid siteID = SPContext.Current.Site.ID;
using (SPSite site = new SPSite(siteID))
{
site.AllowUnsafeUpdates = true;
using (SPWeb web = site.OpenWeb(webID))
{
// Do something
}
}
}
}
CurrentLoggedInUser, webID and siteID are declared and assigned in a large number of functions. What I want to know: is there some reason that would make it a bad idea to declare some page level variables and assign them in Page_Load and remove the redundant "CurrentLoggedInUser", "webID", "siteID" declarations and assignments? I'm thinking something like this:
Guid _webId;
Guid _siteId;
SPUser _currentLoggedInUser;
protected void Page_Load(object sender, EventArgs e)
{
_webId = SPContext.Current.Web.ID;
_siteId = SPContext.Current.Site.ID;
_currentLoggedInUser = SPContext.Current.Web.CurrentUser;
// Do some work
}
protected void FunctionA(string message)
{
// No longer need to get webID, siteID or CurrentLoggedInUser - can
// use _webId, _siteId and _currentLoggedInUser
}
I figure it'd clean up the code a good bit and anything I can start to do to reduce this monster .ascx page and simplify the logic (I've found lots of code that does nothing) would be a good thing.