SPListItem not added to SPList - sharepoint

I'm using the following code to add an item to a list on the top level of my application but it is not adding anything, does anyone know why? Is there anything missing?
It doesn't return me any error, just doesn't add the item and the list remains empty.
The code is in the FeatureActivated method of the feature where the list instance is being deployed.
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPList icons = web.GetList(path)
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPListItem icon = icons.Items.Add();
icon[SPBuiltInFieldId.Title] = "title";
icon[new Guid("d3429cc9-adc4-439b-84a8-5679070f84cb")] = "class1";
icons.Update();
}

you have to call the Update() method of the icon object, not icons.

I found out there are 2 ways of successfully add an item to a list:
Like Andreas Scharf said:
SPListItem item = list.Items.Add();
item["Title"] = "some title";
item.Update();
Some other way using the AddItem() instead of the Add() from the items collection
SPListItem item = list.AddItem();
item["Title"] = "some title"; // Add item's field values
item.Update(); //also the item is updated, not the list

Related

Can't use SPItemEventProperties ListItem on ItemAdded in Event Receiver

I'm using event receivers to modify some of the inputs in a SharePoint 2013 site.
They are fairly straight forward, here is a simple example
public override void ItemAdded(SPItemEventProperties properties)
{
base.ItemAdded(properties);
using (SPSite site = new SPSite(properties.WebUrl))
{
using (SPWeb web = site.OpenWeb(properties.RelativeWebUrl))
{
//web.AllowUnsafeUpdates = true;
SPListItem item = properties.ListItem; // Boom!
var title = item["Title"].ToString();
item["Title"] = title.Replace(" ", "_");
//item.Update();
//item.SystemUpdate(false);
}
}
}
This renders the error
Message:
Method not found: 'Microsoft.BusinessData.Runtime.IEntityInstance Microsoft.BusinessData.Runtime.NotificationParser.GetChangedEntityInstance(Microsoft.BusinessData.MetadataModel.IEntity, Microsoft.BusinessData.MetadataModel.ILobSystemInstance)'.
Source:
Microsoft.SharePoint
StackTrace:
at Microsoft.SharePoint.SPItemEventProperties.get_ListItem()
at eventreceivers.Kundregister.PrivateCustomer.PrivateCustomer.<>c__DisplayClass2.<ItemAdded>b__0()
at Microsoft.SharePoint.SPSecurity.<>c__DisplayClass5.<RunWithElevatedPrivileges>b__3()
at Microsoft.SharePoint.Utilities.SecurityContext.RunAsProcess(CodeToRunElevated secureCode)
I have ensured that those methods are available in the class.
Any advices are highly appreciated, thanks!
I was already facing the same issue.
instead of using
SPListItem item = properties.ListItem;
use following code to get item,
SPListItem item = properties.Web.Lists.TryGetList(properties.ListTitle).GetItemById(properties.ListItemId);
All the best!
Regards,
Praveen Singh

Cannot add new item to list in ItemAdded Event Receiver

Can anybody tell me why this code doesn't work?
The "adding code" itself works, but unfortunately not in an ItemAdded Event.
I need this code in the ItemAdded Event and therefor i cannot use ItemAdding.
Thanks for any help.
public override void ItemAdded(SPItemEventProperties properties)
{
SPSite site = new SPSite("http://air_sim:39167/");
SPWeb web1 = site.RootWeb;
SPList List = web1.Lists["Announcements"];
SPListItem newitem = List.Items.Add();
newitem["Title"] = "Example";
newitem.Update();
}
Did you do any steps to attach event receiver to your list?
If no, you can install a feature to manage event receivers and
verify that the event receiver is added and if not, add it manually:
http://chrissyblanco.blogspot.com/2007/08/event-receiver-management.html
Maybe exception is thrown somwere? For example, if such site or list
with such name doesn't exist, exception will be thrown. Also if you
don't initialise required fields of your item, the Update() call
will throw exception.
By the way the properties variable contains many useful properties:
SPListItem newitem = properties.List.Items.Add();
newitem["Title"] = "Example";
newitem.Update();
Do you use Sharepoint 2010 or Sharepoint2007?
Do you use VS2008 or VS2010?
If you couldn’t use debugger, use EventLog:
public override void ItemAdded(SPItemEventProperties properties)
{
EventLog.WriteEntry("DebugSharepoint", "ItemAdded fired");
try
{
SPSite site = new SPSite("http://air_sim:39167/");
SPWeb web1 = site.RootWeb;
SPList List = web1.Lists["Announcements"];
SPListItem newitem = List.Items.Add();
newitem["Title"] = "Example";
newitem.Update();
}
catch(Exception e)
{
EventLog.WriteEntry("DebugSharepoint", e.Message, EventLogEntryType.Error);
}
}
Attach a debugger.
Go to cmd and type iisapp. You would get the worker process id.
Then open your event handler project and go to the tools and attach process and set the debug point on ItemAdded as well as ItemAddding event
Try the below solutions:
Check whether the Site exists with that name.
Check whether user has the permission to insert item.
Try using AllowUnsafeUpdates:
SPSite site = new SPSite("site address");
SPWeb web1 = site.RootWeb;
SPList List = web1.Lists["Announcements"];
web1.AllowUnsafeUpdates = true;
SPListItem newitem = List.Items.Add();
newitem["Title"] = "Example";
newitem.Update();
web1.AllowUnsafeUpdates = false;

how to update infopath form library item field programatically?

I was successfully able to update one of the fields (which was of type boolean) from infopath for library item using sharepoint object Model as if it was a list item.
But for another field which is of type text, the same code just gets executed but does not change the field value !!!!
I am using following code, which works for that boolean field but for another field of type string , not sure why it is not working. Any idea ?
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPWeb web;
SPSite site = new SPSite("http://sharepointsite");
web = site.OpenWeb();
SPList formLibList = web.Lists["FormLibraryName"];
SPQuery query = new SPQuery(); query.Query = "<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>" + titleName + "</Value></Eq></Where>";
web.Site.WebApplication.FormDigestSettings.Enabled = false;
web.AllowUnsafeUpdates = true;
SPListItemCollection col = formLibList.GetItems(query);
if (col.Count > 0)
{
col[0]["CustomerName"] = "test customer name";
col[0].Update();
}
web.Site.WebApplication.FormDigestSettings.Enabled = true; web.AllowUnsafeUpdates = false;
});
Thanks,
Nikhil
I had to declare SPListItem and set it instead of directly modifying list item collection.
It's not an answer to your question (you already found the solution yourself), but you may want to put your SPSite and SPWeb objects in a using block. In your example code you are not disposing them, which results in a memory leak. The correct way would be like this:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite("http://sharepointsite"))
{
using (SPWeb web = site.OpenWeb())
{
// the rest of your code
}
}
});

update DateTime field with webservice UpdateListItems

is it possible to set a DateTime filed to be null/empty when calling UpdateListItems?
I can set the field to a date value, but not set it to be empty.
Yes, it's possible.
I have tested with both a required and non-required datefield and setting the field to null works.
using (SPSite site = new SPSite("http://intranet"))
{
using (SPWeb web = site.OpenWeb("site"))
{
SPList list = web.Lists["MyCustomList"];
SPListItem item = list.Items.Add();
item["Title"] = "My Item";
item["UpdateDate"] = null;
item.Update();
list.Update();
}
}

Filter a SharePoint list by audience

Using the SharePoint SDK, I'm attempting to retrieve a list and display the contents in a composite control. The list is audience aware and I'd like to maintain that in my control. How can I go about getting this list, filtered by audience, using the SharePoint SDK? Here's some of the code I'm working with:
SPWeb currentWeb = SPContext.Current.Site.RootWeb;
SPList shortcuts = currentWeb.Lists["Shortcuts"];
Here's some of the code I'm using now, and it's not quite working for me. According to how the audiences are set up, I should be getting results:
protected override void CreateChildControls()
{
dropdown = new DropDownList();
dropdown.Items.Add(new ListItem("Select...", ""));
SPWeb currentWeb = SPContext.Current.Site.RootWeb;
SPList shortcuts = currentWeb.Lists["Shortcuts"];
ServerContext context = ServerContext.GetContext(currentWeb.Site);
AudienceManager audManager = new AudienceManager(context);
AudienceCollection audiences = audManager.Audiences;
AudienceLoader audienceLoader = AudienceLoader.GetAudienceLoader();
foreach (SPListItem listItem in shortcuts.Items)
{
string audienceFieldValue = (string)listItem["Target Audiences"];
if (AudienceManager.IsCurrentUserInAudienceOf(audienceLoader, audienceFieldValue, false))
{
dropdown.Items.Add(new ListItem(listItem.Title, listItem.Url));
}
}
Controls.Add(dropdown);
base.CreateChildControls();
}
On:
if (AudienceManager.IsCurrentUserInAudienceOf(audienceLoader, audienceFieldValue, false))
It's never returning true, even when it should be.
Here's a more succinct code snippet. Main changes are removal of unused objects, and a more efficient version of the foreach loop.
protected override void CreateChildControls()
{
dropdown = new DropDownList();
dropdown.Items.Add(new ListItem("Select...", ""));
SPWeb currentWeb = SPContext.Current.Site.RootWeb;
SPListItemCollection scItems = currentWeb.Lists["Shortcuts"].Items;
AudienceLoader audienceLoader = AudienceLoader.GetAudienceLoader();
// Iterate over a copy of the collection to prevent multiple queries to the list
foreach (SPListItem listItem in scItems)
{
string audienceFieldValue = (string)listItem["Target Audiences"];
if (AudienceManager.IsCurrentUserInAudienceOf(audienceLoader, audienceFieldValue, false))
{
dropdown.Items.Add(new ListItem(listItem.Title, listItem.Url));
}
}
Controls.Add(dropdown);
base.CreateChildControls();
}
Here's a code snippet that maybe could be of use, to determine each items audience:
SPList shortcuts = currentWeb.Lists["Shortcuts"];
SPListItemCollection items = list.Items;
Audience siteAudience;
ServerContext context = ServerContext.GetContext(site);
AudienceManager audManager = new AudienceManager(context);
foreach (SPListItem item in items)
{
string ID = item["Target Audiences"].ToString();
string NewID = ID.Remove(36);
Guid guid = new Guid(NewID);
siteAudience = audManager.GetAudience(guid);
}

Resources