Programmatically access external list associated column - sharepoint

Hi I have 2 external lists 'A' and 'B'. with an associated column in A, that looks up for B.
When i view/edit item in browser, it shows correct values as shown in picture below.
But when i try to access the list in code, i can access all column values, but associated column value comes null.
The code look something like this :
items = listReports.GetItems();
System.Collections.Generic.List<ReportItem> reportItems = new List<ReportItem>();
foreach (SPListItem it in items)
{
if (it != null)
{
ReportItem item = new ReportItem();
// extItem comes null
var extItem = it["ExtCol"];
// extItem comes null
DateTime date;
if (DateTime.TryParse(it["GeneratedOn"].ToString(), out date))
{
item.dateGenerated = date.Date;
}
DateTime time;
if (DateTime.TryParse(it["GeneratedOn"].ToString(), out time))
{
item.timeGenerated = time.Date;
}
reportItems.Add(item);
}
}

I'm not sure, but, "ExtCol" - is that rigth name for field in your external type? For external items sharepoint may substitute a name of external item/column in the source field name.

Related

Adding multiple objects to ArrayList that match a selected string

What I am trying to do: Fill the namesArray with all the objects that match a certain criteria.
The Activity object is made of four strings "category, name, note, time"
The getCategory(activityArray) returns a string which is the selected category, I'm trying to sort the objects where their category matches the selected category into the new namesArray
So this namesArray will end up containing only Activity objects with selected category.
This is my code:
public static void viewActivity(ArrayList<Activity> activityArray) {
String categ = getCategory(activityArray);
String holder;
ArrayList<Activity> namesArray = new ArrayList<Activity>();
for(Activity obj : activityArray) {
holder = obj.getCategory();
if(holder == categ) {
System.out.println(obj.getName());
namesArray.add(obj);
}
}
}
When I run the debugger, first iteration works, and the first object where it's category matches the selected category is added to the namesArray. But then the if statement just seems to stop working, the holder String does not change and stays the same.
So how do I get my method to add every matching object to the namesArray instead of only the first one?
Thanks
Solved by changing the
if(holder == categ) {
to
if(holder.equals(categ)) {

Filter out users in a drop down on PCF

In ClaimCenter I am trying to filter a drop down list to only display users that have a certain role. I am using a User input cell. There is no value range on the userinput cell only value. The value is set the user that they select so right now it's displaying all the users in the system instead of just the ones with the role that i want. Is there a way to show just the users that have the "Adjuster" role. I don't see a filter option either on this cell.
Right click the element and select "Change Element Type"
Then select "Range Input".
Then in the ValueRange property add a call to the code that you write.
The code to should find the subset of users that you want to show in the drop down and return them as a List or User[], something like this might work
function myValueRangeFunction(pClaim: Claim) : User[] {
//gets the group from the DB by public ID
var adjusterGroup = Group ("cc:123");
var adjustersOnly = new Set<User>();
var groupUsers = adjusterGroup.MembersNoSystemUsers
adjustersOnly.addAll(groupUsers*.Users)
return adjustersOnly.toArray()
}
You need to change the input type to Range Input (or Range Cell in case you are using List View) where valueRange property calls a method which retrieves users with a specific role.
.pcf file:
<RangeInput
editable="true"
id="userInput"
label=""Adjusters""
value="claim.AssignedUser"
valueRange="UserRoleUtil_Ext.Adjusters"
valueType="entity.User"/>
UserRoleUtil_Ext.gs:
uses gw.api.database.Query
uses gw.api.database.Relop
class UserRoleUtil_Ext {
public static property get Adjusters() : User[] {
var adjusterRole = Query.make(Role).compare(Role#Name, Relop.Equals, "Adjuster").select().AtMostOneRow
// Alternatively, you can retrieve the Role by its public-id, e.g.:
// var roleRetrievedById = Query.make(Role).compare(Role#PublicID, Relop.Equals, "cc:1").select().AtMostOneRow
return adjusterRole.AllUsersArray
}
}

Value does not fall within the expected range - Exception for SharePoint Lookup Field

I am trying to copy data from one list to other list (both lists are on different sites) along with lookup columns. But, I am getting an error for lookup field as:
Value does not fall within the expected range
Code works and data gets copied for other non-lookup fields. I tried every possible way including increasing List View Lookup Threshold and all possible ways of code but still error persists at ExecuteQuery().
Below is my code for lookup field:
if (field is FieldLookup && field.InternalName == "Country")
{
var CountryLookup = (item.FieldValues["Country"] as FieldLookupValue).LookupValue.ToString();
var CountryLookupId = (item.FieldValues["Country"] as FieldLookupValue).LookupId.ToString();
FieldLookupValue flvRDS = new FieldLookupValue();
flvRDS.LookupId = int.Parse(CountryLookupId);
itemToCreate["Country"] = flvRDS;
itemToCreate.Update();
destContext.ExecuteQuery();
}
Help is really appreciated.
I assume item is the new ListItem you're trying to create on your target list.
But you're never in fact reading any value from field here! So basically, you're trying to set your new FieldLookup.LookupId with the item["Country"].LookupId, which should logically be empty at this moment.
Here's a method I use to retrieve a lookup field ListItem from a value, feel free to modify it to fit your need, since I don't know how you want to retrieve it (SPList is an alias for Microsoft.SharePoint.Client.List).
private ListItem GetLookupItem(FieldLookup lookupField, string lookupValue)
{
string mappingField = lookupField.LookupField;
Microsoft.SharePoint.Client.List lookupList = Context.Web.Lists.GetById(new Guid(lookupField.LookupList));
Context.Load(lookupList);
Context.ExecuteQuery();
ListItemCollection libListItems = lookupList.GetItems(CamlQuery.CreateAllItemsQuery());
Context.Load(libListItems, items => items.Include(
itemlookup => itemlookup.Id,
itemlookup => itemlookup[mappingField]));
Context.ExecuteQuery();
foreach (ListItem mappedItem in libListItems)
{
object mappedField = mappedItem[mappingField];
if (mappedField != null && mappedField.ToString().Equals(lookupValue))
return mappedItem;
}
return null;
}
Now that you have the corresponding ListItem, you can set your item.LookupId with its Id:
if (field is FieldLookup && field.InternalName == "Country")
{
FieldLookupValue flvRDS = new FieldLookupValue();
flvRDS.LookupId = GetLookupItem(field as FieldLookup, "France").Id; // here, dunno how you get your country's name
itemToCreate["Country"] = flvRDS;
itemToCreate.Update();
destContext.ExecuteQuery();
}
Feel free to add some more previous code if you want an answer more suited for your specific issue.

How to get all possible values for SPFieldLookup

I have a lookup field in sharepoint which just references another list. I wonder how do I programatically enumerate all possible values for this field?
For example, my lookup field "Actual City" refers list "Cities" and column "Title", I have 3 cities there. In code I would like to get list of all possible values for field "Actual City", smth like (metacode, sorry):
SPFieldLookup f = myList["Actual City"];
Collection availableValues = f.GetAllPossibleValues();
//this should return collection with all cities a user might select for the field
I wrote some code to handle this for my project just the other day. Perhaps it will help.
public static List<SPFieldLookupValue> GetLookupFieldValues(SPList list, string fieldName)
{
var results = new List<SPFieldLookupValue>();
var field = list.Fields.GetField(fieldName);
if (field.Type != SPFieldType.Lookup) throw new SPException(String.Format("The field {0} is not a lookup field.", fieldName));
var lookupField = field as SPFieldLookup;
var lookupList = list.ParentWeb.Lists[Guid.Parse(lookupField.LookupList)];
var query = new SPQuery();
query.Query = String.Format("<OrderBy><FieldRef Name='{0}'/></OrderBy>", lookupField.LookupField);
foreach (SPListItem item in lookupList.GetItems(query))
{
results.Add(new SPFieldLookupValue(item.ID, item[lookupField.LookupField].ToString()));
}
return results;
}
Then to use it, your code would look something like this:
var list = SPContext.Current.Web.Lists["My List"];
var results = GetLookupFieldValues(list, "Actual City");
foreach (SPFieldLookupValue result in results)
{
var value = result.LookupValue;
var id = result.LookupId;
}
I think there is no explicit method returning what you want. But the SPFieldLookup class stores all the info you need to request this information manually: LookupField and LookupList
So you could retrieve the information by getting it form the list you lookup field uses. To make it reusable you could implement it as a Extension Method. So the next time you could really call f.GetAllPossibleValues();.
As I understand you want to query all values that are in use?
If so, you would have to query items where Actual City is not null, query would look something like:
<Where><IsNotNull><FieldRef Name='Actual City'/></IsNotNull></Where>
Then, for each queried item you would
List<SPFieldLookupValue> result = new List<SPFieldLookupValue>(returnedItemCount * 5);
foreach (SPListItem item in queriedItems) {
object lookup = item["Actual City"];
SPFieldLookupValueCollection lookupValues = new SPFIeldLookupValueCollection(
(lookup != null) ? lookup.ToString() : ""
);
foreach (SPFieldLookupValue lookupValue in lookupValues) {
if (!result.Contains(lookupValue)) {
result.Add(lookupValue);
}
}
}
Or you could use HashTable where LookupId would be string and LookupValue would be int id and then check if HashTable.ContainsKey(lookupId)... must be faster to find an integer in hashtable rather than string in list, but the resource intensive part is to probably query all items where that field contains some value and then loop...
If you want to enumerate all possible values, that means you basically want to get all the Title field values from all the items in the Cities list. I don't think there is a method like GetAllPossibleValues() in SharePoint, but you can either just list all the items in Cities and get their titles, if there's just a few, or use a CAML query if there's plenty.

My look up column shows items but when created shows blank values

I have a list named "Projects" which has a number column named "Job Number",
I have attached an ItemAdded event handler to Job Number to increment.
Within the Projects list, I created a look up column named "Original Job" which looks up the value from the column Job Number.
When I click new item, I see the drop down values of all my Job numbers but when I choose one and click create item, there is no value, shows empty.
Here is my code:
SPList lookupList = currentSite.Lists["Projects"];
SPField lookupField = lookupList.Fields["Job Number"];
projectList.Fields.AddLookup("Original Job", lookupList.ID, false);
SPFieldLookup lookup = (SPFieldLookup)projectList.Fields["Original Job"];
lookup.LookupField = lookupField.InternalName;
lookup.Update();
Here is an image
http://pic100.picturetrail.com/VOL783/3746656/21927341/372654494.jpg
Can someone please explain why this occurs?
YOu need to call the Update method of the Item you're itself, not the SPFieldLookup lookup
variable, your code should look like this:
protected override ItemAdded(properties)
{
var item = web.Lists[properties.ListId].GetItemById(properties.ListItemId);
if (item != null)
{
if (item.Fields.ContainsField("Job Number"))
{
// get selectedValue from the original job??
item["Job Number"] = selectedValue;
item.Update();
//or item.SystemUpdate();
}
}
}

Resources