Returning empty IQueryable<> - entity-framework

I have this method that tries to get a list of things:
private static IQueryable<Thing> GetThings(int thingsType)
{
try
{
return from thing in entities.thing.Include("thingStuff")
select thing;
}
catch (Exception exception)
{
return new EnumerableQuery<Thing>(?????);
}
}
}
I want to return an empty IQueryable if I can't for whatever reason get the query to run. I don't want to return NULL because that could break the calling code. Is it possible or am I going totally wrong about this?

These answers are good and do work, however I have always felt using Empty and not creating a new List is cleaner:
Enumerable.Empty<Thing>().AsQueryable();

Try the following:
private static IQueryable<Thing> GetThings(int thingsType)
{
IQueryable<Thing> things = new List<Thing>().AsQueryable();
try
{
things = from thing in entities.thing.Include("thingStuff")
select thing;
return things;
}
catch (Exception exception)
{
return things;
}
}

I would add block finally {} and put my return type in that code.
This will take care of the issue by returning the type that your application expects.
private static IQueryable<T> GetThings(int thingsType)
{
IQueryable<T> list = new List<Thing>().AsQueryable();
try
{
list = from thing in entities.thing.Include("thingStuff")
select t;
}
catch (Exception exception)
{
// handle exception here;
}
finally {
return list;
}
}
}

Returning empty IQueryable<>
DbSet.Take(0)

I think this would be tidier:
private static IQueryable<T> GetThings(int thingsType)
{
try
{
return from thing in entities.thing.Include("thingStuff")
select t;
}
catch (Exception exception)
{
// Exception handling code goes here
return new List<Thing>().AsQueryable();
}
}

Related

ResponseEntity in RestController

i need your help.
I have method for creating entity in RestController, but i can not understand how to use ResponseEntity. I just return ResponseEntity.ok, but it's not correct i think.
I got advice to wrap it into object with data and success fields, but i didn't get it.
#PostMapping()
public ResponseEntity<String> create(#Valid #RequestBody Course course) {
try {
courseService.add(course);
} catch (ServiceException e) {
log.error("Can not create course", e);
}
return ResponseEntity.ok("Course is valid");
}
#PutMapping("/{id}")
public ResponseEntity<String> update(#Valid #RequestBody Course course, #PathVariable("id") int id)
throws ServiceException {
courseService.update(id, course);
return ResponseEntity.ok("Course is valid");
}
You can try this: ResponseEntity<>("Course is valid", HttpStatus.OK)
For more details and guide : https://www.baeldung.com/spring-response-entity
I did something like this:
return new ResponseEntity<>(course, HttpStatus.CREATED);

Why do I never get the ObjectDisposedException?

My test method looks like this:
private static System.Timers.Timer _myTimer;
static void Main(string[] args)
{
using (_myTimer = new System.Timers.Timer(1000))
{
_myTimer.Elapsed += (o, e) => Console.WriteLine($"timer elapsed");
_myTimer.AutoReset = true;
_myTimer.Enabled = true;
Thread.Sleep(4000); // let the timer fire a couple of times
} // dispose timer?
Thread.Sleep(2000); // timer won't fire here
try
{
Console.WriteLine($"no problem accessing _myTimer: {_myTimer.Interval}"); // this won't throw an ObjectDisposedException on _myTimer
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex}");
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
try
{
Console.WriteLine($"no problem accessing _myTimer: {_myTimer.Interval}"); // still no ObjectDisposedException
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex}");
}
try
{
//_myTimer.Start(); // throws the ObjectDisposedException
_myTimer.Dispose(); // does not throw the ObjectDisposedException
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex}");
}
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
try
{
Console.WriteLine($"no problem accessing _myTimer: {_myTimer.Interval}"); // still no ObjectDisposedException
}
catch (Exception ex)
{
Console.WriteLine($"Exception: {ex}");
}
Console.WriteLine("Press any key to continue...");
Console.ReadLine();
}
I would expect to get the ObjectDisposedException after leaving the using block.
Accessing the _myTimer.Interval works all the way to the end of the program. Also, I can call _myTimer.Dispose() anytime. Even waiting for the GarbageCollector does not help to get the ObjectDisposedException.
However, I do get the ObjectDisposedException if I call _myTimer.Start() after leaving the using block.
How can _myTimer be around for the entire lifetime of my program?
Calling Dispose doesn't remove the object or references to it. It will not be GCed as long as there are references to it. Dispose releases unmanaged resources within the object, which is likely but by no means guaranteed to cause at least some of its methods to stop working and start throwing ObjectDisposedException.

CachedRowSet always returns empty

public CachedRowSet execute(String asql) throws ServiceUnavailableException {
try (Connection connection = getDatabaseConnection();
Statement statement = connection.createStatement();) {
try (ResultSet resultSet = statement.executeQuery(asql);
CachedRowSet rowset = CachedRowSetFactory.getCachedRowSet()) {
rowset.populate(resultSet);
return rowset;
}
} catch (SQLException se) {
throw new ServiceUnavailableException("Database broken " + se);
} catch (Exception ne) {
throw new ServiceUnavailableException("JNDI Lookup broken ");
}
return null;
}
Hi everyone. I have a sample code as above. The problem is that returned rowset is always empty, even though there are lots of data in database.
Any suggestions? Thank you.

Azure Mobile Apps Offline Client Throws NotSupportedException on Query

I have a Azure Mobile Apps Xamarin.Forms PCL client and have Offline Sync enabled. I tried to Pull data from my backend and afterwards query data from the offline storage with a Where clause. That throws the following exception and I don't know why.
Sync error: 'fahrerinfo.Imei.Equals("02032032030232")' is not supported in a 'Where' Mobile Services query expression.
public async Task SyncAsync()
{
ReadOnlyCollection<MobileServiceTableOperationError> syncErrors = null;
try
{
await OfflineSyncStoreManager.Instance.TruckFahrerTable.PullAsync("allTruckFahrerItems",
OfflineSyncStoreManager.Instance.TruckFahrerTable.CreateQuery());
Debug.WriteLine("SyncAsync: PUSH/PULL completed.");
}
catch (MobileServicePushFailedException e)
{
Debug.WriteLine("SyncAsync: PUSH failed.");
Debug.WriteLine(e.Message);
}
catch (Exception e)
{
Debug.WriteLine("SyncAsync: PUSH/PULL failed.");
Debug.WriteLine(e.Message);
//Debugger.Break();
}
}
public async Task<ObservableCollection<TruckFahrer>> GetTruckFaherAsync(bool syncItems)
{
try
{
if (syncItems)
{
await OfflineSyncStoreManager.Instance.SyncAsync().ConfigureAwait(false);
}
var deviceInfo = DependencyService.Get<IDeviceInfo>().GetPhoneInfo();
var imeiString = deviceInfo[trucker_rolsped.PhoneInfo.PhoneInfo.ImeiKey];
var imei = imeiString.Equals("000000000000000") ? deviceInfo[trucker_rolsped.PhoneInfo.PhoneInfo.IdKey] : imeiString;
IEnumerable<TruckFahrer> items =
await OfflineSyncStoreManager.Instance.TruckFahrerTable
//.Where(fahrerinfo => fahrerinfo.Imei.Equals(imei)) TODO: Why does that throw an exception???
.ToEnumerableAsync();
// TODO: Because above does not work
items = items.Where(fahrer => fahrer.Imei.Equals(imei));
return new ObservableCollection<TruckFahrer>(items);
}
catch (MobileServiceInvalidOperationException msioe)
{
Debug.WriteLine(#"Invalid sync operation: {0}", msioe.Message);
Debugger.Break();
}
catch (Exception e)
{
Debug.WriteLine(#"Sync error: {0}", e.Message);
Debugger.Break();
}
return null;
}
Thanks for any hint,
Eric
Are you a Java developer too? I'm and had this issue because in Java we need to compare strings with String#equals method, haha.
For some reason MobileServices doesn't allow us to use Equals in this situation.
To fix your problem, use == instead. As you can see here C# difference between == and Equals() both have the same effect in this case.
Where(fahrerinfo => fahrerinfo.Imei == imei)

JPA #OneToMany not persisting/cascading

I have the following code in UserController in my Session Scoped Bean
public void addItemToBundle(ItemEntity item){
//System.out.println(item.getTitle());
try {
em.getTransaction().begin();
UserEntity user = em.find(UserEntity.class, this.username);
BundleEntity bundle = new BundleEntity();
BundleEntityPK compositePk = new BundleEntityPK();
compositePk.setCheckedOutDate(new Date());
compositePk.setItemId(item.getItemId());
compositePk.setUsername(user.getUsername());
bundle.setId(compositePk);
Set<BundleEntity> bundles = new HashSet<BundleEntity>();
bundles.add(bundle);
user.setBundleEntities(bundles);
em.persist(user);
em.flush();
em.getTransaction().commit();
} finally {
}
}
public String addToBundle(){
try {
addItemToBundle(item);
} catch (NullPointerException e) {
e.getMessage();
}
return null;
}
This code uses private ItemEntity item; which gets passed in by the following JSF markup:
<p:commandLink action="#{itemController.item}">
<f:setPropertyActionListener target="#{itemController.selectedItem}" value="#{movie}" />
</p:commandLink>
(I'm using PrimeFaces in this example) The problem is that the addItemToBundle is not calling any SQL code in the console (I have FINE enabled) and the bundle never gets created or added to the user. I also tried em.persist(user) and em.flush() and setting cascadeType in my UserEntity with no luck.
#OneToMany(mappedBy="userEntity",cascade=CascadeType.PERSIST)
private Set<BundleEntity> bundleEntities;
Thanks!
You know that this:
try {
addItemToBundle(item);
} catch (NullPointerException e) {
e.getMessage();
}
is very bad practice, right? Maybe, that's the problem here, you run into a NPE and never notice it.
You should at least log the exception to know what's going on there (just for demo purposes, I've used stdout, please replace with your favorite logging framework):
try {
addItemToBundle(item);
} catch (NullPointerException e) {
System.err.println(e.getMessage()); //use logger here
}