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?
Related
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;
}
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,
My Task have multiple relateddocId for example RelatedDoc="3,5,2,6", now i need to add multiplevalue to the sharepoint lookup fields called related Document which is in task list. how to add this?
For ref see my code below
private static void CreateItem(SPWeb web, SPList TaskList, string FolderURL, string ItemName, string RelatedDoc)
{
var ParentURL = string.Empty;
if (!TaskList.ParentWebUrl.Equals("/"))
{
ParentURL = TaskList.ParentWebUrl;
}
SPListItem _taskList = TaskList.AddItem(ParentURL + FolderURL, SPFileSystemObjectType.File, null);
_taskList["Title"] = ItemName;
string DocName = "4,6,3,6";//Document ref id.
SPFieldLookupValue lookupvalue = new SPFieldLookupValue();
if (DocName != "")
lookupvalue = new SPFieldLookupValue(RelatedDoc, DocName);
_taskList["EYRelatedSharedDocument"] = lookupvalue;
_taskList.Update();
}
SPFieldLookupValueCollection documents = new SPFieldLookupValueCollection();
foreach ( ... )
{
documents.Add(new SPFieldLookupValue(documentId, documentTitle));
}
_taskList["EYRelatedSharedDocument"] = documents;
_taskList.Update();
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.
I have a list "Numbers". Items in this list are from 1 to 10(a column other than ID will display this number).
item[1st item]["order"]=1;item[2nd item]["order"]=2;......item[10th item]["order"]=10;
If any item got deleted, lets say item[6th item]["order"]=6; got deleted, then the items in that list should be 1 to 9 i.e. when the item gets deleted, automatically have to order these values. Here i am using ItemDeleted Event Handler to achieve this functionality. But its not working. My code is :
public override void ItemDeleted (SPItemEventProperties properties)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
string mysiteUrl = properties.WebUrl;
SPSite mysite = new SPSite(mysiteUrl);
SPWeb myweb = mysite.OpenWeb();
myweb.AllowUnsafeUpdates = true;
SPList mylist = myweb.Lists["Numbers"];
for (int i = 0; i < mylist.ItemCount; i++)
{
int order = int.Parse(mylist.Items[i]["order"].ToString());
if (!(i + 1 == order))
{
int categoryId = int.Parse(mylist.Items[i]["ID"].ToString());
SPListItem item = mylist.GetItemById(categoryId);
item["Priority"] = i + 1;
mylist.Update();
}
}
myweb.AllowUnsafeUpdates = false;
});
}
I installed and activated the feature. But its not working. I dont know what going wrong here.Please help me on this issue
Try calling Update() on the SPListItem and not the SPList