Logo 
Search:

Sharepoint Forum

Ask Question   UnAnswered
Home » Forum » Sharepoint       RSS Feeds

impersonation issue in webpart

  Asked By: Sally    Date: Dec 27    Category: Sharepoint    Views: 1640

I am trying to acheive impersonation functionality in my webparts but
its not
working fine can any check my code sequence where as for
impersonation i am
using impersonation class downloaded it from www.15seconds.com
this impersonation class is working fine in asp.net webforms where as
its
not working in my current webPart Scenario.

i am facing security exception like accesss denied and unthorized
user logon
exception that means impersonation has some issue in my webpart thats
why i
provided the code so that some one can really look in to it sequence
may be
thats what i am missing, where as i kept the trust level as full in
my
web.config and i have also tried deploying webpart to bin folder and
GAC both
didnt work,
whenever i apply impersonation on asp.net webforms that are using
sharepoint
object model through same class impersonation.cs it work fine like
anything
anyone come up with smart solution

using System;
using System.ComponentModel;
using System.Web.UI;
using System.Collections;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Xml.Serialization;
using System.Drawing;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Portal;
using Microsoft.SharePoint.Portal.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
//using Impersonator;

namespace AreaManager
{
/// <summary>
/// Description for WebPart1.
/// </summary>
[DefaultProperty("Text"),
ToolboxData("<{0}:AreaManager runat=server></{0}:AreaManager>"),
XmlRoot(Namespace="Microsoft.SharePoint.WebPartPages.WebPart")]
public class AreaManager :Microsoft.SharePoint.WebPartPages.WebPart
{
private Button btnAdd = null;
private Label lblMessage = null;
private TextBox txtArea = null;
private DropDownList lstAreas = null;
private Button btnDelete = null;
private AreaService.AreaService areaService = null;
private ListItem lstDataAreas = null;
private bool check = false;
private Impersonator impersonator = null;
private string userName = "umar.riaz";
private string password = "123456789";
private string domain = "ARWENTECH";

protected override void CreateChildControls()
{
try
{

//Text Box For Area Title Input
txtArea = new TextBox();
txtArea.Text = "";
txtArea.Visible = true;
Controls.Add(txtArea);

//Add button for creating area
btnAdd = new Button();
btnAdd.Text = "Create Area";
btnAdd.Visible = true;
btnAdd.Click += new EventHandler(btnAdd_Click);
Controls.Add(btnAdd);

//Message for temporary messages
lblMessage = new Label();
lblMessage.Text = "";
lblMessage.Visible = true;
Controls.Add(lblMessage);

//Area List Box thats lists down areas under home hierarchy
lstAreas = new DropDownList();
lstAreas.EnableViewState = true;
lstAreas.AutoPostBack = false;
lstAreas.Visible = true;
populateList();
Controls.Add(lstAreas);

btnDelete = new Button();
btnDelete.Text = "Delete Area";
btnDelete.Visible = true;
btnDelete.Click += new EventHandler(btnDelete_Click);
Controls.Add(btnDelete);

}
catch(Exception ex)
{
lblMessage.Text = ex.Message+" .. "+ex.StackTrace;
}
}


/// <summary>
/// Render this Web Part to the output parameter specified.
/// </summary>
/// <param name="output"> The HTML writer to write out to </param>
protected override void RenderWebPart(HtmlTextWriter output)
{
try
{

this.Page.EnableViewState = true;
txtArea.RenderControl(output);
btnAdd.RenderControl(output);
output.WriteLine("<br>");
lblMessage.RenderControl(output);
output.WriteLine("<br>");
lstAreas.RenderControl(output);
output.WriteLine("<br>");
btnDelete.RenderControl(output);
output.WriteLine("<br>");
//ArrayList list = GetSiteGroupListForCurrentUser();
// output.Write("<p>Site Groups for " +
SPControl.GetContextWeb(Context).CurrentUser.LoginName + "
");
// output.Write("<ol>");
// foreach(string GroupName in list)
// {
//output.Write("<li>" + GroupName + "</li>");
// lblMessage.Text += GroupName.ToString();
// }
//output.Write("</ol></p>");

}
catch(Exception ex)
{
lblMessage.Text = ex.Message+" .. "+ex.StackTrace;
}
}


private void populateList()
{
try
{
areaService = new AreaService.AreaService();
areaService.Credentials =
System.Net.CredentialCache.DefaultCredentials;
Guid homeGuid = areaService.GetHomeAreaID();

//Search Sub Area Guid
Guid searchGuid = areaService.GetSearchAreaID();
//KeyWords Sub Area Guid
Guid keyWordsGuid = areaService.GetKeywordsAreaID();
//My Site Sub Area Guid
Guid mySiteGuid = areaService.GetMySiteAreaID();

//All Sub Areas Guid
Guid []subareas = areaService.GetSubAreas(homeGuid);

//First Entry In the DataAreas Combox Box
lstDataAreas = new ListItem(" None ","0");
lstAreas.Items.Add(lstDataAreas);

for(int i = 0; i<subareas.Length;++i)
{
if( subareas[i] != searchGuid && subareas[i] != keyWordsGuid &&
subareas[i] != mySiteGuid)
{
if( isAccessibleArea(subareas[i]) )
{
lstDataAreas = new
ListItem(areaService.GetAreaData(subareas
[i]).AreaName,areaService.GetAreaData(subareas[i]).AreaID.ToString
());
lstAreas.Items.Add(lstDataAreas);
}
}
}
lstAreas.EnableViewState = true;
}
catch(Exception ex)
{
lblMessage.Text = ex.Message+" .. "+ex.StackTrace;
}
}





private void btnAdd_Click(object sender, System.EventArgs e)
{
try
{
Impersonator i = new
Impersonator("umar.riaz","ARWENTECH.COM","123456789");
i.Impersonate();
SPWeb web = SPControl.GetContextWeb(Context);
SPRoleCollection allRoles = web.CurrentUser.Roles;
foreach(SPRole role in allRoles)
{
lblMessage.Text += role.Name;
}
i.Undo();
}
catch(Exception ex)
{
lblMessage.Text = ex.Message+" .. "+ex.StackTrace;
}
}


public void btnDelete_Click(object sender, System.EventArgs e)
{
try
{

if(lstAreas.SelectedValue != "0")
{
lblMessage.Text = "";
areaService = new AreaService.AreaService();
areaService.Credentials =
System.Net.CredentialCache.DefaultCredentials;
bool flag = false;
string areaGuid = lstAreas.Items[lstAreas.SelectedIndex].Value;;
for(int j = 0; j< lstAreas.Items.Count;++j)
{
if(flag == false)
{
if(areaGuid == lstAreas.Items[j].Value )
{
areaService.DeleteArea( new Guid(lstAreas.Items[j].Value) );
flag = true;
lstAreas.Items.Remove(new
ListItem(lstAreas.Items[j].Text,lstAreas.Items[j].Value));
}
}
}
}
else
{
lblMessage.Text = "Select and area from list to be deleted";
lblMessage.ForeColor = Color.Blue;
}
}
catch(Exception ex)
{
lblMessage.Text += ex.Message;
}
}




private void AddArea(string title)
{


string CurrentSiteUrl = SPControl.GetContextWeb(Context).Url;
try
{
impersonator = new Impersonator
("umar.riaz","ARWENTECH.COM","123456789");
impersonator.Impersonate();

SPSite tmpSite = new SPSite(CurrentSiteUrl);
// suppress user prompt for alternative logon upon access denied
error
tmpSite.CatchAccessDeniedException = false;
// open SPWeb object for current site
SPWeb tmpWeb = tmpSite.OpenWeb();
//SPControl.GetContextWeb(Context);
SPRoleCollection roles = tmpWeb.CurrentUser.Roles;
foreach(SPRole role in roles)
{
lblMessage.Text += role.Name+"..";
}

areaService = new AreaService.AreaService();
areaService.Credentials =
System.Net.CredentialCache.DefaultCredentials;

string strTitle = String.Empty;
if(title == "")
{
strTitle = "testArea2";
}
else
strTitle = title;
Guid homeGuid = areaService.GetHomeAreaID();
Guid newAreaGuid = areaService.CreateArea
(homeGuid,strTitle,"SPSDOCHOME");
AreaService.AreaData areaData = areaService.GetAreaData(newAreaGuid);
lstAreas.Items.Add(new
ListItem(areaData.AreaName,areaData.AreaID.ToString()));
txtArea.Text = "";
impersonator.Undo();

}
catch(Exception ex)
{
lblMessage.Text = ex.Message+" .. "+ex.StackTrace;
}
}

/// <summary>
/// Detail: this method accessible areas for current user
/// </summary>
/// <param name="areaGuid"></param>
/// <returns>bool</returns>
private bool isAccessibleArea(Guid areaGuid)
{
try
{
bool flag = false;
ArrayList lstItems = new ArrayList();
SPWeb web = SPControl.GetContextWeb(Context);
SPWebCollection subWebs = null;
SPWeb rootWeb = SPControl.GetContextSite(Context).RootWeb;
subWebs = rootWeb.GetSubwebsForCurrentUser();
foreach(SPWeb myweb in subWebs)
{
lstItems.Add(myweb.ID);
}

for(int i = 0; i<lstItems.Count;++i)
{
if( (Guid)lstItems[i] == areaGuid)
{
flag = true;
break;
}
}
return flag;
}
catch(Exception ex)
{
lblMessage.Text += ex.Message;
return false;
}
}


private bool IsCurrentUserInSiteGroup(string TargetSiteGroup)
{
bool UserIsInSiteGroup = false;
string CurrentSiteUrl = SPControl.GetContextWeb(Context).Url;
string CurrentUserLogon =
SPControl.GetContextWeb(Context).CurrentUser.LoginName;
Impersonator imp = null;
try
{
// Impersonatate using credential of account in the SP admin group
imp = new Impersonator("umar.riaz", "ARWENTECH.COM", "123456789");
imp.Impersonate();
// create new SPSite object for current site collection
SPSite tmpSite = new SPSite(CurrentSiteUrl);
// suppress user prompt for alternative logon upon access denied
error
//tmpSite.CatchAccessDeniedException = false;
// open SPWeb object for current site
SPWeb tmpWeb = tmpSite.OpenWeb();
// Get SPRole object for target site group
SPRole SiteGroup = tmpWeb.Roles[TargetSiteGroup];
// enumerate through site group members and look for match with
current
user
foreach(SPUser User in SiteGroup.Users)
{
if(User.LoginName.Equals(CurrentUserLogon))
{
UserIsInSiteGroup = true;
break;
}
}
}
finally
{ // undo impersonation to revert back to caller identity
if(imp != null) imp.Undo();
}
return UserIsInSiteGroup;
}


private ArrayList GetSiteGroupListForCurrentUser()
{
ArrayList list = new ArrayList();
string CurrentSiteUrl = SPControl.GetContextWeb(Context).Url;
string CurrentUserLogon =
SPControl.GetContextWeb(Context).CurrentUser.LoginName;
Impersonator imp = null;
try
{
// Impersonatate using credential of account in the SP admin group
imp = new Impersonator("umar.riaz", "ARWENTECH", "123456789");
imp.Impersonate();
// create new SPSite object for current site collection
SPSite tmpSite = new SPSite(CurrentSiteUrl);
// suppress user prompt for alternative logon upon access denied
error
tmpSite.CatchAccessDeniedException = false;
// open SPWeb object for current site
SPWeb tmpWeb = tmpSite.OpenWeb();

foreach(SPRole SiteGroup in tmpWeb.Roles)
{
foreach(SPUser User in SiteGroup.Users)
if(User.LoginName.Equals(CurrentUserLogon))
{
list.Add(SiteGroup.Name);
break;
}
}
}
finally
{
// undo imperonation to revert back to identity of user
if(imp != null) imp.Undo();
}
return list;
}

}
}

Share: 

 

No Answers Found. Be the First, To Post Answer.

 
Didn't find what you were looking for? Find more on impersonation issue in webpart Or get search suggestion and latest updates.




Tagged: