JPA/ JPQL: How to use member-of with an hash-map - jpql

I have problem using the member-of Statement. The problem I think is, that I made a mistake with the elements --> parameter.get("" i + anlass) but I don't know how to do it right.
Are there any other possibilities to ask if a certain element is an #ManyToMany List from another Object?
Here's my Code:
/*My Beans:
#Entity
public class Rezept implements Serializable {
...........
#ManyToMany(mappedBy="rezepten", cascade = {CascadeType.PERSIST})
List<Allergie> allergien = new ArrayList<>();
#ManyToMany(mappedBy="rezepten", cascade = {CascadeType.PERSIST})
List<Anlass> anlässe = new ArrayList<>();
#ManyToMany(mappedBy="rezepten", cascade = {CascadeType.PERSIST})
List<Grundzutat> grundzutaten = new ArrayList<>();*/
//The method is in the RezeptBean
public List<Rezept> searchByFilters(List<Anlass> anlaesse, List<Grundzutat> grundzutaten, List<Allergie> allergien) {
// WHERE-Bedingungen für die Filteroptionen zusammenbauen
String select = "SELECT r FROM Rezept r";
String where = "";
Map<String, Object> parameters = new HashMap<>();
int i = 0;
for (Anlass anlass : anlaesse) {
i++;
parameters.put("" + i, anlass);
if (!where.isEmpty()) {
where += " AND ";
}
//Here I want to see if the element parameters.get("" + i) is member
of r.anlässe
where += ":" + parameters.get("" + i) + " MEMBER OF r.anlässe";
}
for (Grundzutat grundzutat : grundzutaten) {
i++;
parameters.put("" + i, grundzutat);
if (!where.isEmpty()) {
where += " AND ";
}
where += ":" + parameters.get("" + i) + " MEMBER OF r.grundzutaten";
}
for (Allergie allergie : allergien) {
i++;
parameters.put("" + i, allergie);
if (!where.isEmpty()) {
where += " AND ";
}
where += ":" + parameters.get("" + i) + " MEMBER OF r.allergien";
}
// Finalen SELECT-String zusammenbauen und Suche ausführen
if (!where.isEmpty()) {
select += " WHERE " + where;
}
Query query = em.createQuery(select);
for (String key : parameters.keySet()) {
query.setParameter(key, parameters.get(key));
}
return query.getResultList();
}
}
This is the log file:
Warnung: A system exception occurred during an invocation on EJB RezeptBean, method: public java.util.List rezept.ejb.RezeptBean.searchByFilters(java.util.List,java.util.List,java.util.List)
Warnung: javax.ejb.EJBException
at com.sun.ejb.containers.EJBContainerTransactionManager.processSystemException(EJBContainerTransactionManager.java:752)
at com.sun.ejb.containers.EJBContainerTransactionManager.completeNewTx(EJBContainerTransactionManager.java:702)
at com.sun.ejb.containers.EJBContainerTransactionManager.postInvokeTx(EJBContainerTransactionManager.java:507)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4566)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2074)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2044)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:220)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
at com.sun.proxy.$Proxy1243.searchByFilters(Unknown Source)
at rezept.ejb.__EJB31_Generated__RezeptBean__Intf____Bean__.searchByFilters(Unknown Source)
at rezept.web.SuchServlet.doGet(SuchServlet.java:125)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at rezept.web.JavaFilter.doFilter(JavaFilter.java:48)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager:
Exception Description: Syntax error parsing [SELECT r FROM Rezept r WHERE :rezept.jpa.Anlass#2c9e9a75 MEMBER OF r.anlässe AND :rezept.jpa.Grundzutat#3c634785 MEMBER OF r.grundzutaten AND :rezept.jpa.Grundzutat#3c30782 MEMBER OF r.grundzutaten AND :rezept.jpa.Allergie#4f608eda MEMBER OF r.allergien AND :rezept.jpa.Allergie#1482f49f MEMBER OF r.allergien].
[29, 56] The named input parameter ''{0}'' is not following the rules for a Java identifier.
[81, 112] The named input parameter ''{0}'' is not following the rules for a Java identifier.
[142, 172] The named input parameter ''{0}'' is not following the rules for a Java identifier.
[202, 231] The named input parameter ''{0}'' is not following the rules for a Java identifier.
[258, 287] The named input parameter ''{0}'' is not following the rules for a Java identifier.
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1616)
....................
Has somebody an idea what I can do different?

You don't really have to prefix the column name in WHERE clause with a :, it is used only for parameter values.
The query from the stack-trace shows the usage of : in your query:
SELECT r FROM Rezept r
WHERE :rezept.jpa.Anlass#2c9e9a75 MEMBER OF r.anlässe AND
:rezept.jpa.Grundzutat#3c634785 MEMBER OF r.grundzutaten AND
:rezept.jpa.Grundzutat#3c30782 MEMBER OF r.grundzutaten AND
:rezept.jpa.Allergie#4f608eda MEMBER OF r.allergien AND
:rezept.jpa.Allergie#1482f49f MEMBER OF r.allergien
This can be corrected in your Java code as follows (Change the following line to as shown without the : to resolve the issue:
Change this:
where += ":" + parameters.get("" + i) + " MEMBER OF r.anlässe";
to this:
where += parameters.get("" + i) + " MEMBER OF r.anlässe";
Hope this helps #Alina!

Related

Kafka Message Key - byte[] and String Simultaneously

I'm having a very confusing issue with Kafka - specifically trying to obtain the Key of a message.
The key seems to think it's both a String and a byte[]
The following code produces the exception below:
Map<String, Integer> topicCount = new HashMap<>();
topicCount.put(myConsumer.getTopic(), 1);
Map<String, List<KafkaStream<byte[], byte[]>>> consumerStreams = myConsumer.getConsumer().createMessageStreams(topicCount);
List<KafkaStream<byte[], byte[]>> streams = consumerStreams.get(myConsumer.getTopic());
System.out.println("Listening to topic " + myConsumer.getTopic());
for (final KafkaStream stream : streams) {
ConsumerIterator<String, byte[]> it = stream.iterator();
while (it.hasNext()) {
System.out.println("Message received from topic");
MessageAndMetadata<String, byte[]> o = it.next();
Object messageKey = o.key();
System.out.println("messageKey is type: " + messageKey.getClass().getName());
System.out.println("messageKey is type: " + messageKey.getClass().getCanonicalName());
System.out.println("o keyDecoder: " + o.keyDecoder());
System.out.println("Key from message: " + o.key()); //This throws exception - [B cannot be cast to java.lang.String
//System.out.println("Key as String: " + new String(o.key(), StandardCharsets.UTF_8)); //uncomment this compile Exception - no suitable constructor found for String(java.lang.String,java.nio.charset.Charset)
byte[] bytesIn = o.message(); //getting the bytes is fine
System.out.println("MessageAndMetadata: " + o);
///other code cut
}
}
Exception:
Listening to topic MyKafkaTopic
Message received from topic
messageKey is type: [B
messageKey is type: byte[]
o decoder: kafka.serializer.DefaultDecoder#2e0d0acd
[WARNING]
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.codehaus.mojo.exec.ExecJavaMojo$1.run(ExecJavaMojo.java:293)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassCastException: [B cannot be cast to java.lang.String
at com.foo.bar.KafkaCFS.process(KafkaCFS.java:153)
at com.foo.bar.KafkaCFS.run(KafkaCFS.java:63)
at com.foo.bar.App.main(App.java:90)
... 6 more
Maven:
<dependency>
<groupId>org.apache.kafka</groupId>
<artifactId>kafka_2.10</artifactId>
<version>0.9.0.1</version>
</dependency>
If I uncomment the System.out line then I cannot even compile:
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /C:/Dev/main/java/com/foo/bar/KafkaCFS.java:[152,56] no suitable constructor found for String(java.lang.String,java.nio.charset.Charset)
constructor java.lang.String.String(byte[],int) is not applicable
(argument mismatch; java.lang.String cannot be converted to byte[])
How is it that the compiler thinks the Key is a String (which is what I expected it to be) but that runtime it's a byte array?
What can I do to get the Key as a String?
Thanks,
KA.
This did not match! You are declare streams as KafkaStream<byte[], byte[]> and then you expect ConsumerIterator<String, byte[]> it = stream.iterator(); it should be ConsumerIterator<byte[], byte[]> it = stream.iterator(); to match generics. Then you can get o.key() and create a string from it via new String(o.key());
Better off setting KafkaStream generic parameter type is (byte[], byte[]). Try to change code like this:
ConsumerIterator<byte[], byte[]> it = stream.iterator();
while (it.hasNext()) {
String key = new String(it.next().key());
...
}

How to search text of a data table in jsf , row by row?

I have a search text and I have to search the input text in the same page just like we do search in any web page by ctrl+f it will displays all the occurrences of the input text how to do it in jsf+icefaces. My xhtml is
<h:inputText id="searchTextField" size="12" maxlength="10" value="#{editSplitAsgnsBean.searchTextField}">
</h:inputText>
<ice:commandButton styleClass="buttonPurple" value="#{msgs['EditSplitAsgns.Button.searchButton']}" id="searchButton"
actionListener="#{editSplitAsgnsController.searchButton}">
<ace:ajax execute="#this" render="#sortDataTable" />
</ice:commandButton>
in my controller I am doing this but getting NullPointerException
public void searchButton(ActionEvent e) {
searchTextField = editSplitAsgnsBean.getSearchTextField();
if(isNullOrEmpty(searchTextField)) { return; }
if(!validateInput(searchTextField, true, 10)){
popupHandler.displayMessage(getMessageString(EDIT_SPLIT_ASSIGNMENT_SEARCHSTRING_VALIDATION_MESSAGE));
return;
}
resetSearchData();
findMatchedColumn(SEARCH);
}
public void nextButton(ActionEvent e) {
findMatchedColumn(NEXT);
}
private void findMatchedColumn(String action) {
EditSplitAsgnsData searchRow = null;
String search = editSplitAsgnsBean.getSearchTextField();
if (NEXT.equals(action) && lastFoundIndex != -1) {
index++;
if (matchedColumns.size() > index) {
selectColumn = matchedColumns.get(index);
selectCell(getTable(), lastFoundIndex, selectColumn);
return;
}
}
int newFoundIndex = getTable().findRow(search, selectedColumns, lastFoundIndex + 1, DataTable.SearchType.CONTAINS, true);
matchedColumns.clear();
index = 0;
if (SEARCH.equals(action) && newFoundIndex == -1) {
popupHandler.displayMessage(getMessageString(COMMON_NOSORTSCHEME_DATA_MSG, search));
return;
}
if (NEXT.equals(action) && newFoundIndex == -1) {
popupHandler.displayMessage(getMessageString(EDIT_SPLIT_ASSIGNMENT_SEARCHSTRING_VALIDATION_MESSAGE, search));
searchFlag = false;
selectCell(getTable(), lastFoundIndex, selectColumn);
return;
}
searchFlag = true;
getTable().navigateToRow(newFoundIndex);
getTable().setRowIndex(newFoundIndex);
searchRow = (EditSplitAsgnsData) getTable().getRowData();
searchMatches(searchRow, search);
if (!CollectionsUtil.isNullOrEmpty(matchedColumns)) {
selectColumn = matchedColumns.get(index);
}
lastFoundIndex = newFoundIndex;
selectCell(getTable(), lastFoundIndex, selectColumn);
}
private void resetSearchData() {
lastFoundIndex = -1;
selectColumn = -1;
searchFlag = false;
}
Stack Trace
java.lang.NullPointerException
at com.fedex.emea.gss.controller.EditSplitAsgnsController.findMatchedColumn(EditSplitAsgnsController.java:483)
at com.fedex.emea.gss.controller.EditSplitAsgnsController.searchButton(EditSplitAsgnsController.java:464)
at com.fedex.emea.gss.controller.EditSplitAsgnsController$$FastClassByCGLIB$$6f1285ca.invoke(<generated>)
at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:191)
at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:689)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:131)
at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:119)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:622)
at com.fedex.emea.gss.controller.EditSplitAsgnsController$$EnhancerByCGLIB$$6e6697f4.searchButton(<generated>)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.apache.el.parser.AstValue.invoke(AstValue.java:278)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:273)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.event.MethodExpressionActionListener.processAction(MethodExpressionActionListener.java:148)
at javax.faces.event.ActionEvent.processListener(ActionEvent.java:88)
at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:775)
at javax.faces.component.UICommand.broadcast(UICommand.java:300)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:786)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1251)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
I am new to jsf so dont know how to fix the issue
Your problem is in the execute="#this", this means you are only sending the command button in your request but not your Textfield.
In order to fix this, here are possible solutions
execute="#form" will send all the form attributes in the request
execute="searchTextField" will send the searchTextFieldId in the request. This is the best solution. Take care of the path of the "searchFieldId". You need to use the full path
As another advice, I usually use the "listener" attribute of the "ajax" and avoid "actionListener". Theoritically you dont need ajax with commandbutton. commandButton uses already ajax. Hope this helps

JAXB -Unmarshalling with a general URL

I have a method in Java for unmarshalling XML-files with the given URL.
For URL's like "http:// ..." everything works fine, but for URL's like "file://localhost/C:/Users/.../filename.xml" I receive following exception.
I have no idea why he won't accept my "file://localhost/"-URL's.
javax.xml.bind.UnmarshalException
- with linked exception:
[org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.]
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.createUnmarshalException(AbstractUnmarshallerImpl.java:335)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.createUnmarshalException(UnmarshallerImpl.java:563)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:249)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:214)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:157)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:204)
at preferee.data.access.IO_transfer.jaxb.XMLconverter.getItemFromStream(XMLconverter.java:40)
at preferee.data.access.IO_transfer.jaxb.XMLconverter.getItemFromURL(XMLconverter.java:57)
at preferee.data.access.testServer.LocalTestServer.<init>(LocalTestServer.java:42)
at preferee.data.access.testServer.TestProvider.<init>(TestProvider.java:16)
at preferee.data.access.Providers.createTestProvider(Providers.java:29)
at preferee.tests.FakeServerTests.MovieDao_TEST.run(MovieDao_TEST.java:22)
at preferee.tests.FakeServerTests.MovieDao_TEST.main(MovieDao_TEST.java:16)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.createSAXParseException(ErrorHandlerWrapper.java:203)
at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.fatalError(ErrorHandlerWrapper.java:177)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:441)
at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:368)
at com.sun.org.apache.xerces.internal.impl.XMLScanner.reportFatalError(XMLScanner.java:1436)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:999)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:606)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:117)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:510)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:848)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:777)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1213)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:649)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:243)
By the way this is my method-implementation:
Class classObject = ... ;
public T getItemFromURL(String url) throws DataAccessException {
JAXBContext jc = null;
T item = null;
try (InputStream XML_Stream = new URL(url).openStream();)
{
jc = JAXBContext.newInstance(classObject);
item = (T) jc.createUnmarshaller().unmarshal(XML_Stream);
} catch (IOException e) {
throw new DataAccessException("( originele error: " + e.getClass() +" ) " + e.getMessage() + ": Kon Bestand niet ophalen of lezen." );
} catch (JAXBException e) {
throw new DataAccessException(e.getMessage());
}
return item;
}
Your URL for hitting your file system is not correct. It should be like:
file:///c|/path/to/file
Update
Will this "file:///" work on other systems like mac, linux?
You can use a file URL on any OS. Of course the URL needs to match the file layout there (i.e. no C drive in Linux).
And is there any way to convert c:\ ... to c|/ ... / easily?
File file = new File("C:/Users/.../filename.xml");
String url = file.toURI().toURL().toString();

'id' could not be resolved ..?

i am using EF 4.1 and when I use the following code i get an error:
'id' could not be resolved in the current scope or context. Make sure that all referenced variables are in scope, that required schemas are loaded, and that namespaces are referenced correctly. Near simple identifier, line 6, column 1.
c#
foreach (Person Profile in _ProfilesRepository.GetProfiles(filterExpression.ToString(), sortingName, request.SortingOrder.ToString(), request.PageIndex, request.RecordsCount, request.PagesCount.HasValue ? request.PagesCount.Value : 1))
{
//the error happens here when it comes back from the GetProfiles call : (
response.Records.Add(new JqGridRecord(Convert.ToString(Profile.ID), new List<object>()
{
Profile.Name,
Profile.JobTitle,
Profile.Type
}));
}
public IQueryable<Person> GetProfiles(string filterExpression, string sortExpression, string sortDirection, int pageIndex, int pageSize, int pagesCount)
{
if (!String.IsNullOrWhiteSpace(filterExpression))
return db.persons.Where(filterExpression).OrderBy(sortExpression + " " + sortDirection).Skip(pageIndex * pageSize).Take(pageSize);
else
return db.persons.OrderBy(sortExpression + " " + sortDirection).Skip(pageIndex * pageSize).Take(pagesCount * pageSize);
//return db.persons;
}
The message appears when using orderBy("fieldname asc/desc")
db.persons.OrderBy(sortExpression + " " + sortDirection)
When I try to use orderBy using lambda expression it's working normally, no error message.
db.persons.OrderBy(x=>x.FieldName)
Try This, add "it" before your short expression/fieldname :
OrderBy("it."+sortExpression + " " + sortDirection).Skip(pageIndex *
PageSize).Take(pageSize); OrderBy("it."+sortExpression + " " +
sortDirection).Skip(pageIndex * pageSize).Take(pagesCount * pageSize);

SPListItemCollection.GetDataTable() doesn't return all columns?

I ran into an issue when using the GetDataTable() method. I'm trying to return the default SharePoint column "FileRef" in my results to use. I include it in my SPQuery.ViewFields
Query:
<Where><IsNotNull><FieldRef Name='FileRef'/></IsNotNull></Where>
ViewFields:
<FieldRef Name='Title' /><FieldRef Name='Category' /><FieldRef Name='FileRef' /><FieldRef Name='ID' /><FieldRef Name='Created' />
I can even see it returned in the items.XML but when I call GetDataTable() it is not put in the datatable.
SPListItemCollection items = list.GetItems(spq);
dtItems = items.GetDataTable();
Why isn't GetDataTable working correctly? Am I going to have to write my own conversion method?
You can use this code:Improving SharePoint's SPListItemCollection GetDataTable(), let's get all the fields I need
I'd recommend you a better solution
As SPListItemCollection has Xml proeprty that stores all item data, you can use this XSLT to get data in normal XML format and then create DataSet from XML.
This Idea can be converted to handy extension function:
using System.Data;
using System.Xml;
using System.Xml.Xsl;
using Microsoft.SharePoint;
namespace Balticovo.SharePoint
{
public static partial class Extensions
{
static string sFromRowsetToRegularXmlXslt =
"<xsl:stylesheet version=\"1.0\" " +
"xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" " +
"xmlns:s=\"uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882\" " +
"xmlns:z=\"#RowsetSchema\">" +
"<s:Schema id=\"RowsetSchema\"/>" +
"<xsl:output method=\"xml\" omit-xml-declaration=\"yes\" />" +
"<xsl:template match=\"/\">" +
"<xsl:text disable-output-escaping=\"yes\"><rows></xsl:text>" +
"<xsl:apply-templates select=\"//z:row\"/>" +
"<xsl:text disable-output-escaping=\"yes\"></rows></xsl:text>" +
"</xsl:template>" +
"<xsl:template match=\"z:row\">" +
"<xsl:text disable-output-escaping=\"yes\"><row></xsl:text>" +
"<xsl:apply-templates select=\"#*\"/>" +
"<xsl:text disable-output-escaping=\"yes\"></row></xsl:text>" +
"</xsl:template>" +
"<xsl:template match=\"#*\">" +
"<xsl:text disable-output-escaping=\"yes\"><</xsl:text>" +
"<xsl:value-of select=\"substring-after(name(), 'ows_')\"/>" +
"<xsl:text disable-output-escaping=\"yes\">></xsl:text>" +
"<xsl:value-of select=\".\"/>" +
"<xsl:text disable-output-escaping=\"yes\"></</xsl:text>" +
"<xsl:value-of select=\"substring-after(name(), 'ows_')\"/>" +
"<xsl:text disable-output-escaping=\"yes\">></xsl:text>" +
"</xsl:template>" +
"</xsl:stylesheet>";
public static DataTable GetFullDataTable(this SPListItemCollection itemCollection)
{
DataSet ds = new DataSet();
string xmlData = ConvertZRowToRegularXml(itemCollection.Xml);
if (string.IsNullOrEmpty(xmlData))
return null;
using (System.IO.StringReader sr = new System.IO.StringReader(xmlData))
{
ds.ReadXml(sr, XmlReadMode.Auto);
if (ds.Tables.Count == 0)
return null;
return ds.Tables[0];
}
}
static string ConvertZRowToRegularXml(string zRowData)
{
XslCompiledTransform transform = new XslCompiledTransform();
XmlDocument tidyXsl = new XmlDocument();
try
{
//Transformer
tidyXsl.LoadXml(Extensions.sFromRowsetToRegularXmlXslt);
transform.Load(tidyXsl);
//output (result) writers
using (System.IO.StringWriter sw = new System.IO.StringWriter())
{
using (XmlTextWriter tw = new XmlTextWriter(sw))
{
//Source (input) readers
using (System.IO.StringReader srZRow = new System.IO.StringReader(zRowData))
{
using (XmlTextReader xtrZRow = new XmlTextReader(srZRow))
{
//Transform
transform.Transform(xtrZRow, null, tw);
return sw.ToString();
}
}
}
}
}
catch
{
return null;
}
}
}
}
By the way, using this method, you will get, if needed, file attachment URL's (SPQuery.IncludeAttachmentUrls = true) not just TRUE/FALSE values as you would get it by using previously mentioned method.
Regarding Janis' answer - I'd remove the bits that do a substring on the ows_ and attempt to remove it, just use:-
"<xsl:value-of select=\"name()\"/>" +
because SP2010 now includes fields such as ETag which don't being with "ows_" and the solution fails. Very good solution otherwise.

Resources