Rare error when trying to save data "unhandled exception on the current circuit" - entity-framework-core

I am using VS 2022, Blazor server project. When I trying to save data
async public static Task<bool> updateObject(Firecall obj)
{
Firecall r;
try
{
using (var context = new sptContext())
{
r = context.Firecalls.Where(c => c.Mguid == obj.Mguid).FirstOrDefault();
bool новое = (r == null);
if (новое)
{
r = new Firecall();
}
r.comment = obj.comment;
if (новое)
await context.Firecalls.AddAsync(r);
if (busy)
return false;
try
{
busy = true;
await context.SaveChangesAsync();
}
catch (Exception)
{
return false;
}
finally {
busy = false;
}
}
return true;
}
catch (Exception)
{
return false;
}
}
sometimes I get error:
Sometimes an error occurs, sometimes not. No error in debugger.
How to solve problem?
P.S. Data in each operation is saved as expected. Only after the operation is completed the indicated error message appear
And calling savechanges method from #code block of .razor view:
async private void SaveChanges()
{
bool rez = await firecallRepository.updateObject(_currentFireCall);
}

Related

DeveloperError Exception of type 'Google.GoogleSignIn+SignInException', googleplaystore, unity, google login?

I have weird behaviour for my SignInWithGoogle.
I have everything set up for QAuth, SSH, WebClieng etc.
And when I sent a build to my phone directly. All work fine. I can SignIn, LogIn etc.
But when I made an aab build and uploaded it to google console and downloaded it from GooglePlay, as a tester, I received DeveloperError Exception of type 'Google.GoogleSignIn+SignInException.
Is there maybe something I need to change on QAuth to fix that?
public class SignInWithGoogle : MonoBehaviour
{
public static string slaveUserEmail;
public static string slaveUserPassword;
string webClientId = "536446807232-vh3olku8c637olltqlge92p17qmsqmtl.apps.googleusercontent.com";
private GoogleSignInConfiguration configuration;
FirebaseAuth _auth;
bool _initialized = false;
void Awake()
{
FireBaseInit.OnInitialized += OnFirebaseInit;
configuration = new GoogleSignInConfiguration
{
WebClientId = webClientId,
RequestIdToken = true
};
}
public void OnFirebaseInit()
{
if (_initialized) return;
_auth = FirebaseAuth.DefaultInstance;
_initialized = true;
Debug.Log("GoogleAuth Initialized");
}
public void OnSignIn()
{
Debug.Log("Calling SignIn");
GoogleSignIn.Configuration = configuration;
GoogleSignIn.Configuration.UseGameSignIn = false;
GoogleSignIn.Configuration.RequestIdToken = true;
var signInCompleted = new TaskCompletionSource<FirebaseUser>();
Debug.Log("SignInInit");
try
{
GoogleSignIn.DefaultInstance.SignIn().ContinueWith(task =>
{
if (task.IsFaulted)
{
using (IEnumerator<Exception> enumerator =
task.Exception.InnerExceptions.GetEnumerator())
{
if (enumerator.MoveNext())
{
GoogleSignIn.SignInException error =
(GoogleSignIn.SignInException)enumerator.Current;
Debug.Log("Got Error: " + error.Status + " " + error.Message);
}
else
{
Debug.Log("Got Unexpected Exception?!?" + task.Exception);
}
}
}
else if (task.IsCanceled)
{
Debug.Log("Canceled");
}
else
{
Debug.Log("Welcome in Google: " + task.Result.DisplayName + "!");
Debug.Log("GEt Ceds");
Credential credential = GoogleAuthProvider.GetCredential(task.Result.IdToken, null);
Debug.Log("Creds added");
Debug.Log("Firebase Log In try!");
FirebaseAuth.DefaultInstance.SignInWithCredentialAsync(credential).ContinueWith(authTask =>
{
if (authTask.IsCanceled)
{
Debug.Log("Auth Canceld");
signInCompleted.SetCanceled();
}
else if (authTask.IsFaulted)
{
Debug.Log("Auth Faulted");
signInCompleted.SetException(authTask.Exception);
}
else
{
Debug.Log("Auth Coplited");
signInCompleted.SetResult(((Task<FirebaseUser>)authTask).Result);
}
});
}
});
}
catch (Exception ex)
{
Debug.Log(ex.Message);
}
}
The full error:
Got Error: DeveloperError Exception of type 'Google.GoogleSignIn+SignInException' was thrown. <>c__DisplayClass8_0:b__0(Task`1) System.Threading.ThreadPoolWorkQueue:Dispatch()

SpringBoot to Flutter Stream using application/x-ndjson

I am trying to get a Flutter app to process a NDJSON stream properly, but cannot get it to work.
I have a SpringBoot server that the Flutter app requests a stream from.
SpringBoot side:
#GetMapping(value = "/streaming", produces = {
// MediaType.APPLICATION_JSON_VALUE,
MediaType.APPLICATION_NDJSON_VALUE
})
public Flux<String> getItemsStream(){
FluxSinkImpl<String> fluxSinkConsumer = new FluxSinkImpl<>();
try {
logger.info("streaming New Stream!");
synchronized (fluxSinkConsumers) {
fluxSinkConsumers.add(fluxSinkConsumer);
}
return Flux.create(fluxSinkConsumer).doOnNext(s -> {
logger.info("streaming doOnNext ["+s+"]");
}).doFinally(signalType -> {
logger.info("streaming Done ["+signalType+"]");
synchronized (fluxSinkConsumers) {
fluxSinkConsumers.remove(fluxSinkConsumer);
}
});
} catch (Exception e) {
logger.error("Failed to register Stream",e);
throw e;
}
}
private synchronized void publishEvent(String jsonStr) {
Set<FluxSinkImpl> fluxSinkConsumersCopy;
synchronized (fluxSinkConsumers) {
fluxSinkConsumersCopy = new HashSet<>(fluxSinkConsumers);
}
fluxSinkConsumersCopy.forEach(fluxSink -> {
try {
logger.info("streaming publishEvent");
fluxSink.publishEvent(jsonStr);
} catch (Throwable t) {
logger.info("streaming Failed to publish");
t.printStackTrace();
synchronized (fluxSinkConsumers) {
fluxSinkConsumers.remove(fluxSink);
}
}
});
}
The flutter side:
void startStreamListener2() async {
try {
final client = new http.Client();
http.Request request = http.Request("GET", Uri.parse(host+'streaming'));
request.headers['Content-type'] = 'application/x-ndjson';
request.headers['Accept'] = 'application/x-ndjson';
Future<http.StreamedResponse> streamedResponseFuture = client.send(request);
Stream<http.StreamedResponse> asStream = streamedResponseFuture.asStream();
print('startStreamListener1 [${host+'streaming'}]');
final StreamController<http.StreamedResponse> controller2 = new StreamController<http.StreamedResponse>();
asStream.asyncMap((event) {
event.stream.listen((value) {
print('startStreamListener4 listen [${utf8.decode(value)}]');
});
});
controller2.stream.listen((http.StreamedResponse event) {
event.stream.listen((value) {
print('startStreamListener3 listen [${utf8.decode(value)}]');
});
});
StreamSubscription<http.StreamedResponse> listen = asStream.listen((http.StreamedResponse event) {
event.stream.listen((value) {
print('startStreamListener2 listen [${utf8.decode(value)}]');
});
});
listen.onDone(() {
print('startStreamListener2 Done');
});
listen.onError((error) {
print('startStreamListener2 Error[$error] runtimeType[${error.runtimeType}]');
if (error is ClientException) {
print('ClientException [${(error as ClientException).message}]');
}
});
} catch (error) {
print('startStreamListener error [$error]');
}
}
When I use a Browser to connect directly to the stream, it works just fine. I see pushed messages as they are generated. The Stream is supposed to be open for a long time with asynchronous messages being pushed towards listeners (Flutter in this case).
Flutter does register, but does not trigger onData on single message. It does register the SpringBoot server restarting.

Postgres JDBC fetchSize() ignored

Why I'm having the fetch size ignored, I set it to 2, but whenever I run the program it returns whole records! If I print the fetch size will print 2, but the result will return whole records. Any implementation that I can return rows according to the fetch size? i.e I have 10 records in my DB I need to return 2 records for each trip in my tableAsStream method?
private Stream<SecurityGroup> tableAsStream(Context context, Connection connection) throws SQLException {
try {
connection.setAutoCommit(false);
Statement statement = connection.createStatement();
statement.setFetchSize(FETCH_SIZE);
ResultSet resultSet = statement.executeQuery(SELECT_SCHEDULE_MODULES_QUERY);
log.info("Returning a stream of SecurityGroups from the prepared statement ");
return StreamSupport.stream(new Spliterators.AbstractSpliterator<SecurityGroup>(Long.MAX_VALUE, Spliterator.ORDERED) {
#Override
public boolean tryAdvance(Consumer<? super SecurityGroup> action) {
try {
if(!resultSet.next()) return false;
action.accept(createRecord(resultSet));
return true;
} catch(SQLException ex) {
throw new RuntimeException(ex);
}
}
}, false);
} catch(SQLException sqlEx) {
throw sqlEx;
}
}
public void migrate(Context context) throws Exception {
Connection connection = context.getConnection();
// do{
log.info("Migration script started for (SCHEDULE_SHIFTS_EDIT_SELF).");
List<SecurityGroup> securityGroupList = tableAsStream(context, connection).collect(Collectors.toList());
securityGroupList.stream()
.flatMap(securityGroup -> securityGroup.getModules().stream())
.filter(securityModule -> securityModule.getName() == ModuleName.SCHEDULE)
.forEach(filteredSecurityModule -> {
boolean editPermissionExists = filteredSecurityModule.getFeatures().stream()
.anyMatch(x->PermissionName.SCHEDULE_SHIFTS_EDIT == x.getName());
boolean editSelfPermissionExists = filteredSecurityModule.getFeatures().stream()
.anyMatch(x->PermissionName.SCHEDULE_SHIFTS_EDIT_SELF == x.getName());
if (editPermissionExists && !editSelfPermissionExists) {
filteredSecurityModule.getFeatures().add(SecurityFeature.of(PermissionName.SCHEDULE_SHIFTS_EDIT_SELF, true, false));
}
});
updateSecurityGroups(securityGroupList, context);
log.info("Migration script Ended for (SCHEDULE_SHIFTS_EDIT_SELF).");
// } while(condition);
}

RxJava Problem with reading a file with Observable and take operator

My working environment is JDK 1.6 and RxJava 2
I want to make an Observable which emits an item that is a file line string read via BufferedReader as follows:
...
Observable<String> fileLineObservable = Observable.defer(new Callable<String>(){
return new ObservableSource<String> call() throws Exception {
return new ObservableSource<String>() {
public void subscribe(Observer<String> observer) {
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(filePath));
String line = null;
while ((line = reader.readLine()) != null) {
observer.onNext(line);
}
observer.onComplete();
... catching exception and close reader
}
}
}
}
});
I also want to make an Observer that observes the above Observable with one take(count) operator as follows:
fileLineObservable.take(2)
.subscribe(new Consumer<String>() {
public void onNext(String line) {
... do something with the file line string
}
});
I meet NullPointerException when executing the above code and I know why. The NPE is caused by that the second call of onNext leads to execute onComplete on the TakeObserver instance and inside the onComplete method, upstream.dispose that is not set(null) is called. The upstream variable of TakeObserver is supposed to be set with onSubscribe(Disposable disposable) when it subscribes an Observable.
How can I solve this problem? Should I implement my own Disposable class to set the upstream of TakeObserver?
What about this solution?
Observable<String> observableFile2(Path path) {
return Observable.using(
() -> Files.newBufferedReader(path),
reader -> {
return Observable.fromIterable(() -> {
return new Iterator<>() {
private String nextLine = null;
#Override
public boolean hasNext() {
try {
nextLine = reader.readLine();
return nextLine != null;
} catch (Exception ex) {
return false;
}
}
#Override
public String next() {
if (nextLine != null) {
return nextLine;
}
throw new IllegalStateException("nextLine can not be null.");
}
};
});
},
BufferedReader::close
);
}
Observable#using makes sure, that the BufferedReader is closed properly on disposable / onError
Observable#fromIterable wraps the readLine calls and handles onComplete for us.
Testing
testImplementation("org.junit.jupiter:junit-jupiter-api:5.6.2")
testRuntimeOnly("org.junit.platform:junit-platform-launcher:1.6.2")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.6.2")
testRuntimeOnly("org.junit.vintage:junit-vintage-engine:5.6.2")
testImplementation("com.google.jimfs:jimfs:1.1")
Tests
#Test
void name() {
observableFile2(hello).take(2)
.test()
.assertValues("line0", "line1")
.assertComplete();
}
#Test
void name2() {
observableFile2(hello).take(10)
.test()
.assertValues("line0", "line1", "line2", "line3")
.assertComplete();
}
#Test
void name3() {
observableFile2(hello2)
.test()
.assertComplete();
}

How to Repeat Previous Actions in Exception in EF 6

I am having a problem with repeating previous operations when there is an error in the SaveChanges method of Entity Framework.
Below is the code block
public static int SaveChangesTask(this DbContext db)
{
int result = -1;int countLoop = 0;
bool continueLoop = true;
var modifiedOrAddedEntities = db.ChangeTracker.Entries().Where(a => a.State != EntityState.Detached
&& a.State != EntityState.Unchanged).ToList();
while (continueLoop && countLoop<3)
{
try
{
result= db.SaveChanges();
continueLoop = false;
}
catch(Exception ex)
{
string error = ex.ToSystemException();
if(error.ToLowerInvariant().Contains("ORA-00060".ToLowerInvariant()) || error.ToLowerInvariant().Contains("deadlock"))
{
foreach (var item in modifiedOrAddedEntities)
{
db.Entry(item).State = item.State;
}
countLoop++;
Random rnd = new Random();
System.Threading.Thread.Sleep(rnd.Next(1, 5)* 1000);
}
else
{
throw ex;
}
}
}
return result;
}
But when I want to add old tracking objects to context, Entity Framework Throws Exception like that
"The entity type DbEntityEntry is not part of the model for the current context"