Access Denied Run With Elevated Privileges delegate.
You problably have this problem i ask to heaven "WHY?????", well the answer is bad code, yes i do have the read 12 times the sdk to follow the microsoft good source code.
I have this problem, and .AllowUnsafeUpdates = true; dont answer because the using method was bad, then i find this Post this give some ligths on my BAD code :P .
But first We have to read the best pratices by microsoft, after reading this well, hope dont have this problem anymore....
//simple steep
String str;
using(SPSite oSPsite = new SPSite("http://server"))
{
using(SPWeb oSPWeb = oSPSite.OpenWeb())
{
str = oSPWeb.Title;
str = oSPWeb.Url;
}
}
//This steep is the most complete but like microsoft say Response.Redirect WILL NOT execute the finally block
String str;
SPSite oSPSite = null;
SPWeb oSPWeb = null;
try
{
oSPSite = new SPSite("http://server");
oSPWeb = oSPSite.OpenWeb(..);
str = oSPWeb.Title;
if(bDoRedirection)
{
if (oSPWeb != null)
oSPWeb.Dispose();
if (oSPSite != null)
oSPSite.Dispose();
Response.Redirect("newpage.aspx");
}
}
catch(Exception e)
{
}
finally
{
if (oSPWeb != null)
oSPWeb.Dispose();
if (oSPSite != null)
oSPSite.Dispose();
}
So after you learn this first litle steep i start to understan whats wrong with my code, and understand what Kjetil Gullen do.
Thanks Kjetil Gullen.
public void CreateDocArchive()
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPWeb _webInUserContext = SPContext.Current.Web;
SPSite _siteInUserContext = SPContext.Current.Site;
Guid _webGuid = _webInUserContext.ID;
Guid _siteGuid = _siteInUserContext.ID;
using (SPSite _site = new SPSite(_siteGuid))
{
_site.AllowUnsafeUpdates = true;
SPWeb _web = site.OpenWeb();
_web.AllowUnsafeUpdates = true;
Guid _id = web.Lists.Add(
"My DocLib",
"Description of my docLib",
web.ListTemplates["Document Library"]);
SPList _docLib = web.Lists[_id];
_docLib.EnableVersioning = true;
_docLib.AllowEveryoneViewItems = false;
_docLib.EnableSyndication = false;
_docLib.EnableAssignToEmail = false;
_docLib.Update();
SPFolder _folder = _docLib.RootFolder.SubFolders.Add("My readonly folder");
_folder.Update();
SPListItem i = _folder.Item;
i.Web.AllowUnsafeUpdates = true;
i.BreakRoleInheritance(true);
i.Web.AllowUnsafeUpdates = true;
foreach (SPRoleAssignment spra in i.RoleAssignments)
{
spra.RoleDefinitionBindings.RemoveAll();
spra.Update();
}
SPRoleDefinition rd = _mappe.Item.Web.RoleDefinitions.GetByType(SPRoleType.Reader);
SPRoleAssignment ra = new SPRoleAssignment(_webInUserContext.CurrentUser);
ra.RoleDefinitionBindings.Add(rd);
i.RoleAssignments.Add(ra);
i.Update();
}
});
}
No comments:
Post a Comment