SharePoint, List.Items and List.GetItems(Query) and Linq - linq

Following on from suggestions, I am trying to use List.GetItems(Query) to retrieve my initial data subset rather than the entire list contents via List.Items. However, whereas List.Items.Cast() results in a usable IEnumerable for Linq, List.GetItems(Query).Cast() does not.
Working Code:
IEnumerable<SPListItem> results = SPContext.Current.Web.Lists[ListName].Items.Cast<SPListItem>().Where(item => item["Date"] != null).Where(item => DateTime.Parse(item["Date"].ToString()) >= StartDate).Where(item => DateTime.Parse(item["Date"].ToString()) <= EndDate);
MessageLine = results.Count().ToString();
Non-working Code:
string SPStartDate = SPUtility.CreateISO8601DateTimeFromSystemDateTime(this.StartDate);
string SPEndDate = SPUtility.CreateISO8601DateTimeFromSystemDateTime(this.EndDate);
SPQuery MyQuery = new SPQuery();
MyQuery.Query = "<Where><And><And><Geq><FieldRef Name='Date'/><Value Type='DateTime'>" + SPStartDate + "</Value></Geq><Leq><FieldRef Name='Date'/><Value Type='DateTime'>" + SPEndDate + "</Value></Leq></And></Where>";
IEnumerable<SPListItem> results = SPContext.Current.Web.Lists[ListName].GetItems(MyQuery).Cast<SPListItem>();
MessageLine = results.Count().ToString();
The List.GetItems(Query).Cast() method produces the following Exception on the .Count() line:
Microsoft.SharePoint.SPException:
Cannot complete this action. Please
try again. --->
System.Runtime.InteropServices.COMException
(0x80004005): Cannot complete this
action. Please try again. at
Microsoft.SharePoint.Library.SPRequestInternalClass.GetListItemDataWithCallback(String
bstrUrl, String bstrListName, String
bstrViewName, String bstrViewXml,
SAFEARRAYFLAGS fSafeArrayFlags,
ISP2DSafeArrayWriter pSACallback,
ISPDataCallback pPagingCallback,
ISPDataCallback pSchemaCallback) at
Microsoft.SharePoint.Library.SPRequest.GetListItemDataWithCallback(String
bstrUrl, String bstrListName, String
bstrViewName, String bstrViewXml,
SAFEARRAYFLAGS fSafeArrayFlags,
ISP2DSafeArrayWriter pSACallback,
ISPDataCallback pPagingCallback,
ISPDataCallback pSchemaCallback) ---
End of inner exception stack trace ---
at
Microsoft.SharePoint.Library.SPRequest.GetListItemDataWithCallback(String
bstrUrl, String bstrListName, String
bstrViewName, String bstrViewXml,
SAFEARRAYFLAGS fSafeArrayFlags,
ISP2DSafeArrayWriter pSACallback,
ISPDataCallback pPagingCallback,
ISPDataCallback pSchemaCallback) at
Microsoft.SharePoint.SPListItemCollection.EnsureListItemsData()
at
Microsoft.SharePoint.SPListItemCollection.Undirty()
at
Microsoft.SharePoint.SPBaseCollection.System.Collections.IEnumerable.GetEnumerator()
at
System.Linq.Enumerable.d__aa1.MoveNext()
at
System.Linq.Enumerable.Count[TSource](IEnumerable1
source) at
Test.GetTransactionsInPeriod() at
Test.CreateChildControls()
Can anyone suggest anything?

From the error message it looks like the CAML Query is wrong. You may want to run it through something like U2U's CAML Query Builder to double check. The error message is thrown by SharePoint before the requested casts. Glancing over it, I think you have an extra <And> at the beginning (<Where><And><And>)
By the way: Don't use SPWeb.Lists[Name]. This will load every list in the SPWeb (including Metadata), which is rather resource intensive. One of the SPWeb.GetList or SPWeb.Lists.GetList methods is better.

Related

PowerQuery: Getting error info when it's too late to `try`?

Short Version
In PowerQuery, when the error occurs before I'm able to use try, how do I catch an error and get the reason and message strings?
Long Version
In PowerQuery (using Excel if that matters),
OleDb.DataSource(
MyConnectionString,
[Query="SELECT * FROM NonExistingTable"]
)
returns an error. Great. I want that because I'm trying to make a quick and dirty tool that grabs data from multiple tables, but some people don't have access to all tables and who knows what else will happen in the future. However, I want to handle that error so it degrades gracefully, preferably presenting an explanation to the user based on the info within the error.
Therefore, I attempted error handling with try, like so:
try OleDb.DataSource(
MyConnectionString,
[Query="SELECT * FROM NonExistingTable"]
)
and I had expected it to return something like
[
HasError = true,
Error = [
Reason = "OLE DB",
Message = "Invalid object name: 'NonExistingTable'.",
Details = ...
]
]
but instead, what's returned is
[
HasError = false,
Value = Error
]
where Error is an error object containing the information I want.
I had then tried to make a workaround with something like
let
tryRecord = try OleDb.DataSource(MyConnectionString, [Query="SELECT * FROM NonExistingTable"]),
ret = if (tryRecord[HasError]) then
// It's an error
tryRecord
else try
// If Value.Type() doesn't throw an error then tryRecord[Value] isn't an error, so return it.
(if Value.Type(tryRecord[Value]) = null then null else tryRecord)
otherwise
// tryRecord[Value] contains an error!
try error tryRecord[Value]
in
ret
but try error tryRecord[Value] is not unpacking the error object within tryRecord[Value] like I had hoped.
How do I get the reason and message strings from an error object?

Can't figure out serialization error in Elasticsearch Python API

My code is displayed below.
client = Elasticsearch(url, http_auth = (username, password), verify_certs = False, read_timeout=50, terminate_after=25000)
examplename = 'GEOS.fp.asm.inst1_2d_smp_Nx.20180508_1700.V01.nc4'
s = Search(using = client, index = [set_index]).source(['metadata.Filename'])\
.query('match', Filename={examplename})
total = s.count()
The error message is:
elasticsearch.exceptions.SerializationError: ({'query': {'match': {'Filename': set(['GEOS.fp.asm.inst1_2d_smp_Nx.20180508_1700.V01.nc4'])}}}, TypeError("Unable to serialize set(['GEOS.fp.asm.inst1_2d_smp_Nx.20180508_1700.V01.nc4']) (type: <type 'set'>)",))
In general, I don't need my search term to match the whole document. So for example if the document is named GEOS.fp.asm.inst1_2d_smp_Nx.20180508_1700.V01.nc4, I want that document to be returned if I query for 20180508.
in .query('match', Filename={examplename}) you are passing in a set which is not json serializable. I believe it should have been just .query('match', Filename=examplename). Hope this helps!

Linq to entities giving error when generic repository is used with List<T> object

In my ASP.NET Web API project, I am trying to use the generic repositories with the List objects under one of the methods. But it is throwing exception
Exception thrown: 'System.Data.SqlClient.SqlException' in System.Data.dll
System.Data.Entity.Core.EntityCommandExecutionException: Calling 'Read' when the data reader is closed is not a valid operation. --->
System.Data.SqlClient.SqlException: Execution Timeout Expired. The
timeout period elapsed prior to completion of the operation or the
server is not responding. ---> System.ComponentModel.Win32Exception:
The wait operation timed out
lstFinalResult object contains few rows. partnerRepo is a generic repo and will have data at the later stage, i suppose.
Please advise, where am i making the mistake. Can we mix the List with generic repository objects in the linq query ?
Here is the linq code :-
List<UserDocumentResult> lstFinalResult = new List<UserDocumentResult>();
foreach (DocumentMapping dm in lstMappings)
{
lstFinalResult.Add(new UserDocumentResult { PID = dm.PartnerID,
DocMappingID = dm.DocumentMappingID,
EntityType = "",
Name = ""
});
}
var partnerRepo = _docRepository.PtGenericRepo.Get();
var entityCodesRepo = _docRepository.EntityCodeGenericRepo.Get();
---While debugging, I am getting error in the below code only.
var qualifiedPartnerSet = (from tmp in lstFinalResult
join px in partnerRepo on tmp.PID equals px.PartnerID
join ecx in entityCodesRepo on px.EntityCodeID equals ecx.EntityCodeID
select new UserDocumentResult
{
PID = px.PartnerID,
MappingID = tmp.MappingID,
EntityType = ecx.DisLabel.Trim(),
Name = px.NameLine1.Trim() + px.NameLine2.Trim(),
}).ToList();

How to pass symbol as parameter of post request in ruby?

This code work well
Geokit::default_units = :miles #:kms, :nms, :meters
But this code make errors
puts params[:unit] # miles
Geokit::default_units = params[:unit] #:miles, :kms, :nms, :meters
What is wrong with this?
That's because all that goes through the params is an string, if you want a symbol, then consider using .to_sym:
params = { unit: 'miles' }
p params[:unit].class # String
p params[:unit].to_sym.class # Symbol
have you confirmed that params[:unit] is actually a symbol, and not a string?
Geokit::default_units = params[:unit].to_sym
If the above solves your problem, then you didn't have a symbol in there to start with (likely, if params has been read from an HTTP request)

NullPointerException using DOMParser and selectSingleNode

String url = "http://www.amazon.com/Classic-Starts-Great-Expectations/dp/1402766459/ref=sr_1_1?s=books&ie=UTF8&qid=1294405505&sr=1-1";
DOMParser parser = new DOMParser();
parser.parse(url);
Document document = parser.getDocument();
DOMReader reader = new DOMReader();
org.dom4j.Document nhddoc = reader.read(document);
//book price
Node price = nhddoc.selectSingleNode("/HTML/BODY/DIV[2]/FORM/TABLE[3]/TBODY/TR/TD/DIV/TABLE/TBODY/TR/TD[2]/B");
System.out.println(price.getText().toString().trim());
the error i get is :
Exception in thread "main" java.lang.NullPointerException
at nekodom4j.Main.main(Main.java:44)
does the null pointer exception means no node was selected ?
I have no particular idea what the cause of the problem might be, but the first thing I would do to debug it would be to walk the path one level at a time and see where it fails to return what you expect.
Node html = nhddoc.selectSingleNode("/HTML");
/* maybe print out some information about the Node just acquired */
Node body = html.selectSingleNode("/BODY");
etc...

Resources