Sharepoint event handling.. which column changed? - sharepoint

I'm writing an event handler to handle the updating of a particular SPItem in a list. The event is asynchronous and I get the SPEvenItemProperties without a problem. What I would like to find out is which of the SPItems columns' actually fired the event. Anyone have any idea how?
Thanks in advance.

Your answer depends a bit on from where and how the SPListItem is retrieved. In a regular list, you do not have access to the previous values of the item. If you turn on versioning, you can get access to the previous versions, depending on permissions, of course.
For a document library you can use the SPItemEventProperties.BeforeProperties to get the previous metadata for a document.
For a document library you can try something like this:
foreach (DictionaryEntry key in properties.BeforeProperties)
{
string beforeKey = (string)key.Key;
string beforeValue = key.Value.ToString();
string afterValue = "";
if (properties.AfterProperties[beforeKey] != null)
{
afterValue = properties.AfterProperties[beforeKey].ToString();
if (afterValue != beforeValue)
{
// Changed...
}
}
}
.b

I think the best way to do this would be to look through the BeforeProperties and AfterProperties of the SPItemEventProperties and check which fields have different values.
These contain the values of all fields of the item before and after the event occurred.

Related

NotesXSPDocument and NotesDocument

I have created a function in SSJS Library. Because I use it in more than one XPages.
When I call this function behind a button I cannot see the value in the field
If I print it out I can see the value at the Admin Console but cannot see it in the form Even if I get page with full refreshed.
Actually my another question is.. is it possible to compare notesXSPDocument and NotesDocument. Maybe someoen can say that what is the best way for that?
function deneme(document1:NotesXSPDocument,otherDocfromOtherDatabase:NotesDocument)
{
//do staff here
if (document1.getItemValueString("field1")==otherDocfromOtherDatabase.getItemValueString("field2"))
{ //do some staff here...
document1.replaceItemValue("fieldName","FieldValue");}
}
You can compare item values from Document and XSPDocument, just be careful with the type you are comparing.
In your code you are comparing 2 javascript strings with == operator.
The code seems to be OK, just remember to save the document1 after the changes and maybe check that the items have some value.
var valueFromXspDoc = document1.getItemValueString("field1");
var valueFromDoc = otherDocfromOtherDatabase.getItemValueString("field2");
if (valueFromXspDoc && valueFromDoc && (valueFromXspDoc === valueFromDoc)) {
// stuff here...
document1.replaceItemValue("fieldName","FieldValue");
document1.save();
}
Don not compare it with == sign. A better way is to document1.getItemValueString("field1").equals(otherDocfromOtherDatabase.getItemValueString("field2"))

Can't set Orchard field values unless item already created

I seem to be having a problem with assigning values to fields of a content item with a custom content part and the values not persisting.
I have to create the content item (OrchardServices.ContentManager.Create) first before calling the following code which modifies a field value:
var fields = contentItem.As<MyPart>().Fields;
var imageField = fields.FirstOrDefault(o => o.Name.Equals("Image"));
if (imageField != null)
{
((MediaLibraryPickerField)imageField).Ids = new int[] { imageId };
}
The above code works perfectly when against an item that already exists, but the imageId value is lost if this is done before creating it.
Please note, this is not exclusive to MediaLibraryPickerFields.
I noticed that other people have reported this aswell:
https://orchard.codeplex.com/workitem/18412
Is it simply the case that an item must be created prior to amending it's value field?
This would be a shame, as I'm assigning this fields as part of a large import process and would inhibit performance to create it and then modify the item only to update it again.
As the comments on this issue explain, you do need to call Create. I'm not sure I understand why you think that is an issue however.

CRM PlugIn Pass Variable Flag to New Execution Pipeline

I have records that have an index attribute to maintain their position in relation to each other.
I have a plugin that performs a renumbering operation on these records when the index is changed or new one created. There are specific rules that apply to items that are at the first and last position in the list.
If a new (or existing changed) item is inserted into the middle (not technically the middle...just somewhere between start and end) of the list a renumbering kicks off to make room for the record.
This renumbering process fires in a new execution pipeline...We are updating record D. When I tell record E to change (to make room for D) that of course fires the plugin on update message.
This renumbering is fine until we reach the end of the list where the plugin then gets into a loop with the first business rule that maintains the first and last record differently.
So I am trying to think of ways to pass a flag to the execution context spawned by the renumbering process so the recursion skips the boundary edge business rules if IsRenumbering == true.
My thoughts / ideas:
I have thought of using the Depth check > 1 but that isn't a reliable value as I can't explicitly turn it on or off....it may happen to work but that is not engineering a solid solution that is hoping nothing goes bump. Further a colleague far more knowledgeable than I said that when a workflow calls a plugin the depth value is off and can't be trusted.
All my variables are scoped at the execute level so as to avoid variable pollution at the class level....However if I had a dictionary object, tuple, something at the class level and one value would be the thread id and the other the flag value then perhaps my subsequent execution context could check if the same owning thread id had any values entered.
Any thoughts or other ideas on how to pass context information to a new pipeline would be greatly appreciated.
Per Nicknow sugestion I tried sharedvariables but they seem to be going out of scope...:
First time firing post op:
if (base.Stage == EXrmPluginStepStage.PostOperation)
{
...snip...
foreach (var item in RenumberSet)
{
Context.ParentContext.SharedVariables[recordrenumbering] = "googly";
Entity renumrec = new Entity("abcd") { Id = item.Id };
#region We either add or subtract indexes based upon sortdir
...snip...
renumrec["abc_indexfield"] = TmpIdx + 1;
break;
.....snip.....
#endregion
OrganizationService.Update(renumrec);
}
}
Now we come into Pre-Op of the recursion process kicked off by the above post-op OrganizationService.Update(renumrec); and it seems based upon this check the sharedvariable didn't carry over...???
if (!Context.SharedVariables.Contains(recordrenumbering))
{
//Trace.Trace("Null Set");
//Context.SharedVariables[recordrenumbering] = IsRenumbering;
Context.SharedVariables[recordrenumbering] = "Null Set";
}
throw invalidpluginexception reveals:
Sanity Checks:
Depth : 2
Entity: ...
Message: Update
Stage: PreOperation [20]
User: 065507fe-86df-e311-95fe-00155d050605
Initiating User: 065507fe-86df-e311-95fe-00155d050605
ContextEntityName: ....
ContextParentEntityName: ....
....
IsRenumbering: Null Set
What are you looking for is IExecutionContext.SharedVariables. Whatever you add here is available throughout the entire transaction. Since you'll have child pipelines you'll want to look at the ParentContext for the value. This can all get a little tricky, so be sure to do a lot of testing - I've run into many issues with SharedVariables and looping operations in Dynamics CRM.
Here is some sample (very untested) code to get you started.
public static bool GetIsRenumbering(IPluginExecutionContext pluginContext)
{
var keyName = "IsRenumbering";
var ctx = pluginContext;
while (ctx != null)
{
if (ctx.SharedVariables.Contains(keyName))
{
return (bool)ctx.SharedVariables[keyName];
}
else ctx = ctx.ParentContext;
}
return false;
}
public static void SetIsRenumbering(IPluginExecutionContext pluginContext)
{
var keyName = "IsRenumbering";
var ctx = pluginContext;
ctx.SharedVariables.Add(keyName, true);
}
A very simple solution: add a bit field to the entity called "DisableIndexRecalculation." When your first plugin runs, make sure to set that field to true for all of your updates. In the same plugin, check to see if "DisableIndexRecalculation" is set to true: if so, set it to null (by removing it from the TargetEntity entirely) and stop executing the plugin. If it is null, do your index recalculation.
Because you are immediately removing the field from the TargetEntity if it is true the value will never be persisted to the database so there will be no performance penalty.

SPList Item get value - ArgumentException

I have an SPListItem and I have an array of column names.
When I try to access the SPListItem values using the code below:
for(int i=0;i<arrColName.length;i++)
{
string tempValue = item[arrColName[i]].ToString();
// Works fine in case the the specific column in the list item is not null
// Argument exception - Values does not fall witing expected range
// exception in case the value //is null
}
I think that you used an SPQuery to get the list items and forgot to add the field into the viewfields property of SPQuery.
query.ViewFields = string.Format("<FieldRef Name=\"{0}\" Nullable=\"True\" />", mFieldName);
Usually when you test your program with the farm account the code will work, with normal users you get an ArgumentException.
Another problem/feature which causes ArgumentException is the new ListView Threshold. If th elist you try to access has too many items, this Exception is raised. A way to handle this is to increase the threshold with powershell for the list.
Not only check if item != null but also item["FieldName"] != null. Because if you will try to call .ToString() on null, you will get exception.
And if that field with internal name "FieldName" name does not exist, you will also get an exception. So you would probably try
SPFieldCollection fields = list.Fields;
foreach (SPListItem item in list.Items) {
if (fields.Contains("FieldName") && item["FieldName"] != null) {
string fieldValue = item["FieldName"].ToString();
}
}
I had a similar situation with custom cascade field (or column). I did it following way and it seemed to work for the custom field types.
item.Properties["Country"] = "Mexico"; // custom field
item.Properties["nCity"] = "Cancun"; // custom field
item["Document Descriptions"] = "Test document description.";
Note: I added item.Properties for the custom columns. No need to add properties for built in field type (else they don't work).
Does your array contain the internal names or the display names of the columns? If it's the latter you might try item[item.Fields[arrColName[i]].InternalName].ToStrinng(); instead.
Sharepoint Lists aren't stored as a array with a static size.
You have to use the built in sharepoint iterator to go through each element
For example:
SPList checklist = //Some initiliaztion
foreach (SPListItem item in checklist.Items){
//work
}
This will do work on each item in your SPlist
Edit:
Wrong advice, I didn't see the code until after the edit.
Maybe try a cast?
(String)item[colname]

Can a SharePoint list item have it's Targeted Audience calculated or otherwise automatically specified?

I want to show targeted (filtered) content from a list to users. I already have a column in the list that basically has the Target Audience value. This field is a multi-choice column (checkbox input) which I prefer over the current input field for Targeted Audiences.
To get audience filtering to work I unfortunately need to have the Targeted Audience field filled out for every list item. My current plan is to use a simple SharePoint designer workflow to set the Targeted Audiences field based on my other field, but I'm wondering if there is a better way. Am I just looking at this wrong?
Note that I know audiences can also be used to hide/show web parts, but that is not something I am interested in.
You could try and give this a whirl...
SPField audienceField = null;
try
{
audienceField = list.Fields[Microsoft.SharePoint.Publishing.FieldId.AudienceTargeting]
}
catch
{}
if(audienceField != null)
{
try
{
Audience siteAudience;
ServerContext context = ServerContext.GetContext(site);
AudienceManager audManager = new AudienceManager(context);
foreach (SPListItem item in list.Items)
{
string audienceName = item["fakeAudienceField"]; //should be the audience name created in SSP
siteAudience = audManager.GetAudience(audienceName);
Guid id = siteAudience.AudienceID;
item["Target Audiences"] = id.ToString()+";;;;";
item.Update();
}
}
catch
{}
I do not believe Target Audiences can be set up as a calculated field, in which case your options are workflow or a list item event receiver.
To set the audience field value, you can use AudienceManager.GetAudienceIDsAsText; Gary Lapointe has a post with example usage.
Maybe use a webpart to display the content of the list and use Audiences on the webpart sounds a solution easier to manage...

Resources