Error when I run the SPDisposeChecker tool - sharepoint

I am getting the error "Disposable type not disposed Microsoft.SharePoint.SPWeb ***This may be a false positive depending on how the type was created or if it is disposed outside the current scope".
Below is my code :
public static int AddtoList( string title)
{
int returnValue = int.MinValue;
SPUser sysAcount = SPContext.Current.Web.AllUsers[#"SHAREPOINT\SYSTEM"];
SPUserToken sysAcountToken = sysAcount.UserToken;
using (SPSite siteCollection = new SPSite(SPContext.Current.Site.Url, sysAcountToken))
{
SPWeb currentWeb = siteCollection.RootWeb;
SPList list = currentWeb.Lists[MyList];
SPListItem newItem = errorList.Items.Add();
newItem[TitleColumnName] = title;
currentWeb.AllowUnsafeUpdates = true;
newItem.SystemUpdate(false);
currentWeb.AllowUnsafeUpdates = false;
returnValue = newItem.ID;
}
return returnValue;
}
I understood that when we use RootWeb we do not have dispose the object. Please let me know what does this error message mean and how do I correct it . I have several blogs bug failed to understand the error. Please help me.

Do you have the most up to date version of SPDisposeCheck?
An older version (Dec 2010?) incorrectly flagged .RootWeb
http://blogs.technet.com/b/stefan_gossner/archive/2010/12/15/first-issue-with-spdisposecheck-has-been-identified-by-the-community.aspx

Please try below code sample for SPDisposeChecker error resolve.
public static int AddtoList( string title)
{
int returnValue = int.MinValue;
SPUser sysAcount = SPContext.Current.Web.AllUsers[#"SHAREPOINT\SYSTEM"];
SPUserToken sysAcountToken = sysAcount.UserToken;
using (SPSite siteCollection = new SPSite(SPContext.Current.Site.Url, sysAcountToken))
{
//Add below code for dispose currentWeb object end of the functionality
using(SPWeb currentWeb = siteCollection.RootWeb)
{
SPList list = currentWeb.Lists[MyList];
SPListItem newItem = errorList.Items.Add();
newItem[TitleColumnName] = title;
currentWeb.AllowUnsafeUpdates = true;
newItem.SystemUpdate(false);
currentWeb.AllowUnsafeUpdates = false;
returnValue = newItem.ID;
}
}
return returnValue;
}
Happy SharePointing !!!
Thanks,

Related

sharepoint event handler data deleted when check in

I'm writing an eventHandler to auto add a string when a file is added to a doclib.
public override void ItemAdding(SPItemEventProperties properties)
{
SPSite site = new SPSite("url");
SPWeb web = site.OpenWeb("myWebSite");
SPList list = web.Lists["DocCompteur"];
string num = "000", chaine = "";
int compteur = 0;
SPListItem item = list.Items[0];
num = item["compteur"].ToString();
compteur = int.Parse(num);
compteur++;
chaine = compteur.ToString("000");
item["compteur"] = chaine;
item.Update();
properties.AfterProperties["DocNumber"] = "pv" + chaine;
//properties.ListItem.File.CheckIn("Automatic checkIn");
}
The problem is that when I add a file, I have to check in new information. If I check in, the string disappear. If I cancel, the string stay...
With an image, I don't have that problem...
What's wrong with my eventHandler?

Why Drop down gets reset after post back?

My requirement is to select a value from a drop down and fetch the corresponding three fields and drop down must have the selected value in it.
However my code it fetches the corresponding three fields and sets the drop down selected value to first value.
Please tel me how to solve this issue.
Below are my code at page load and corresponding methods:
public partial class RegisterWebPartUserControl : UserControl
{
string titleid;
protected void Page_Load(object sender, EventArgs e)
{
DataSet ds = new DataSet();
SPSite oSPSiteCollection = SPContext.Current.Site;
SPWeb oSPWeb = SPContext.Current.Web;
SPList oSPList = oSPWeb.Lists["Registered"];
string names = oSPWeb.CurrentUser.ToString();
TxtEmployeeName.Text = names.ToString();
SPList oSPListCalender = oSPWeb.Lists["Scheduled Courses"];
DataTable dataTable = oSPListCalender.Items.GetDataTable();
dataTable.TableName = "Table1";
ds.Tables.Add(dataTable);
ddlDrop.DataSource = ds.Tables["Table1"];
ddlDrop.DataTextField = "Title";
ddlDrop.DataValueField = "TitleID";
titleid = ddlDrop.SelectedValue;
ddlDrop.DataBind();
}
protected void ddlDrop_SelectedIndexChanged(object sender, EventArgs e)
{
FetchReadOnlyFields(titleid);
}
public void FetchReadOnlyFields(string titleID)
{
string oStartDate = null;
string oEndDate = null;
string oPrerequisite = null;
SPSite oSPSiteCollection = SPContext.Current.Site;
SPWeb oSPWeb = SPContext.Current.Web;
SPList oSPList = oSPWeb.Lists["Registered"];
SPListItemCollection oItemCollection = oSPList.Items;
SPListItem ospListItem = oItemCollection.Add();
SPList oSPList1 = oSPWeb.Lists["Scheduled Courses"];
SPListItemCollection oItemCollectionCourse = oSPList1.Items;
SPFieldCalculated titleIDCourse = (SPFieldCalculated)oItemCollectionCourse.Fields["TitleID"];
SPField fieldStartDate = oItemCollectionCourse.Fields["Start Date"];
SPField fieldEndDate = oItemCollectionCourse.Fields["End Date"];
foreach (SPListItem ospListItemCourse in oItemCollectionCourse)
{
string value = titleIDCourse.GetFieldValueAsText(ospListItemCourse["TitleID"]);
if (titleID == value)
{
oPrerequisite = ospListItemCourse["Prerequisite"].ToString();
TxtPrerequisite1.Text = SPHttpUtility.ConvertSimpleHtmlToText(oPrerequisite, oPrerequisite.Length);
oStartDate = ospListItemCourse["Start Date"].ToString();
TxtStartDate.Text = oStartDate;
oEndDate = ospListItemCourse["End Date"].ToString();
TxtEndDate.Text = oEndDate;
break;
}
}
}
}
Hope to seek your help.
Thank you
This code
ddlDrop.DataBind();
Should be called only once. On the first load of the page.
Try
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack){ // this is what has changed
DataSet ds = new DataSet();
SPSite oSPSiteCollection = SPContext.Current.Site;
SPWeb oSPWeb = SPContext.Current.Web;
SPList oSPList = oSPWeb.Lists["Registered"];
string names = oSPWeb.CurrentUser.ToString();
TxtEmployeeName.Text = names.ToString();
SPList oSPListCalender = oSPWeb.Lists["Scheduled Courses"];
DataTable dataTable = oSPListCalender.Items.GetDataTable();
dataTable.TableName = "Table1";
ds.Tables.Add(dataTable);
ddlDrop.DataSource = ds.Tables["Table1"];
ddlDrop.DataTextField = "Title";
ddlDrop.DataValueField = "TitleID";
ddlDrop.DataBind();
}
titleid = ddlDrop.SelectedValue;
}

Allowing UserProfileManager Permissions in SharePoint 2010

I am trying to display a list of users in a custom webpart using the UserProfileManager. For some reason, I can view the webpart and all profiles are output to the screen (maybe because I am an administrator). But when a standard user logs in, they encounter a 403 page.
I have done some reading up on this and I know its something to do with permissions. This is what I have in my code:
private DataTable GetProfiles()
{
DataTable dtUserProfile = new DataTable();
//...DataTable Columns
SPSecurity.RunWithElevatedPrivileges(delegate()
{
Guid guid = SPContext.Current.Site.ID;
using (SPSite intranet = new SPSite(guid))
{
SPUserToken userToken = intranet.Owner.UserToken;
//Get current intranet context.
SPServiceContext sContext = SPServiceContext.GetContext(intranet);
UserProfileManager profileManager = new UserProfileManager(sContext);
int totalUsers = int.Parse(profileManager.Count.ToString());
Random random = new Random();
for (int i = 0; i < NumberOfUsersToRetrieve(NoOfProfiles, totalUsers); i++)
{
int randNumber = random.Next(1, totalUsers);
DataRow drUserProfile;
UserProfile up = profileManager.GetUserProfile(randNumber);
drUserProfile = dtUserProfile.NewRow();
drUserProfile["DisplayName"] = up.DisplayName;
drUserProfile["FirstName"] = up["FirstName"].Value;
drUserProfile["LastName"] = up["LastName"].Value;
drUserProfile["Department"] = up["Department"].Value;
drUserProfile["ContactNumber"] = up["Office"].Value;
drUserProfile["MySiteUrl"] = up.PublicUrl;
dtUserProfile.Rows.Add(drUserProfile);
}
}
});
return dtUserProfile;
}
My code basically gets a random collection of users depending on the number of users I want to return.
Is it possible to create a SPUserToken for a user that all permissions needed to retrieve the user profiles?
Thanks!
I appreciate this question is old, but I had the exact same problem. To help the original poster and other users, I have altered the code from the original post to the following:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPSite sc = new SPSite(SPContext.Current.Site.ID);
SPServiceContext context = SPServiceContext.GetContext(sc);
HttpContext currentContext = HttpContext.Current;
HttpContext.Current = null;
UserProfileManager profileManager = new UserProfileManager(context);
IEnumerator profileEnum = profileManager.GetEnumerator();
while (profileEnum.MoveNext())
{
UserProfile up = (UserProfile)profileEnum.Current;
if ((up["FirstName"] != null && up["FirstName"].Value != null && !String.IsNullOrEmpty(up["FirstName"].Value.ToString()))
&& (up.PublicUrl != null && !String.IsNullOrEmpty(up.PublicUrl.ToString())))
{
DataRow drUserProfile;
drUserProfile = dtUserProfile.NewRow();
drUserProfile["DisplayName"] = up.DisplayName;
drUserProfile["FirstName"] = up["FirstName"].Value;
drUserProfile["LastName"] = up["LastName"].Value;
drUserProfile["Department"] = up["Department"].Value;
drUserProfile["Location"] = up["SPS-Location"].Value;
drUserProfile["MySiteUrl"] = up.PublicUrl.ToString().Replace(#"\", #"\");
dtUserProfile.Rows.Add(drUserProfile);
}
}
}
HttpContext.Current = currentContext;
Hopefully this code should resolve the error.
Instead of getting the UserToken of SPSite.Owner, have you tried SPSite.SystemAccount.UserToken, or SPWeb.AllUsers["user"].UserToken;
I'd do the latter if possible, rule of least privileges etc.

using SPSecurity.RunWithElevatedPrivileges gets an error

the error i get is
The security validation for this page is invalid. Click Back in your Web browser, refresh the page and try the operation again.
i am using moss 2007
protected void btnSubmit_Click(Object sender, EventArgs e)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPUtility.ValidateFormDigest();
using (SPSite mySite = new SPSite(_sLibUrl))
{
TextBox txtFirstName = (TextBox)usercontrol.FindControl("txtFirstName");
TextBox txtLastName = (TextBox)usercontrol.FindControl("txtLastName");
TextBox txtPhone = (TextBox)usercontrol.FindControl("txtPhone");
TextBox txtEmail = (TextBox)usercontrol.FindControl("txtEmail");
TextBox txtSubject = (TextBox)usercontrol.FindControl("txtSubject");
TextBox txtContant = (TextBox)usercontrol.FindControl("txtContant");
mySite.AllowUnsafeUpdates = true;
SPListItemCollection listItems = mySite.AllWebs[WebName].Lists[_sLibName].Items;
SPListItem item = listItems.Add();
item["FirstName"] = txtFirstName.Text;
item["LastName"] = txtLastName.Text;
item["Phone"] = txtPhone.Text;
item["Email"] = txtEmail.Text;
item["Subject"] = txtSubject.Text;
item["Contant"] = txtContant.Text;
item.Update();
mySite.AllowUnsafeUpdates = false;
mySite.AllWebs[WebName].Lists[_sLibName].Update();
txtFirstName.Text = string.Empty;
txtLastName.Text = string.Empty;
txtPhone.Text = string.Empty;
txtEmail.Text = string.Empty;
txtSubject.Text = string.Empty;
txtContant.Text = string.Empty;
}
Label lblMessage = (Label)usercontrol.FindControl("lblMessage");
// lblMessage.Text = "טופס נשלח בהצלחה";
});
}
catch (Exception ex)
{
Label lbl = (Label)usercontrol.FindControl("lblMessage");
lbl.Text = ex.Message;
}
}
Try putting mySite.AllowUnsafeUpdates = false; after mySite.AllWebs[WebName].Lists[_sLibName].Update();
i found the solution what i need to do is to remove the
mySite.AllowUnsafeUpdates = true;
and
mySite.AllowUnsafeUpdates = false;
and it works
I work with this solution always
using (var site = new SPSite(SPContext.Current.Site.ID))
using (var web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
//add, update and etc. programatically crud operations with lists
web.AllowUnsafeUpdates = false;
}

"Access denied" when trying to update an alert for a user

i am getting this error when trying to update an alert for a user in the team discussion list.
My code is :
SPUser user = mysite.OpenWeb().CurrentUser;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPSite site = new SPSite(mysite.ID);
SPWeb myweb = site.OpenWeb();
string id = this.Page.Request.QueryString["RootFolder"].ToString();
string[] rootfolder = id.Split(#"//".ToCharArray());
myweb.AllowUnsafeUpdates = true;
SPList mylsit = myweb.Lists["Team Discussion"];
SPListItem item = mylsit.GetItemById(21);
SPUser curruser = myweb.EnsureUser(user.LoginName);
Response.Write(curruser.LoginName);
SPAlert newAlert = user.Alerts.Add();
newAlert.AlertType = SPAlertType.Item;
newAlert.Item = item;
newAlert.Properties["eventtypeindex"] = "1";
newAlert.AlertFrequency = SPAlertFrequency.Immediate;
newAlert.Update(false);
myweb.AllowUnsafeUpdates = false;
});
And i am getting the error when the alert.update() is executing. please help me on this
The only thing I can see of note is the "! Important" section in the below MSDN article on the RunWithElevatedPrivileges function:
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsecurity.runwithelevatedprivileges.aspx
It would seem you are doing some form of writing, and may not have called ValidateFormDigest?

Resources