sharepoint object model itemadding eventreceiver - sharepoint

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).

Related

While deleting the customer, how can i set null value for the custom field for the assigned contacts in Acumatica

I have tried multiple ways, but getting Another process error in the default version of Acumatica 19.106.0020
On top of it i have a customized code on both customer and contact screen, my requirement to clear the value of the custom field that is created in contact table when customer is deleting from the screen AR303000 i need to set null value of the custom field for the deleted contact from the customer.
i have tried by setting value on Customer_RowDeleting event but continuously getting Another process error, below is the screenshot error
Below is the code that i was tried
protected virtual void Customer_RowDeleting(PXCache sender, PXRowDeletingEventArgs e, PXRowDeleting BaseEvent)
{
BaseEvent?.Invoke(sender, e);
Customer rows = e.Row as Customer;
if (rows == null)
return;
if (Base.BAccount.Cache.GetStatus(Base.BAccount.Current) == PXEntryStatus.Deleted)
{
foreach (Contact BACT in PXSelectReadonly<Contact,
Where<Contact.bAccountID, Equal<Required<Contact.bAccountID>>,
And<Contact.contactType, NotEqual<ContactTypesAttribute.bAccountProperty>>>>.Select(Base, rows.BAccountID))
{
ContactMaint congraph = PXGraph.CreateInstance<ContactMaint>();
Contact CTData = PXSelectReadonly<Contact,
Where<Contact.contactID, Equal<Required<Contact.contactID>>>>.Select(Base, BACT.ContactID);
if (CTData != null)
{
congraph.Contact.Current = CTData;
if (congraph.Contact.Current != null)
{
congraph.Contact.SetValueExt<ContactExt.usrKWBAccountId>(congraph.Contact.Current, null);
congraph.Contact.Update(congraph.Contact.Current);
congraph.Save.Press();
}
}
}
}
}
Thanks in advance.
Hi Chris, please find the attached image here
I don't recommend to create graphs during RowDeleting event. If you have Acuminator installed, you will see a warning about creating graphs in event handlers.
Instead, call your custom code during the Persist method. Persist method is called during Delete operation. After the Base persist is finished, your custom code can perform it's work. Try something like this
public class CustomerMaint_Extension : PXGraphExtension<CustomerMaint>
{
public delegate void PersistDelegate();
[PXOverride]
public void Persist(PersistDelegate baseMethod)
{
Customer currentCustomer = Base.CurrentCustomer.Current; //get the customer record before it's deleted, i.e. Customer.bAccountID
baseMethod(); //let the base delete process happen first
if (Base.CurrentCustomer.Cache.GetStatus(currentCustomer) == PXEntryStatus.Deleted)
{
using (PXTransactionScope ts = new PXTransactionScope())
{
//here is where you add your code to delete other records
ts.Complete(); //be sure to complete the transaction scope
}
}
}
}
Also you might want to unpublish other customization packages, and see if the error continues without those packages. That is one way to determine the source of the error...by process of elimination.

Document library field wont update field value

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

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);
}

Loss of properties webpart toolpart moss 2007

I've got the following problem:
I created a WebPart with a ToolPart,
this toolpart has multiple controls (textbox, dropdownlist, ...)
when I fill in everything and apply, it all goes ok,
even when i press ok. But when i go back to
edit -> modify webpart, all my data i've entered is gone.
How can i solve this?
Thanks
You'll need to save the values from the Toolpart in the webpart's properties. For example, lets say I want to save a string for "Title"... in the webpart define a property:
private const string DEFAULT_WPPColumnTitle = "Title";
private string _WPPColumnTitle = DEFAULT_WPPColumnTitle;
[Browsable(false)]
[WebPartStorage(Storage.Shared)]
public string WPPColumnTitle
{
get { return this._WPPColumnTitle; }
set { this._WPPColumnTitle = value; }
}
I always use the prefix "WPP" to keep all the web part properties together.
Then, in the Toolpart's ApplyChanges override, save the control's value (_ddlColumnsTitle) to the webpart (WPPColumnTitle):
/// <summary>
/// Called by the tool pane to apply property changes to
/// the selected Web Part.
/// </summary>
public override void ApplyChanges()
{
// get our webpart and set it's properties
MyCustomWebPart et = (MyCustomWebPart)ParentToolPane.SelectedWebPart;
et.WPPColumnTitle = _ddlColumnsTitle.SelectedValue;
}
Lastly, if the user edited the properties already, we want the Toolpart to be pre-populated with the user's configuration. In the CreateChildControls() method of your Toolpart, initialize the controls:
protected override void CreateChildControls()
{
try
{
MyCustomWebPart et = (MyCustomWebPart)ParentToolPane.SelectedWebPart;
// ... code to create _ddlColumnsTitle and add it to the Controls
// default our dropdown to the user's selection
ListItem currentItem = _ddlColumnsTitle.Items.FindByValue(et.WPPColumnTitle);
if (null != currentItem)
{
_ddlColumnsTitle.SelectedValue = currentItem.Value;
}
}
catch (Exception ex)
{
_errorMessage = "Error adding edit controls. " + ex.ToString();
}
}
Open up the debugger and double check that the values are getting applied to your propertries on Apply (i.e. WPPColumnTitle is set).
If so then problem is that SharePoint is not serializing/deserializing the value from the property (WPPColumnTitle) to the database and back - verify by writing out this property on the web part - as soon as you leave the page and come back it will be empty.
If so then check things like this on class
[XmlRoot(Namespace = "YourNamespace")]
and this (not strictly necessary) on properties
[XmlElement(ElementName = "ColumnTitle")]
I've also seen problems if you name your web part class "WebPart" so call it MyWebPart
I've solved it with adding a property in my webpart "IsNeverSet" (bool)
and when i go to the "CreateControls()" of my toolpart, I get this property
and if it's false, I load all the properties from my webpart and fill them in the toolpart.
So I found it with the help of Kit Menke

Resources