SharePoint note programmatically write error - c#

My question relates to programmatically writing to a Sharepoint list field of the type "Note". Reading from the field is straightforward.
//Retrieving the list row
SPListItem baseItem = baseList.GetItemById(itemId) as SPListItem;
string value = Convert.ToString(baseItem["NameOfTheNoteField"]);
But then I try to write to to a Note field;
SPListItem item ...;
item["NameOfTheNoteField"] = "MyValue";
It results in the following error:
Value does not fall within the expected range ...
What does the Note field expect if not a string!?

You actually shouldn't think of it as a Note field, but a SPMultiLineText field.
To update it you first need to get the current value and edit that - also you shouldn't use Convert.ToString() with it but GetFieldValueAsHtml or GetFieldValueAsText.
Ultimately your way of setting the value should have worked. Value does not fall within the expected range could also be coming from somewhere else - e.g. you are not using the correct name of the field and hence item["NameofNoteField"] is throwing an error. Try to debug it.
Taking your example and updating the current text in the field:
SPListItem baseItem = baseList.GetItemById(itemId) as SPListItem;
SPFieldMultiLineText mlfield = baseItem.Fields.GetField("NameOfTheNoteField") as SPFieldMultiLineText;
string fieldtext = multilineField.GetFieldValueAsHtml(item["NameOfTheNoteField"], baseItem );
//or use GetFieldValueAsText
fieldtext += "I am the update of the text";
baseItem ["NameOfTheNoteField"] = fieldtext;
baseItem.Update()

Related

How to Update KTA RunTimeField with an object?

I am trying to update an object (Generic List object) to RuntimeFiledCollection. When I try to update using the following code, I am getting always Serialization error :(
//My object which need to update set with the documentRuntimeField value
List<docInfo> docInfoList = new List<docInfo>
docInfo = new docInfo { ID = "11233", PageNumber = 1, text ="MyOwnText"};
docInfoList.Add(docInfo);
// Construct DOcument RuntimeFields Collection
var docRunTimeCollection = new CaptureDocumentService.RuntimeFieldCollection();
var docRunTimeField = new CaptureDocumentService.RuntimeField
{ Name = "FieldName", Value = docInfoList };
docRunTimeCollection.Add(docRunTimeField);
captureDocumentServiceClient.UpdateDocumentFieldValues(sessionId, null, validDocumentId, docRunTimeCollection);
I always get sterilization error as shown below. Can someone give me an example how to update document field values with an object. Any help ?
Error : There was an error while trying to serialize parameter http://www.kofax.com/agilityservices/sdk:runtimeFields.InnerException message was System.Collections.Generic.List
For RuntimeField class, you can see the the Value property is of type Object, but that is misleading, because it is not an arbitrary container. It takes the type that you defined for that field in your Extraction Group. But essentially that just means it will take a DateTime for a Date field or numeric types for a Number field, and anything else would be casted to string.
If you actually using a Table Field, then you cannot use the API to set the contents of the entire table. You would instead set the RuntimeField.TableRow and RuntimeField.TableColumn properties to use the API to set individual cells.

Why does my allocation get ignored, when setting values to a workitem-field?

I'm trying to automatically create a new workitem, after I choosed the project and one of its workitem-types. For test purposes, I'm iterating over all projects and all of their workitem-types, to create for every workitem-type a new workitem. I know, that there are required fields, which have to have a value, before trying to save that workitem. That's why I'm trying to set "default"-values for that field, but if I log the ArrayList, which I get from the .Validate()-method, I can see, that there are the same fields as before. It seems like my allocation to the fields gets ignored.
In the following example, I would have still the field "GemeldetVon" inside the invalidFields list, at the end.
Does anyone seeing, what I'm doing wrong?
Here is my snippet:
foreach (WorkItemType workItemType in workItemTypes)
{
WorkItem workitem = new WorkItem(workItemType);
workitem.Title = "OTRS-TFS-Connector Test-Workitem";
ArrayList requiredFields = workitem.Validate();
if (requiredFields != null) {
foreach(Field f in requiredFields) {
if (f.Name.Equals("GemeldetVon")) {
workitem.Fields["GemeldetVon"].Value = "some Value";
}
if...
}
}
}
ArrayList invalidFields = workitem.Validate();
IIRC you should call the WorkItem.Open or the WorkItem.PartialOpen method before setting Fields' values.
It's done now. It was because of invalid values, which I tried to assign. My example field needs an user as value, an not just some string. It's working, if I assign valid values. Thanks :)

Convert webcontrols.ListItem to an object of a class

when I try to cast a list item as an object, I get the following. "Cannot convert type 'System.Web.UI.WebControls.ListItem' to 'ASPGigManager2.GigOpportunity'"
Is there anyway you can do this? Here is my code:
GigOpportunity gigOpportunity;
gigList.removeGig((GigOpportunity)lstGigs.SelectedItem);
I have tried to go the long way round and convert it to string but I still get a conversion error, string to GigOpportunity.
GigOpportunity gigOpportunity;
string test;
test = Convert.ToString(lstGigs.SelectedItem);
gigOpportunity = test;
Its as it says, you cannot convert a ListItem to GigOpportunity. And since this is ASP.NET, your original object no longer exists inside the list control. So, during your initial binding, set the DataValueField property to a unique value that identifies each gig (such as a primary key).
Then, on a callback, you have to find your original gig again. For example:
var selectedValue = lstGigs.SelectedValue;
var gig = gigList.Where(x => x.SomeKeyValue == selectedValue).Single();
gigList.Remove(gig);
Better yet, turn you gigList into a dictionary who's key is the same key you used as the value. Then, all you have to do is
gigDict.Remove(lstGigs.SelectedValue);

How to programmatically populate Sitecore items (Add item and fields)?

I'm now battling with adding items via C# to Sitecore database.
The code below executes correctly, however the items aren't being created.
Also, I noticed, that the item["FieldName"]=value; syntax doesn't actually populate the Fields collection.
And Fields collection on the item seems read only, so I can't just call .Add on it (such method doesn't exist).
So - what is the correct way of creating a child item and populating its fields?
I am using the Master database for both the Sitecore backend and this code.
The code I use below:
using (new Sitecore.SecurityModel.SecurityDisabler())
{
Database db = Factory.GetDatabase(this.Database);
foreach (var vacancy in Articles.Tables[0].Rows)
{
var rootItem = db.GetItem(this.RootItem);
DataRow dr = (DataRow) vacancy;
var newItem = rootItem.Add(string.Format("{0} {1}", dr["numericID"], dr["job_name"]),
db.GetTemplate(new ID("{GUID}")));
newItem.Editing.BeginEdit();
newItem["Job Title"] = dr["job_name"].ToString();//
newItem.Editing.EndEdit();
}
}
More info:
newItem.Template.Fields returns a collection with 100 fields
newItem.Fields returns a FieldCollection with only 9 elements in it.
When I pass through the code newItem["field"].Value = value; it does not increment the newItem.Fields collection count.
Of course the "field" key is consistent with ones present in newItem.Template.Fields[x].Name.
1) Check some things first f.ex:
assing the template to a variable and check what you get there.
and better don't do it by ID rather by path:
var templateItem = db.GetTemplate("yourTemplatePath");
now check whether that is the template you want?
make sure it's published (it can always cause some inconsistencies)
2) As to the fields not being 'visible', have you tried: item.Fields.ReadAll()
3) What do you mean by "items not being created"? how would you check that?
4) Also - are you sure that this.Database == "master" ?
I would recommend two changes:
(1) The item naming approach:
var newItem = rootItem.Add(ItemUtil.ProposeValidItemName(string.Format("{0} {1}", dr["numericID"], dr["job_name"])), db.GetTemplate(new ID("{GUID}")));
This change will handle invalid characters in the proposed name from your other data source.
(2) The field value setting approach:
newItem.Fields["Job Title"].Value = dr["job_name"].ToString();
This will set the raw value of the field to the provided string.
I would suggest setting the field value as
newItem.Fields["Job Title"].Value = dr["job_name"].ToString();//
Everything else looks ok.

Adding enum to combobox

Hi may i know how to get the enum value below to bind into the combobox?
I wrote the below code which works well but wonder is this the best way.
public enum CourseStudentStatus
{
Active = 1,
Completed = 2,
TempStopped = 3,
Stopped = 4,
}
//Bind Course Status
Dictionary<string, int> list = new Dictionary<string, int>();
foreach (int enumValue in Enum.GetValues(typeof(CourseStudentStatus)))
list.Add(Enum.GetName(typeof(CourseStudentStatus), enumValue), enumValue);
var column = ((DataGridViewComboBoxColumn)dgv.Columns["studentCourseStatus"]);
column.DataPropertyName = "StudentStatus";
column.DisplayMember = "Key";
column.ValueMember = "Value";
column.DataSource= list.ToList();
----------------- UPDATE -------------------
Hi i have changed my code to this according to Sanjeevakumar Hiremat and it works perfectly.
cbStatus.DataSource = Enum.GetValues(typeof(CourseStudentStatus));
However, when i want to a Get() and want to bind the value back to the cbStatus, it cast error {"Object reference not set to an instance of an object."}
cbStatus.SelectedValue = Course.Status;.
The cbStatus.Datasource is not empty and it has value after bound to cbStatus.DataSource = Enum.GetValues(typeof(CourseStudentStatus));
please advice.
Following should be the simplest way to bind it.
column.DataSource = Enum.GetValues(typeof(CourseStudentStatus));
To get the selected value you need to cast it to the enum type.
CourseStudentStatus selectedValue = (CourseStudentStatus)column.SelectedValue
Enum.GetValues returns an array of the enumType values which can then be bound to any control.
I've tested this on a standalone combobox, not in a combobox column in DataGridView, YMMV.
I don't think there is a best way. I used to do something similar with a GenericListItem<T> class where T is the backing value, in your case, an enum.
This class exposed Display string and Value T properties to bind to. I think I was also overriding ToString because it is the default if you don't specify the DisplayMember. I went further and made a constructor taking just Value and defaulting Display to Value.ToString, which in the case of enums works I think.
I'd then make a List<GenericListItem<T>>, feed that into the DataSource of the column and set the DisplayMember and ValueMember properties accordingly in code. This list is the alternative to the dictionary used in your example.
But I'm not saying it's a better solution :-) however it means you can remove code, say enum iteration, into this class or specialise the class for handling certain data types better, all with the end goal of being inserted into a list and bound to a control.

Categories

Resources