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

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

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

Listbox not always adding item using Windows Azure MobileServiceCollection with WP8

I'm using Windows Azure Mobile Services to store and retrieve data in my Windows Phone 8 app. This is a bit of a complicated issue so I will do my best to explain it.
Firstly I'm using raw push notifications to receive a message and when it receives the message it updates a listbox in my app. When I open my app, navigate to the page with the ListBox and receive a push notification the ListBox updates fine. If I press back, then navigate to the same page with the ListBox, the push notification is received, the code to update the ListBox executes with no errors yet the ListBox doesn't update. I have checked that the same code runs using the OnNavigatedTo handler in both scenarios, but it seems like the ListBox does not bind correctly in the second instance when I press back and then re-navigate to the same page. Here are some code snippets:
MobileServiceCollection declarations:
public class TodoItem
{
public int Id { get; set; }
[JsonProperty(PropertyName = "text")]
public string Text { get; set; }
}
private MobileServiceCollection<ToDoItem, ToDoItem> TodoItems;
private IMobileServiceTable<TodoItem> todoTable = App.MobileService.GetTable<TodoItem>();
Push Notification Received Handler:
void PushChannel_HttpNotificationReceived(object sender, HttpNotificationEventArgs e)
{
string message;
using (System.IO.StreamReader reader = new System.IO.StreamReader(e.Notification.Body))
{
message = reader.ReadToEnd();
}
Dispatcher.BeginInvoke(() =>
{
var todoItem = new TodoItem
{
Text = message,
};
ToDoItems.Add(todoItem);
}
);
}
I have tried using:
ListItems.UpdateLayout();
and
ListItems.ItemsSource = null;
ListItems.ItemsSource = ToDoItems;
before and after the code in the above procedure that adds the ToDoItem but it didn't help.
The following procedure is called in my OnNavigatedTo event handler, and refreshes the Listbox and assigns ToDoItems as the items source:
private async void RefreshTodoItems()
{
try
{
ToDoItems = await todoTable
.ToCollectionAsync();
}
catch (MobileServiceInvalidOperationException e)
{
MessageBox.Show(e.Message, "Error loading items", MessageBoxButton.OK);
}
ListItems.ItemsSource = ToDoItems;
}
The above procedure is async but I have made sure it completes before receiving any notifications. Even so, as mentioned above when I open the app, navigate to the page that shows the ListBox it updates fine. When I press back, navigate to the same page again, it doesn't work. When I back out of the app, re-open it, navigate to the page with the ListBox, it works again, and then fails if I press back and re-open the page. So it seems the ListBox is not binding to ToDoItems correctly when I press back and navigate to the same page.
Any help appreciated. Thanks.
Can you modify your approach a bit to use Data Binding and the MVVM model to bind your model to your view.
It might look like a bit of effort initially but will save you a lot of debugging hours later on.
Just follow the below steps
Create a new class that implements INotifyPropertyChanged
Add the below method implementation
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
Add public ObservableCollection<TodoItem> TodoItems{ get; private set; } and initialize it in the constructor.
Every PhoneApplicationPage has a DataContext member. Assing it to a singleton instance of the above class that you create.
In the XAML, add the property ItemsSource="{Binding TodoItems}" to the list.
In the DataTemplate of the list use ItemsSource="{Binding Text}" for the control you wish to display this value on. ( e.g. TextBlock )
Now whenever you add elements to the collection, it will be reflected in the UI, and vice-versa.

EventReceiver to Create folder sharepoint 2010

I have this event receiver c# class that I am trying to implement on a Sharepoint site. It did not work. I have deployed it from visual studio 2010 after it was build ok. Does anyone see what is the problem? Is the code ok? or is the problem on the SP? Thank you.
- here is the new code
using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;
namespace EventReceiverCFolder.EventReceiver1
{
/// <summary>
/// List Item Events
/// </summary>
public class EventReceiver1 : SPItemEventReceiver
{
/// <summary>
/// An item is being added.
/// </summary>
public override void ItemAdded(SPItemEventProperties properties)
{
try
{
if (properties.ListTitle == "CF") // list where the item was added
{ // if item was added to this list then create a folder on - Dlib - list
UpdateFolder(properties);
}
}
catch (Exception ex)
{
properties.Status = SPEventReceiverStatus.CancelWithError;
properties.ErrorMessage = ex.Message;
properties.Cancel = true;
}
}
private void UpdateFolder(SPItemEventProperties properties)
{
string foldername = properties.ListItem["Title"].ToString();
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
//inside RunWithElevatedPriviliges I need to open a new site (an elevated site)
using (SPSite site = new SPSite(properties.Web.Site.ID))
{
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPList list = web.Lists.TryGetList("DLib"); // this is doc Library where the new folder will be created
//note that we are creating a list item, not a folder - a folder IS a list item
SPListItem createdFolder = list.Items.Add(list.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder, null);
if (createdFolder != null)
{
createdFolder["Name"] = foldername;
createdFolder.Update();
}
list.Update();
}
}
});
}
finally { }
}
}
}
Don't do this: SPUser privilegedAccount = properties.Web.AllUsers[#"SHAREPOINT\SYSTEM"];
Read up on using SPSecurity.RunWithElevatedPrivileges. See the MSDN documentation here.
Also don't do a using (SPSite... and inside the using block you try to get the web via SPContext.Current - that web won't be elevated anymore.
The correct way is something along these lines (I didn't try this, so it' just to give you an idea where you are headed):
private void UpdateFolder(SPItemEventProperties properties)
{
string foldername = properties.ListItem["Title"].ToString();
SPSecurity.RunWithElevatedPrivileges(delegate()
{
//inside RunWithElevatedPriviliges I need to open a new site (an elevated site)
using (SPSite site = new SPSite(properties.Web.Site.ID))
{
using (SPWeb web = site.OpenWeb())
{
web.AllowUnsafeUpdates = true;
SPList list = web.Lists.TryGetList("ListTitle"); //is that really the list title?
//note that we are creating a list item, not a folder - a folder IS a list item
SSPListItem createdFolder = list.Items.Add(list.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder, null);
if (newFolder != null)
{
createdFolder["Name"] = foldername;
createdFolder.Update();
}
list.Update();
}
}
});
}
Also try to debug your code, set breakpoints etc.
I had to get folder name like this:
string foldername = Convert.ToString(properties.AfterProperties["Title"]);
Did you try to debug it? try to debug and tell us what error you are getting.
BUT before you debug first use sharepoint manager to see if your event receiver is attached properly.
If you dont know how to debug sharepoint event receiver then please see this

Creating Document set programatically in sharepoint 2010

I am creating a document set programatically on buttom click event
public void btnCreateDocumentSet_Click(object sender, EventArgs e)
{
try
{
lblError.Text = string.Empty;
SPSecurity.RunWithElevatedPrivileges(() =>
{
using (web = SPControl.GetContextSite(Context).RootWeb)
{
web.AllowUnsafeUpdates = true;
String url = web.Lists[" Tracker"].RootFolder.ServerRelativeUrl.ToString();
SPList list = web.Lists["Tracker"];
Hashtable props = new Hashtable();
props.Add("Number", "item1");
props.Add("Type", "item2");
DocumentSet ds = DocumentSet.Create(list.RootFolder, "NewDocumentSet3", web.ContentTypes["MydocumentSet2"].Id, props, true);
//test
//web.Dispose();
}
}
);
}
catch (SPException ex)
{
lblError.Text = ex.Message;
}
}
I am not getting any exceptions.On button click i am redirected to an error like the following
However the document set named NewDocumentSet3 is created in document library but it looks like a folder(the icon i mean) . when i go to document library->documents tab->New Document I am not getting the document set type .Kindly advise me on this issue.
Thanks in advance
First of all, turn off custom errors, like the screenshots tells you.
Then replace your catch of SPException with a catch of all Exceptions.
Even better yet, test code like this in a separate console app, not right inside handlers.
Look up some resources on the internet on how to debug SharePoint applications. A breakpoint will get you a long way in this particluar situation.
I am very wary of your list called "[space]Tracker". Looks suspicious to me.
Try adding
props.Add("HTML_x0020_File_x0020_Type", "SharePoint.DocumentSet");
to the properties hashset that gest passed in to DocumentSet.Create method.

Resources