Get value from SPFieldUser with AllowMultipleValues fails only in a Timer Job - sharepoint-2010

This one is weird.
I'm executing this code in a Timer Job in SharePoint 2010 ...
...
// Get the field by it's internal name
SPField field = item.Fields.GetFieldByInternalName(fieldInternalName);
if (field != null)
{
SPFieldUser userField = (SPFieldUser)field;
object value = null;
if (userField.AllowMultipleValues)
{
// Bug when getting field value in a timer job? Throws an ArgumentException
users = new SPFieldUserValueCollection(item.ParentList.ParentWeb, item[userField.Id].ToString());
}
else
{
// Get the value from the field, no exception
value = item[userField.Id];
}
}
...
This code works perfectly when run in a simple ConsoleApplication but when run in the context of a Timer Job in SharePoint 2010 it throws an ArgumentException in the line ...
users = new SPFieldUserValueCollection(item.ParentList.ParentWeb, item[userField.Id].ToString());
I've tried many variations to retreive a value from a SPFieldUser but all fail only when a Timer Job is executing it and the field has AllowMultipleValues property set to TRUE.
I have tried debugging with Reflector and it seems that the exception is being thrown here in SPListItem ...
public object this[Guid fieldId]
{
get
{
SPField fld = this.Fields[fieldId];
if (fld == null)
{
throw new ArgumentException();
}
return this.GetValue(fld, -1, false);
}
...
And this here would be the exception stack trace...
System.ArgumentException was caught
Message=Value does not fall within the expected range.
Source=Microsoft.SharePoint
StackTrace:
at Microsoft.SharePoint.SPFieldMap.GetColumnNumber(String strFieldName, Boolean bThrow)
at Microsoft.SharePoint.SPListItemCollection.GetColumnNumber(String groupName, Boolean bThrowException)
at Microsoft.SharePoint.SPListItemCollection.GetRawValue(String fieldname, Int32 iIndex, Boolean bThrow)
at Microsoft.SharePoint.SPListItem.GetValue(SPField fld, Int32 columnNumber, Boolean bRaw, Boolean bThrowException)
at Microsoft.SharePoint.SPListItem.get_Item(Guid fieldId)
at FOCAL.Point.Applications.Audits.AuditUtility.GetPeopleFromField(SPListItem item, String fieldInternalName)
Sighh... any thoughts?

This generally means that you have requested too many lookup fields in a single SPQuery which would cause too many self-joins of the true-lookup-table in the content database unless SharePoint Foundation throttled resources. There is a threshold setting that is at 8 lookups per query for ordinary users. Make sure your query only returns the necessary lookup or person/group fields. If you can't decrease the usage, then consider altering the threshold setting.

Related

Index was out of range exception when attempting to access Worksheets object

I have an .XLSX created by a 3rd party. I can read it in Excel just fine, however if I try to read it with EPPlus, I get the following exception:
Index was out of range. Must be non-negative and less than the size of the collection.
Parameter name: index
at System.ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource)
at OfficeOpenXml.Style.ExcelStyle..ctor(ExcelStyles styles, ChangedEventHandler ChangedEvent, Int32 positionID, String Address, Int32 xfsId)
at OfficeOpenXml.Style.XmlAccess.ExcelNamedStyleXml..ctor(XmlNamespaceManager NameSpaceManager, XmlNode topNode, ExcelStyles styles)
at OfficeOpenXml.ExcelStyles.LoadFromDocument()
at OfficeOpenXml.ExcelStyles..ctor(XmlNamespaceManager NameSpaceManager, XmlDocument xml, ExcelWorkbook wb)
at OfficeOpenXml.ExcelWorkbook.get_Styles()
at OfficeOpenXml.ExcelWorkbook.get_MaxFontWidth()
at OfficeOpenXml.ExcelWorksheet.get_DefaultColWidth()
at OfficeOpenXml.ExcelWorksheet.LoadColumns(XmlReader xr)
at OfficeOpenXml.ExcelWorksheet.CreateXml()
at OfficeOpenXml.ExcelWorksheet..ctor(XmlNamespaceManager ns, ExcelPackage excelPackage, String relID, Uri uriWorksheet, String sheetName, Int32 sheetID, Int32 positionID, eWorkSheetHidden hide)
at OfficeOpenXml.ExcelWorksheets..ctor(ExcelPackage pck, XmlNamespaceManager nsm, XmlNode topNode)
at OfficeOpenXml.ExcelWorkbook.get_Worksheets()
If I open the file in Excel and then save it as a new file, EPPlus can read the file just fine. Obviously, this is not a solution that is reasonable for the end users of my system.
I can send the file to the developers if they need, or I can provide more diagnostic information if needed and available.
I'm going to check in with the developers of the other app to try to figure out what API they are using to generate the .XLSX.
code:
using (var package = new ExcelPackage(importEquipmentFile.InputStream))
{
foreach (var ws in package.Workbook.Worksheets.Where(ws => ws.Hidden == eWorkSheetHidden.Visible))
...
and this simplified blows up too:
using (var package = new ExcelPackage(importEquipmentFile.InputStream))
{
foreach (var ws in package.Workbook.Worksheets)
...
Here's the problem. In the code below
positionID = -1 and _styles.CellStyleXfs list is empty, so the "else" gets called
internal ExcelStyle(ExcelStyles styles, OfficeOpenXml.XmlHelper.ChangedEventHandler ChangedEvent, int positionID, string Address, int xfsId) :
base(styles, ChangedEvent, positionID, Address)
{
Index = xfsId;
ExcelXfs xfs;
if (positionID > -1)
{
xfs = _styles.CellXfs[xfsId];
}
else
{
xfs = _styles.CellStyleXfs[xfsId];
}
and that throws an exception because the code that's called can't handle an empty list.
public T this[int PositionID]
{
get
{
return _list[PositionID]; // <<<--- this blows up because _list has no members
}
}
I tweaked the code to be this, and it worked OK, but I'm not sure of the best way to deal with that list being empty:
if (positionID > -1 || _styles.CellStyleXfs.Count == 0)

ImmutablePropertyException periodically when changing enum field's value via Rational Team Concert API

Hitting this issue with changing certain enumeration-based fields in my new RTC work item for a RTC API tool I'm working on.
Basically, I get an ImmutablePropertyException the first time I change the field, but the next time it works without an exception.
Want to get rid of the exceptions. I'm using a value RTC is actually returning to me as a valid enum value for the field.
Assigning RTC work item field: odc.impact a field value of ->
Integrity [odc.impact.literal.l4]
EXCEPTION: Could not assign value,
even though it was found in the enumeration list: [Unassigned,
Installability, Standards, Integrity]
com.ibm.team.repository.common.internal.ImmutablePropertyException at
com.ibm.team.repository.common.internal.util.ItemUtil$ProtectAdapter.notifyChanged(ItemUtil.java:2070)
at
org.eclipse.emf.common.notify.impl.BasicNotifierImpl.eNotify(BasicNotifierImpl.java:380)
at
com.ibm.team.repository.common.model.impl.StringExtensionEntryImpl.setTypedValue(StringExtensionEntryImpl.java:178)
at
com.ibm.team.repository.common.model.impl.StringExtensionEntryImpl.setValue(StringExtensionEntryImpl.java:360)
at org.eclipse.emf.common.util.BasicEMap.putEntry(BasicEMap.java:303)
at org.eclipse.emf.common.util.BasicEMap.put(BasicEMap.java:584) at
org.eclipse.emf.common.util.BasicEMap$DelegatingMap.put(BasicEMap.java:799)
at
com.ibm.team.repository.common.model.impl.ItemImpl.setStringExtension(ItemImpl.java:1228)
at
com.ibm.team.workitem.common.internal.model.impl.WorkItemImpl.setEnumeration(WorkItemImpl.java:3779)
at
com.ibm.team.workitem.common.internal.model.impl.WorkItemImpl.setValue(WorkItemImpl.java:2915)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:95)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:56)
at java.lang.reflect.Method.invoke(Method.java:620) at
com.ibm.team.repository.common.internal.util.ItemStore$ItemInvocationHandler.invoke(ItemStore.java:597)
at com.sun.proxy.$Proxy18.setValue(Unknown Source) at
com.rtc.vda.WorkItemInitialization.setAttributeValueEx(WorkItemInitialization.java:237)
at
com.rtc.vda.WorkItemInitialization.setAttributeValue(WorkItemInitialization.java:210)
at
com.rtc.vda.WorkItemInitialization.execute(WorkItemInitialization.java:186)
at
com.ibm.team.workitem.client.WorkItemOperation.execute(WorkItemOperation.java:85)
at
com.ibm.team.workitem.client.WorkItemOperation.doRun(WorkItemOperation.java:272)
at
com.ibm.team.workitem.client.WorkItemOperation.run(WorkItemOperation.java:242)
at
com.ibm.team.workitem.client.WorkItemOperation.run(WorkItemOperation.java:189)
at com.rtc.vda.RTCUtilities.createWorkItem(RTCUtilities.java:191) at
com.rtc.vda.RTCMain.main(RTCMain.java:178)
Assigning: odc.impact -> Integrity [odc.impact.literal.l4]
This is the code snippet to set the enum value:
public boolean setAttributeValueEx (IWorkItem w, String attributeKey, String valueName) {
// (REO) Get the attribute
IAttribute a = customAttributesMap.get(attributeKey);
// (REO) Buffer of valid values for error reporting
StringBuffer b = new StringBuffer();
try {
// (REO) Get the enumeration for this attribute from the repository (DO NOT CACHE IT OR YOU WILL HAVE PROBLEMS)
IWorkItemClient workItemClient = (IWorkItemClient) rtcParameters.getTeamRepository().getClientLibrary(IWorkItemClient.class);
IEnumeration<? extends ILiteral> rtcAttrEnumeration = workItemClient.resolveEnumeration(a, curMonitor);
// (REO) Find an enum value that matches this string and assign it
for (ILiteral literal : rtcAttrEnumeration.getEnumerationLiterals()) {
String vName = literal.getName();
String vId = literal.getIdentifier2().getStringIdentifier();
b.append(",");
b.append(vName);
if (valueName.equalsIgnoreCase(vName)) {
String msg2 = "Assigning: " + a.getIdentifier() + " -> " + vName + " [" + vId + "]";
RTCMain.out(msg2);
w.setValue(a, literal.getIdentifier2()); // (REO) SOURCE OF PERIODIC EXCEPTION
return true;
}
}
} catch (Exception e) {
RTCMain.out("EXCEPTION: Could not assign value, even though it was found in the enumeration list:\n\t[" + b + "]");
e.printStackTrace();
RTCMain.out("");
return false;
}
RTCMain.out("VALUE NOT FOUND: Valid values are:" + b);
return false;
}
Anyone know why I'm getting the periodic ImmutablePropertyException for only some of the fields, and why it goes away on the second call?
Thanks!
You just need to use the workingCopy.getWorkItem() object passed in to the execute() call rather than a cached version in a member variable. The attributes on the workingCopy object are not immutable and work fine.
public class WorkItemCreator extends WorkItemOperation {
...
#Override
protected void execute(WorkItemWorkingCopy workingCopy, IProgressMonitor monitor) throws TeamRepositoryException {
IWorkItem newWorkItem = workingCopy.getWorkItem();
// Set attribute values on newWorkItem to avoid ImmutablePropertyExceptions

Value does not fall within the expected range in SharePoint 2010

I am doing below things,
On Feature Activation, I'm creating a new list with 1 sample row in it.
I'm using our internal API to create a custom list which uses FieldRef.
Sytax is like, FieldRef(string staticName, string displayName, SPFieldType, ... )
And I have created a column like
public static FieldRef SalesPerson = new FieldRef("SalesPersonName", "Person Name", SPFieldType.Text);
In my web part, I'm fetching this list's items.
SPQuery query = new SPQuery();
query.ViewFields = string.Format("
IList returnlist = null;
SPList spList = spWeb.Lists.TryGetList(ListName);
if (spList != null)
{
SPListItemCollection listitems = spList.GetItems(query);
returnlist = new List(listitems.Count); //This Gives Correct Number Of Count
foreach (SPListItem item in listitems)
{
returnlist.Add(new MyClass()
{
_SalesPersonName = item[FIELDS.SalesPerson.DisplayName].ToString();
}
}
}
And This Gives Below Error :
Server Error in '/' Application.
Value does not fall within the expected range.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentException: Value does not fall within the expected range.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Strange "Expected invocation on the mock at least once, but was never performed" error when I am setting up the Mock

I'm getting this error from Moq via NUnit, and it doesn't make much in the way of sense to me.
"Expected invocation on the mock at least once, but was never performed: x => x.DeleteItem(.$VB$Local_item)"
"at Moq.Mock.ThrowVerifyException(MethodCall expected, IEnumerable1 setups, IEnumerable1 actualCalls, Expression expression, Times times, Int32 callCount)
at Moq.Mock.VerifyCalls(Interceptor targetInterceptor, MethodCall expected, Expression expression, Times times)
at Moq.Mock.Verify[T](Mock mock, Expression1 expression, Times times, String failMessage)
at Moq.Mock1.Verify(Expression`1 expression)
at PeekABookEditor.UnitTests.ItemBrowsing.Can_Delete_Item() in C:\Projects\MyProject\MyProject.UnitTests\Tests\ItemBrowsing.vb:line 167"
Very similar code works well in C#, so the error might be minor and syntactical on my part.
Here's my code:
<Test()> _
Public Sub Can_Delete_Item()
'Arrange: Given a repository containing some item...
Dim mockRepository = New Mock(Of IItemsRepository)()
Dim item As New Item With {.ItemID = "24", .Title = "i24"}
mockRepository.Setup(Function(x) x.Items).Returns(New Item() {item}.AsQueryable())
'Act ... when the user tries to delete that product
Dim controller = New ItemsController(mockRepository.Object)
Dim result = controller.Delete(24)
'Assert ... then it's deleted, and the user sees a confirmation
mockRepository.Verify(Sub(x) x.DeleteItem(item))
result.ShouldBeRedirectionTo(New With {Key .action = "List"})
Assert.AreEqual(DirectCast(controller.TempData("message"), String), "i24 was deleted")
End Sub
The guilty line appears to be "mockRepository.Verify(Sub(x) x.DeleteItem(item))"
Any thoughts on how to fix this?
Working C# code isn't the exact same, but here it is:
[Test]
public void Can_Delete_Product()
{
// Arrange: Given a repository containing some product...
var mockRepository = new Mock<IProductsRepository>();
var product = new Product { ProductID = 24, Name = "P24"};
mockRepository.Setup(x => x.Products).Returns(
new[] { product }.AsQueryable()
);
// Act: ... when the user tries to delete that product
var controller = new AdminController(mockRepository.Object);
var result = controller.Delete(24);
// Assert: ... then it's deleted, and the user sees a confirmation
mockRepository.Verify(x => x.DeleteProduct(product));
result.ShouldBeRedirectionTo(new { action = "Index" });
controller.TempData["message"].ShouldEqual("P24 was deleted");
}
In your VB test method, you create Item with a string ItemID = "24", but you call the controller.Delete method with an integer value of 24.
Check your controller code and see if the type discrepancy results in the item not being identified correctly, so either DeleteItem is not called at all, or is called with a different Item.

figuring out reason for maxClauseCount is set to 1024 error

I've two sets of search indexes.
TestIndex (used in our test environment) and ProdIndex(used in PRODUCTION environment).
Lucene search query: +date:[20090410184806 TO 20091007184806] works fine for test index but gives this error message for Prod index.
"maxClauseCount is set to 1024"
If I execute following line just before executing search query, then I do not get this error.
BooleanQuery.SetMaxClauseCount(Int16.MaxValue);
searcher.Search(myQuery, collector);
Am I missing something here? Why am not getting this error in test index?The schema for two indexes are same.They only differ wrt to number of records/data.PROD index has got higher number of records(around 1300) than those in test one (around 950).
The range query essentially gets transformed to a boolean query with one clause for every possible value, ORed together.
For example, the query +price:[10 to 13] is tranformed to a boolean query
+(price:10 price:11 price:12 price:13)
assuming all the values 10-13 exist in the index.
I suppose, all of your 1300 values fall in the range you have given. So, boolean query has 1300 clauses, which is higher than the default value of 1024. In the test index, the limit of 1024 is not reached as there are only 950 values.
I had the same problem. My solution was to catch BooleanQuery.TooManyClauses and dynamically increase maxClauseCount.
Here is some code that is similar to what I have in production.
private static Hits searchIndex(Searcher searcher, Query query) throws IOException
{
boolean retry = true;
while (retry)
{
try
{
retry = false;
Hits myHits = searcher.search(query);
return myHits;
}
catch (BooleanQuery.TooManyClauses e)
{
// Double the number of boolean queries allowed.
// The default is in org.apache.lucene.search.BooleanQuery and is 1024.
String defaultQueries = Integer.toString(BooleanQuery.getMaxClauseCount());
int oldQueries = Integer.parseInt(System.getProperty("org.apache.lucene.maxClauseCount", defaultQueries));
int newQueries = oldQueries * 2;
log.error("Too many hits for query: " + oldQueries + ". Increasing to " + newQueries, e);
System.setProperty("org.apache.lucene.maxClauseCount", Integer.toString(newQueries));
BooleanQuery.setMaxClauseCount(newQueries);
retry = true;
}
}
}
I had this same issue in C# code running with the Sitecore web content management system. I used Randy's answer above, but was not able to use the System get and set property functionality. Instead I retrieved the current count, incremented it, and set it back. Worked great!
catch (BooleanQuery.TooManyClauses e)
{
// Increment the number of boolean queries allowed.
// The default is 1024.
var currMaxClause = BooleanQuery.GetMaxClauseCount();
var newMaxClause = currMaxClause + 1024;
BooleanQuery.SetMaxClauseCount(newMaxClause);
retry = true;
}
Add This Code
#using Lucene.Net.Search;
#BooleanQuery.SetMaxClauseCount(2048);
Just put, BooleanQuery.setMaxClauseCount( Integer.MAX_VALUE );and that's it.