You are on page 1of 1

try

{
windowsimpersonationcontext context = null;

// get current identity


windowsidentity currentidentity = windowsidentity.getcurrent();
windowsprincipal currentprincipal = new
windowsprincipal(currentidentity);

// output current principal


writer.write("--- currentprincipal ---<br>");
writer.write("windowsidentity.getcurrent().name: " +
windowsidentity.getcurrent().name + "<br>");
writer.write("thread.currentprincipal.identity.nam e : " +
currentprincipal.identity.name + "<br>");
// try impersonating the app pool user
///reverttoself();
// the next 3 steps are the important steps
windowsidentity wi = windowsidentity.getcurrent();
currentprincipal = new windowsprincipal(wi);
windowsimpersonationcontext wic = wi.impersonate();
// output windowsidentity
///writer.write("--- reverttoself() ---<br>");
writer.write("windowsidentity.getcurrent().name: "
+ windowsidentity.getcurrent().name + "<br>");
writer.write("thread.currentprincipal.identity.nam e : "
+ currentprincipal.identity.name + "<br>");
// impersonate back to original identity
wic.undo();
currentprincipal = new windowsprincipal(currentidentity);
currentidentity.impersonate();
// output windowsidentity
writer.write("--- impersonate() ---<br>");
writer.write("windowsidentity.getcurrent().name: " +
windowsidentity.getcurrent().name + "<br>");
writer.write("thread.currentprincipal.identity.nam e : " +
currentprincipal.identity.name + "<br>");

context = currentidentity.impersonate();

///write your code

context.undo();

}
catch (exception ex)
{
// display diagnostic error information if exception occurs
writer.write("<div>");
writer.write("<b>exception type</b>: " + ex.gettype().tostring() +
"<br>");
writer.write("<b>exception message</b>: " + ex.message + "<br>");
writer.write("<b>stack trace</b>:<br>" + ex.stacktrace.replace("\n",
"<br>"));
writer.write("</div>");
}