Document library field wont update field value - sharepoint

on ItemAdded on a field,
public override void ItemAdded(SPItemEventProperties properties)
{
this.EventFiringEnabled = false;
using (SPWeb web = new SPSite(properties.WebUrl).OpenWeb())
{
SPList list = web.Lists[properties.ListId];
SPListItem item = list.GetItemById(properties.ListItemId);
var test = item["MyField"] = "";
item.SystemUpdate(false);
}
this.EventFiringEnabled = true;
}
}
}
when adding a dokument directly to my library its clear the field, men when i publish the document and then try to unpublish and then i select Remove this document but create a draft of the document, on this event it wont clear my field, i get the value and everything but in the en it still has the old value?

I've not checked this for sure but I think I remember when dealing with event receivers in document libraries it's a little funny. I believe the itemAdded event fires when you upload the document, you then continue to fill out your metadata for that document and when you click save the itemupdating and itemupdated event is fired. If you debug you will see this I think.
I believe you want to change to ItemUpdated
Cheers
Truez

Related

Sharepoint 2013- update document metadata using itemupdating or itemupdated event is not working

I am trying to update custom metadata for a document when document is added to the library using item updated event, but it is not working. A custom aspx application is using a href element to point to the URL of the document. Click it on it opens windows explorer view similar to the one that is OOB sharepoint 2013 explorer view. Now when user copy the document from library1(says lives in site1 in sitecollection1) to library2(lives in site2 in sitecollection2) via copy-paste option, I need to clear some of the metadata of the document. I am trying the Lukasz's suggestion for it, but the metadata is not clearing. In the debug mode, even though event firing is disabled before update, I see the updated event is being called again one more time which is strange. At the end, my metadata is not being cleared. I tried with both updating and updated event. Any idea? here is my code for updated:
public override void ItemUpdated(SPItemEventProperties properties)
{
base.ItemUpdated(properties);
ClearNotes(properties);
}
private void ClearNotes(SPItemEventProperties properties)
{
try
{
SPListItem listItem = properties.ListItem;
listItem["Notes1"] = string.Empty;
listItem["ReviewNote"] = null;
base.EventFiringEnabled = false;
listItem.Update();
}
catch (Exception ex)
{
//logging error to db
}
finally
{
base.EventFiringEnabled = true;
}
}
I think it must be this.EventFiringEnable = false;
Not base. ...
You can also do it with itemupdating and Afterproperties, then you dont need to disable the EventFiring and need no update:
public override void ItemUpdating(SPItemEventProperties properties)
{
base.ItemUpdating(properties);
///...
properties.AfterProperties["Notes1"] = string.Empty;
}

How to update field value in current item via event receiver?

EDIT: I've realized that my approach in the second code block was unnecessary. I could accomplish the same thing by doing the following in ItemUpdated:
SPListItem thisItem = properties.ListItem;
thisItem.File.CheckOut();
thisItem["Facility Number"] = "12345";
thisItem.Update();
thisItem.File.CheckIn("force check in");
Unfortunately, I'm still getting the same error message when "thisItem.Update();" is executed: he sandboxed code execution request was refused because the Sandboxed Code Host Service was too busy to handle the request
I actually was receiving the error above when deploying my sandbox solution originally and used this link (http://blogs.msdn.com/b/sharepointdev/archive/2011/02/08/error-the-sandboxed-code-execution-request-was-refused-because-the-sandboxed-code-host-service-was-too-busy-to-handle-the-request.aspx) to fix it.
I am trying to write a C# event receiver that changes the value of a field when a document is added/changed in a library. I have tried using the following code:
public override void ItemUpdating(SPItemEventProperties properties)
{
base.ItemUpdating(properties);
string fieldInternalName = properties.List.Fields["Facility Number"].InternalName;
properties.AfterProperties[fieldInternalName] = "12345";
}
Unfortunately, this is only working for certain fields. For example, if I replaced "Facility Number" with "Source", the code will execute properly. This may be the fact that we are using a third party software (called KnowledgeLake) that replaces the default edit form in SharePoint with a Silverlight form. Anyway, because I was having challenges with the code above (again, because I think the Silverlight form may be overriding the field after the ItemUpdating event fires), I have tried the following code:
public override void ItemUpdated(SPItemEventProperties properties)
{
base.ItemUpdated(properties);
//get the current item
SPListItem thisItem = properties.ListItem;
string fieldName = "Facility Number";
string fieldInternalName = properties.List.Fields[fieldName].InternalName;
string fieldValue = (string)thisItem["Facility Number"];
if (!String.IsNullOrEmpty(fieldValue))
{
//properties.AfterProperties[fieldInternalName] = "123456789";
SPWeb oWebsite = properties.Web as SPWeb;
SPListItemCollection oList = oWebsite.Lists[properties.ListTitle].Items;
SPListItem newItem = oList.GetItemById(thisItem.ID);
newItem.File.CheckOut();
thisItem[fieldInternalName] = "12345";
thisItem.Update();
newItem.File.CheckIn("force");
}
}
First off, the above seems a little klunky to me as I would love to just use the AfterProperties method. Additionally, I am getting the following error when "newItem.Update()" is executed: he sandboxed code execution request was refused because the Sandboxed Code Host Service was too busy to handle the request
Am I missing something here? I would love to utilize the first code block. Any help would be appreciated.
Josh was able to answer his own question, which helped me fix my problem as well. Here is a working code snippit.
public override void ItemUpdated(SPItemEventProperties properties)
{
string internalName = properties.ListItem.Fields[columnToUpdate].InternalName;
//Turn off event firing during item update
base.EventFiringEnabled = false;
SPListItem item = properties.ListItem;
item[internalName] = newVal;
item.Update();
//Turn back on event firing
base.EventFiringEnabled = true;
base.ItemUpdated(properties);
}

Sharepoint workflow not updating

I have written a workflow for that autofills a column in a sharepoint list. When I add a new entry nothing happens. However, if I go to another list and then return to the list with the workflow I can see that it has worked. I have set up the workflow to start when a new item is created, is there some other setting in the workflow to make it update instantly?
No there is no. You should use SPItemEventReceiver instead and use ItemUpdating method. This is what works instantly and the workflow requires some time to start and it runs asynchronously. Furthermore workflows are heavy and you should avoid using them for very simple actions.
The sample code for an event receiver is
public class MyEventReceiver :SPItemEventReceiver
{
public override void ItemUpdating(SPItemEventProperties properties)
{
UpdateField(properties);
}
public override void ItemAdding(SPItemEventProperties properties)
{
UpdateField(properties);
}
private void UpdateField(SPItemEventProperties properties)
{
EventFiringEnabled = false;
var item = properties.ListItem;
// do calculation here
item.SystemUpdate(false); // this update that is most suitable for automatic updates
EventFiringEnabled = true;
}
}
And then add this event receiver to a list. I hope this link helps
You can also try to add a Calculated column to your list if you cannot use Visual Studio. This way the hardest point is to define a formula that will takes data from other columns of the list item and performs a calculation. link1 and link2 can give you more information on how to write a formula in the calculated column in SharePoint with no code.

Sharepoint: Create a subweb from an item event handler

I have a "project list" (title, lead, members, site-URL) that is supposed to refer to team sites under the site that has the project list. So I added an SPItemEventReceiverto my feature in a sandbox solution to do that.
In ItemAdding(properties), I invoke the following:
string projectName = properties.AfterProperties["Title"].ToString();
SPWeb currentWeb = properties.Web;
SPWeb subweb = currentWeb.Webs.Add(projectName, projectName,
"Project site for " + projectName, (uint) currentWeb.Locale.LCID,
Microsoft.SharePoint.SPWebTemplate.WebTemplateSTS, true, false);
But when debugging, the call to Add throws an SPException wrapping a COMException for a HResult code of FAILED with the message The sandboxed code execution request was refused because the Sandboxed Code Host Service was too busy to handle the request.
Is there something wrong with the parameters, or should I delegate the actual creation to a workflow instead?
Following try with this:
public override void ItemAdding(SPItemEventProperties properties)
{
base.ItemAdding(properties);
// Get the web where the event was raised
SPWeb spCurrentSite = properties.OpenWeb();
//Get the name of the list where the event was raised
String curListName = properties.ListTitle;
//If the list is our list named SubSites the create a new subsite directly below the current site
if (curListName == "SubSites")
{
//Get the SPListItem object that raised the event
SPListItem curItem = properties.ListItem;
//Get the Title field from this item. This will be the name of our new subsite
String curItemSiteName = properties.AfterProperties["Title"].ToString();
//Get the Description field from this item. This will be the description for our new subsite
string curItemDescription = properties.AfterProperties["Description"].ToString();
//Update the SiteUrl field of the item, this is the URL of our new subsite
properties.AfterProperties["SiteUrl"] = spCurrentSite.Url + "/" + curItemSiteName;
//Create the subsite based on the template from the Solution Gallery
SPWeb newSite = spCurrentSite.Webs.Add(curItemSiteName, curItemSiteName, curItemDescription, Convert.ToUInt16(1033), "{8FCAD92C-EF01-4127-A0B6-23008C67BA26}#1TestProject", false, false);
//Set the new subsite to inherit it's top navigation from the parent site, Usefalse if you do not want this.
newSite.Navigation.UseShared = true;
newSite.Close();
}
}
Seems to be some deadlock situation; I solved my particular case by using the post-event ItemAdded instead (changing from setting values in AfterProperties to updating the ListItem instead). There, for some reason, the call to Webs.Add() completes normally...

sharepoint object model itemadding eventreceiver

I am trying to add a event receiver on a list for itemadding. I have a field called EmployeeName people picker from which i need to get userprofile of that particular employee on item adding and trying to get EmployeeNo auto updated from userprofile.
I using as below: but not working
public override void ItemAdding(SPItemEventProperties properties)
{
base.ItemAdding(properties);
UserProfileManager profileManager = new UserProfileManager(context);
UserProfile myProfile = profileManager.GetUserProfile(item["EmployeeName"].ToString());
if (myProfile["EmployeeNo"].Value != null)
{
properties.AfterProperties["EmployeeNo"] = (myProfile["EmployeeNo"]).ToString();
}
item.Update();
}
Please help me on this.
Check if you use the correct internal column names.
Where do you get "item" from? Try using properties.ListItem instead.
Don't call properties.ListItem.update() (or item.update() in your code).

Resources